我有一個Python腳本,每5秒查詢一次MySQL數據庫,收集最新的三個ID的幫助臺票據。我使用MySQLdb作爲我的驅動程序。但問題是在我的「while」循環中,當我檢查兩個數組是否相等時。如果不相等,我會打印「新票已到。」但是這絕不會打印!見我的代碼:Python「While」循環邏輯錯誤?
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()
現在,當這個跑了,然後我創建了一個新的機票,輸出看起來是這樣的:
[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]
凡我輸出的格式是:
[Previous_Last_Ticket, Prev_2nd_to_last, Prev_3rd] --> [Current_Last, 2nd-to-last, 3rd]
注意數量的變化,更重要的是,缺少「新票已經抵達」!
美麗!就是這樣!謝謝! – armani 2012-04-01 20:30:52
或者你可以在'copy'模塊中使用'copy'功能。 – 2012-04-01 20:31:48
是的,有很多方法可以解決這個問題。你可以使用'copy',或者你也可以使用'list(IDarray)'。 – 2012-04-01 20:32:31