python - 从相邻目录导入时出现 ImportError
问题描述
我知道以前有人问过这个问题,但是我尝试过的任何方法都没有为我工作。我有以下目录结构。
C:\USERS\PC\DESKTOP\MyProject
│ .gitignore
│ conftest.py
│ README.md
│ __init__.py
│
├───.github
│ └───workflows
│ build.yml
│
├───.vscode
│ launch.json
│ settings.json
│
├───dependencies
│ dev_requirements.txt
│
├───src
│ │ __init__.py
│ │
│ ├───benchmark
│ │ performance.py
│ │ __init__.py
│ │
│ └───sorting
│ bubble_sort.py
│ heap_sort.py
│ __init__.py
│
└───tests
└───sorting
test_sorting.py
(我把我所有的东西都放了,但是tests
, dependencies
, .github
, 等是无关紧要的)
我要做的是在不手动更改 sys.path的情况下导入bubble_sort
和输入heap_sort
performance.py
我试过的:
添加以下内容
performance.py
(vscode 不显示任何 lint 错误)from sorting.bubble_sort import bubble_sort bubble_sort(None)
结果:
No module named 'sorting'
使用相对导入:
from ..sorting.bubble_sort import bubble_sort
结果:(什么??每个目录中
attempted relative import with no known parent package
都没有包含所有这些s的已知包??__init.py
如果它是相关的,这是我的.vscode/launch.json
:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}
这是我的.vscode/settings.json
:
{
"python.linting.flake8Enabled": true,
"python.linting.pycodestyleEnabled": true,
"python.linting.enabled": true,
"python.testing.pytestArgs": [
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.nosetestsEnabled": false,
"python.testing.pytestEnabled": true
}
解决方案
您可以像这样导入函数:
$ cat test.py
#! /usr/bin/env python
from src.sorting.bubble import thesort
thesort()
$ cat src/sorting/bubble.py
#! /usr/bin/env python
def thesort():
print('hallo from the bubble')
$ python test.py
hallo from the bubble
要在目录中升级,我认为您需要像这样制作一个 kickstarter 脚本(来自更高级别目录的命令):
$ cat start.py
#! /usr/bin/env python
from test.test import runscript
runscript()
$ cat test/test.py
#! /usr/bin/env python
from test.src.sorting.bubble import thesort
from benchmark.performance import evalfunc
def runscript():
thesort()
evalfunc()
$ cat test/src/sorting/bubble.py
#! /usr/bin/env python
def thesort():
print('hallo from the bubble')
$ cat benchmark/performance.py
#! /usr/bin/env python
def evalfunc():
print('hallo from performance')
$ python start.py
hallo from the bubble
hallo from performance
推荐阅读
- c - DevkitARM,模拟器上的白屏如果我在代码中使用for循环?
- java - 尝试将对象保存到数据库时出现 Hibernate 407 错误。(@OneToMany 关系)
- r - 用于 stat_density_ridges 的具有多个/条件 scale_fill_manual 的 GGplot
- javascript - 应用谷歌翻译时页面以默认语言和选定语言闪烁
- email - Amazon WorkMail:可以使用 AWS SES 和 Lambda 来处理收到的电子邮件吗?
- javascript - ESModules [object Module] 如何创建模块的实例?
- c# - ObservableCollection.Clear 离开幻象元素
- javascript - WooCommerce 的动态交付时间计数器作为简码
- python - request.get_json() 适用于本地主机但不适用于远程主机
- oracle - Oracle Golden Gate 是否也可以复制存储过程定义更改?