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

Anu*_*eep 6 python linux windows signals python-3.x

我正在尝试了解OS概念和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
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)

我在哪里做错了?它仅适用于操作系统吗?

Mar*_*ers 8

singal.SIGALRM在Windows上不起作用有任何特定原因吗?

是的,Windows OS 没有实现该信号您发现示例以以下内容开头:

这是一个最小的示例程序。它使用该alarm()功能来限制等待打开文件所花费的时间。[...]

signal.alarm()函数记录为:

可用性:Unix。

接下来,SIG*模块文档页面上其他部分的部分说明:

请注意,并非所有系统都定义相同的信号名称集。此模块仅定义系统定义的名称。

因此SIGALRM在Windows上不可用,因此会出现属性错误。

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

有关使用线程的替代方法,请参见python:与SIGALRM等效的windows

  • 好的。那么,是否有 SIGALRM 的替代方案可以在 Windows 中执行或多或少相同的操作? (2认同)
  • @Anudeep:我已经链接到一个讨论替代方案的帖子。 (2认同)