在Visual Studio Code中,如果我在终端中单击运行python文件,则活动脚本将在默认工作目录中执行。我想做的是自动将 cwd 更改为我要运行的脚本的位置。我知道我可以使用cd
手动更改它,但是如果我经常在不同的脚本之间切换,它会变得非常烦人。那么有什么简单的方法可以实现它吗?
您可以使用调试配置执行此操作。
python 调试器支持cwd
属性,您可能希望将其设置为${fileDirname}
- 当前打开的文件的目录。
如果您从菜单"调试/打开配置"中进行选择,它将打开一个名为 launch.json 的文件。
这是我添加了"cwd":"${fileDirname}"
属性的配置。
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd": "${fileDirname}"
}
]
参考:
哪些变量可用:https://code.visualstudio.com/docs/editor/variables-reference
启动.json 属性:https://code.visualstudio.com/docs/editor/debugging#_launchjson-attributes