【问题标题】:"cannot import name 'SIGPIPE' from 'signal'" in Windows 10Windows 10 中的“无法从‘信号’导入名称‘SIGPIPE’”
【发布时间】:2019-11-05 20:05:03
【问题描述】:

我正在尝试将lolcat 用于我的终端,但它正在抛出ImportError

$ lolcat
Traceback (most recent call last):
  File "C:/Users/eriku/Anaconda3/Scripts/lolcat", line 18, in <module>
    from signal import signal, SIGPIPE, SIG_DFL
ImportError: cannot import name 'SIGPIPE' from 'signal' (C:\users\eriku\anaconda3\lib\signal.py)

这里提到的导入 (signal.py) 是我机器上安装的 Anaconda 的一部分。我也尝试在 Anaconda 提示符下执行 lolcat,因为它在涉及不同终端时可能非常占主导地位,但这并没有帮助。有什么想法吗?

【问题讨论】:

    标签: python windows-10 signals


    【解决方案1】:

    Windows 似乎不支持SIGPIPE

    参见https://docs.python.org/3/library/signal.html#module-contents上的SIG*部分:

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

    【讨论】:

      【解决方案2】:

      检查lolcat's source code 表明这是Python CLI 程序尝试avoid printing IOError: [Errno 32] Broken pipe when receiving SIGPIPE on Linux 但忘记了Windows 的典型问题。

      我在我的代码中使用以下函数,而其他人可能更喜欢check if sys.platform == "win32"

      def reset_sigpipe_handling():
          """Restore the default `SIGPIPE` handler on supporting platforms.
          
          Python's `signal` library traps the SIGPIPE signal and translates it
          into an IOError exception, forcing the caller to handle it explicitly.
      
          Simpler applications that would rather silently die can revert to the
          default handler. See https://stackoverflow.com/a/30091579/1026 for details.
          """
          try:
              from signal import signal, SIGPIPE, SIG_DFL
              signal(SIGPIPE, SIG_DFL)
          except ImportError:  # If SIGPIPE is not available (win32),
              pass             # we don't have to do anything to ignore it.
      

      还要注意official docs recommend handling the exception instead:

      不要将 SIGPIPE 的处置设置为 SIG_DFL 以避免 BrokenPipeError。这样做会导致您的程序在您的程序仍在写入时任何套接字连接被中断时意外退出。

      ...但是建议的解决方案不完整(如果您需要在不重置 SIGPIPE 处理程序的情况下解决此问题,请参阅this)。

      最后,"OSError: [Errno 22] Invalid argument" on Windows with print() and output piped 表示 Windows 上也存在潜在问题,但表现为“OSError: [Errno 22] Invalid argument” 而不是 BrokenPipeError。

      【讨论】:

        猜你喜欢
        • 2020-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-19
        相关资源
        最近更新 更多