为什么这个while循环会“卡住”?
我在写的程序里有一个循环,它会从一个网站获取交易数据,并生成响应。这个循环会一直运行,只要网站没有交易数据,但一旦获取到结果,它就会回应,然后停止继续这个循环。任何建议都欢迎。
while True:
atran = getatran()
ntid = getntid()
if (ntid != otid and ntid != "-1"):
otid = ntid
tlidfile = open('last_transaction_id.txt', 'w')
tlidfile.write(str(otid))
tlidfile.close()
for x in range(len(atran['transactions'])) :
amount = atran['transactions'][x-1]['amount']
currency = atran['transactions'][x-1]['currency']
note = atran['transactions'][x-1]['note']
if note[:14] == "Transfer from:":
sender = note[15:]
if (sender == "satoshi4free") or (sender == "rabbit") or (sender == "mehbot") or (currency != 17): pass
else: flip(currency,amount,sender)
print "New: " + str(ntid)
print "Old: " + str(otid)
sleep(1)
我加了'print "New: "'和'print "Old: "'这两行代码来帮助排查问题。巧合的是,当ntid不等于"-1"时,循环就停止了。不过,循环至少会执行到'print "Old: "'这行代码,我猜测,它也会执行'sleep'这行。
我还有一个类似的功能,它会获取消息并做出回应,运行得非常顺利。具体代码如下:
while(condition == True):
amsg = getamsg()
nid = getnid()
if (nid != oid and nid != "-1"):
oid = nid
try:
for x in range(len(amsg['message_list'])) :
msg = amsg['message_list'][x-1]['msg']
pm = amsg['message_list'][x-1]['me']
sender = amsg['message_list'][x-1]['by']
if (msg.lower() == 'ping'):
condition = pong()
sleep(1)
if (msg.lower() == 'help'):
condition = helper()
sleep(1)
if (msg.lower() == 'luckydoge'):
condition = lucky()
sleep(1)
except (TypeError,KeyError):
pass
sleep(1)
1 个回答
0
我觉得你可以把你的问题标题改成:
为什么我的 while 循环“卡住”了?
很明显,你的代码中有某个地方卡住了。要找出是什么原因,你可以在每一行加上 print
语句(这是最简单的方法),或者更复杂一点(除非你有一个能帮你调试的开发工具):用调试器逐步执行代码,或者用性能分析工具来运行它。
我觉得这样回答你的问题已经很直接了,但目前的信息不足以给你更具体的分析。