Natjo
Natjo

Reputation: 2118

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?

Upvotes: 2

Views: 5319

Answers (2)

madjaoue
madjaoue

Reputation: 5224

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

Upvotes: 4

Fabian Ying
Fabian Ying

Reputation: 1254

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.

Upvotes: 2

Related Questions