Python Glossary Русский

all Python 3socketfunction

socket.fromfd()

creating sockets

Builds a socket object from an existing file descriptor, duplicating the descriptor first.

Syntax

sock = socket.fromfd(fd, family, type, proto=0)

The descriptor is duplicated (dup), so the original and the new object have different numbers and separate lives: closing one does not close the other, and both must be closed. Python does not verify the family and type, so wrong values make the object lie about itself. To take ownership of a descriptor instead of copying it, use socket.socket(fileno=fd).

Examples

import socket
a, b = socket.socketpair()
c = socket.fromfd(a.fileno(), a.family, a.type)
print(c.fileno() != a.fileno())  # → True — это копия дескриптора
a.close()
c.sendall(b'still open')
print(b.recv(1024))  # → b'still open'
c.close()
b.close()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy