gpt4 book ai didi

python - signal.alarm 没有按时触发异常

转载 作者:太空狗 更新时间:2023-10-30 01:13:27 25 4
gpt4 key购买 nike

我稍微修改了 official docs 中的信号示例(页面底部)。

我正在调用 sleep 10 但我希望在 1 秒后发出警报。当我运行以下代码片段时,触发异常的时间超过 1 秒(我认为它运行了整整 10 秒)。

import signal, os

def handler(signum, frame):
print 'Interrupted', signum
raise IOError("Should after 1 second")

signal.signal(signal.SIGALRM, handler)
signal.alarm(1)

os.system('sleep 10')

signal.alarm(0)

在单线程应用程序中,如何确保在超时后终止函数?

最佳答案

来自 the docs :

A Python signal handler does not get executed inside the low-level (C) signal handler. Instead, the low-level signal handler sets a flag which tells the virtual machine to execute the corresponding Python signal handler at a later point(for example at the next bytecode instruction).

因此,在某些情况下,诸如 signal.alarm() 生成的信号在超时后无法终止函数。 the function should cooperate by allowing other Python code to run (e.g., by calling PyErr_CheckSignals() periodically in C code)或者你应该 use a separate process, to terminate the function in time .

如果您使用 subprocess.check_call('sleep 10'.split()) 而不是 os.system('sleep 10'),您的情况就可以得到解决。

关于python - signal.alarm 没有按时触发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34878618/

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