How does Python work to access OS API functions like socket ()?

UPDATED Questions:

  • Where does the socket object really get created? I found this on line 4188 in socketmodule.c , but it looks like it's called sock_new not socket?

    static PyObject *sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) 
  • Is there any agreement to find out where a module such as socketmodule.c is imported? In other words, when I see "from _socket import", who do I know this imports (without looking at the entire repository)?


ORIGINAL:

 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) 

I am trying to understand how this code works specifically, how / where Python actually calls the OS function call in socket ():

 class _socketobject(object): __doc__ = _realsocket.__doc__ __slots__ = ["_sock", "__weakref__"] + list(_delegate_methods) def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None): if _sock is None: _sock = _realsocket(family, type, proto) self._sock = _sock for method in _delegate_methods: setattr(self, method, getattr(_sock, method)) 

When I look at BSD sockets on Wikipedia, I see this example, which makes sense because the socket function is defined under types.h. In the above example, I see a realsocket call that looks like an OS function call, but I don't define it anywhere (I don’t see anything about sockets in the Python27 / include headers).

  /* Server code in C */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(void) { struct sockaddr_in stSockAddr; int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); 
+6
source share
1 answer

It has everything to do with the 1st and 2nd lines of socket.py:

 import _socket from _socket import * 

If you run Python and run the following code:

 import socket print dir(socket) print dir(socket._socket) 

You will notice that a socket only exports a few extra things compared to socket._socket .

Now what is socket._socket ? This is a dynamic Python module (meaning that it can be used just like any other Python module), but it is written in C (therefore, after compilation it has an OS-specific form of its own: .so on Nix and .dll (. pyd) to Win). Its location in the Python lib folder (where socket.py is also located): lib-dynload / _socket * .so.

You can see where the modules are by printing them (in the same console where you ran the code above, which you can enter):

 print socket print socket._socket 

If you're more interested, its source code is in the Python source code archive in $ {PYTHON_SRC_DIR} /Modules/socketmodule.c (it also has a header file). These files define shell functions (which are visible from Python), and they call their own functions (for example, socket from /usr/include/sys/socket.h).

+5
source

All Articles