2

I have a directory structure:

root_dir
 ├── src
 │   └── p1.py
 └── lib
     ├── __init__.py
     ├── util1.py
     └── util2.py

I want to run src/p1.py which uses lib/util1.py using an import statement import lib.util1 as u1.

It runs fine when I use PyCharm, but I want to also run it from command line. How can I run the program from command line?

I have tried cd root_dir then python src/p1.py.

But it produces the following error:

Traceback (most recent call last):
  File "./src/p1.py", line 1, in <module>
    import lib.util1 as u1
ImportError: No module named lib.util1

How can I run the python program src/p1.py from the command line?

Edit: Based on the suggestion from @Sumedh Junghare, in comments, I have added __init__.py in lib folder. But still it produces the same error!

Sourabh Bhat
  • 1,793
  • 16
  • 21

2 Answers2

2

You need the following steps

  1. Add __init__.py at lib folder.

Add this line at p1.py file on top

import sys
sys.path.append('../') 
import lib.util1 as u1

Run the p1.py file from src dir. Hope it will work.

Edit:

If you do not want to add sys.path.append('../'), set PYTHONPATH in env-var from this resource. How to add to the pythonpath in Windows?

Saiful Azad
  • 1,823
  • 3
  • 17
  • 27
  • I have seen similar solutions on Stackoverflow. But I don't want to change the source files as it is running fine in PyCharm. Is it possible to tell python to include lib folder? I think since PyCharm is able to do it, it must be possible without changing the source. – Sourabh Bhat Dec 13 '18 at 11:04
  • This is because if you run python in the PyCharm's terminal it has different sys.path. Try running interactive python both in the PyCharm's terminal and in your normal terminal and then: `import sys` and `print(sys.path)`and compare the output. – arudzinska Dec 13 '18 at 11:18
0

Improving on Saiful's answer, You can do the following which will allow you to run the your program from any working directory

import sys
import os
sys.path.append(os.path.join(os.path.realpath(os.path.dirname(__file__)), "../"))
import lib.util1 as u1
yossiz74
  • 889
  • 1
  • 9
  • 16