6

This is my project structure:

/project
|    /package
|    |    __init__.py
|    |    module1.py
|    |    module2.py
|    main.py

In main.py, I import module1.py. In module1.py, I import module2.py:

module1.py

from package import module2
#do something

I run python main.py OK. But when I run python module1.py (inside package) or python /package/module1.py (inside project), I got ImportError:

Traceback (most recent call last):
  File "package/module1.py", line 5, in <module>
    from package import engine
ImportError: No module named 'package'

When I run module1.py in PyCharm, it's OK.

So, my question is : how to run file module1.py without main.py?

Thank you.

Community
  • 1
  • 1
Tuan Chau
  • 1,243
  • 1
  • 16
  • 30
  • 1
    Add your project directory to [PYTHONPATH][1]. [1]: http://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7 – Jose Varez Sep 17 '14 at 10:50

1 Answers1

9

Sol 1: When you use from package import module2 python does not know where to look for package unless its added to path. You can running it as

PYTHONPATH=/path/to/project python module1.py

Sol 2: If module1.py and module2.py are in the same folder, you don't need to use from package import module2.
Just using import module2 should be fine. Now running module1.py will work.

Sol 3: If you insist on using from package import module2. You cant append path to package in your script

import sys                                               
from os.path import dirname, abspath                     
sys.path.insert(0, dirname(dirname(abspath(__file__))))  
from package import module2
Ashoka Lella
  • 6,631
  • 1
  • 30
  • 39