Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python设置进程的时间_Python - Fatal编程技术网

用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?您可以使用并发模

我想为python中的进程设置一个时间限制,因为这个进程不会以自身结束。 是这样的:

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”,为什么您需要它?