1

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 2

1

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->

import os

filepath= os.path.dirname(os.path.abspath(__file__))
os.chdir(filepath) # move your working directory to this file's directory

<-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's sys.path with the updated working path dir:

<-SNIP->

import sys

if os.path.abspath('.') not in sys.path:
    sys.path = [os.path.abspath('.')] + sys.path

<-SNIP->

Sign up to request clarification or add additional context in comments.

2 Comments

This is a solution which involves modifying the code, which is not always doable
Please see the link at the top of my answer for the config change in VSCode... My "however" addition was for further information, in case that's what the "underlying question" was (it's what my underlying question was when I was starting out!), rather than a "you must do this to get what you need".
1

As you know, you can add the cwd parameter in launch.json. You can also use Ctrl+F5 for Run Without Debugging action.

enter image description here

Another option is to use the Code Runner extension, which allows to set cwd.

enter image description here

Reminder, if you use Code Runner, you need to use the Run Code option to execute the script.

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.