我正在开发一个Python程序,它使用一个线程从串行连接无限读取并根据输入处理异常。
本质上:在一个线程中,我想永远做某事,如果发生了什么事情就引发异常,从异常中返回并在处理任何未来异常时继续做某事。
我已经创建了一个测试程序来使用time.sleep()来模拟这种行为,以便隔离我的问题。
import threading
import time
class TimeError(Exception):
def __init__(self, mesg):
self.mesg=mesg
class myObject(object):
def __init__(self):
self.threadRunning=False
def my_thread(self):
threadCount=0
try:
while True:
time.sleep(1)
print "Child: {}".format(threadCount)
threadCount = threadCount + 1
if threadCount>=5:
raise TimeError("5 seconds elapsed!")
except TimeError as e:
print (e.mesg)
print "Exiting thread!"
self.threadRunning=False
def my_parent(self): #start thread and wait
childThread = threading.Thread(target=self.my_thread)
childThread.daemon = True
childThread.start()
self.threadRunning = True
parentCount=0
while (self.threadRunning == True):
print "Parent: {}".format(parentCount)
parentCount = parentCount + 1
time.sleep(1)
print "Program complete."
fooObject = myObject()
fooObject.my_parent()
我收到的输出是
Parent: 0
Child: 0
Parent: 1
Child: 1
Parent: 2
Child: 2
Parent: 3
Child: 3
Parent: 4
Child: 4
5 seconds elapsed!
Exiting thread!
Parent: 5
Program complete.
我对Python很新,并且使用异常(我的背景是C)。我知道异常用于调试和恢复正常执行流程中的异常。我已经读到它是unwise to throw your own Exceptions,但对于我的最终申请,我必须这样做。
那么,在处理线程中的异常后,如何回到While True无限循环?我想继续增加threadCount并处理异常,而不是退出线程。
答案 0 :(得分:1)
通过煮沸我的代码以便提出这个问题,我找到了解决方案。
简而言之,while循环应该围绕try / except块,而不是相反。这是因为......
如果在执行try子句期间发生异常,则跳过>子句的其余部分。然后,如果其类型匹配以> except关键字命名的异常,则执行except子句,然后在try语句之后继续执行>
https://docs.python.org/2/tutorial/errors.html#handling-exceptions
我的假设是,Exception的行为就像一个中断,因为它执行处理代码,然后在异常被引发之后返回执行点。这不是C ......
固定代码:
import threading
import time
class TimeError(Exception):
def __init__(self, mesg):
self.mesg=mesg
class myObject(object):
def __init__(self):
self.threadRunning=False
def my_thread(self):
threadCount=0
while True:
try:
time.sleep(1)
print "Child: {}".format(threadCount)
threadCount = threadCount + 1
if threadCount>=5:
raise TimeError("5 seconds elapsed!")
except TimeError as e:
print (e.mesg)
print "Exiting thread!"
self.threadRunning=False
def my_parent(self): #start thread and wait
childThread = threading.Thread(target=self.my_thread)
childThread.daemon = True
childThread.start()
self.threadRunning = True
parentCount=0
while (self.threadRunning == True):
print "Parent: {}".format(parentCount)
parentCount = parentCount + 1
time.sleep(1)
print "Program complete."
fooObject = myObject()
fooObject.my_parent()
预期输出:
Parent: 0
Child: 0
Parent: 1
Child: 1
Parent: 2
Child: 2
Parent: 3
Child: 3
Parent: 4
Child: 4
5 seconds elapsed!
Parent: 5
Parent: 6
Child: 5
5 seconds elapsed!
Child: 6
5 seconds elapsed!
Parent: 7
Parent: 8
Child: 7
5 seconds elapsed!
Child: 8
5 seconds elapsed!
...indefinately