首页 > 解决方案 > 无法在同一目录 Visual Studio Code 中找到/导入 .py 文件

问题描述

我一直在互联网上,花了几个小时试图解决这个问题。这可能是一件非常简单的事情,所以请让我放松一下。这是我第一次使用 Visual Studio Code。我已经尝试过以下链接中提供的解决方案:

  1. VS Code - pylinter 找不到模块
  2. python模块的vscode导入错误
  3. 无法让 VSCode/Python 调试器找到我的项目模块
  4. https://code.visualstudio.com/docs/python/environments

我的文件夹结构如下所示:

我正在尝试运行 urls.py 文件,该文件尝试使用 -

from . import views

但我收到以下错误:

Traceback(最近一次通话最后一次):文件“c:/Users/abc/projects/telusko/calc/urls.py”,第 7 行,来自 . 导入视图 ImportError:无法导入名称“视图”

我已经尝试了所有可能的组合,目前我的 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"
        }],
    "env": {"PYTHONPATH": "c:/Users/abc/projects/telusko/"},
    "python.pythonPath": "c:/Users/abc/Envs/test/Scripts/python.exe" 
}

我正在使用虚拟环境来运行这个项目,环境位于 - “c:/Users/abc/projects/telusko/test/”

我的项目目录位于 -

“c:/Users/abc/projects/telusko/”

标签: pythonpython-3.xdjangovisual-studiovisual-studio-code

解决方案


我创建了一个与您的文件夹结构相同的项目,并且 venv 在文件夹 test 下称为 env。

在此处输入图像描述 urls.py 和views.py 是同级模块,所以import语句应该是

from views import *

os.getcwd() 方法是显示您当前的工作目录。


推荐阅读