gpt4 book ai didi

python - Windows 中 python 的程序超时

转载 作者:太空狗 更新时间:2023-10-30 02:34:38 25 4
gpt4 key购买 nike

您好,我在 SE 上看到了很多处理类似问题的问题,但我发现很多答案都不清楚且令人困惑。我的问题很简单。如何在 Windows 平台上使用 Python v2.6 在一定时间后终止正在运行的函数?如果我有:

def my_function(start):
x=start
while True:
print x
x=x+1
return x

我怎样才能在 X 秒后停止?请清楚地回答我的函数放在哪里以及如何调整时间限制。谢谢

最佳答案

如果你只想运行一个超时的普通函数,试试:

from datetime import timedelta, datetime
from time import sleep

endtime = datetime.utcnow() + timedelta(seconds = 2)

while True:
sleep(1) # just an example
if datetime.utcnow() > endtime: # if more than two seconds has elapsed
break

如果您谈论的是停止线程,则有一篇关于用线程执行此操作的博客文章涵盖了所有基础。

How (not) to set a timeout on a computation in Python . author也使用这个网站。

基本上,答案是在 Python 中没有“正确的方法”来执行此操作,但如果您不在 Windows 上,SIGALARM 可以工作。

关于python - Windows 中 python 的程序超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7150840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com