vscode执行python程序的时候,如果涉及到相对路径,那么都是以workspace路径开始的,而不是执行文件的所在文件夹。这个实际上并不是vscode的问题,而是python插件的问题。
1. vscode内修改
这部分说一下,实际上有两种方式,对应debug和run两种情况,但是网上说的基本都只有一种,或者直接否定另一种,个人觉得是不对的。
debug时
首先生成.vscode下的launch.json(可以在run and debug窗口,选择create a launch.json file自动生成)
launch.json生成
然后在launch.json中增加"cwd": "${fileDirname}"
,如果是自动生成的那么最终得到的是如下的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: 当前文件",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true,
"cwd": "${fileDirname}"
}
]
}
run时
File->Preferences->Settings
中找到如下的选项,一般搜索terminal就会出现,勾选即可。
选项
2. 直接使用绝对路径
既然相对路径存在问题,那就直接使用绝对路径。当然这部分不用自己手打,先不说打的对不对,至少这么长不好看xD。
import os
ROOT_PATH = os.path.normpath(os.path.abspath(os.path.dirname(__file__)))
这样得到的ROOT_PATH就是当前文件的绝对地址了,写一个config,要用的时候import就行了