是否可以从python的子线程中杀死父线程?
我在 Windows 上使用 Python 3.5.2.
I am using Python 3.5.2 on windows.
我想运行一个 python 脚本,但保证它不会超过 N 秒.如果确实花费超过N秒,则应该引发异常,并且程序应该退出.最初我以为我可以在开始时启动一个线程,在抛出异常之前等待 N 秒,但这只能向计时器线程抛出异常,而不是向父线程抛出异常.例如:
I would like to run a python script but guarantee that it will not take more than N seconds. If it does take more than N seconds, an exception should be raised, and the program should exit. Initially I had thought I could just launch a thread at the beginning that waits for N seconds before throwing an exception, but this only manages to throw an exception to the timer thread, not to the parent thread. For example:
import threading
import time
def may_take_a_long_time(name, wait_time):
print("{} started...".format(name))
time.sleep(wait_time)
print("{} finished!.".format(name))
def kill():
time.sleep(3)
raise TimeoutError("No more time!")
kill_thread = threading.Thread(target=kill)
kill_thread.start()
may_take_a_long_time("A", 2)
may_take_a_long_time("B", 2)
may_take_a_long_time("C", 2)
may_take_a_long_time("D", 2)
输出:
A started...
A finished!.
B started...
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Program Files\Python35\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Program Files\Python35\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "timeout.py", line 11, in kill
raise TimeoutError("No more time!")
TimeoutError: No more time!
B finished!.
C started...
C finished!.
D started...
D finished!.
这甚至可能吗?我意识到我可以做这样的事情:
Is this even remotely possible? I realize I could do something like this:
import threading
import time
def may_take_a_long_time(name, wait_time, thread):
if not thread.is_alive():
return
print("{} started...".format(name))
time.sleep(wait_time)
print("{} finished!.".format(name))
def kill():
time.sleep(3)
raise TimeoutError("No more time!")
kill_thread = threading.Thread(target=kill)
kill_thread.start()
may_take_a_long_time("A", 2, kill_thread)
may_take_a_long_time("B", 2, kill_thread)
may_take_a_long_time("C", 2, kill_thread)
may_take_a_long_time("D", 2, kill_thread)
但是这个方法会失败,例如,may_take_a_long_time("B", 60, kill_thread)
被调用.
But this method fails if, for example, may_take_a_long_time("B", 60, kill_thread)
was called.
所以我想我的 TL;DR 问题是,对主线程本身设置时间限制的最佳方法是什么?
So I guess my TL;DR question is, what's the best way to put a time limit on the main thread itself?
您可以使用 _thread.interrupt_main
(此模块在 Python 2.7 中称为 thread
):
import time, threading, _thread
def long_running():
while True:
print('Hello')
def stopper(sec):
time.sleep(sec)
print('Exiting...')
_thread.interrupt_main()
threading.Thread(target = stopper, args = (2, )).start()
long_running()