操作系统之间的 Python 3 导入行为差异



我可能需要一些主要的睡眠,但这让我甚至很难考虑它。

我在 2 台独立的机器中有以下结构:

.
├── testmod
│   ├── __init__.py
│   └── test.py
└── testmod2
    ├── __init__.py
    └── hello.py

有问题的机器是:

  • CentOS (Linux 版本 7.2.1511(
  • macOS Sierra (10.12.4(

我绝对在两台机器上运行Python 3.6:

Python 3.6.1(默认,2017 年 4 月 7 日,09:32:32([GCC 4.8.5 20150623(红色( Hat 4.8.5-11(] 在 Linux 上

Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04( [GCC 4.2.1 (苹果公司内部版本 5666((点 3(]论达尔文

唯一包含内容的文件是 test.py:

from testmod2 import hello
print(hello)

从根目录(testmod 和 testmod2 共存的地方(,我正在运行以下命令:

python3.6 testmod/test.py

macOS 输出:

<module 'testmod2.hello' from '/Users/joao/Documents/tests/testmod2/hello.py'>

分素输出:

Traceback (most recent call last):
  File "testmod/test.py", line 1, in <module>
    from testmod2 import hello
ModuleNotFoundError: No module named 'testmod2'

我被难住了。我在这里显然错过了什么?

我看到在 Centos 上,脚本 dir 没有附加到您的 sys.path 前面。在我的 Ubuntu 盒子上,它是前缀的,一切正常。我找到了有关该主题的以下文档:python 命令有一个新选项 -I,它导致它在"隔离模式"下运行,这意味着 sys.path 既不包含脚本的目录......

也许你需要检查默认情况下python运行时使用了哪些选项。

对于其他想知道的人,我的$PYTHONPATH根本没有在 CentOS 中设置。我怀疑其他人可能会遇到同样的问题,因此解决方案可能是

export PYTHONPATH="."

尽管这将起作用,但实际上并不建议向$PYTHONPATH添加相对路径 - 添加代码所在的绝对路径可能更明智:

export PYTHONPATH="/your/python/code"

(更永久的解决方案当然是将上述内容添加到您的 ~/.bashrc 或类似内容中(

最新更新