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

? 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:
-
Open the Run and Debug panel
Click on the "Run and Debug" icon in the Activity Bar (or pressCtrl Shift D
). -
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)
-
Edit the configuration to include arguments
Modify theargs
array inlaunch.json
to include your command-line arguments.
{ "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.
- Start debugging
PressF5
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}
inlaunch.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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

pandas.melt() is used to convert wide format data into long format. The answer is to define new column names by specifying id_vars retain the identification column, value_vars select the column to be melted, var_name and value_name, 1.id_vars='Name' means that the Name column remains unchanged, 2.value_vars=['Math','English','Science'] specifies the column to be melted, 3.var_name='Subject' sets the new column name of the original column name, 4.value_name='Score' sets the new column name of the original value, and finally generates three columns including Name, Subject and Score.

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

VSCodeisalightweight,cross-platformcodeeditorwithIDE-likefeaturesviaextensions,idealforwebandopen-sourcedevelopment;2.VisualStudioisafull-featured,Windows-onlyIDEdesignedforcomplex.NET,C ,andenterpriseapplications;3.VSCodeperformsfasteronlower-endma

First, define a ContactForm form containing name, mailbox and message fields; 2. In the view, the form submission is processed by judging the POST request, and after verification is passed, cleaned_data is obtained and the response is returned, otherwise the empty form will be rendered; 3. In the template, use {{form.as_p}} to render the field and add {%csrf_token%} to prevent CSRF attacks; 4. Configure URL routing to point /contact/ to the contact_view view; use ModelForm to directly associate the model to achieve data storage. DjangoForms implements integrated processing of data verification, HTML rendering and error prompts, which is suitable for rapid development of safe form functions.

Gotohttps://code.visualstudio.comanddownloadtheWindowsUserInstaller.2.Runthe.exefile,allowchanges,andselectrecommendedoptionsincludingaddingtoPATHandcreatingadesktopshortcut.3.ClickFinishtolaunchVSCodeafterinstallation.4.Optionallyinstallusefulextens

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

Use psycopg2.pool.SimpleConnectionPool to effectively manage database connections and avoid the performance overhead caused by frequent connection creation and destruction. 1. When creating a connection pool, specify the minimum and maximum number of connections and database connection parameters to ensure that the connection pool is initialized successfully; 2. Get the connection through getconn(), and use putconn() to return the connection to the pool after executing the database operation. Constantly call conn.close() is prohibited; 3. SimpleConnectionPool is thread-safe and is suitable for multi-threaded environments; 4. It is recommended to implement a context manager in combination with context manager to ensure that the connection can be returned correctly when exceptions are noted;
