Python“While”循环逻辑错误?

2024-09-30 01:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python脚本,它每5秒查询一个MySQL数据库,收集帮助台问题的最新三个ID。我使用MySQLdb作为我的驱动程序。但问题出在我的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()

当这个运行时,我创建了一个新的票证,输出如下所示:

^{pr2}$

我的输出格式是:

[Previous_Last_Ticket, Prev_2nd_to_last, Prev_3rd] --> [Current_Last, 2nd-to-last, 3rd]

注意到数字的变化,更重要的是,缺少“一张新票来了”!在


Tags: inidfordbexamplemysqlcursornum
2条回答

问题出在以下几行:

IDarray_prev = IDarray

在Python中,这使得IDarray_prev引用与IDarray相同的底层列表。一方面的变化会反映在另一方面,因为它们都指向同一件事。在

要制作列表的副本,以便以后比较,请尝试:

^{pr2}$

[:]是Python切片表示法,意思是“整个列表的副本”。在

Python使用引用,因此在第一次while迭代之后基本上都会更改这两个列表(因为在将IDarray分配给IDarray_prev之后,它们都具有相同的引用)。在

尝试使用IDArray_prev = list(IDarray)分配IDarray的副本。在

相关问题 更多 >

    热门问题