vscode python相对路径的问题

vscode python相对路径的问题

最近使用使用vscode连接wsl2写python时,经常遇到找不到包中的方法的问题,最终发现vscode在执行python代码时目录不是从当前python文件开始算起,而是从当前工作区的目录开始算起,比如说我打开的是/home/lenovo/code,在我的code目录下有一个py_learn文件夹下有geometry.py main.py 两个文件

geometry.py

python 复制代码
# geometry.py
def area_circle(radius):
    return 3.14159 * radius ** 2

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
    
    def area(self):
        return self.length * self.width
    
PI = 3.14159

main.py

python 复制代码
# main.py
import geometry
# 使用函数
print(geometry.area_circle(5))  # 78.53975

# 使用类
rect = geometry.Rectangle(4, 3)
print(rect.area())  # 12

默认情况下,会说geometry模块没有area_circle方法,这是因为python默认是从/home/lenovo/code寻找的geometry而不是/home/lenovo/code/py_learn中寻找,如果想让python程序执行时,默认从当前py文件的路径下开始寻找

可以配置vscode的launch.json文件

  1. 打开调试面板(Ctrl+Shift+D)。

  2. 点击"创建 launch.json 文件"。

  3. 修改或添加以下内容:

json 复制代码
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd": "${fileDirname}"  // 设置为脚本所在目录
        }
    ]
}

这样每次执行py程序就会从当前的py文件的目录开始算起

相关推荐
Ray Liang36 分钟前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮4 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽4 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健19 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞21 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python