当 运行 python 作为脚本导入失败,但在 iPython 中导入失败?

import fails when running python as script, but not in iPython?

我有一个结构如下的项目:

folder1
       |
       folder2
             |
             tests

我在每个文件夹中都有 __init__.py。当我在 folder1 的父目录中时,我 运行 iPython 并执行

from folder1.folder2.tests.test1 import main
main()

一切正常。然而当我 运行

python folder1/folder2/tests/test1.py

我收到 ImportError: No module named folder1.folder2.file1,我在 test1 中的导入语句是

from folder1.folder2.file1 import class1

对此感到困惑 - 我猜这是一个路径问题,但我不明白我的代码有什么问题(其他文件夹中有许多类似的设置)以及为什么它仍然适用于 iPython 而不是python 运行 作为脚本。

有脚本文件和没有脚本文件的module search path (python 3 docu)是不同的:

交互式python解释器

(适用于 pythonipython

$ python
Python 2.7.3 (default, Dec 18 2014, 19:10:20) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.path)
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/pymodules/python2.7/gtk-2.0', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']
>>>

请注意第一个条目是一个空字符串。空字符串是相当于 . 的相对路径。模块搜索路径中的相对路径是相对于解释器进程的当前工作目录的,因此这只是您调用解释器的当前工作目录。 (在你的例子中,这恰好是你项目的根。)

正在执行脚本文件

$ echo 'import sys' > /tmp/pathtest.py
$ echo 'print(sys.path)' >> /tmp/pathtest.py 
$ python /tmp/pathtest.py 
['/tmp', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/pymodules/python2.7/gtk-2.0', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']

注意这里,第一个条目是包含我们作为参数传递的脚本文件的目录的绝对路径。

我在导入 numpy 或依赖于 numpy 的任何库时遇到了类似的问题。问题是我的项目文件夹中有一个文件名 random.py。

Numpy 中有 random.py 的随机函数,但导入它占用了我的项目文件夹的 random.py。

最好的解决办法是不要使用任何库的标准模块名称来命名任何文件。

享受.. :)