Could anyone help me find the problem in my Python script? This script simply gets a request posted from an HTML form with a few radio buttons.
import cgi
from file import *
form = cgi.FieldStorage()
print "Content-type: text/html"
print
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">"""
print "<html>"
print "<head>"
print "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">"
print "<title></title>"
print "</head>"
print "<body>"
choice = form.getvalue('option')
f = File("onlineVotes.txt")
if choice is None:
print "<p class='error'>Please choose an option before voting.</p>"
print "<br><a href='onlinePoll.html' class='backVoteAgain'>Go back</a>"
else:
if f.exists() == False:
f.startWrite()
f.write(choice)
print choice
print "<div class='voteBar' style='width: 250px;'>"
print 1
print "</div>"
else:
f.startRead()
choice = f.read() + " " + choice
choiceList = choice.split()
filterList = []
for item in choiceList:
if item not in filterList:
filterList.append(item)
choiceDict = {}
for elem in filterList:
print "<br>" + elem
counts = choiceList.count(elem)
choiceDict['%s' % elem] = counts
maxValue = max(choiceDict.values())
barWidth = counts*250/maxValue
print "<div class='voteBar' style='width: %spx;'>" % str(barWidth)
print counts
print maxValue
print "</div>"
totalVotes = str(sum(choiceDict.values()))
print "<br>Total number of votes: " + totalVotes
f.startWrite()
f.write(choice)
f.close()
print "</body>"
print "</html>"
The problem with this is that when option1 gets 10 votes, option2 gets 5 votes and option3 gets 3 votes, the value of max(choiceDict.values()) is 10, which is good as expected. However, when option1 gets 10 votes, option2 gets 11 votes and option3 gets 5 votes, the max value for option1 stays at 10 while it is 11 for both option2 and option3.
Where did I do wrong?
Related
I'm trying to send an html table in an email. I'm not sure if this is the best way or not, but right now I read in the CSV, create a table, and then email the info.
Here is what I have so far:
def create_table():
print("<html><table>")
# column headers
print("<th>")
print("<td>Tech</td>")
print("<td>Total</td>")
print("<td>Average</td>")
print("</th>")
infile = open("test.csv","r")
for line in infile:
row = line.split(",")
tech = row[0]
total = row[1]
average = row[2]
print("<td>%s</td>" % tech)
print("<td>%s</td>" % total)
print("<td>%s</td>" % average)
print("</table></html>")
SERVER = "localhost"
FROM = "forsdani#amazon.com"
TO = ["forsdani#amazon.com"] # must be a list
SUBJECT = "this is my email"
TEXT = "TABLE GOES HERE?"
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
If I do something like
TEXT = create_table()
then I get "None" for the text in the email. I'm not sure how to correct get the data from the function to the body of the email.
Your function does not return any values, it only prints them.
Instead of something like:
def create_table():
print("Hello, World!")
output = create_table() # output is None
Try:
def create_table():
string_to_return = "Hello, World!"
return string_to_return
output = create_table() # output is "Hello, World!"
Here's the function changed to return a value:
def create_table():
message = ""
message += "<html><table>" + "\n"
# column headers
message += "<th>" + "\n"
message += "<td>Tech</td>" + "\n"
message += "<td>Total</td>" + "\n"
message += "<td>Average</td>" + "\n"
message += "</th>" + "\n"
infile = open("test.csv","r")
for line in infile:
row = line.split(",")
tech = row[0]
total = row[1]
average = row[2]
message += ("<td>%s</td>" % tech) + "\n"
message += ("<td>%s</td>" % total) + "\n"
message += ("<td>%s</td>" % average) + "\n"
message += ("</table></html>") + "\n"
return message
The code is set run a command in my cisco device -- cache the output and query the outcome but if there is another line within the same outcome then to execute it.
peeringip = raw_input("Enter the customer's peering IP : ")
print
print
sitee = raw_input('Enter the Site(/col/ash/')
site = sitee.upper()
def cisco(routername,shrninc,showipint,showtunnel,shipprefix):
conn = SSH2()
conn.connect(routername)
conn.login(account1)
conn.execute('Terminal Length 0')
bgpstatements = shrninc + peeringip
print "Router Name: ",routername
conn.execute(bgpstatements)
showcomoutputbgp = conn.response
if 'neighbor' in showcomoutputbgp:
print "============"
print "-------------------"
print "============"
print "-------------------"
print
print "BGP configuration : ",conn.response
print
print "CHECKING PREFIX-LIST"
elif 'ROUTE' in showcomoutputbgp:
chkprefix = re.search("ROUTE",showcomoutputbgp)
prefix_name = chkprefix.group()
locate_prefix = shipprefix + prefix_name
conn.execute(locate_prefix)
print "PREFIX-LIST INFO : "
else:
print "No BGP neighbor"
No output for the Elif...
You need to indent this section because of the if statement. Also, instead of all the blank prints you can add \n to your previous prints. It makes it look neater and easier to read.
def cisco(routername,shrninc,showipint,showtunnel,shipprefix):
conn = SSH2()
conn.connect(routername)
conn.login(account1)
conn.execute('Terminal Length 0')
bgpstatements = shrninc + peeringip
print "Router Name: ",routername
conn.execute(bgpstatements)
showcomoutputbgp = conn.response
if 'neighbor' in showcomoutputbgp:
print "============"
print "-------------------"
print "============"
print "-------------------\n"
print "BGP configuration : ",conn.response + "\n"
print "CHECKING PREFIX-LIST"
elif 'prefix-list' in showcomoutputbgp:
chkprefix = re.search(r'(prefix-list)',showcomoutputbgp)
prefix_name = chkprefix.group()
locate_prefix = shipprefix + prefix_name
conn.execute(locate_prefix)
print "PREFIX-LIST INFO : ",conn.response + "\n"
else:
print "No BGP neighbor""
def cisco(routername,shrninc,showipint,showtunnel,shipprefix):
conn = SSH2()
conn.connect(routername)
conn.login(account1)
conn.execute('Terminal Length 0')
bgpstatements = shrninc + peeringip
print "Router Name: ",routername
conn.execute(bgpstatements)
showcomoutputbgp = conn.response
if 'neighbor' in showcomoutputbgp:
print "============"
print "-------------------"
print "============"
print "-------------------"
print
print "BGP configuration : ",conn.response
print
print "CHECKING PREFIX-LIST"
elif 'prefix-list' in showcomoutputbgp:
chkprefix = re.search(r'(prefix-list)',showcomoutputbgp)
prefix_name = chkprefix.group()
locate_prefix = shipprefix + prefix_name
conn.execute(locate_prefix)
print "PREFIX-LIST INFO : ",conn.response
print
else:
print "No BGP neighbor"
I wrote a python-cgi script (raspberry) that shows a page in the browser with some data. I will enter in this page from an other pc (linux, mac, etc.) entering usual address (//localhost/cgi-bin/myscript.py) in the browser. The page will be shown in fullscreen mode. I would have a button on the page that, as pushed, the page will close and exit the browser. I tried with pygame button and with submit (post or get method) button but with no success (I'm not really expert!).
Anybody can help me?
Thanks
#!/usr/bin/python
import os.path, sys, datetime, time
import cgi, cgitb
import os
import RPi.GPIO as io
import pygame, random, pygame.font, pygame.event, pygame.draw, string
import common
pygame.init()
io.setmode(io.BCM)
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
ctime = datetime.datetime.now()
clock = ctime.strftime("%H:%M")
date = ctime.strftime("%A %d")
form = cgi.FieldStorage()
fileobj = open('/sys/bus/w1/devices/28-0000065fb5c1/w1_slave','r')
lines1 = fileobj.readlines()
fileobj.close()
Temp2 = int(5)
Temp= form.getvalue(Temp2)
print "Content-type: text/html\n\n"
def main():
print "<html>"
print "<head>"
print "<meta http-equiv='refresh' content='5' >"
print "</head>"
print "<body>"
print "<body bgcolor=""#000000"">"
fileobj = open('/sys/bus/w1/devices/28-0000065fb5c1/w1_slave','r')
lines1 = fileobj.readlines()
fileobj.close()
Temp2 = int(5)
if (lines1[0][-4])=='Y':
pos1=lines1[1].index('t=')
Temp2 = int(lines1[1][pos1+2:])/1000
Temp2=round(Temp2,1)
time.sleep(1)
print "<table style=""width:1920px"">"
print "<tr height=""60"">"
print "</tr>"
print "<tr height=""400"">"
print "<td width=""442px"" >"
print "</td>"
if Temp2 <= 32:
print "<td width=""345"" background=""//192.168.10.32/dashblue.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp2
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
elif Temp2 > 32 and Temp2 <= 37:
print "<td width=""345"" background=""//192.168.10.32/dashgreen.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp2
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
if Temp2 > 37:
print "<td width=""345"" background=""//192.168.10.32/dashred.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp2
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
file = open('/home/pi/Downloads/temperat.txt','r')
lines = file.readlines()
file.close()
Temp = float(lines[0][:4])
Temp=round(Temp,1)
if Temp <= 22:
print "<td width=""345"" background=""//192.168.10.32/dashblue.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
elif Temp > 22 and Temp <= 26:
print "<td width=""345"" background=""//192.168.10.32/dashgreen.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
if Temp > 27:
print "<td width=""345"" background=""//192.168.10.32/dashred.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
Hum=int(lines[1])
print "<td width=""345"" background=""//192.168.10.32/dashblue.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print"<p align=""center"">"
print "<b>"
print Hum
degree = chr(37)
print degree
print "</b>"
print "</p>"
print "</td>"
print "<td width=""6%"" >"
print "</font>"
print "</td>"
print "</tr>"
print "<tr height=""80"">"
print "<td width=""6%"" >"
print "</td>"
print "<td width=""345"">"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "</p>"
print "<p align=""center"">"
print "Water Temperature"
print "</p>"
print "</font>"
print "</td>"
print "<td width=""345"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "Bath Temperature"
print "</p>"
print "</font>"
print "</td>"
print "<td width=""345"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print"<p align=""center"">"
print "Bath Humidity"
print "</p>"
print "</font>"
print "</td>"
print "<td width=""442px"" >"
print "</td>"
print "</tr>"
print "</table>"
print "<font size=""10"" color=""#00FFF"" face=""sans-serif"" >"
print "<h1 align=""center"">now..%s    %s</h1>" % (date,clock)
print "</font>"
print "</body>"
print "</html>"
for event in pygame.event.get():
if event.type == QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_F6):
pygame.quit()
sys.exit()
if (__name__=='__main__'):
main()
Your problem is not a Python problem, it's a JavaScript problem, and like #rob said, it's a duplicate of this question: stackoverflow.com/questions/2076299/...
And to summarize it for you; you'd need JavaScript to close the window, but as it happens JavaScript is sandboxed in a way that prevents it from closing a window that was not opened by the same script on the page, so if you open a tab or a window in your browser and navigate to a page, that page cannot kill itself nor can it kill the browser, it can only close and kill any windows it launches by JavaScript.
The only thing you can do is to navigate to a different page like executing window.location = 'A DIFFERENT URL' in JavaScript; you can even navigate to about:blank which shows a blank page on most browsers.
I am writing a Quiz app using python Script. My HTML file Contains 1 Question at a time Displayed along with its 4 options. Below there are 2 buttons for Questions to Navigate. "Previous" and "Next". once the option is chosen, user can click next button and the selected value should be stored somewhere for further calculation of score and next Question
should be displayed.
I am new to Cgi stuff. So far i am able to load Question 1. and i am stuck further.
Somebody please help
i am storing questions and options in a seperate file like this
question|optionA|optionB|optionC|optionD|answer
#!/usr/bin/python
import cgi, Cookie, os, cgitb, linecache
cgitb.enable()
cookie = Cookie.SimpleCookie()
attempt = 0
qc= 0
scr = 0
wrng = 0
total = 0
cur = 1
cookie["Attempted"] = attempt
cookie["Correct"] = qc
cookie["Score"] = scr
cookie["Wrong"] = wrng
cookie ["Count"] = total
cookie["Current"] = cur
file = "quest" # my question bank
data = linecache.getline(file,cur)
data = data.strip('\n')
data = data.split('|')
form = cgi.FieldStorage()
if form.getvalue('prev'):
if(cur > 1):
cur = int (cookie["Current"].value) - 1
cookie["Current"] = cur
print cookie
print "Content-type:text/html\r\n\r\n"
HTML CODE
print "<span id=\"disQ\">"
print data[0]
print "</span></br>"
print "<input type=\"radio\" name=\"qstn\" value=\"1\" /><span>" + data[1] + "</span></br>"
print "<input type=\"radio\" name=\"qstn\" value=\"2\" /><span>" + data[2] + "</span></br>"
print "<input type=\"radio\" name=\"qstn\" value=\"3\" /><span>" + data[3] + "</span></br>"
print "<input type=\"radio\" name=\"qstn\" value=\"4\" /><span>" + data[4] + "</span></br>"
print "<input id=\"prev\" name=\"prev\" type=\"submit\" value=\"PREV\" onclick=\"this.form.submit()\">"
print "<input id=\"next\" name=\"next\" type=\"submit\" value=\"NEXT\" onclick=\"this.form.submit()\">"
print "<h5>Total Questions : </h5><span class = \"data\" id=\"total\">"+ cookie["Count"].value + "</span>"
print "<h5>Attempted :</h5><span class = \"data\" id=\"attempt\">" + cookie["Attempted"].value + "</span>"
print "<h5>Correct :</h5><span class = \"data\" id=\"correct\">" + cookie["Correct"].value + "</span>"
print "<h5>Wrong :</h5><span class = \"data\" id=\"wrong\">" + cookie["Wrong"].value + "</span>"
print "<h5>Score :</h5><span class = \"data\" id=\"score\">" + cookie["Score"].value + "</span>"
My needs check windows process number.
import sys
import os
import commands
ip = sys.argv[5]
val = sys.argv[1]
oid = "HOST-RESOURCES-MIB::hrSWRunName"
cmd = "snmpwalk -v 2c -c public %s %s" % (ip,oid)
(r_c,r_e) = commands.getstatusoutput(cmd)
if r_c != 0:
print "C - snmpwalk is Error."
else:
for i in r_e.split('\n'):
a = i.split(':')[-1].strip(' "')
print a
Result:
conhost.exe
conhost.exe
conhost.exe
conhost.exe
fdhost.exe
cmd.exe
fdhost.exe
I hope the result is. I do not know how to achieve it.
if sys.argv[1] <5:#count(conhost.exe)
print "critical -"
else:
print "OK - "
How the statistics of my results? conhost.exe 4 conhost.exe 1 conhost.exe 1
# replace here
else:
processes = r_e.split('\n')
programs = 0
for program in processes:
programFile = program.split(':')[-1].strip(' "')
# the first argument you pass to the program should be conhost.exe
if programFile == sys.argv[1]:
programs = programs + 1
if programs < 5 :#count(conhost.exe)
print "critical: running less than 5 times:", sys.argv[1]
else:
print "OK"
second version
# replace here
else:
processes = r_e.split('\n')
processes = map(lambda program: program.split(':')[-1].strip(' "'), processes)
if processes.count(sys.argv[1]) < 5 :#count(conhost.exe)
print "critical: running less than 5 times:", sys.argv[1]
else:
print "OK"