本文介绍了导入声明适用于PyCharm,但不适用于终端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有这个文件夹结构

project
  /somepackage
    /subpackage
     __init__.py
     bar.py
   __init__.py
   foo.py

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

bar.py:
print("bar")

所以我的预期输出是

bar
foo

从PyCharm运行时,此方法工作正常.但是,当我从终端运行它时,我会收到一个ImportError:

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'

我发现了这个问题,该问题与同样的问题.但是,没有建议的解决方案对我有用,因为我确实使用的是与PyCharm相同的Python解释器,并且我目前位于包含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!

推荐答案

您像脚本一样运行foo.py,但实际上却像模块一样使用它.因此,正确的解决方案是将其作为模块运行:

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=.

(或者,您可以在其中放置绝对目录,当然,您应该附加PYTHONPATH中已经存在的任何其他目录.)这与PyCharm的功能较为接近,但从哲学上讲不太正确.

(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.

这篇关于导入声明适用于PyCharm,但不适用于终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 19:53
查看更多