简体   繁体   中英

Execute a python file from different directory

I try to understand how to split up python files belonging to the same project in different directories. If I understood it right I need to use packages as described here in the documentation .

So my structure looks like this:

.
├── A
│   ├── fileA.py
│   └── __init__.py
├── B
│   ├── fileB.py
│   └── __init__.py
└── __init__.py

with empty __init__.py files and

$ cat A/fileA.py 
def funA():
    print("hello from A")

$ cat B/fileB.py 
from A.fileA import funA

if __name__ == "__main__":
    funA()

Now I expect that when I execute B/fileB.py I get "Hello from A" , but instead I get the following error:

ModuleNotFoundError: No module named 'A'

What am I doing wrong?

One way to solve this is to add module A into the path of fileB.py by adding

import sys
sys.path.insert(0, 'absolute/path/to/A/')

to the top of fileB.py.

Your problem is the same as: Relative imports for the billionth time

TL;DR: you can't do relative imports from the file you execute since main module is not a part of a package.

As main:

python B/fileB.py

Output:

Traceback (most recent call last):
  File "p2/m2.py", line 1, in <module>
    from p1.m1 import funA
ImportError: No module named p1.m1

As a module (not main):

python -m B.fileB

Output:

hello from A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM