Import operation works on PyCharm, but not from the terminal

Pycharm 2016.2.3, Mac OS X 10.11.1, Python 3.5 (Homebrew);

I have this folder structure

project /somepackage /subpackage __init__.py bar.py __init__.py foo.py foo.py: import somepackage.subpackage.bar print("foo") bar.py: print("bar") 

So my expected result

 bar foo 

This works great on startup with PyCharm. However, when I run it from my terminal, I get ImportError:

 $ pwd $ /home/project (not the actual path; just omitting some personal stuff) $ python3.5 somepackage/foo.py File "foo.py", line 1, in <module> import somepackage.subpackage.bar ImportError: No module named 'somepackage' 

I found this question regarding the same issue. However, none of the proposed solutions works for me, since I really use the same Python interpreter as PyCharm, and I am now in the folder containing the somepackage/ folder.

Does anyone have any other suggestions on how to solve this problem? Thank you!

+6
source share
1 answer

You use foo.py as a script, but you really use it as a module. Therefore, the correct solution is to run it as a module:

 python3 -m somepackage.foo 

For the record, another alternative is to change your path, for example:

 export PYTHONPATH=. 

(Or you can put an absolute directory in it, and, of course, you should add any other directories that are already in your PYTHONPATH.) This is closer to what PyCharm does, but less philosophically correct.

+10
source

Source: https://habr.com/ru/post/1011811/


All Articles