Table of Contents
✅ 1. Use launch.json to Pass Arguments
Steps:
✅ 2. Access Arguments in Your Python Script
Example using argparse:
✅ 3. Alternative: Run via Terminal (Manual)
✅ 4. Pro Tips
Summary
Home Development Tools VSCode How to run Python script with arguments in VSCode

How to run Python script with arguments in VSCode

Jul 30, 2025 am 04:11 AM
python vscode

To run a Python script with arguments in VSCode, configure launch.json by opening the Run and Debug panel, creating or editing the launch.json file, and adding the desired arguments in the "args" array within the configuration. 2. In your Python script, use argparse or sys.argv to access the passed arguments, ensuring they match the order and format specified in launch.json. 3. Alternatively, manually run the script with arguments in the VSCode integrated terminal using the command python your_script.py arg1 --option value for quick tests without debugging. 4. For best results, use "${file}" to target the current file, set "console": "integratedTerminal" for clear I/O visibility, and create multiple configurations for different argument sets like "Test Mode" or "Prod Mode". Once launch.json is set up, you can reliably run and debug scripts with arguments using F5, leveraging standard VSCode and Python extension features without needing additional tools.

How to run Python script with arguments in VSCode

Running a Python script with arguments in VSCode is straightforward once you set up the configuration properly. Here's how to do it step by step.

How to run Python script with arguments in VSCode

✅ 1. Use launch.json to Pass Arguments

The most common and reliable way to run a Python script with command-line arguments in VSCode is by configuring a debug launch setting using launch.json.

Steps:

  1. Open the Run and Debug panel
    Click on the "Run and Debug" icon in the Activity Bar (or press Ctrl Shift D).

    How to run Python script with arguments in VSCode
  2. Create a launch.json file
    If you don’t already have one:

    • Click "create a launch.json file"
    • Select Python as the environment
    • Choose "Python File" (it uses the currently selected file)
  3. Edit the configuration to include arguments
    Modify the args array in launch.json to include your command-line arguments.

    How to run Python script with arguments in VSCode
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Run with Args",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "args": [
                "arg1_value",
                "arg2_value",
                "--option", "true"
            ]
        }
    ]
}

? Replace "arg1_value", etc., with the actual values you want to pass.

  1. Start debugging
    Press F5 or click the "Run" button in the Debug panel — your script will run with the specified arguments.

✅ 2. Access Arguments in Your Python Script

Make sure your script uses sys.argv or argparse to read the arguments.

Example using argparse:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("input_file")
parser.add_argument("--option", default="false")

args = parser.parse_args()

print(f"Input file: {args.input_file}")
print(f"Option: {args.option}")

With the launch.json config above, this would receive:

  • input_file = "arg1_value"
  • --option = "true"

✅ 3. Alternative: Run via Terminal (Manual)

If you don't want to use the debugger, you can manually run your script in the VSCode integrated terminal:

python your_script.py arg1 arg2 --flag value

This is quick for testing, but not ideal if you want consistent setups or debugging.


✅ 4. Pro Tips

  • Use ${file} in launch.json so it always runs the currently open Python file.
  • Set "console": "integratedTerminal" to see input/output clearly.
  • You can create multiple configurations for different argument sets (e.g., "Test Mode", "Prod Mode").

Summary

Method Best For
launch.json with args Debugging with arguments
Integrated Terminal Quick manual runs
Multiple configs Testing different inputs

Just set up launch.json once, and you can easily run and debug scripts with arguments anytime.

Basically, that’s it — no extensions needed, just standard VSCode Python extension.

The above is the detailed content of How to run Python script with arguments in VSCode. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
What are class methods in Python What are class methods in Python Aug 21, 2025 am 04:12 AM

ClassmethodsinPythonareboundtotheclassandnottoinstances,allowingthemtobecalledwithoutcreatinganobject.1.Theyaredefinedusingthe@classmethoddecoratorandtakeclsasthefirstparameter,referringtotheclassitself.2.Theycanaccessclassvariablesandarecommonlyused

How to debug a Rust program in VSCode How to debug a Rust program in VSCode Aug 22, 2025 am 09:33 AM

Yes, VSCode can debug Rust programs, but it requires installing rust-analyzer, CodeLLDB extension and lldb or gdb debugger. After configuring launch.json and setting breakpoints, you can start debugging through F5, check variables, step-by-step execution and evaluate expressions. Although it is not as convenient as JavaScript and other languages, efficient debugging can be achieved through correct configuration.

python asyncio queue example python asyncio queue example Aug 21, 2025 am 02:13 AM

asyncio.Queue is a queue tool for secure communication between asynchronous tasks. 1. The producer adds data through awaitqueue.put(item), and the consumer uses awaitqueue.get() to obtain data; 2. For each item you process, you need to call queue.task_done() to wait for queue.join() to complete all tasks; 3. Use None as the end signal to notify the consumer to stop; 4. When multiple consumers, multiple end signals need to be sent or all tasks have been processed before canceling the task; 5. The queue supports setting maxsize limit capacity, put and get operations automatically suspend and do not block the event loop, and the program finally passes Canc

How to debug a Scala application in VSCode How to debug a Scala application in VSCode Aug 21, 2025 pm 03:36 PM

Yes, VSCode can debug Scala applications through Metals extension. First, install the Metals extension and import the Scala project. Make sure to enable the debug adapter and enable metals.enable-debugging-features in the settings. Then set breakpoints in the main method or test. Start debugging through the "Debug" option of F5 or the code lens. Debug parameters can be configured with launch.json to support local running and remote JVM additional debugging. During debugging, pay attention to ensuring that the code is executed and the build has been imported successfully, and finally implement variable checking and single-step execution functions similar to other IDEs.

How to debug a shell script in VSCode How to debug a shell script in VSCode Aug 17, 2025 am 03:57 AM

InstalltheShellScriptextensioninVSCodeforsyntaxhighlightingandShellCheckintegration.2.InstallShellCheckonyoursystem(viaapt,brew,orapk)tocatchsyntaxerrorsandunsafepatterns.3.Enabledebuggingbyaddingset-xinyourscriptorrunningitwithbash-x./script.shtotra

How to debug a Perl script in VSCode How to debug a Perl script in VSCode Aug 23, 2025 am 06:23 AM

Yes,debuggingaPerlscriptinVSCodeispossibleusingthePerlDebugAdapterandPerlLanguageServerdespitelackingnativesupport.First,ensurePerlisinstalledandverifywithperl-v,theninstallthePerl::LanguageServermoduleviacpanPerl::LanguageServerorcpanmPerl::Language

How to run a Python script and see the output in a separate panel in Sublime Text? How to run a Python script and see the output in a separate panel in Sublime Text? Aug 17, 2025 am 06:06 AM

ToseePythonoutputinaseparatepanelinSublimeText,usethebuilt-inbuildsystembysavingyourfilewitha.pyextensionandpressingCtrl B(orCmd B).2.EnsurethecorrectbuildsystemisselectedbygoingtoTools→BuildSystem→Pythonandconfirming"Python"ischecked.3.Ifn

How to use the problems panel in VSCode How to use the problems panel in VSCode Aug 20, 2025 am 03:58 AM

TheProblemspanelinVSCodeisaccessedviathe"Problems"icon,Ctrl Shift M(orCmd Shift M),orView>Problems,whereitdisplayserrors,warnings,andsuggestionsgroupedbyfileandsortedbyseverity;1)Clickinganissuenavigatesdirectlytoitslocationincode,2)Prob

See all articles