In Python, command-line arguments allow you to pass information to a Python script when running it from the command line or terminal. This is useful for making your script more dynamic and customizable without modifying the script itself.
Accessing Command-Line Arguments in Python:
Python provides the sys
module to handle command-line arguments. Specifically, the sys.argv
list holds the arguments passed to the script.
Syntax:
Steps to Use Command-Line Arguments:
- Import the
sys
Module: You need to importsys
to accesssys.argv
. - Run the Script with Arguments: When you run a Python script from the command line, you can pass additional arguments after the script name.
Example 1: Basic Example of Command-Line Arguments
Python Script (example.py):
How to run the script:
Output:
In this example, sys.argv
contains a list where:
sys.argv[0]
is the name of the script (example.py
),sys.argv[1:]
contains the arguments passed after the script name (arg1
,arg2
,arg3
).
Example 2: Using Command-Line Arguments in a Program
Here’s an example where we pass two numbers to the script and calculate their sum.
Python Script (sum.py):
How to run the script:
Output:
In this example:
- We use
sys.argv[1]
andsys.argv[2]
to fetch the two command-line arguments. - The script converts them to
float
to handle decimal numbers and calculates their sum.
Example 3: Using argparse
Module for Advanced Argument Parsing
For more complex command-line parsing (e.g., flags, optional arguments), you can use the argparse
module. This module provides a more structured way to handle arguments and automatically generates help messages.
Python Script (example_argparse.py):
How to run the script:
Output:
With argparse
, you can also add optional arguments, set default values, and automatically generate usage help.
Key Features of argparse
:
- Positional arguments: Arguments that are required and are passed in a specific order.
- Optional arguments: Arguments that are optional, typically with flags (e.g.,
-v
or--verbose
). - Help messages: Automatically generated help and usage documentation.
For example:
This will display the automatically generated help message:
Summary:
sys.argv
: A simple way to access command-line arguments as a list.argparse
: A powerful module for advanced command-line argument parsing, with features like help messages, optional arguments, and default values.
Using command-line arguments in Python makes your scripts more flexible and allows users to customize them without editing the code itself.