Python importing a module from a parallel directory

后端 未结 1 621
灰色年华
灰色年华 2020-12-14 09:01

How would I organize my python imports so that I can have a directory like this.

project
|      \\
|      __init__.py
|     
src
|   \\
|    __init__.py
|            


        
相关标签:
1条回答
  • 2020-12-14 09:14

    Python adds the folder containing the script you launch to the PYTHONPATH, so if you run

    python test/tests.py
    

    Only the folder test is added to the path (not the base dir that you're executing the command in).

    Instead run your tests like so:

    python -m test.tests
    

    This will add the base dir to the python path, and then classes will be accessible via a non-relative import:

    from src.classes import etc
    

    If you really want to use the relative import style, then your 3 dirs need to be added to a package directory

    package
    * __init__.py
    * project
    * src
    * test
    

    And you execute it from above the package dir with

    python -m package.test.tests
    

    See also:

    • https://docs.python.org/2/using/cmdline.html
    • http://www.stereoplex.com/blog/understanding-imports-and-pythonpath
    0 讨论(0)
提交回复
热议问题