for and in and enumerate and if ...... AHHHHHHH - python

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"

Related

pyodbc: print datatype in python

I just started learning Python and I got into pyodbc. I would like to print the datatypes of the columns just once above the actual data. But right now, it prints the datatypes through the whole loop or the program shuts down. I'm not sure about what exactly my mistake is.
def selectPlace(dbc):
cursor = dbc.cursor()
try:
cursor.execute('SELECT Nr, address from Place')
except:
print ('Error')
cursor.close()
return
print ('\nPlaces:')
i = 0
for row in cursor:
if i == 0:
print('Datatypes: ', type(row[0]), type(row[1]))
i = 1
print (row[0], row[1])
# print type(row[0])
cursor.close()
x = input('Input : ')
return x

How to prevent 'NoneType' object is not subscriptable error' when MS SQL does not contain data in the table?

Currently I get a ''NoneType' object is not subscriptable error' if I search for data that is not in the MS SQL table.
Instead of stopping Python and outputting this error, I just want it to state that the 'data does not exist' and request another search.
Here is my current code:
cursor = connection.cursor()
SQLCommand = ("SELECT Name, Location_ID "
"FROM dbo.PB_Location "
"WHERE Location_ID = ?")
Values = [choice]
cursor.execute(SQLCommand,Values)
results = cursor.fetchone()
os.system('cls' if os.name == 'nt' else 'clear')
# note: UID column is an integer. You can't normally take an integer and place it in a string.
# so you must add str(results[2])
print (" ")
print("Name: " + results[0] + " Location ID: " + str(results[1]))
connection.close()
The below doesn't work, but would I do something close to this?
cursor = connection.cursor()
SQLCommand = ("SELECT Name, Location_ID "
"FROM dbo.PB_Location "
"WHERE Location_ID = ?")
Values = [choice]
cursor.execute(SQLCommand,Values)
while True:
results = cursor.fetchone()
if results is None:
break
os.system('cls' if os.name == 'nt' else 'clear')
# note: UID column is an integer. You can't normally take an integer and place it in a string.
# so you must add str(results[2])
print (" ")
print("Name: " + results[0] + " Location ID: " + str(results[1]))
connection.close()
Oh, I figured it out...
cursor = connection.cursor()
SQLCommand = ("SELECT Name, Location_ID "
"FROM dbo.PB_Location "
"WHERE Location_ID = ?")
Values = [choice]
cursor.execute(SQLCommand,Values)
results = cursor.fetchone()
if results:
os.system('cls' if os.name == 'nt' else 'clear')
print (" ")
print ("Name: " + results[0] + " Location ID: " + str(results[1]))
connection.close()
else:
print (" Does not exist.")
connection.close()

sqlite3.OperationalError: database is locked - How to avoid this?

I'm using an open source piece of python code that basically pulls in a location of an entity and saves these details to a DB in real time. lets call it scanner the scanner program. DB file it saves it to is a sqlite file: db.sqlite.
As this is happening my piece of code in question is searching the db file every 45 seconds performing a select statement to find a certain value. This will work a couple of times but after running for a couple of minutes concurrently with the scanner program they run into a DB lock error:
sqlite3.OperationalError: database is locked
So what can I do to my code to ensure this lock does not happen. I cannot change how the scanner program accesses the DB. Only my program.
Any help here would be great. I've seen timeouts mentioned along with threading but I am not sure on either.
from datetime import datetime
import sqlite3
import time
import json
import tweepy
def get_api(cfg):
auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
return tweepy.API(auth)
# Fill in the values noted in previous step here
cfg = {
"consumer_key" : "X",
"consumer_secret" : "X",
"access_token" : "X",
"access_token_secret" : "X"
}
with open('locales/pokemon.en.json') as f:
pokemon_names = json.load(f)
currentid = 1
pokemonid = 96 #test
while 1==1:
conn = sqlite3.connect('db.sqlite')
print "Opened database successfully";
print "Scanning DB....";
time.sleep(1)
cur = conn.execute("SELECT * FROM sightings WHERE pokemon_id = ? and id > ?", (pokemonid, currentid))
row = cur.fetchone()
if row is None:
print "No Pokemon Found \n "
time.sleep(1)
while row is not None:
#get pokemon name
name = pokemon_names[str(pokemonid)]
#create expiry time
datestr = datetime.fromtimestamp(row[3])
dateoutput = datestr.strftime("%H:%M:%S")
#create location
location = "https://www.google.com/maps/place/%s,%s" % (row[5], row[6])
#inform user
print "%s found! - Building tweet! \n" % (name)
time.sleep(1)
#create tweet
buildtweet = "a wild %s spawned in #Dublin - It will expire at %s. %s #PokemonGo \n "%(name, dateoutput, location)
#print tweet
#log
print buildtweet
currentid = row[0]
time.sleep(1)
#send tweet
api = get_api(cfg)
tweet = buildtweet
try:
status = api.update_status(status=tweet)
print "sent!"
except:
pass
print "this tweet failed \n"
time.sleep(30)
row = cur.fetchone()
cur.close()
conn.close()
print "Waiting..... \n "
time.sleep(45)
conn.close()

Attribute Error : "timer" object has no attribute "download"

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)

IndentationError expected an indented block for Network automication

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"

Categories