【发布时间】:2018-05-22 17:20:54
【问题描述】:
我想监控一个进程并在它运行超过 N 秒时自动终止它。
我正在编辑这个问题,以回应它与以下内容重复的建议: Is there any way to kill a Thread in Python?
我认为我的问题略有不同,因为我专注于线程完成后的基本清理(这实际上可能比上述可能的重复更困难,因为每个人似乎都说这是不可能的)。
作为一个简单的测试,我正在尝试以下方法来尝试在 2 秒后终止该进程:
import threading
import sys
import time
def after_timeout():
print "KILL THE WORLD HERE!"
# whats the secret sauce here (if any)?
# sys.exit() and other variants aren't
# killing the main thread... is it possible?
threading.Timer(2, after_timeout).start()
i = 0
while True:
print i
i += 1
time.sleep(1)
【问题讨论】:
-
我 99% 确定我很愚蠢,只是在这里遗漏了一些非常基本的东西。但是...我不能保证我的长期运行过程实际上是在迭代,所以我不能保证它会在这样的解决方案中达到“if e.is_set()”。
-
@zvone hrmm...我可能同意。 :-) 现在阅读该问题的答案。
-
@zvone 刚刚发布了我的问题的更新以及我目前提出的批评解决方案 :-)