Articles

Command Line Arguments in Python (sys.argv, argparse)

Learn how to use Python command line arguments with `sys.argv`, `getopt`, and `argparse`. Compare each method and build flexible, user-friendly scripts with real examples.

What are command line arguments in Python?

How can you customize your Python scripts to handle tasks without rewriting code? Command-line arguments are the answer!

Python Command line arguments are parameters passed to a script when it’s executed from the command line interface. These arguments allow users to customize how a Python program runs without modifying the source code. By accepting command line arguments, Python scripts become more flexible, reusable, and suitable for automation.

For example, you can process a specific file or configure settings without changing the script to make the program more dynamic and adaptable.

Python provides three main ways to handle command-line arguments:

  1. sys.argv: A simple way to access command-line arguments as a list of strings.
  2. getopt: A built-in module for parsing command-line options and arguments in a structured way.
  3. argparse: An advanced and flexible module that provides built-in validation, help messages, and better argument handling.

Now, let’s look at how to handle command-line arguments in Python, starting with sys.argv.

Related Course

Data Visualization with Python: Visual Arguments

Learn good design principles for telling a visual story with data using Matplotlib.Try it for free

Using Python’s sys.argv module

sys.argv is a list that stores command-line arguments passed to a Python script. The first element, sys.argv[0], represents the script name, while the remaining elements are the actual arguments provided by the user. These arguments are always treated as strings, so they may need to be converted to the appropriate data types when working with numbers or other values.

Syntax for sys.argv in Python is:

import sys   

# Accessing command-line arguments   
arguments = sys.argv  # List of arguments   
script_name = sys.argv[0]  # Name of the script   

# Checking if an argument is provided before accessing it   
if len(sys.argv) > 1:   
  first_argument = sys.argv[1]  # First argument   
else:   
  first_argument = None  # No argument provided 

Let’s look at an example to understand how sys.argv works in practice:

import sys
# Ensure that the correct number of arguments is provided
if len(sys.argv) < 3:
print("Usage: python script.py <number1> <number2>")
sys.exit(1)
# Retrieve the script name and the two numbers from sys.argv
script_name = sys.argv[0]
number1 = float(sys.argv[1])
number2 = float(sys.argv[2])
# Display the script name and the numbers received
print("Script Name:", script_name)
print("First Number:", number1)
print("Second Number:", number2)
# Multiply the two numbers
product = number1 * number2
print("Product:", product)

Run this script using the following command:

python script.py 3.5 2

The output will be:

Script Name: script.py
First Number: 3.5
Second Number: 2.0
Product: 7.0

This script takes two numbers as command-line arguments, multiplies them, and prints the result, without needing to rewrite the code every time you want to multiply different numbers.

Note: Always check the length of sys.argv before accessing indices to avoid IndexError.

While sys.argv works for basic argument handling, it lacks structure when handling optional arguments or flags. The getopt module helps by providing a more organized way to parse command-line arguments.

Using Python’s getopt module

With getopt, scripts can accept short (-f) and long (--file) options, making argument handling more structured and flexible. It lets you define which options your script should expect and whether those options need associated values. This means you can control the inputs more strictly and provide a better user experience.

Syntax for getopt in Python is:

getopt.getopt(args, short_options, long_options) 

Parameters:

  • args: List of command-line arguments (typically sys.argv[1:]).
  • short_options: A string of single-character options. A colon (:) after a character indicates it requires a value (e.g., "f:o:" for -f <value> and -o <value>).
  • long_options: List of long-form options with = if they require values (e.g., ["file=", "output="]).

Here’s an example of how getopt works:

import sys
import getopt
try:
opts, args = getopt.getopt(sys.argv[1:], "f:o:", ["file=", "output="])
except getopt.GetoptError as err:
print(f"Error: {err}")
sys.exit(1)
for opt, arg in opts:
if opt in ("-f", "--file"):
print(f"Input file: {arg}")
elif opt in ("-o", "--output"):
print(f"Output file: {arg}")

On running the following command in the terminal:

python script.py -f input.txt --output result.txt

The output will be:

Input file: input.txt
Output file: result.txt

This script uses getopt to parse command-line options for specifying input and output files. It supports short (-f, -o) and long (--file, --output) flags for flexible script customization.

However, getopt still requires manual error handling and lacks built-in help messages. To simplify argument parsing further, Python provides argparse, which we’ll explore next.

Using Python’s argparse module

The argparse module, introduced in Python 2.7, simplifies command-line argument handling by offering built-in support for required and optional arguments, flags, automatic help messages, and type validation.

The key features of argparse are as follows:

  • Positional and optional arguments: Helps to define required inputs and optional parameters.
  • Short and long-form flags: Supports for both -v and --verbose.
  • Automatic help messages: The --help flag is generated automatically.
  • Type validation and default values: Ensures correct input types and provides fallback values.

Syntax for argparse is:

import argparse 

parser = argparse.ArgumentParser(description="Script description here") 

parser.add_argument("positional_arg", help="Description of positional argument") 

parser.add_argument("-o", "--optional", help="Description of optional argument") 

parser.add_argument("-f", "--flag", action="store_true", help="Boolean flag argument") 

args = parser.parse_args() 

print(args.positional_arg, args.optional, args.flag) 

Here,

  • argparse.ArgumentParser: Creates a new argument parser object.

    • description: A short text explaining what the script does (shown in --help)
  • add_argument: Defines the arguments the script accepts.

    • filename: A positional argument (must be provided).
    • help: A description shown in --help.
    • "-o", "--optional": Specifies an optional argument that users can provide.
    • "-f", "--flag": Defines a flag that users can use.
    • action="store_true": Sets the argument to True if present; otherwise, it defaults to False.
  • parse_args: Parses the command-line arguments and returns a Namespace object with attributes.

Now that you understand how to use argparse to handle inputs, let’s look at some common arguments you’ll use to customize your scripts.

Common arguments used with argparse

Here are some of the commonly used arguments with argparse:

Argument syntax Type Description
-h, --help Flag Displays the help message, showing all available arguments and their descriptions.
-v, --verbose Flag Enables verbose mode for more detailed output.
-o, --output String Specifies the output file or location.
-f, --file String Specifies a file to be processed.
-n, --num Integer Defines a numeric value for the argument.
-l, --log String Specifies a log level or log file.
-i, --input String Defines the input file or directory.
--overwrite Flag A Boolean flag to enable overwriting existing files.
-t, --timeout Integer Specifies the timeout period in seconds.
--config String Specifies a configuration file.

Let’s say we have a script argparse_output_example.py:

import argparse
# Initialize the ArgumentParser object
parser = argparse.ArgumentParser(
description="A script that takes an input file and an output file."
)
# Define the input argument
parser.add_argument("input", help="The input file to process.")
# Define the output argument
parser.add_argument(
"-o", "--output", help="The output file to save the results", required=True
)
# Parse the command-line arguments
args = parser.parse_args()
# Example processing
with open(args.input, "r") as infile:
data = infile.read()
# Writing the processed data to the output file
with open(args.output, "w") as outfile:
outfile.write(data)
print(f"Data from {args.input} has been written to {args.output}")

Use the following command to run the script:

python argparse_output_example.py input.txt -o output.txt

The output will be:

Data from input.txt has been written to output.txt

In this example, the script reads the contents of input.txt and writes it to output.txt. The -o argument lets the user specify the output file location. If the user omits the -o argument, the script throws an error, prompting them to specify it.

While sys.argv and getopt provide basic functionality for handling command-line arguments, argparse offers several advanced features, making it a more powerful and user-friendly option for building flexible, robust command-line interfaces.

sys.argv vs getopt vs argparse: Which command line argument method to use?

Choosing the correct method for handling command-line arguments depends on the complexity of the script and the features required. For smaller scripts, sys.argv may suffice, but for more advanced use cases involving multiple options, flags, and input validation, methods like getopt and argparse offer more structure and flexibility.

Here is a table that summarizes the key differences between sys.argv. getopt and argparse:

Feature sys.argv getopt argparse
Ease of use Easy to use, minimal functionality Moderate complexity, structured parsing Very user-friendly, with many built-in features
Argument types Handles only positional arguments Supports both short and long options Supports positional, optional arguments, flags, and more
Error handling Limited error handling (manual) Provides basic error handling Comprehensive error handling with auto-generated help messages
Help messages No built-in help support No built-in help support Auto-generates help messages (--help)
Argument validation No argument validation Requires manual validation Supports type validation and default values
Complexity Low Moderate High (but more powerful and flexible)
Support for flags Not natively supported Supports flags (-f, --flag) Supports flags and Boolean options
Flexibility Limited flexibility Moderate flexibility Highly flexible and customizable
Automatic documentation None None Built-in support for automatic help messages

Which method to use for handling command-line arguments in Python?

Conclusion

Command-line arguments in Python let you customize how your scripts run without changing the code itself. Depending on your needs, from simple scripts to complex applications, Python offers several ways to handle these arguments efficiently.

In this article, we explored three main methods for working with command-line arguments in Python:

  • sys.argv, which is straightforward and suited for positional arguments.

  • getopt, which introduces support for short and long options with basic error handling.

  • argparse, the most feature-rich option that provides input validation, automatic help messages, and flexible argument types.

Each method has its strengths, so picking the right one depends on how complex your script is and how user-friendly you want it to be.

To further explore the command line, check out the Learn the Command Line course from Codecademy and read about the commonly used command line commands.

Frequently asked questions

1. What is the difference between sys.argv, getopt, and argparse?

sys.argv provides basic access to command-line arguments as a list, suitable for simple needs. getopt supports short and long options with basic error handling. argparse offers advanced features like argument parsing, validation, and automatic help messages, ideal for complex scripts.

2. When should I use argparse instead of sys.argv or getopt?

Use argparse when your script requires user-friendly interfaces, multiple argument types, or automatic help and error messages. It’s best for scripts with complex or optional arguments.

3. Can I mix positional and optional arguments with these methods?

sys.argv can handle positional arguments only, while getopt and argparse support both positional and optional arguments, with argparse offering the most flexibility.

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team