【问题标题】:Python import class simple example errorPython导入类简单示例错误
【发布时间】:2016-01-08 12:36:35
【问题描述】:

我想知道为什么我构建类的简单示例无法正常工作:

树形结构如下所示

class_project/
├── class_project
│   ├── __init__.py
│   └── classtheclass.py
└── tests 
    ├── __init__.py
    └── test.py

classtheclass.py 看起来像这样:

class ClassTheClass(object):
    def __init__(self):
        print "yeees"

test.py 看起来像这样:

from class_project.classtheclass import ClassTheClass


i = ClassTheClass()

init.py 为空

所以如果我在 shell 上执行

python test.py

它给了我

Traceback(最近一次调用最后一次):文件“test.py”,第 1 行,在 from class_project.classtheclass import ClassTheClass ImportError: No module named class_project.classtheclass

这有什么问题。在 Pycharm 中,这甚至可以工作......!

【问题讨论】:

  • 你试过了吗:from classtheclass import ClassTheClass
  • 把test.py放到class_project里面(在tests后面),执行test.py就可以访问classtheclass了。

标签: python python-2.7


【解决方案1】:

当您运行 python test.py 时,解释器将在标准库位置(例如 /usr/local/lib/python2.7/site-packages 和朋友)和您调用解释器的 tests 文件夹中查找 Python 代码(这组位置称为“Python 路径”,您可以通过以下方式查看:import sys; print sys.path)。

这些位置都不包括class_project.classtheclass

有多种方法可以解决这个问题。

您可以将PYTHONPATH 环境变量设置为包含class_project

export PYTHONPATH="/path/to/class_project:$PYTHONPATH"  # Note: this has to be the top-level class_project directory, you have two with this name here.
python test.py  # This will now work

您也可以使用相对导入,但我认为这是解决问题而不是解决问题。

【讨论】:

  • 啊我明白了...你知道如何用 virtualenv 管理它吗?但是如果 eim 在顶层调用 python tests/test.py 时会出现同样的错误
  • @Jurudocs 您可以将export ... 添加到activate 脚本的底部。我不会推荐它。这通常不是您期望(或需要)virtualenv 处理的事情。最终,您将只使用测试运行程序(或 IDE)为您执行此操作。现在可能看起来很麻烦,但你最终会发现这不是问题。
  • 嗯,好吧,我将在远程服务器上使用 ansible 运行测试...这就是为什么我认为我需要它
  • 你能想到更优雅的解决方案吗?
【解决方案2】:

你的文件树结构错误,如果你没有用新的lib路径导出PYTHONPATH,你必须把test.py放在下面的结构中,让test.py从class_project访问classtheclass。

class_project/
├── class_project
│   ├── classtheclass.py
│   └── __init__.py
└── test.py

【讨论】:

  • 项目层面的测试正常吗?
【解决方案3】:

Python搜索导入的模块如下,例如import foo

  • 首先搜索built-in模块,如果foo不是built-in模块,进入下一步
  • 解释器将搜索sys.pathsys.path 将包括:当前目录、PYTHONPATH 和安装依赖路径。如果foosys.path 中,它将被导入。否则,它将是ImportError

在这里,您可以在项目父目录执行或将/path/to/project显式添加到sys.path

【讨论】:

    猜你喜欢
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    相关资源
    最近更新 更多