File descriptor support

class jeepney.FileDescriptor(fd)[source]

A file descriptor received in a D-Bus message

This wrapper helps ensure that the file descriptor is closed exactly once. If you don’t explicitly convert or close the FileDescriptor object, it will close its file descriptor when it goes out of scope, and emit a ResourceWarning.

to_file(mode, buffering=-1, encoding=None, errors=None, newline=None)[source]

Convert to a Python file object:

with fd.to_file('w') as f:
    f.write('xyz')

The arguments are the same as for the builtin open() function.

The FileDescriptor can’t be used after calling this. Closing the file object will also close the file descriptor.

Note

If the descriptor does not refer to a regular file, or it doesn’t have the right access mode, you may get strange behaviour or errors while using it.

You can use os.stat() and the stat module to check the type of object the descriptor refers to, and fcntl.fcntl() to check the access mode, e.g.:

stat.S_ISREG(os.stat(fd.fileno()).st_mode)  # Regular file?

status_flags = fcntl.fcntl(fd, fcntl.F_GETFL)
(status_flags & os.O_ACCMODE) == os.O_RDONLY  # Read-only?
to_socket()[source]

Convert to a socket object

This returns a standard library socket.socket() object:

with fd.to_socket() as sock:
    b = sock.sendall(b'xyz')

The wrapper object can’t be used after calling this. Closing the socket object will also close the file descriptor.

to_raw_fd()[source]

Convert to the low-level integer file descriptor:

raw_fd = fd.to_raw_fd()
os.write(raw_fd, b'xyz')
os.close(raw_fd)

The FileDescriptor can’t be used after calling this. The caller is responsible for closing the file descriptor.

fileno()[source]

Get the integer file descriptor

This does not change the state of the FileDescriptor object, unlike the to_* methods.

close()[source]

Close the file descriptor

This can safely be called multiple times, but will raise RuntimeError if called after converting it with one of the to_* methods.

This object can also be used in a with block, to close it on leaving the block.

exception jeepney.NoFDError[source]

Raised by FileDescriptor methods if it was already closed/converted