Python Command-Line Arguments - sys.argv and argparse


Introduction

Command-line arguments are a way to interact with Python scripts and provide input parameters when executing them. Python offers two main modules for handling command-line arguments: sys.argv and argparse. In this guide, we'll explore how to use both methods for parsing and handling command-line arguments in Python.


Prerequisites

Before you begin, make sure you have the following prerequisites in place:

  • Python Installed: You should have Python installed on your local environment.
  • Basic Python Knowledge: Understanding Python fundamentals is crucial for working with command-line arguments.

Using sys.argv

The sys.argv list provides access to command-line arguments. The first item (sys.argv[0]) is the script name, and subsequent items are the arguments passed to the script.


Sample Python Code with sys.argv

Here's a basic Python script that uses sys.argv to accept command-line arguments:

import sys
# Print the script name
print("Script Name:", sys.argv[0])
# Print all command-line arguments
print("Arguments:", sys.argv[1:])

Using argparse

The argparse module provides a more powerful and structured way to parse command-line arguments. It allows you to define expected arguments, options, and help messages.


Sample Python Code with argparse

Here's a basic Python script that uses argparse to define and parse command-line arguments:

import argparse
parser = argparse.ArgumentParser(description="A simple argument parser")
parser.add_argument('input', help='Input file')
parser.add_argument('--output', help='Output file', required=True)
args = parser.parse_args()
print("Input file:", args.input)
print("Output file:", args.output)


Conclusion

Handling command-line arguments in Python is a fundamental skill for script and application development. This guide has introduced you to both sys.argv and argparse, which can be used in various scenarios. As you continue to work with Python, you'll encounter numerous situations where effective command-line argument handling is invaluable.