How to have multi-directory or multi-package pytho

2019-08-17 21:10发布

问题:

I have project structure like this:

package1/__init__.py
package1/file1.py
package1/file2.py

package2/__init__.py
package2/file1.py
package2/file2.py

__init__.py
script1.py
script2.py

Unfortunately, I found that I can run code only from root directory, for example, from script1.py. If I run say from pakage2/file2.py, all links between files are lost, i.e. all imports of package1 from package2 becomes not found.

What is the correct directory structure in Python, which constraints package structure over all directories?

回答1:

You either need both package1 and package2 to be inside a package, in which case they can both import from each other:

root_package/
    __init__.py
    package1/
    package2/

Or add the packages to your PYTHONPATH, in which case any python script on your system can import from them:

export PYTHONPATH="$PYTHONPATH:/path/to/package1:/path/to/package2"

Update: you cannot import as part of a package if you are running the scripts directly. What you should do is define classes and functions in your packages as desired, then import them from another script:

root_package/
    __init__.py
    my_script.py
    package1/
    package2/

script.py:

from package1 import ...
from package2 import ...