我正在使用线程从流 (/dev/tty1) 中读取字符串,同时处理主循环中的其他内容。我希望线程在按下 CTRL-C 时与主程序一起终止。
from threading import Thread
class myReader(Thread):
def run(self):
with open('/dev/tty1', encoding='ascii') as myStream:
for myString in myStream:
print(myString)
def quit(self):
pass # stop reading, close stream, terminate the thread
myReader = Reader()
myReader.start()
while(True):
try:
pass # do lots of stuff
KeyboardInterrupt:
myReader.quit()
raise
通常的解决方案 - run() 循环内的 bool 变量 - 在这里不起作用。处理这个问题的推荐方法是什么?
我可以只设置 Daemon 标志,但随后我将无法使用 quit() 方法,这可能在以后证明很有值(value)(进行一些清理)。有任何想法吗?
最佳答案
AFAIK,Python 3 中没有内置机制(就像在 Python 2 中一样)。您是否尝试过使用 PyThreadState_SetAsyncExc
行之有效的 Python 2 方法? , 记录 here和 here ,或替代跟踪方法 here ?
这是 PyThreadState_SetAsyncExc
的稍微修改版本从上面的方法:
import threading
import inspect
import ctypes
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
关于multithreading - 如何在读取流时正确终止 Python3 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5899692/