Visual Studio Code: run Python file with arguments
Asked Answered
R

12

89

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.

Rettarettig answered 30/4, 2017 at 9:8 Comment(0)
W
79

Visual Studio Code only supports one launch.json file. However, it supports two or more configurations that appear in the debug 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"
        }
    ]
}

Set your desired Config Option in the drop down and put a breakpoint in your Python script, for example on the first line under def main(...) and then press F5 or Run> Start Debugging.

Pro Tip: see the Variable Substitution reference its the perfect way to automate things for the whole team by not hardcoding individuals info or settings in the configs instead using things in Build Pipelines such as Environmental Variables from the get go!

Pro Tip:

Default settings (hardcoded POCO constructor values).

A settings (aka launch.json) file to override the default hardcoded values using optional settings.

Environmental Variables to override any setting.

Wheelchair answered 12/12, 2019 at 7:37 Comment(7)
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?Fugacity
@Thyrst' I've updated the answer could you take another look, thanks.Wheelchair
Can I use the launch config somehow for normal runs, not for debugging? Or how would I pass args without debugging?Lavinialavinie
@CGFoX maybe try simulating it? https://mcmap.net/q/242772/-python-error-the-following-arguments-are-requiredWheelchair
@Leo, Select a configration in debug panel, then Ctrl - F5 to run it withou debugging.Hibbitts
@Hibbitts so that is run without debugging but from the debugging panel...Zicarelli
@Fugacity the configuration works for both debugging and running it without debuggingZicarelli
I
6

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.

Iridic answered 30/4, 2017 at 19:42 Comment(2)
Thanks for the answer. However I don't get it.. Ctrl+Shift+B runs the script but how I can pass arguments to it?Rettarettig
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.Rettarettig
I
6

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.

Ideogram answered 10/12, 2018 at 18:37 Comment(1)
Could you include how to "set up Visual Studio Code to always pass in the --interactive argument" please?Condyloid
H
5

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.

Hoofbeat answered 22/6, 2019 at 20:9 Comment(5)
how do i run this?Epispastic
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.Hoofbeat
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' " ?Epispastic
yes. in the value of the command. you should put something like this "python /path/to/run.py train"Hoofbeat
clicking "play" buttons still fails with no argsYakut
C
2

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

Candlewick answered 17/12, 2020 at 20:40 Comment(0)
H
1

If you've already known how to set args in launch.json, and debug. And your question is how to run python with arguments, just Run->Run without debugging.

Hedjaz answered 22/9, 2023 at 19:34 Comment(0)
P
0

I have looked for a solution to the issue described here but don't think any of the answers are sufficient so I have created a debugpy-run utility to solve it.

If you have the VS Code Python extension installed then the full debugpy debugger is already bundled with it. The utility finds the path where debugpy is installed and then runs it for program and arguments you specify, in listen mode. Connect to it from within VS Code using the Python "Remote Attach" debug configuration (using the default host and port settings). You can just control+c and then re-run the command with changed arguments using your shell history and command line editing facilities, for each debug run.

Pavlov answered 18/4, 2021 at 23:35 Comment(0)
V
0

In addition, to xdhmoore's answers, for those not too familiar with creating configurations in launch.json, it should look as follows:

"configurations": [
    ...,
    {
        "name": "Python: Remote Attach",
        "type": "python",
        "request": "attach",
        "host": "127.0.0.1",
        "port": 5678

    }
]

To start debugging, first issue the command line command in the terminal and then launch the (newly created) launch configuration Python: Remote Attach from the debug launch menu in VS Code.

Versify answered 14/1, 2022 at 8:24 Comment(0)
B
0

I had a similar problem in VS 2019. I wanted to start python file with arguments in environment generated by VS. I wasn't able to find good simple solution, so basically I went to ENV\Scripts folder, opened terminal there and run

python "FullPath\MyFile.py" -some arguments

It works OK, but VS needs to be closed.

Bombardier answered 9/1, 2023 at 19:50 Comment(1)
This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From ReviewWhelm
E
0

An easy solution is to use the %run magic command.

For example:

%run demo.py arg1 arg2

You can run it in the input editor (prompt) of the interactive window.

  1. Focus the input editor with Interactive Window: Focus Input Editor
  2. Type the command and execute it with Shift Enter. If you already typed it once, you can recall it with the arrow up key.
  3. As you can see on the picture, sys.args contains the arguments specified in the command.
  4. You can bring the focus back to the program with View: Focus Previous Editor Group and you can reuse it next time you want to run again.

VSCode execute file from Input Editor

Another possibility is to run the command from a selection.

  1. Create a comment with the command
  2. Select it without the comment character
  3. Execute the selection with Jupyter: Run Selection/Line in Interactive Window.
  4. As you can see on the picture, sys.args contains the arguments specified in the command.

Execute file from selection

Note that the file must be saved. This is not the case when using the command Jupyter: Run Current File in Interactive Window.

With a block comment, it’s even simpler because you don’t need to select the command, you just need the cursor to be on the line of the command.

"""
%run demo.py arg1 arg2
"""
Ellie answered 4/3 at 14:46 Comment(0)
B
-2

If you are using a virtual environment, be sure to use the full path to the environment's Python interpreter.

Bolide answered 20/4, 2020 at 20:44 Comment(0)
K
-6

Maybe this will do what you want: create a python.bat file in your %PATH% that points to python.exe:

C:\Users\joecoder\AppData\Local\Programs\Python\Python37\python.exe %*

Then use a Visual Studio Code terminal window (you can open a new one from the Terminal tab at the top of Visual Studio Code) to change directory to where your .py file resides, and run as normal:

PS C:\Users\joecoder> cd vscode\python
PS C:\Users\joecoder\vscode\python> python test.py 1 2 3

Of course this runs outside of Visual Studio Code, so be sure to write out changes after edits and you'll have to use print() style debugging.

Kos answered 10/9, 2019 at 17:35 Comment(2)
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 :)Kos
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.Askari

© 2022 - 2024 — McMap. All rights reserved.