【问题标题】:Where is the actual file for a module? [duplicate]模块的实际文件在哪里? [复制]
【发布时间】:2017-09-24 23:25:19
【问题描述】:

我显然安装了多个版本的模块,我试图找出文件的位置,因为其中只有一个来自包管理,我想删除另一个。

有没有一种简单的方法可以在导入模块后询问 Python 在哪里找到模块?

【问题讨论】:

    标签: python


    【解决方案1】:

    如果模块不是内置的,你可以这样做:

    import your_module
    print(your_module.__file__)
    

    测试:

    >>> import os
    >>> print(os.__file__)
    L:\Python34\lib\os.py
    

    如果模块是内置的,你会得到一个错误:

    >>> import sys
    >>> print(sys.__file__)
    Traceback (most recent call last):
      File "<string>", line 301, in runcode
      File "<interactive input>", line 1, in <module>
    AttributeError: 'module' object has no attribute '__file__'
    >>> 
    

    (使用hasattr检查模块是否具有__file__属性也是避免错误的一种选择;if hasattr(module_name, '__file__'):

    另外:直接打印模块:

    >>> print(os)
    <module 'os' from 'L:\\Python34\\lib\\os.py'>
    

    【讨论】:

    • 只做print module 有点“优雅”,仍然有用import os; print os 打印&lt;module 'os' from '/usr/lib/python2.7/os.pyc'&gt;import sys; print sys 打印&lt;module 'sys' (built-in)&gt;
    • 可能值得添加if hasattr(module_name, '__file__'):
    • 好建议。我希望你不介意我用这些来编辑我的答案。
    【解决方案2】:

    导入模块后可以使用__file__

    >>> import os 
    >>> os.__file__
    '/usr/lib/python2.7/os.pyc'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 2018-02-07
      • 2015-12-10
      • 2016-12-10
      • 1970-01-01
      • 2018-11-07
      • 2020-11-08
      相关资源
      最近更新 更多