Skip to main content
 首页 » 编程设计

python之内置模块和非内置模块有什么区别

2025年05月04日7lonelyxmas

我对 python 内置模块和非内置模块感到困惑。这里我使用 sys 模块来查找内置模块,

import sys 
 
def dump(module): 
    print module, "=>", 
    if module in sys.builtin_module_names: 
        print "<BUILTIN>" 
    else: 
        module = __import__(module) 
        print module.__file__ 
 
dump("os") 
dump("sys") 
dump("string") 
dump("strop") 
dump("zlib") 

输出:

os => /usr/lib/python2.7/os.pyc 
sys => <BUILTIN> 
string => /usr/lib/python2.7/string.pyc 
strop => <BUILTIN> 
zlib => <BUILTIN> 

我的问题是为什么 python 家伙划分这些模块?。这是什么原因吗。我只需要知道这一点,如果有人知道请解释。

请您参考如下方法:

sys.builtin_module_names 中列出的内置模块(__main__ 除外)没有__file__ 属性。

根据 the documentation - Data model :

Modules

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

似乎代码区分它们以避免AttributeError:

>>> import sys 
>>> sys.__file__ 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'module' object has no attribute '__file__' 

但是,还有其他模块没有列在 sys.builtin_module_names 中,但没有 __file__ 属性。例如:

>>> import cPickle 
>>> cPickle.__file__ 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'module' object has no attribute '__file__' 

为避免此异常,应修改函数 dump:

def dump(module): 
    print module, "=>", 
    module = __import__(module) 
    print getattr(module, '__file__', 'No File')