Python: where is the code for os.mkdir?

我只是一个虾纸丫 提交于 2019-12-20 04:38:35

问题


I've been looking through the code of the os module (just to be clear, I'm looking at the file /usr/lib/python2.7/os.py), and I've been trying to find the code for the mkdir function. From what I could tell, it comes from the 'posix' module, and its a built-in function, same as range or max:

>>> import posix
>>> posix.mkdir
<built-in function mkdir>
>>> max
<built-in function max>

I'm guessing the code for these is written in C somewhere, and the python interpreter knows where to find them. Could someone explain, or point me to some resources that do, how and where these built-in function are written and how they are integrated with the interpreter?

Thanks!


回答1:


On POSIX platforms (and on Windows and OS/2) the os module imports from a C module, defined in posixmodule.c.

This module defines a posix_mkdir() function that wraps the mkdir() C call on POSIX platforms, CreateDirectoryW on Windows.

The module registers this function, together with others, in the module PyMethodDef posix_methods structure. When the module is imported, Python calls the PyMODINIT_FUNC() function, which uses that structure to create an approriate module object with the posix_methods structure and adds a series of constants (such as the open() flag constants) to the module.

See the Extending Python with C or C++ tutorial on how C extensions work.



来源:https://stackoverflow.com/questions/16617809/python-where-is-the-code-for-os-mkdir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!