python ModuleNotFoundError error in absolute import package?

Viewed 114

I have a file structure like this.

.
└── E:\test
    ├
    ├── M2
    │   └── demo.py
    |       
    │       
    └── MA
    │    └── MA1
    │    │   ├── __init__.py
    │    │   │
    │    │   └── ma1.py
    │    ​│__ __init__.py

ma1.py

def foo():
    print("I am here")

demo.py

from MA.MA1.ma1 import foo
print(foo())

I am use python3.8 and win10 system.
In cmd I try to cd test directory and python .\M2\demo.py, it show error?

PS E:\test> python .\M2\demo.py    
Traceback (most recent call last):
  File ".\M2\demo.py", line 1, in <module>
    from MA.MA1.ma1 import foo
ModuleNotFoundError: No module named 'MA'
2 Answers

The python interpreter does not search modules in test\ directory since you execute the script from test\M2\. You can tell python to search from test\ by adding directory "test" to the PYTHONPATH variable. For windows command line:

set PYTHONPATH=%PYTHONPATH%;E:\test

For linux terminal:

export PYTHONPATH=path_to_test_dir

Remember 2 things:

1- Python searches sys.path to find modules and packages.

2- When you run your script like you did, only it's directory will be added to the sys.path. So you have to add the directory which MA is inside it manually. Do the following inside demo.py:

import sys
sys.path.insert(0, r'E:\test')

from MA.MA1.ma1 import foo
print(foo())

Alternatively you can set PYTHONPATH variable.

Related