我知道以前有人问过这个问题,但我尝试过的任何方法都不适合我。我有以下目录结构。
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
等都无关紧要)
我想要做的是在 bubble_sort
中导入 heap_sort
和 performance.py
而无需手动触摸更改 sys.路径
我尝试过的:
在 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
(什么?在每个目录中没有包含所有这些 __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
}
答案 0 :(得分:0)
您可以像这样导入函数:
$ 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