vscode python相对路径的问题

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

geometry.py

# 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

# 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. 修改或添加以下内容:

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

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

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐