python-3.x - 如何为不是函数python3的代码块设置超时

标签 python-3.x timeout

在花了很多时间在 stackoverflow 中寻找解决方案后,我没有找到一个好的解决方案来为代码块设置超时。有一些近似值可以为函数设置超时。不过,我想知道如何在没有函数的情况下设置超时。我们以下面的代码为例:

    print("Doing different things")
    for i in range(0,10)
         # Doing some heavy stuff

    print("Done. Continue with the following code")

那么,如果 for 循环在 x 秒后还没有完成,你将如何中断它?尽管 for 循环没有正确完成,但只需继续代码(也许保存一些 bool 变量以知道已达到超时)。

最佳答案

我认为在不使用不可能的函数的情况下有效地实现这一点,看看这段代码..

import datetime as dt
print("Doing different things")
# store 
time_out_after = dt.timedelta(seconds=60)
start_time = dt.datetime.now()
for i in range(10):
    if dt.datetime.now() > time_started + time_out:
        break
    else:
        # Doing some heavy stuff
print("Done. Continue with the following code")

问题:在每个循环周期开始时都会检查超时,因此可能需要超过指定的超时时间才能中断循环,或者在最坏的情况下,它可能不会中断循环,因为它可以'不要中断永远不会完成迭代的代码。


更新:

正如op重播的那样,他想要更有效的方法,这是一个正确的方法,但是使用函数。

import asyncio


async def test_func():

    print('doing thing here , it will take long time')
    await asyncio.sleep(3600) # this will emulate heaven task with actual Sleep for one hour
    return 'yay!' # this will not executed as the timeout will occur early


async def main():
    # Wait for at most 1 second
    try:
        result = await asyncio.wait_for(test_func(), timeout=1.0) # call your function with specific timeout
        # do something with the result
    except asyncio.TimeoutError:
        # when time out happen program will break from the test function and execute code here
        print('timeout!')
        print('lets continue to do other things')


asyncio.run(main())

预期输出:

doing thing here , it will take long time

timeout!

lets continue to do other things

注意:

现在超时将在您指定的时间之后发生。在此示例代码中,一秒钟后。

您将替换这一行:

await asyncio.sleep(3600)

使用您的实际任务代码。

尝试一下,让我知道你的想法。谢谢。

阅读 asyncio 文档: link

更新2019年2月24日

正如 op 指出的,asyncio.run 在 python 3.7 中引入,并要求在 python 3.6 上提供替代方案

3.7 之前版本的 python 的 asyncio.run 替代方案:

替换

asyncio.run(main())

使用旧版本的代码(我认为是 3.4 到 3.6)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

关于python-3.x - 如何为不是函数python3的代码块设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54689032/

相关文章:

python - 将列表中的值附加到字典中

jQuery - 如果悬停超过 5 秒则显示 div

coldfusion - 使用 ColdFusion 上传文件,文件过大超时?

java - Web 服务读取超时,但操作仍然完成?

PHP/MySQL 在 session 超时时更新数据库

python-3.x - 使用Opencv Python每秒播放一帧

python - 打开多个 CSV 文件

python - 如何修复 Python 3.x 中 input() 函数中的 NameError?

Perl 子程序超时

python - 来自 Gtk.Entry 的插入文本信号上的 Gtk 3 位置属性始终为 0