sys.path 修改不适用于 python2,但适用于 python3



我正在尝试导入脚本'main/main.py'中的模块foo.foo

以下是目录结构:

chenjiasheng@ubuntu:~/code/test$ pwd
/home/chenjiasheng/code/test
chenjiasheng@ubuntu:~/code/test$ find
.
./foo
./foo/foo.py
./main
./main/main.py

两个文件的内容是:

chenjiasheng@ubuntu:~/code/test$ cat ./foo/foo.py 
pass
chenjiasheng@ubuntu:~/code/test$ cat ./main/main.py 
import sys
sys.path.append('/home/chenjiasheng/code/test')
print(sys.path)
import foo.foo

"main/main.py"应该将"foo/"附加到其模块搜索路径中。但是用python2运行它会得到ImportError

chenjiasheng@ubuntu:~/code/test$ python2 main/main.py 
['/home/chenjiasheng/code/test/main', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linues', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/home/chenjiasheng/code/test']
Traceback (most recent call last):
  File "main/main.py", line 4, in <module>
    import foo.foo
ImportError: No module named foo.foo

相比之下,使用 python3 运行它是可以的:

chenjiasheng@ubuntu:~/code/test$ python3 main/main.py 
['/home/chenjiasheng/code/test/main', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linu
chenjiasheng@ubuntu:~/code/test$

根据手册,https://docs.python.org/2/tutorial/modules.html#the-module-search-path,sys.path变量应该适用于python2和python3。

那我做错了什么?

您的foo包没有用于将其标识为包的__init__.py文件。在 Python 3 下,它仍然可以作为命名空间包的一部分导入,但此功能不会向后移植到 Python 2。添加一个空__init__.py应该意味着你也可以在Python 2中导入该包。

最新更新