python - Python 3 中的导入错误
问题描述
我有 Python 3 中的结构:
my_module/
my_module/
any_name.py
tests/
tests.py
然后,我尝试在tests.py中使用:
from my_module.any_name import my_class
我收到错误:
ModuleNotFoundError: No module named 'my_module'
有谁知道是什么问题?
解决方案
my_module
首先,拥有and非常令人困惑my_module/my_module
,但让我们忽略它。
为了my_module
工作,外部my_module
必须在你的sys.path
.
所以,如果你这样做:
$ cd tests
$ python tests.py
......那么你的sys.path
意志只是按照你通常的方式,加上my_module/tests
。它不会包含my_module
,因此您在任何地方都找不到my_module/my_module
。
解决方法包括:
- 有一个顶级
test.py
的from tests import tests.py
和tests.run()
。 python -m tests.tests
从顶级目录运行代码my_module
,而不是python tests.py
从my_module/tests
.- 手动
tests/tests.py
插入os.path.join(__path__, '../my_module
)sys.path
。 - 使用
setuptools
/pkg_resources
而不是尝试手动执行所有操作。 - 做这里描述的 hacky 旧式的事情。(你真的不想这样做,除非你需要兼容 Python 2.7 或 3.2 或旧的
distribute
/distutils
版本pkg_resources
。)
推荐阅读
- ios - 为什么只显示集合视图的一半?
- python - 无法从 anaconda 启动 Jupyter
- android - How can a Delagetes.observable in a BroadcastReceiver be unit tested?
- amazon-s3 - 使用 boto3 键错误从 S3 下载文件
- asp.net-core - .netcore web API Post 在没有 SSL 的情况下无法工作
- c# - RestSharp 请求中的错误?, XML , ':' 字符,十六进制值 0x3A,不能包含在名称中
- java - Spring @ConfigurationProperties 解析器忽略外部化属性
- arrays - 在一行中使用 /bin/sh 声明一个数组
- java - 将 JBOSS EAP 7.1.5 迁移到 JBOSS EAP 7.2 时出现休眠问题
- node.js - 将下一个 js 更新到 v9 后链接错误 - 参数 'url' 必须是字符串,而不是未定义