gpt4 book ai didi

python - 为什么 signal.SIGALRM 在 Windows 上的 Python 中不起作用?

转载 作者:IT王子 更新时间:2023-10-29 01:12:31 30 4
gpt4 key购买 nike

我正在尝试了解操作系统概念和 Python 库。

我遇到了 Python 文档中提到的一个特定示例 https://docs.python.org/3/library/signal.html在 Windows 上对我不起作用的链接。

import signal, os

def handler(signum, frame):
print('Signal handler called with signal', signum)
raise OSError("Couldn't open device!")

# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
# This open() may hang indefinitely
fd = os.open('/dev/ttyS0', os.O_RDWR)

signal.alarm(0) # Disable the alarm

singal.SIGALRM 不能在 Windows 上运行有什么具体原因吗?

自动完成甚至在 Pycharm IDE 中显示 SIGALRM(我假设如果这样显示,将会有一个变量或函数)。

但是当我运行该程序时,在 Windows 上出现以下错误。我还没有在 Linux 上检查过这个。

Traceback (most recent call last):
File "C:/Users/preddy53/Desktop/syst.py", line 8, in <module>
signal.signal(signal.SIGALRM, handler)
AttributeError: module 'signal' has no attribute 'SIGALRM'

我哪里做错了?它仅特定于操作系统吗?

最佳答案

Is there any specific reason why singal.SIGALRM is not working on windows?

是的,Windows 操作系统没有实现该信号example you found开始于:

Here is a minimal example program. It uses the alarm() function to limit the time spent waiting to open a file; [...]

signal.alarm() function记录为:

Availability: Unix.

接下来,模块文档页面上其他地方的 SIG* 部分指出:

Note that not all systems define the same set of signal names; only those names defined by the system are defined by this module.

因此 SIGALRM 在 Windows 上不可用,因此您会得到一个属性错误。

请注意,Windows 也没有 /dev 虚拟文件系统,因此 os.open('/dev/ttyS0', os.O_RDWR) 调用将失败也是。

参见 python: windows equivalent of SIGALRM使用线程的替代方法。

关于python - 为什么 signal.SIGALRM 在 Windows 上的 Python 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52779920/

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