使用 python 获取 socket/file-descriptor 中的可用字节数

Get amount of bytes available in socket/file-descriptor with python

POSIX C

int bytes_available;
ioctl(fd, FIONREAD, &bytes_available);

如何在 python 中执行相同的操作?

我认为您正在寻找函数 fcntl.ioctl in fcntl standard library and it internally uses the ioctl system call

根据文档,

fcntl.ioctl(fd, request, arg=0, mutate_flag=True) This function is identical to the fcntl() function, except that the argument handling is even more complicated.

The request parameter is limited to values that can fit in 32-bits. Additional constants of interest for use as the request argument can be found in the termios module, under the same names as used in the relevant C header files.

The parameter arg can be one of an integer, an object supporting the read-only buffer interface (like bytes) or an object supporting the read-write buffer interface (like bytearray).

In all but the last case, behaviour is as for the fcntl() function.

If a mutable buffer is passed, then the behaviour is determined by the value of the mutate_flag parameter.

If it is false, the buffer’s mutability is ignored and behaviour is as for a read-only buffer, except that the 1024 byte limit mentioned above is avoided – so long as the buffer you pass is at least as long as what the operating system wants to put there, things should work.

If mutate_flag is true (the default), then the buffer is (in effect) passed to the underlying ioctl() system call, the latter’s return code is passed back to the calling Python, and the buffer’s new contents reflect the action of the ioctl(). This is a slight simplification, because if the supplied buffer is less than 1024 bytes long it is first copied into a static buffer 1024 bytes long which is then passed to ioctl() and copied back into the supplied buffer.

If the ioctl() fails, an OSError exception is raised.

An example:

>>> import array, fcntl, struct, termios, os
>>> os.getpgrp()
13341
>>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, "  "))[0] 
13341
>>> buf = array.array('h', [0])
>>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1) 
0
>>> buf 
array('h', [13341])