Import statement works on PyCharm but not from terminal

Pibborn picture Pibborn · Oct 28, 2016 · Viewed 12.3k times · Source

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 output is

bar
foo

This works fine when run from PyCharm. However, when I run it from my terminal I get an 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 have found this question, which is about the same problem. However, none of the suggested solutions work for me, as I am indeed using the same Python interpreter as PyCharm does and I am currently in the folder that contains the somepackage/ folder.

Does anyone have any other suggestions about how to solve this issue? Thank you kindly!

Answer

Arthur Tacca picture Arthur Tacca · Oct 28, 2016

You are running foo.py like a script, but you are really using it like a module. So the proper solution is to run it as a module:

python3 -m somepackage.foo

For the record, another alternative is to edit your path like:

export PYTHONPATH=.

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