I had an error 'ModuleNotFoundError' when I run python file in .sh file.
First this is directory structure.
- my_project/
--- common_lib/
----- __init__.py
----- my_module.py
--- dir_1/
----- test.py
----- test.sh
And this is contents of each file.
common_lib/init.py
def test_func():
print(1)
common_lib/my_module.py
def module_func():
print("This is module.")
dir_1/test.py
import common_lib as cl
cl.test_func()
dir_1/test.sh
#!/usr/bin/env bash
python test.py
When I run test.py file directly using editor such as 'vs code' or 'pycharm', I got the right result '1'. But when I run test.sh file, I got the following error.
ModuleNotFoundError: No module named 'common_lib'
How can I import python package without 'No module Error' in this case?
Place an (empty) __init__.py
into your package root as well as all subdirectories. Then you can call the script as a module out of dir_1
:
.
├── __init__.py
├── common_lib
│ └── __init__.py
└── dir_1
├── __init__.py
├── test.py
└── test.sh
test.sh:
#!/usr/bin/env bash
cd .. && python -m dir_1.test
Output:
./test.sh
1
Have a look at the Packages-docs for more details.