3

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!

3
  • @warl0ck This also produces same error. Commented Dec 13, 2018 at 10:52
  • you can make lib a python package by adding __init__.py in this directory. Then you can use import statement as usual. Commented Dec 13, 2018 at 10:52
  • 1
    What about: PYTHONPATH=${PYTHONPATH}:. python src/p1.py ? Commented Dec 13, 2018 at 10:58

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.