我有一些遗留的Python2.7代码,它们使用wxPython来创建gui。gui代码使用_thread.start_new_thread来启动从另一个模块导入的函数。我们正在将这段代码转换到Python3.9,我想用threading.Thread替换_thread,这样我就可以使用thread.excepthook了。但是,当我用threading.Thread替换_thread时,我的代码就挂起了。
例如,我有:
import _thread
import custom_module
_thread.start_new_thread(custom_module.go, (arg1, arg2))其中custom_module有一个可执行的go函数。这在两个Python3.9中都工作得很好,但我尝试使用threading.excepthook,所以我尝试用下面的代码替换它:
import threading
import custom_module
threading.Thread(target=custom_module.go, args=(arg1, arg2)).start()但是当我的代码到达线程时,它就会挂起。
_thread和threading之间有没有什么不同,会导致线程在threading上挂起而不是_thread上挂起
此外,在Python2.7中,我使用sys.excepthook来管理线程中发生的异常,但这不再起作用。当线程中发生异常时,线程就会结束。有什么想法吗?
所以看起来问题并不在于threading.Thread不工作。我能够让一条打印语句在我的custom_module.go函数的开头执行。它实际上挂在主程序中证实的记录器的logger.info语句上。
def init_logger():
"""Initialize."""
logger = logging.getLogger('FDS')
logger.setLevel('INFO')
logging.Formatter.converter = time.gmtime
formatter = logging.Formatter('%(asctime)s.%(msecs)03d | %(levelname)-8s |' +
' %(name)s | %(message)s',
datefmt='%Y/%j-%H:%M:%S')
# set up log buffers (will flush into log file & GUI once started)
mh_file = logging.handlers.MemoryHandler(capacity=1000, flushLevel='DEBUG')
mh_file.setFormatter(formatter)
logger.addHandler(mh_file)
mh_gui = logging.handlers.MemoryHandler(capacity=1000, flushLevel='DEBUG')
mh_gui.setFormatter(formatter)
logger.addHandler(mh_gui)
logger.info('=' * 80)
logger.info('Starting FDS - Release ' + __version__ + '...')
# create application
logger.info('Building GUI...')
app = wx.App(False)
logger.debug('FDS GUI application created.', extra={'same_line':True})然后我的代码就挂了
def go()
logger.info('Performing input validation...')
.
.
.发布于 2021-05-20 20:05:38
我想通了。我用一个以前用来覆盖sys.excepthook的函数覆盖了threading.excepthook,并且我没有更改该函数的参数(假设参数保持不变)。但是,在threading.excepthook覆盖函数中,您只能提供单个参数(https://docs.python.org/3/library/threading.html)。当我修复我的线程能够正常工作并正确处理错误时。
https://stackoverflow.com/questions/67539049
复制相似问题