Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

python - Import statement works on PyCharm but not from 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 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!

question from:https://stackoverflow.com/questions/40304117/import-statement-works-on-pycharm-but-not-from-terminal

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...