用Python设置进程的时间
我想为python中的进程设置一个时间限制,因为这个进程不会以自身结束。 是这样的:用Python设置进程的时间,python,Python,我想为python中的进程设置一个时间限制,因为这个进程不会以自身结束。 是这样的: def forever(): pass somethink_to_do_this_20_secounds: forever() print("this print after 20 seconds of forever() work") 我找到了一个关于检查程序执行时间的主题,但没有找到设置程序时间限制的主题 我如何在Python中实现这一点?通过使用subprocess?您可以使用并发模
def forever():
pass
somethink_to_do_this_20_secounds:
forever()
print("this print after 20 seconds of forever() work")
我找到了一个关于检查程序执行时间的主题,但没有找到设置程序时间限制的主题
我如何在Python中实现这一点?通过使用subprocess?您可以使用并发模块触发一个单独的线程并等待20秒
from concurrent.futures import ThreadPoolExecutor, TimeoutError
from time import sleep
def forever():
sleep(21)
pool = ThreadPoolExecutor()
future = pool.submit(forever)
try:
result = future.result(20)
except TimeoutError:
print("Timeout")
print("this print after 20 seconds of forever() work")
你的代码格式正确吗?forever()是否使用循环?如果有帮助,请检查此项:您想对函数或进程设置限制?您也可以使用signal,您提到的“subprocess”,为什么您需要它?