【问题标题】:fcntl.ioctl always fails on Python 2fcntl.ioctl 在 Python 2 上总是失败
【发布时间】:2015-09-10 21:16:07
【问题描述】:

以下总是失败:

import fcntl
import termios

buffer = bytearray(8)
fcntl.ioctl(2, termios.TIOCGWINSZ, buffer, True)

总是失败:

Traceback (most recent call last):
  File "testit.py", line 5, in <module>
    fcntl.ioctl(2, termios.TIOCGWINSZ, buffer, True)
TypeError: ioctl requires a file or file descriptor, an integer and optionally an integer or buffer argument
  • 第一个参数很容易满足“文件描述符”标准。
  • termios.TIOCGWINSZ == 21523,一个整数
  • 第三个参数是一个缓冲区。

为什么?它在 Python 3 中执行得很好,但是我们在生产中使用 Python 2。

编辑:这与Python's issue #10345 非常相似,除了与该错误的提交者不同,我使用可变缓冲区。

【问题讨论】:

    标签: python ioctl


    【解决方案1】:

    问题是bytearray 不是您要查找的缓冲区类型。

    这行得通:

    import fcntl
    import termios
    import array
    
    buffer = array.array('h', [0]*8)
    assert fcntl.ioctl(2, termios.TIOCGWINSZ, buffer, True) == 0
    print buffer  # first two bytes are set to terminal's height and width.
    

    【讨论】:

    • 好的……为什么会这样?文档声称,“或支持读写缓冲区接口的对象”——bytearray 不支持吗? (仅在 Python 2 中?)
    • 示例部分中的 The docs 建议将 array 模块用于可变缓冲区。例如。 bytearray 缺少返回 fcntl 想要的指针的 buffer_info 方法。 ctypes 也可以工作:buf = (ctypes.c_byte * 4)(0, 0, 0, 0),将它传递给调用,看看 list(buf) 显示什么。可能 Python3 刚刚学会了在幕后使用 bytearray 做这个技巧,尽管我无法轻易找到任何相关信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 2013-07-08
    • 2021-05-11
    • 2013-03-24
    相关资源
    最近更新 更多