How to create a socket.socket() object from a socket fd?

Peter Otten __peter__ at web.de
Sat Jan 21 18:31:54 EST 2017


Grant Edwards wrote:

> Given a Unix file discriptor for an open TCP socket, I can't figure
> out how to create a python 2.7 socket object like those returned by
> socket.socket()
> 
> Based on the docs, one might think that socket.fromfd() would do that
> (since the docs say that's what it does):

[...]

> Note that the socket.socket() object has a '_sock' attribute, which
> appears to contain an object like that returned by socket.fromfd():
> 
>   repr(osock._sock):
>   <socket object, fd=4, family=2, type=1, protocol=0>
> 
> That prompts a question: given a "socket object" as returned by
> socket.fromfd(), how does one create a "socket._socketobject object"
> as returned by socket.socket()?

The socket.py source reveals that you can do it like this:

mysocket = socket.socket(_sock=socket.fromfd(...))

The code has

from _socket import socket  # actually a star import
...
_realsocket = socket
...
socket = _socketobject

which looks very much like an ad-hoc hack gone permanent.




More information about the Python-list mailing list