Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 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?

See Question&Answers more detail:os

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

1 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...