IOError: [Errno 25] 设备的 ioctl 不合适

ane*_*ayf 6 python python-2.7 python-3.x

我有以下代码来查找 Linux 中控制台的宽度,它适用于 Python 2.7 和 Python 3.X:

def get_default_console_width():
   try:
      from shutil import get_terminal_size
      console_width, rows = shutil.get_terminal_size()
   except Exception:
      import termios, fcntl, struct, sys
      s = struct.pack('hh', 0, 0)
      x = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, s)
      rows, console_width = struct.unpack("hh", x)
   return console_width
Run Code Online (Sandbox Code Playgroud)

在我的 test_something.py 文件中,我测试了一些调用get_default_console_width()的函数,它给了我这个错误:

IOError: [Errno 25] Inappropriate ioctl for device
Run Code Online (Sandbox Code Playgroud)

我知道有一些类似的帖子也有同样的问题,但我没有找到任何对这种情况有帮助的内容。

任何帮助表示赞赏!谢谢!

dil*_*epa 1

大多数 IDE(例如PyCharmWing)都具有模拟终端,因此运行包含的代码get_terminal_size()将触发 [Errno 25] Inappropriate ioctl for device因为操作系统无法获取IDE 内模拟终端的列。在操作系统的本机终端中运行代码为我解决了这个问题。