In Visual Studio Code, if I click run python file in terminal, the active script would be executed in the default working directory. What I want to do is automatically changing cwd to the location of the script I would like to run. I know I can use cd to manually change it, but it would become very annoying if I frequently switch between different scripts. So is there any easy way to realize it?
1 Answer
You can do this with the debug configuration.
The python debugger supports the cwd attribute, and you probably want to set it to ${fileDirname} - the current opened file's directory.
If you choose from the menu Debug / Open Configurations, it'll open a file called launch.json.
Here's my config with the "cwd":"${fileDirname}" attribute added.
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd": "${fileDirname}"
}
]
Reference:
Which variables are available: https://code.visualstudio.com/docs/editor/variables-reference
Launch.json attributes: https://code.visualstudio.com/docs/editor/debugging#_launchjson-attributes