【发布时间】:2017-06-13 19:22:03
【问题描述】:
对此我会觉得自己像个白痴,我不知道是不是因为现在是星期五晚了,但我很难理解为什么我对这个非常简单的代码有问题.
目录结构:
~/testapp/
~/testapp/__init__.py
~/testapp/settings.py
~/testapp/workers/a.py
~/testapp/settings.py:
x = 1
~/testapp/workers/a.py:
from settings import x
当通过 PyCharm 运行 ~/testapp/workers/a.py 时,它运行良好。但是在终端中运行时,我得到:
m@G750JW:~$ python testapp/workers/a.py
Traceback (most recent call last):
File "testapp/workers/a.py", line 1, in <module>
from settings import x
ImportError: No module named settings
我还在 ~/testapp/workers/a.py 中尝试了以下内容:
from testapp.settings import x
并得到同样的错误。我也试过:
from ..settings import x
但这会返回:
m@G750JW:~/$ python testapp/workers/a.py
Traceback (most recent call last):
File "python testapp/workers/a.py", line 1, in <module>
from ..settings import testvar
ValueError: Attempted relative import in non-package
我之前运行过很多使用相同导入方法的应用程序,但从未遇到过问题。我不知道为什么会突然发生这种情况。
在 stackoverflow 和 google 上查看其他类似问题时,每个人都提到设置和检查系统路径,我已经这样做了。如前所述,通过 PyCharm 运行它可以正常工作。如果我在导入前将 ~/testapp/workers/a.py 更改为打印 sys.path、sys.executable 和 os.getcwd(),那么 PyCharm 和控制台中的结果是一样的。
【问题讨论】:
标签: python python-2.7 pycharm python-import importerror