0

I have the following structure:-

Test
├── package1
│   └── script1.py
│   └── __init__.py
├── package2
    └── script2.py
    └── __init__.py

I want to import script1.py from script2.py and have tried:-

from package1.script1 import *

I am running the script python3 script2.py from a linux terminal but this does not seem to work and I get ModuleNotFoundError: No module named 'package1'. How do I fix this?

2 Answers2

0

Which directory are you in ?

In order to make python to recognize package1,

1 ) You have go to package1's directory via terminal,

cd {package1directory}

or

2 ) You have to append system path to package1's directory as shown below

import sys
sys.path.append('/home/user/package1dir')

3 ) Define PYTHONPATH as system variable. Indicate package1directory

İsmail Altun
  • 21
  • 1
  • 5
0

Ideally you should run a python script from the top level package (which imports and/or runs code that starts the whole application) like the following:

Test
├── package1
│   └── script1.py
│   └── __init__.py
├── package2
|   └── script2.py
|   └── __init__.py
|___ run.py

Then run python3 run.py

When you import from package1.script1 import *, you are saying to Python to search the packages from the path the main script was run. Thus it assumes you are searching package1 from package2. If you place package1 inside package2 and run python3 script2.py, it will also work.

Test
├── package2
    ├── package1
    │   └── script1.py
    │   └── __init__.py
    └── script2.py
    └── __init__.py

If you still want to run from script2 with the same directory structure then you have to either be in the Test directory and run python3 package2/script2.py or modify the python path.

Maicon Mauricio
  • 2,052
  • 1
  • 13
  • 29