我被一个与线程相关的Python问题困住了。你知道吗
import threading
import time
import random
import sys
import echo
class presence(threading.Thread):
def __init__(self, cb):
threading.Thread.__init__(self)
self.callback = cb
def run(self):
minValue = 0
maxValue = 3
try:
while True:
time.sleep(1)
if random.randint(minValue, maxValue) == 1:
self.callback(1)
elif random.randint(minValue, maxValue) == 2:
raise Exception('An error')
else:
self.callback(0)
except:
print 'Exception caught!'
pass
def showAlert():
echo.echo('Someone is behind the door!')
def count(x):
if x == 1:
showAlert()
sys.stdout.flush()
这就是我所说的:
t2 = presence.presence(presence.count)
t2.start()
我最终得到一个"Exception caught!"
,但是线程不再返回警报。你知道吗
我做错什么了?你知道吗
try/except
块应该在循环内。例如:否则,当引发异常并且Python跳转到
except:
块以处理它时,循环将退出。你知道吗您也会注意到,我在示例中有选择地放置了
try/except
块,以便只覆盖可能实际引发异常的代码。这是一个最佳实践,我建议您在代码中使用它。用一个try/except
块包含大部分代码会降低可读性,也会浪费空间(很多行不必要地缩进)。你知道吗相关问题 更多 >
编程相关推荐