skip to Main Content

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


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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search