Visual Studio Code: run Python file with arguments

60,577

Solution 1

Visual Studio Code only supports one launch.json file. However, it supports two or more configurations, and they appear in the left-hand menu/pane's drop down list (instead of "No Configurations").

Enter image description here

In the DEBUG pane, either click the Config button circled in red above or click the blue link "create launch.json file":

Click it and it creates a launch.json file with debugging configurations. Edit this file and add the args in this key-pair format AND add multiple for different args including Variable Substitution!

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File with my args",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "args": [
                "--username", "Jeremy",
                "--account", "Stackoverflow"
            ],
            "console": "integratedTerminal"
        },
        {
            "name": "Python: Current File with UserName arg",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "args": ["${env:USERNAME}"],
            "console": "integratedTerminal"
        }
    ]
}

Put a breakpoint in your Python script, for example on the first line under def main(...) and then press F5 or click Run Menu > Start Debugging.

Solution 2

A workaround is to have your script ask for the command-line arguments (in the internal Visual Studio Code console).

This can be made much more usable by leaning on readline, which allows you to do things like press the Up arrow key to cycle through previous commands (command history), and more. An example:

import argparse, readline

def main():
  # Ask for additional command line arguments if needed (for VSCode)
  parser = argparse.ArgumentParser()
  parser.add_argument('--interactive', action='store_true', default=False)
  (args, rest) = parser.parse_known_args()
  if args.interactive:
    try: readline.read_history_file()
    except: pass
    rest += input("Arguments: ").split(" ")  # Get input args
    try: readline.write_history_file()
    except: pass

  # Your other script arguments go here
  parser.add_argument("-output-dir", default="/out")
  # ...
  args = parser.parse_args(rest)

  print(args)

if __name__ == "__main__":
  main()

Then just set up Visual Studio Code to always pass in the --interactive argument, and your script will always ask for arguments (with history!) even as you set breakpoints.

Solution 3

You can add a custom task to do this. This deals with the tasks.json. You can add a default tasks.json file for you project (project folder). Follow these steps. Keyboard press Ctrl + Shift + B. It will prompt the following popup

Enter image description here

Click on the Configure Build Task If there is already a custom tasks.json file created in the following location .vscode/tasks.json editor will open it. If not, it will give a drop down of suggestions of already existing task runners.

Our intention is to create a custom tasks.json file for our project, so to create one we need to select the Others option from the drop down. Check the screenshot below.

Enter image description here

Once you select the Others option, you could see a default tasks.json file will get created from the root directory of the project to the location .vscode/tasks.json. Below is an example of tasks.json.

Enter image description here

Now edit the tasks.json file to support Python.

  1. Change the Command property from "echo" to "Python"
  2. Keep showOutput as "Always"
  3. Change args (arguments) from ["Hello World"] to ["${file}"] (filename)
  4. Delete the last property problemMatcher
  5. Keep isShellCommand and version properties as unchanged
  6. Save the changes made

You can now open your .py file and run it nicely with the shortcut Ctrl + Shift + B.

Solution 4

If you don’t have a task.json file in your project you can create a new one with press Ctrl + Shift + B. Then choose the first option showing to you then replace all of them with the below:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Run Python with argument",
            "type": "shell",
            "command": "python PROGRAM_NAME.py ARG1 ARG2 ...",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Otherwise add the above configuration in your existed tasks.json file.

Replace PROGRAM_NAME in the above configuration with your program name and ARG1 ARG2 ... indicate your specific arguments.

After all, you can execute your created task with Ctrl + Shift + B and choose the new "Run Python with argument" task.

Solution 5

Another option is you can run your python program from the commandline via

python3 -m debugpy --wait-for-client --listen localhost:5678 myprogram.py

Then you can use a Python: Remote Attach launch.json configuration to connect to the program. It means an extra step every time to you turn on your program: run the program on the CLI then attach debugger, but it does make specifying the arguments more fluid.

To make things even simpler, you could put the above in a bash script and pass through args from CLI to python:

start.sh "my arg that changes all the time"

Then attach via "Remote Attach".

Share:
60,577
Thyrst'
Author by

Thyrst'

Updated on July 24, 2022

Comments

  • Thyrst'
    Thyrst' almost 2 years

    Is there an easy way to run a Python file inside Visual Studio Code with arguments?

    I know I can add a custom configuration in the launch.json file with the args keyword. However, it is annoying to modify the launch.json file every time just because I want to use different arguments.

  • Thyrst'
    Thyrst' about 7 years
    Thanks for the answer. However I don't get it.. Ctrl+Shift+B runs the script but how I can pass arguments to it?
  • Thyrst'
    Thyrst' about 7 years
    I want to start the debugger for example from the command palette with something like debug arg1 arg2, which would start my script like python app.py arg1 arg2.
  • duanev
    duanev over 4 years
    Hilarious. Down votes (I'm guessing) are because I went outside VCS to solve this? My argument: if the tool doens't do what you want in a reasonable way, definitely go outside the box. (feel free to EXPLAIN your downvote below :)
  • remram
    remram almost 4 years
    The down votes are because you did not answer the question. It is safe to assume everyone know how to pass arguments from the terminal, the question is how to do it in VS Code.
  • Leo
    Leo over 3 years
    That is a helpful answer, but the question was about running, not debugging. Is it possible to run the script with arguments without the delays resulting from the debugger?
  • Jeremy Thompson
    Jeremy Thompson over 3 years
    It's an IDE though so can you vscode.exe -path c:\file.py -args a=b to run it?
  • Jeremy Thompson
    Jeremy Thompson over 3 years
    @Thyrst' I've updated the answer could you take another look, thanks.
  • Maths12
    Maths12 over 2 years
    how do i run this?
  • Ehsan Ahmadi
    Ehsan Ahmadi over 2 years
    Create your task then press CTRL + SHIFT + b. VS CODE shows you a list of the current tasks. search your task with the label you have specified. then press enter.
  • Maths12
    Maths12 over 2 years
    say i want to run my pythoin script called run.py , which takes args 'train' or 'validate' in the aboe do i replace command with : ' python run.py 'train' " ?
  • Ehsan Ahmadi
    Ehsan Ahmadi over 2 years
    yes. in the value of the command. you should put something like this "python /path/to/run.py train"