VSCode:如何将模块从我的代码路径导入到同一路径中的另一个文件?

我正在尝试使用VSCode调试python应用程序。但是我无法正确配置我的环境。尝试将类从我的源路径中的一个文件夹导入到另一个文件夹,将显示以下消息:

Traceback (most recent call last):
  File "/Users/mb/library/source/sandbox/lib/lib.py",line 1,in <module>
    from app.main import MyClass
ModuleNotFoundError: No module named 'app'

我创建了一个简单的应用来展示该问题。我的源路径如下:

sandbox
+-- .vscode
    --- launch.json
+-- app
    --- __init__.py
    --- main.py
+-- lib
    -- lib.py
# main.py

class MyClass:
    def __init__(self):
        print('Creating object...')
    def print_message(self,message):
        print(message)
# lib.py

from app.main import MyClass


myclass = MyClass()
myclass.print_message('hello,world!')

尝试使用默认配置运行lib.py来运行当前文件,我得到上面的错误消息。

此外,我创建了一个.vscode/launch.json来设置工作目录,但无济于事。这是我的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","cwd": "${workspaceFolder}"
        },{
            "name": "Python: Module","module": "main"
        }
    ]
}

我敢肯定,我错过了一个简单的设置,但是我不能把手放在上面。


注意

  • 使用的解释器是:Python 3.7.5 64位
  • 上面的代码在PyCharm中工作正常。
  • 在阅读了VSCode文档之后,我在"env": {"PYTHONPATH": "${workspaceFolder}"}上添加了launch.json,但这没有任何好处。
  • 我还创建了一个VSCode task 来回显${workspaceFolder}变量,并且从路径中剥离了所有\的输出,就好像它们没有被转义一样。 这是.vscode/tasks.json中的任务:
{
    "version": "2.0.0","tasks": [
      {
        "label": "workspaceFolder","type": "shell","command": "echo ${workspaceFolder}"
      }
    ]
  }

这是从中获得的输出:

> Executing task: echo C:\Users\mb\library\source\sandbox <

C:Usersmblibrarysourcesandbox

Terminal will be reused by tasks,press any key to close it.
llk4j 回答:VSCode:如何将模块从我的代码路径导入到同一路径中的另一个文件?

让我尝试帮助您。要导入不在当前目录中的文件时,请执行以下操作。

from . import main

对于第二个问题,请访问此LINK

,

看看here

基本上,您想做的是先cd /path/to/sandbox,然后是export PYTHONPATH=$(pwd)

现在,您的应用程序的根目录位于python-path中。

您只需在此级别上对待所有内容。

from app.main import MyClass

本文链接:https://www.f2er.com/3168896.html

大家都在问