Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fcntl.ioctl always fails on Python 2

Tags:

python

ioctl

The following always fails:

import fcntl
import termios

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

Always fails with:

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
  • The first argument trivially meets the "file descriptor" criteria.
  • termios.TIOCGWINSZ == 21523, an integer
  • the third argument is a buffer.

Why? It executes fine in Python 3, but alas, we use Python 2 in production.

Edit: This is very similar to Python's issue #10345, except unlike the filer of that bug, I am using a mutable buffer.

like image 499
Thanatos Avatar asked Jun 21 '26 14:06

Thanatos


1 Answers

The problem is that bytearray is not the buffer type you're looking for.

This works:

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.
like image 168
9000 Avatar answered Jun 24 '26 02:06

9000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!