如何在VS代码中从本地python包导入?

如何在VS代码中从本地python包导入?,python,visual-studio-code,Python,Visual Studio Code,我的项目结构如下: - my_pkg setup.py README.md - my_pkg __init__.py __main__.py - src app.py part.py __init__.py - tests test_app.py test_parts.py

我的项目结构如下:

- my_pkg
    setup.py
    README.md
    - my_pkg
        __init__.py
        __main__.py
         - src
             app.py
             part.py
             __init__.py
         - tests
             test_app.py
             test_parts.py
             __init__.py
在test_app.py中,我有以下导入语句:

import my_pkg.src.app as app
在我的终端中,我可以使用

python -m my_pkg.tests.test_app
这运行正常,没有任何错误,但是当我右键单击test_app.py并选择“在终端中运行Python文件”时,我得到以下错误:

ModuleNotFoundError: No module named 'my_pkg'
我已通过运行以下程序安装了我的_pkg:

pip install -e .
如果我打开一个终端并运行python,然后在python中运行“import my_pkg.src.app as app”,它可以正常工作


我做错了什么。在visual studio代码中运行程序时,如何使导入工作?

因为运行的cwd位于“test.py”文件中

您需要将根目录添加到系统路径

import sys
import os
sys.path.append(os.path.join(os.path.dir(__file__), "from/file/to/root"))
print (sys.path)

将目录更改为“my_pkg”,并按如下方式运行代码

python-m my_pkg.tests.test_应用程序

查看-m标志文档

我通过更改launch.json文件找到了让调试器工作的方法:

{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Python: Module: my_pkg",
            "type": "python",
            "request": "launch",
            "module": "my_pkg",
            "console": "integratedTerminal"
        },
        {
            "name": "Python: Current File (Integrated Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "env" : {"PYTHONPATH": "${workspaceFolder}"},
            "console": "integratedTerminal"
        },
        {
            "name": "Python: Remote Attach",
            "type": "python",
            "request": "attach",
            "port": 5678,
            "host": "localhost",
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}",
                    "remoteRoot": "."
                }
            ]
        },
        {
            "name": "Python: Current File (External Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "env" : {"PYTHONPATH": "${workspaceFolder}"},
            "console": "externalTerminal"
        }
    ]
}
“Python:Module my_pkg”将通过运行带有-m参数的_____;main.py文件来运行我的模块,“Python:Current file(Integrated Terminal)”和“Python:Current file(External Terminal)”运行打开的当前文件,但将workspaceFolder作为PYTHONPATH提供,以便我的导入不会中断


我还没有找到一种方法来更改配置,这样我就可以右键单击一个文件并选择“在终端中运行Python文件”,而不会破坏它。但我只是在终端中手动运行它,直到找到解决方案。

是的,我可以在终端上这样运行它。如何配置VS代码,使其在调试模式下、在终端中运行时以及在运行自动检测的测试时自动运行?