Python Command-Line Arguments
Python command-line arguments allow users to provide input directly when running a Python script from a terminal or command prompt. Instead of changing values inside the source code, users can pass filenames, options, configuration values, and other parameters while launching the program.
Python provides several ways to work with command-line input. The sys, getopt, and argparse modules are commonly used for this purpose, while libraries such as docopt and fire provide additional approaches for creating command-line interfaces.
Table of Contents

What Are Command-Line Arguments?
Command-line arguments are values supplied to a Python program when it is executed through a command-line interface. They make scripts more flexible because users can change the input without modifying the program itself.
For example, a script can receive a filename, enable a particular option, or accept a configuration value directly from the command line.
Common Python Modules for Command-Line Arguments
Python offers different modules for handling command-line input. The appropriate choice depends on how simple or advanced the command-line interface needs to be.
1. Python sys Module
The sys module provides a straightforward way to access command-line arguments through sys.argv. This value is a list containing the arguments supplied when the script was started.
sys.argv[0]contains the script name.sys.argv[1]and subsequent elements contain the supplied arguments.
Arguments are normally separated by spaces. If an argument contains spaces, it should be enclosed in quotation marks.
Example
import sys
print(type(sys.argv))
print("The command-line arguments are:")
for arg in sys.argv:
print(arg)
When the program is executed as python script.py arg1 arg2, the output is:
<class 'list'>
The command-line arguments are:
script.py
arg1
arg2
The sys module is useful when you need simple access to command-line arguments without building a complete argument parser.
2. Python getopt Module
The getopt module provides more structured argument parsing than directly using sys.argv. It supports both short options, such as -h, and long options, such as --help.
Example
import getopt
import sys
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(
argv,
'hm:d',
['help', 'my_file=']
)
print('Options:', opts)
print('Arguments:', args)
except getopt.GetoptError:
print('Error in parsing arguments!')
sys.exit(2)
For a command such as python script.py -h -m my_value --my_file=input.txt, the output is:
Options: [('-h', ''), ('-m', 'my_value'), ('--my_file', 'input.txt')]
Arguments: []
getopt is useful when a program needs to recognize options and positional arguments in a structured way.
3. Python argparse Module
The argparse module provides a more complete approach to building command-line interfaces. It can create help messages, process argument values, and handle invalid input.
Example
import argparse
parser = argparse.ArgumentParser(
description='Example script using argparse'
)
parser.add_argument(
'-f',
'--file',
help='Specify a file name'
)
parser.add_argument(
'-v',
'--verbose',
action='store_true',
help='Enable verbose mode'
)
args = parser.parse_args()
if args.file:
print(f"File name: {args.file}")
if args.verbose:
print("Verbose mode is enabled")
Running the script with python script.py -f myfile.txt -v produces:
File name: myfile.txt
Verbose mode is enabled
The argparse module is suitable for creating organized and user-friendly command-line programs.
Additional Python Modules
4. docopt
docopt provides a different approach to command-line parsing by using a program’s usage documentation to describe its command-line interface.
Example
from docopt import docopt
__doc__ = """
Usage:
my_program.py [--option1] [--option2=<value>] <argument>
Options:
-h, --help Show this help message.
-o, --option1 Enable option 1.
-t, --option2=<value> Specify option 2 value.
"""
if __name__ == '__main__':
arguments = docopt(__doc__, version='1.0')
print(arguments)
When executed with python script.py --option1 --option2=value argument_value, the resulting argument data is:
{
'--help': False,
'--option1': True,
'--option2': 'value',
'<argument>': 'argument_value'
}
5. fire
fire can simplify the process of creating command-line interfaces from Python objects. It can expose methods and functionality through command-line commands with relatively little code.
Example
import fire
class Python:
def hello(self):
print("Hello")
def openfile(self, filename):
print(f"Open file '{filename}'")
if __name__ == '__main__':
fire.Fire(Python)
Example commands and their output:
$ python script.py hello
Hello
$ python script.py openfile my_file.txt
Open file 'my_file.txt'
Comparison of Python Command-Line Modules
| Module | Purpose | Python Version | Key Features |
|---|---|---|---|
sys | Basic argument handling | All | Simple list of arguments |
argparse | Advanced CLI building | >= 2.3 | User-friendly and automatically generated help |
getopt | C-style argument parsing | All | Supports short and long options |
docopt | CLI creation through documentation strings | >= 2.5 | Parses arguments from usage documentation |
fire | Automatic CLI generation | All | Creates command-line functionality with minimal code |
Complete Advance AI Topics: Click Here
SQL Tutorial: Click Here
YT:- DecodeIT
Frequently Asked Questions
1. What are command-line arguments in Python?
Command-line arguments are values passed to a Python script when it is executed from a terminal or command prompt.
2. How does sys.argv work in Python?
sys.argv stores command-line input in a list. The first element contains the script name, while the following elements contain the supplied arguments.
3. What is argparse used for?
argparse is used to create structured command-line interfaces with argument parsing, help messages, and input handling.
4. What is the difference between sys.argv and argparse?
sys.argv provides direct access to command-line arguments, while argparse provides tools for defining, parsing, and documenting arguments in a more structured way.
5. What is the getopt module in Python?
getopt is a module for parsing command-line options and supports both short and long option formats.
6. What is docopt?
docopt creates command-line interfaces by using a usage description and parsing arguments according to that documentation.
7. What is Python Fire?
Python Fire is a library that can automatically create command-line interfaces from Python objects and their methods.
Conclusion
Python command-line arguments provide a practical way to make scripts configurable and interactive without changing their source code. The sys module is useful for straightforward argument access, while getopt provides structured option parsing.
For more feature-rich command-line programs, argparse provides argument definitions, help messages, and parsing support. Tools such as docopt and fire offer alternative approaches for building command-line interfaces. Choosing the appropriate method depends on the complexity and requirements of your Python application.
Keywords: Python Command-Line Arguments, python argparse, python command line arguments example, python command line arguments parser, python command line arguments list, python command line arguments W3Schools, python argparse example, python arguments, python command line arguments, Python Command-Line Arguments tutorial, Python command-line parser