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
1503
276
python connect to sql server pyodbc example python connect to sql server pyodbc example Jul 30, 2025 am 02:53 AM

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

What is statistical arbitrage in cryptocurrencies? How does statistical arbitrage work? What is statistical arbitrage in cryptocurrencies? How does statistical arbitrage work? Jul 30, 2025 pm 09:12 PM

Introduction to Statistical Arbitrage Statistical Arbitrage is a trading method that captures price mismatch in the financial market based on mathematical models. Its core philosophy stems from mean regression, that is, asset prices may deviate from long-term trends in the short term, but will eventually return to their historical average. Traders use statistical methods to analyze the correlation between assets and look for portfolios that usually change synchronously. When the price relationship of these assets is abnormally deviated, arbitrage opportunities arise. In the cryptocurrency market, statistical arbitrage is particularly prevalent, mainly due to the inefficiency and drastic fluctuations of the market itself. Unlike traditional financial markets, cryptocurrencies operate around the clock and their prices are highly susceptible to breaking news, social media sentiment and technology upgrades. This constant price fluctuation frequently creates pricing bias and provides arbitrageurs with

python shutil rmtree example python shutil rmtree example Aug 01, 2025 am 05:47 AM

shutil.rmtree() is a function in Python that recursively deletes the entire directory tree. It can delete specified folders and all contents. 1. Basic usage: Use shutil.rmtree(path) to delete the directory, and you need to handle FileNotFoundError, PermissionError and other exceptions. 2. Practical application: You can clear folders containing subdirectories and files in one click, such as temporary data or cached directories. 3. Notes: The deletion operation is not restored; FileNotFoundError is thrown when the path does not exist; it may fail due to permissions or file occupation. 4. Optional parameters: Errors can be ignored by ignore_errors=True

How to change the font size in vscode? How to change the font size in vscode? Aug 02, 2025 am 02:37 AM

TochangethefontsizeinVSCode,useoneofthesemethods:1.OpenSettingsviaCtrl ,(orCmd ,onMac),searchfor"fontsize",andadjustthe"Editor:FontSize"value.2.OpenSettings(JSON)fromtheCommandPalette,thenaddormodify"editor.fontSize":e.g

How to use VSCode with WSL (Windows Subsystem for Linux) How to use VSCode with WSL (Windows Subsystem for Linux) Aug 01, 2025 am 06:26 AM

InstallWSLandaLinuxdistributionbyrunningwsl--installinPowerShellasAdministrator,thenrestartandsetuptheLinuxdistribution.2.Installthe"Remote-WSL"extensioninVSCodetoenableintegrationwithWSL.3.OpenaprojectinWSLbylaunchingtheWSLterminal,navigat

How to execute SQL queries in Python? How to execute SQL queries in Python? Aug 02, 2025 am 01:56 AM

Install the corresponding database driver; 2. Use connect() to connect to the database; 3. Create a cursor object; 4. Use execute() or executemany() to execute SQL and use parameterized query to prevent injection; 5. Use fetchall(), etc. to obtain results; 6. Commit() is required after modification; 7. Finally, close the connection or use a context manager to automatically handle it; the complete process ensures that SQL operations are safe and efficient.

python read file line by line example python read file line by line example Jul 30, 2025 am 03:34 AM

The recommended way to read files line by line in Python is to use withopen() and for loops. 1. Use withopen('example.txt','r',encoding='utf-8')asfile: to ensure safe closing of files; 2. Use forlineinfile: to realize line-by-line reading, memory-friendly; 3. Use line.strip() to remove line-by-line characters and whitespace characters; 4. Specify encoding='utf-8' to prevent encoding errors; other techniques include skipping blank lines, reading N lines before, getting line numbers and processing lines according to conditions, and always avoiding manual opening without closing. This method is complete and efficient, suitable for large file processing

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

TorunaPythonscriptwithargumentsinVSCode,configurelaunch.jsonbyopeningtheRunandDebugpanel,creatingoreditingthelaunch.jsonfile,andaddingthedesiredargumentsinthe"args"arraywithintheconfiguration.2.InyourPythonscript,useargparseorsys.argvtoacce

See all articles