I’m new to VSCode and I can’t find anywhere the answer to an easy question:
how can I run a python script (let’s say main.py) by creating configurations where I can set a specific working directory folder as well as arguments?
I see that by default the working directory, when running any file, is the workspace directory, but I’m not able to change it anyhow.
When using the Python Debugger, I can easily do that with the "cwd" option inside a configuration of the launch.json, and I want to be able to do the same to just run the code (… and debugging without any breakpoint is not the same, e.g. when there’s parallel computation).
With PyCharm this is very easy, but not with VSCode perhaps?
2
Answers
This has been answered: How to set the working directory for debugging a Python program in VS Code?
However! If you’re going to need the working directory set for your running code, for example if other people will be running your code in an unknown directory and not in VSCode, you will need to add the working directory to your code explicitly:
<-SNIP->
<-SNIP->
If you also need to look at this file’s modules FIRST, for example if your code has its own version of modules that may also exist in the
sys.path
, you can prepend your file’ssys.path
with the updated working path dir:<-SNIP->
<-SNIP->
As you know, you can add the
cwd
parameter in launch.json. You can also use Ctrl+F5 forRun Without Debugging
action.Another option is to use the Code Runner extension, which allows to set cwd.
Reminder, if you use Code Runner, you need to use the
Run Code
option to execute the script.