美文网首页
python模块的导入和运行的若干疑问解决方案

python模块的导入和运行的若干疑问解决方案

作者: ThomasYoungK | 来源:发表于2017-12-31 22:34 被阅读61次

    我经常为python模块或包的导入头疼,各处看了不少文章,并且尝试了好久,总算看到一篇比较详细的回答,第二高的那个评分,其中的内容比较绕,我不想太多的解释。这里只做2点大致的归纳:

    1. 一般的python包都有一个入口文件,如果只是从入口文件去运行代码,那么只要剩下的代码都是按照package的形式组织的,那么就可以用相对路径导入(就是类似from ..xx import yy)。
    2. 但是时常的,我们不仅想只运行入口文件,也想运行其他子文件,那么这时我们就要在每个子文件里面先把最外层的包塞到sys.path里面,用绝对路径【注意,不是指linux的目录路径,指python特有的包路径】导入(就是从最外层的包名开始做导入)
      下面举个例子(以python3为例,用python命令行解释器运行,不考虑pycharm的辅助功能):
      如下的文件结构
    .
    ├── main.py
    └── mypackage
        ├── __init__.py
        ├── mymodule.py
        └── myothermodule.py
    
    

    main.py是入口文件:

    #!/usr/bin/env python3
    
    from mypackage.myothermodule import add
    
    def main():
        print(add('1', '1'))
    
    if __name__ == '__main__':
        main()
    

    mymodlue.py:

    #!/usr/bin/env python3
    
    # Exported function
    def as_int(a):
        return int(a)
    
    # Test function for module
    def _test():
        assert as_int('1') == 1
    
    if __name__ == '__main__':
        _test()
    

    相对路径导入module

    myothermodule.py需要导入mymodule.py,用相对路径包导入,由于module.py和myothermodule.py在同一级目录,因此from .mymodule import as_int

    #!/usr/bin/env python3
    
    from .mymodule import as_int
    
    # Exported function
    def add(a, b):
        return as_int(a) + as_int(b)
    
    # Test function for module
    def _test():
        assert add('1', '1') == 2
    
    if __name__ == '__main__':
        _test()
    

    这时在该目录运行main.py:

    ➜  module python -i main.py
    2
    >>> import sys
    >>> sys.path
    ['/Users/thomas_young/Documents/code/samplemod-master/module', '/Users/thomas_young/miniconda3/lib/python36.zip', '/Users/thomas_young/miniconda3/lib/python3.6', '/Users/thomas_young/miniconda3/lib/python3.6/lib-dynload', '/Users/thomas_young/.local/lib/python3.6/site-packages', '/Users/thomas_young/miniconda3/lib/python3.6/site-packages', '/Users/thomas_young/miniconda3/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg']
    >>> os.getcwd()
    '/Users/thomas_young/Documents/code/samplemod-master/module'
    

    或者在mypackage目录运行main.py:

    ➜ mypackage python -i ../main.py
    2
    >>> sys.path
    ['/Users/thomas_young/Documents/code/samplemod-master/module', '/Users/thomas_young/miniconda3/lib/python36.zip', '/Users/thomas_young/miniconda3/lib/python3.6', '/Users/thomas_young/miniconda3/lib/python3.6/lib-dynload', '/Users/thomas_young/.local/lib/python3.6/site-packages', '/Users/thomas_young/miniconda3/lib/python3.6/site-packages', '/Users/thomas_young/miniconda3/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg']
    >>> os.getcwd()
    '/Users/thomas_young/Documents/code/samplemod-master/module/mypackage'
    

    都可以运行成功,而且sys.path是相同的。工作目录不同影响的只有os.getcwd()不同,影响到读文件的相对路径啥的。
    但是,如果允许以下命令会报错,这是因为相对导入只对入口文件有效,如果想单独允许其他子文件,就得用方法2:绝对路径导入:

    ➜ module python -i mypackage/myothermodule.py
    Traceback (most recent call last):
      File "mypackage/myothermodule.py", line 3, in <module>
        from .mymodule import as_int
    ModuleNotFoundError: No module named '__main__.mymodule'; '__main__' is not a package
    
    ➜ mypackage python -i myothermodule.py
    Traceback (most recent call last):
      File "myothermodule.py", line 3, in <module>
        from .mymodule import as_int
    ModuleNotFoundError: No module named '__main__.mymodule'; '__main__' is not a package
    

    绝对包路径导入

    myothermodule.py中把顶层包路径加入到sys.path,最好删掉本目录的路径,更改导入方式为绝对路径导入即可:

    #!/usr/bin/env python3
    import sys
    
    from pathlib import Path  # if you haven't already done so
    file = Path(__file__).resolve()
    parent, root = file.parent, file.parents[1]
    sys.path.append(str(root))
    # Additionally remove the current file's directory from sys.path
    try:
        sys.path.remove(str(parent))
    except ValueError: # Already removed
        pass
    
    from mypackage.mymodule import as_int
    
    # Exported function
    def add(a, b):
        return as_int(a) + as_int(b)
    
    # Test function for module
    def _test():
        assert add('1', '1') == 2
    
    if __name__ == '__main__':
        _test()
    
    

    上面的代码中,file.parents[0]返回的当前file所在目录'/Users/thomas_young/Documents/code/samplemod-master/module/mypackage',file.parents[1]是父目录,也就是'/Users/thomas_young/Documents/code/samplemod-master/module'目录,依次类推。
    运行以下试试,可以啦:

    ➜  module python -i mypackage/myothermodule.py
    >>> sys.path
    ['/Users/thomas_young/miniconda3/lib/python36.zip', '/Users/thomas_young/miniconda3/lib/python3.6', '/Users/thomas_young/miniconda3/lib/python3.6/lib-dynload', '/Users/thomas_young/.local/lib/python3.6/site-packages', '/Users/thomas_young/miniconda3/lib/python3.6/site-packages', '/Users/thomas_young/miniconda3/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg', '/Users/thomas_young/Documents/code/samplemod-master/module']
    

    同时也不影响入口文件的运行

    ➜  module python -i main.py
    2
    

    不同工作目录下都可以运行,这里就不再赘述了。

    总结

    1. 一般的框架都可以用相对包导入,因为都是从入口文件处运行的
    2. 如果想单独跑某个子文件,在sys.path中加入正确的包路径,进行绝对路径导入即可

    相关文章

      网友评论

          本文标题:python模块的导入和运行的若干疑问解决方案

          本文链接:https://www.haomeiwen.com/subject/atmagxtx.html