Python "Bye" Loop logic is wrong?
I have a Python script that queries the MySQL database every 5 seconds, collecting the last three IDs for support tickets. I am using MySQLdb as my driver. But the problem is in my "while" loop when I check if two arrays are equal. If they are NOT equal, I type "New ticket has arrived". But it never prints! See my code:
import MySQLdb
import time
# Connect
db = MySQLdb.connect(host="MySQL.example.com", user="example", passwd="example", db="helpdesk_db", port=4040)
cursor = db.cursor()
IDarray = ([0,0,0])
IDarray_prev = ([0,0,0])
cursor.execute("SELECT id FROM Tickets ORDER BY id DESC limit 3;")
numrows = int(cursor.rowcount)
for x in range(0,numrows):
row = cursor.fetchone()
for num in row:
IDarray_prev[x] = int(num)
cursor.close()
db.commit()
while 1:
cursor = db.cursor()
cursor.execute("SELECT id FROM Tickets ORDER BY id DESC limit 3;")
numrows = int(cursor.rowcount)
for x in range(0,numrows):
row = cursor.fetchone()
for num in row:
IDarray[x] = int(num)
print IDarray_prev, " --> ", IDarray
if(IDarray != IDarray_prev):
print "A new ticket has arrived."
time.sleep(5)
IDarray_prev = IDarray
cursor.close()
db.commit()
Now that this ran, I created a new ticket, the result looks like this:
[11474, 11473, 11472] --> [11474, 11473, 11472]
[11474, 11473, 11472] --> [11474, 11473, 11472]
[11474, 11473, 11472] --> [11474, 11473, 11472]
[11474, 11473, 11472] --> [11474, 11473, 11472]
[11475, 11474, 11473] --> [11475, 11474, 11473]
[11475, 11474, 11473] --> [11475, 11474, 11473]
[11475, 11474, 11473] --> [11475, 11474, 11473]
[11475, 11474, 11473] --> [11475, 11474, 11473]
[11475, 11474, 11473] --> [11475, 11474, 11473]
Where is the format of my output:
[Previous_Last_Ticket, Prev_2nd_to_last, Prev_3rd] --> [Current_Last, 2nd-to-last, 3rd]
Note the change in numbers and, more importantly, the lack of "New Ticket Arrived"!
source to share
The problem lies in the following line:
IDarray_prev = IDarray
In Python, this means that it IDarray_prev
refers to the same underlying list as IDarray
. Changes in one will be reflected in the other, because they both point to the same thing.
To make a copy of the list that you can use for comparison later, try:
IDarray_prev = IDarray[:]
[:]
is Python's snippet notation which means "a copy of the entire list".
source to share