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文件的目录开始算起

相关推荐
这里有鱼汤8 分钟前
80%新手炒股都在误用技术指标?一文揭秘正确分类与实战组合
后端·python
御龙冀人20 分钟前
解决VSCode无法下载服务器端 Server问的题
服务器·vscode·ssh
小磊哥er34 分钟前
【办公自动化】学习使用Python库让视频剪辑自动化
python
chian-ocean5 小时前
Bright Data 代理 + MCP :解决 Google 搜索反爬的完整方案
人工智能·python
AndrewHZ10 小时前
【python与生活】如何用Python写一个简单的自动整理文件的脚本?
开发语言·python·生活·脚本·文件整理
binbinaijishu8810 小时前
Python爬虫入门指南:从零开始的网络数据获取之旅
开发语言·爬虫·python·其他
Python代狂魔11 小时前
Redis
数据库·redis·python·缓存
做科研的周师兄13 小时前
【机器学习入门】1.2 初识机器学习:从数据到智能的认知之旅
大数据·数据库·人工智能·python·机器学习·数据分析·机器人
王小王-12313 小时前
基于Python的游戏推荐与可视化系统的设计与实现
python·游戏·游戏推荐系统·游戏可视化
KevinWang_14 小时前
让 AI 写一个给图片加水印的 Python 脚本
python