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"
Related
I am doing a C/S project in which one of the function is a downloading file from the server.
The client is written in python and the server is written in java.
-f filename is a command that fetches the file.
The only problem is in the
def download(self,filename):
print "Start download file"
self.sock.send("DOWNLOAD"+"sprt"+filename)
downloadData = self.sock.recv();
print downloadData
and
if message[0:message.find(" ")] == "-f":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage -f filename\n"
else:
client.download(message[message.find(" ")+1:])
part.
AttributeError: 'timer' object has not attribute 'download'.
In contrast the
def upload(self,filename):
print "server ready , now client sending file~~"
try:
f = open(filename,'rb')
while (True):
data = f.read();
#if file is none
if data is None:
break;
#Notify the java server that a file is going to be sent.
#sprt stands for seperator
self.sock.sendall("FILE"+"sprt"+filename+"sprt"+data+'\n')
break;
f.close();
time.sleep(1)
#Notify the java server that the file is complete
self.sock.send("EOF\n")
print "send file success!"
except IOError:
print "No such file or Directory"
the method works normally.
What might cause the problem ? Thanks
Here is the whole file.
import threading
import sys
import time
import socket
class timer(threading.Thread):
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(('localhost', 9991))
self.isrun = True
threading.Thread.__init__(self);
def run(self):
while self.isrun:
revice = self.sock.recv(1024);
print ("recv> " + revice);
self.sock.close()
def send(self,str):
self.sock.send(str + "\n")
def close(self):
self.isrun=False
def upload(self,filename):
print "server ready , now client sending file~~"
try:
f = open(filename,'rb')
while (True):
data = f.read();
#if file is none
if data is None:
break;
#Notify the java server that a file is going to be sent.
#sprt stands for seperator
self.sock.sendall("FILE"+"sprt"+filename+"sprt"+data+'\n')
break;
f.close();
time.sleep(1)
#Notify the java server that the file is complete
self.sock.send("EOF\n")
print "send file success!"
except IOError:
print "No such file or Directory"
def download(self,filename):
print "Start download file"
self.sock.send("DOWNLOAD"+"sprt"+filename)
downloadData = self.sock.recv();
print downloadData
def main():
client = timer()
client.start()
print "Welcome:\n","Command to be used:\n","-a filename\n" "-c number\n", "-f filename\n","-h hostname:port\n","-n name\n","-u certificate\n","-v filename certificate\n","otherwise input will be treated as normal message"
while (True):
# get input from user
message = str(raw_input("send> "));
#Space exists and not occupies the first place
if ((message.find(" "))!= -1 and message.find(" ")>0):
if message[0:message.find(" ")] == "-a":
#if there is a space but there is nothing following -a "-a "
#or if there are more than one space following -a "-a j" or "-a h j" len(message.split(" ") return the size of array after token, need to be exactly 2;
if not message.split(" ")[1] or len(message.split(" "))>2 :
print "Usage -a filename\n"
#normal execution
else:
client.upload(message[message.find(" ")+1:])
if message[0:message.find(" ")] == "-c":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage -c number\n"
else:
print "provide the required circumference (length) of a circle of trust"
if message[0:message.find(" ")] == "-f":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage -f filename\n"
else:
client.download(message[message.find(" ")+1:])
if message[0:message.find(" ")] == "-h":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage- h hostname:port\n"
else:
print "provide the remote address hosting the oldtrusty server"
if message[0:message.find(" ")] == "-n":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage -n name\n"
else:
print "require a circle of trust to involve the named person (i.e. their certificate)"
if message[0:message.find(" ")] == "-u":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage -u certificate\n"
else:
print "upload a certificate to the oldtrusty server"
if message[0:message.find(" ")] == "-v":
#if there are exactly two spaces "-v a b" , normal execution
if(len(message.split(" ")) == 3):
print "vouch for the authenticity of an existing file in the oldtrusty server using the indicated certificate"
else:
print "Usage: -v filename certificate\n"
elif (message == "-l"):
print "list all stored files and how they are protected"
elif(message=="-a") or (message=="-c") or (message=="-f")or (message=="-h") or (message=="-n")or (message=="-u") or (message=="-u") or (message=="-v"):
print"Usage :\n","-a filename\n" "-c number\n", "-f filename\n","-h hostname:port\n","-n name\n","-u certificate\n","-v filename certificate\n"
# exit if the input is 'exit'
elif (message == "exit"):
client.send("EXIT"+"sprt");
client.close();
time.sleep(0.01);
#Normal Commmunication
else:
print "Other situation"
print message;
client.send("NORMAL"+"sprt"+message);
if __name__=='__main__':
main()
The file you are using differs from the one you've posted here in one significant aspect: indentation. Your download method is either indented too much (that would make it defined while running upload) or too little (that would make it a module-level function, instead of one associated with timer). Make sure that the indentation around def download is correct, i.e. 4 spaces.
While you're at it, the line
downloadData = self.sock.recv();
will need some modification too. Most likely, you want something along the lines of
downloadData = self.sock.recv(4096)
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 have a school project that involves programming. I am transferring between batch and python because that is easiest for me.
This is my code written in python:
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
else:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"
My problem is that I can't find a string in a tuple. What happens is that when there is a result, it runs perfectly. But when there isn't a result, nothing happens.
How can I overcome this?
Thank you in advance.
Edit:
I was probably not specific enough when asking my question.
The result variable is in fact a MySQL execution result using the fetchall() command. The whole code of my program is:
import MySQLdb
import sys
import os
print "=========================="
print "Start Registered_Or_Not.py"
print "=========================="
os.chdir("C:/DisabledParkingSpacesImages/textfiles")
f = open("numberplate.txt", "r")
number = f.read()
print number
try:
db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = 'jordan',
db = 'disabledparking'
)
except Exception as e:
sys.exit("Can't access the database")
print "MySQL Connection OK"
cursor = db.cursor()
cursor.execute("SELECT registration FROM registered WHERE EXISTS (SELECT 1 FROM limbo WHERE limbo.registration = registered.registration)")
result = cursor.fetchall()
insert1 = "INSERT INTO log (registration, time, date) VALUES(%s, CURRENT_TIME, CURRENT_DATE);"
insert2 = "INSERT INTO not_registered (registration, time, date) VALUES(%s, CURRENT_TIME, CURRENT_DATE);"
delete = "DELETE FROM limbo WHERE registration=%s;"
print "-------------"
print "Result:"
print result
print "-------------"
TrueFalse = False
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
TrueFalse = True
elif TrueFalse == False:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"
db.commit()
OK, So I answered my own question.
Here is the problematic code:
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
else:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"
And here is the non problematic code:
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
TrueFalse = True
if TrueFalse == False:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"
I am attempting to "replaceDataSource" with our new sde path. I am using v2.7 in Arc10.2. We have multiple direct connect path names and one service connect that has changed servers from using Oracle to Sql Server. My code works all the way through the print statements but then I get the error msg "unable to saveACopy, check my privileges". Please let me know if I'm on the right track with putting all of the various connect names into a list and then iterating through them the way I have written. Also, I have attempted every indent on mxd.saveACopy and del mxd but nothing after two weeks has seemed to work so I thought I'd finally ask for some geo geek wisdom!
Code:
import arcpy, os, glob
arcpy.env.workspace = "C:\Users\kmetivier\Documents\BrokenPaths\Folder5"
for root, subFolders, files in >os.walk(r"C:\Users\kmetivier\Documents\BrokenPaths\Folder5"):
for filename in files:
fullpath = os.path.join(root, filename)
basename, extension = os.path.splitext(fullpath)
if extension.lower() == ".mxd":
print "------------------------------"
print filename
#open the map document
mxd = arcpy.mapping.MapDocument(fullpath)
#get all the layers
for lyr in arcpy.mapping.ListLayers(mxd):
#get the source from the layer
if lyr.supports("datasource"):
pathList = ["Database Connections\PWDB.arvada.org.sde","Database >Connections\GIS - PWDB.sde","Database Connections\PROD - GIS.sde","Database Connections\DC >- PROD - GIS.sde","Database Connections\GIS to SDE1.sde"]
print "%s -> %s" % (lyr, pathList[0])
basename, extension = os.path.splitext (pathList[0])
if extension.lower() == ".sde":
#NEW SOURCE
datapath = r"Database Connections\GEODATA - GIS.sde"
#overwrite the old path
lyr.replaceDataSource(datapath, "SDE_WORKSPACE", "")
print "replaced " + pathList[0] + " with " + datapath
print "---------finished " + filename
mxd.saveACopy(filename +"_2")
del mxd
for lyr in arcpy.mapping.ListLayers(mxd):
if lyr.supports("SERVICEPROPERTIES"):
pathList1= r"(PWDB.arvada.org, 5151, {sde1}, {Database_authentication}, >{GDS}, {""}, {save_username_password}, {version}, {save_version_info}"
servProp = lyr.serviceProperties
print "Layer name:" + lyr.name
print "-----------------------------------------------------"
if lyr.serviceProperties["ServiceType"] != "SDE":
print "Service Type: " + servProp.get('ServiceType', 'N/A')
print " URL: " + servProp.get('URL', 'N/A')
print " Connection: " + servProp.get('Connection', 'N/A')
print " Server: " + servProp.get('Server', 'N/A')
print " Cache: " + str(servProp.get('Cache', 'N/A'))
print " User Name: " + servProp.get('UserName', 'N/A')
print " Password: " + servProp.get('Password', 'N/A')
print ""
if extension.lower() == ".sde":
#This is the NEW SOURCE that you want to point to
datapath1 = r"Database Connections\GEODATA - GIS.sde"
#replace the old path wih the new
lyr.replaceDataSource(pathList1, "SDE_WORKSPACE", "")
print "replaced " + pathList1 + " with " + datapath1
print "finished " + filename
mxd.saveACopy(filename +"_2")
else:
print "Service Type: " + servProp.get('ServiceType', 'N/A')
print " Database: " + servProp.get('Database', 'N/A')
print " Server: " + servProp.get('Server', 'N/A')
print " Service: " + servProp.get('Instance', 'N/A')
print " Version: " + servProp.get('Version', 'N/A')
print " User name: " + servProp.get('UserName', 'N/A')
print " Authentication: " + servProp.get('AuthenticationMode', >'N/A')
print ""
del mxd>>
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?