我正在使用线程同时运行多个函数,目的是从多个网站提取天气数据。我通过 Linux 终端运行这些程序,但是无法通过按 ctrl C 取消它们。我想让它们运行无限长的时间,因此不想添加完成时间,但宁愿必要时取消它们。有谁知道为什么 ctrl C 不取消它们,以及如何解决这个问题?
最佳答案
守护线程
简单地使用守护线程来解决这个问题可能很诱人,当仅只剩下守护线程时,python 执行将停止,并且不会允许它们清理很好。 The docs明确指出:
Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.
让我们听从他们的建议并使用事件。
使用事件
事件是一个简单的标志,可以跨线程安全地设置和读取。在这种情况下,我们将在主线程中创建一个事件,生成一个新线程来完成一些工作,并监听该事件标志以防它停止工作。
import threading
ended = threading.Event()
def do_work():
while not ended.is_set():
# Do your repeated work
pass
# Let's create and start our worker thread!
new_thread = threading.Thread(target=do_work)
new_thread.start()
try:
while not ended.is_set():
ended.wait(1)
except (KeyboardInterrupt, SystemExit):
print("Cancelling")
ended.set()
这里的 try/catch block 在主线程中运行,监听 KeyboardInterrupt
或 SystemExit
异常。如果它捕获到一个,它将设置 stopped
标志,允许线程完成其当前循环迭代,并执行它需要的任何清理。
关于python - 如何停止终端进程运行代码,包括线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44852655/