更新问题:
socket对象实际上是在哪里创建的?我在socketmodule.c的4188行找到了这个,但它看起来像是sock_new not socket?
static PyObject *sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
是否有一些约定来确定像socketmodule.c这样的模块是在哪里导入的?换句话说,当我看到一个“from_socket import*”时,我知道它在导入什么(不搜索整个存储库)?
原件:
sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
我试图理解这段代码是如何工作的,特别是Python如何/在何处对socket()进行OS函数调用:
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))
当我在维基百科上查找BSD sockets时,我看到了这个例子,这个例子很有意义,因为socket函数是在types.h下定义的。在上面的例子中,我看到了对realsocket的调用,它看起来像一个OS函数调用,但是我没有在任何地方定义realsocket(我在Python27/include头中根本看不到关于sockets的任何内容)。
/* 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);
它与1st和2nd行有关
如果启动Python并运行以下代码:
您会注意到,与
socket._socket
相比,socket只导出一些额外的内容。现在,什么是
socket._socket
?它是一个Python动态模块(这意味着它可以像任何其他Python模块一样使用),但它是用C编写的(因此在编译之后,它有一个OS特定的本机形式:。所以在Nix和。dll(.pyd)在Win下。它的位置在python lib文件夹中(其中还包含socket.py):lib dynload/\u socket*.so。您可以通过打印模块来查看模块的位置(在运行上述代码的同一控制台中,您可以键入):
如果您更感兴趣,它的源代码位于${Python SRC_DIR}/Modules/socketmodule.c中的Python源tarball中(它还有一个头文件)。在这些文件中,包装器函数(从Python可见)被定义,它们调用本机函数(例如从/usr/include/sys/socket.h调用socket)。
相关问题 更多 >
编程相关推荐