开发者

Confused about python modules and functions in it

To describe my questions concisely, please have a look at examples below:

  1. Module os have a function getcwd开发者_开发技巧() which returns current working directory. But there are no details about os.getcwd() in /usr/lib/python2.7/os.py file. Where is the implementation of the function?

  2. os.path is also a module in python , but in /usr/lib/python2.7 directory, there is no file named os.path. So when you import os.path in your python script, which file is imported?

Thank all your helps...


1 . The getcwd() functions is implemented in C look here.

2 . os.path is defined in the module os by dynamically detecting the os type and importing the correspondent library and set in it using : sys.modules['os.path'] = path


Modules do not have to be python scripts. Using the C-API you can write modules in C or C++. You can compile them as dynamic libraries, so that the interpreter can load them dynamically, or you can recompile the interpreter and link the modules into it.


If you're on a POSIX system (Linux, Mac OS X), these lines in os.py bring in those bits:

from posix import *
import posixpath as path

And on Windows:

from nt import *
import ntpath as path

(Plus a couple more options for less popular systems)

Note that using from x import * is usually frowned on. This is kind of a special case.


The interactive python shell can be used to check where a module is loaded from, and to see if a method is built-in or python:

>>> import os
>>> os
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> os.path
<module 'posixpath' from '/usr/lib/python2.6/posixpath.pyc'>
>>> os.getcwd
<built-in function getcwd>
>>> os.path.join
<function join at 0x87d1b1c>
>>>

os.path is loaded from posixpath.pyc, os.getcwd is built-in, os.path.join is a python method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜