gpt4 book ai didi

python - try block 在无限 while 循环中导致线程退出

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:43 33 4
gpt4 key购买 nike

我正在开发一个 Python 程序,该程序使用线程无限读取串行连接并根据输入处理异常。

本质上:在一个线程中,我想永远做某事,如果发生某些事情则引发异常,从异常返回并继续永远做某事,同时处理任何 future 的异常。

我创建了一个测试程序来使用 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 并处理异常,而不是退出线程。

最佳答案

通过简化我的代码来提出这个问题,我找到了解决方案。

简而言之,while True 循环应该围绕 try/except block ,而不是相反。这是因为...

If an exception occurs during execution of the try clause, the rest of the >clause is skipped. Then if its type matches the exception named after the >except keyword, the except clause is executed, and then execution continues >after the try statement.

https://docs.python.org/2/tutorial/errors.html#handling-exceptions

我的假设是,异常的行为类似于中断,因为它会执行处理代码,然后返回到引发异常后的执行点。这不是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

关于python - try block 在无限 while 循环中导致线程退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31662423/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com