首页 > 解决方案 > 从相邻目录导入时出现 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_sortperformance.py


我试过的:

  1. 添加以下内容performance.py(vscode 不显示任何 lint 错误)

    from sorting.bubble_sort import bubble_sort
    
    
    bubble_sort(None)
    

    结果:No module named 'sorting'

  2. 使用相对导入: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
}

标签: pythonpython-import

解决方案


您可以像这样导入函数:

$ 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

推荐阅读