【问题标题】:Why is signal.SIGALRM not working in Python on windows?为什么 signal.SIGALRM 在 Windows 上的 Python 中不起作用?
【发布时间】:2019-03-17 17:00:00
【问题描述】:

我正在尝试了解操作系统概念和 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'

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

【问题讨论】:

  • 因为Windows没有这样的信号。
  • 因为它不会有/dev/ttyS0

标签: python linux windows python-3.x signals


【解决方案1】:

singal.SIGALRM 在 Windows 上不起作用有什么具体原因吗?

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

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

signal.alarm() function 记录为:

可用性:Unix。

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

请注意,并非所有系统都定义相同的信号名称集;只有系统定义的名称才被这个模块定义。

所以SIGALRM 在 Windows 上不可用,所以你会得到一个属性错误。

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

请参阅python: windows equivalent of SIGALRM 了解使用线程的替代方法。

【讨论】:

  • 好的。那么,SIGALRM 是否有替代方案可以在 Windows 中或多或少地做同样的事情?
  • @Anudeep:我已经链接到一篇讨论替代方案的帖子。
猜你喜欢
  • 2010-10-02
  • 1970-01-01
  • 2021-07-19
  • 2016-11-12
  • 2021-11-15
  • 2018-01-24
  • 2013-03-04
  • 2012-07-29
  • 1970-01-01
相关资源
最近更新 更多