Python enables the execution of scripts via the command line, allowing for the inclusion of command line arguments. These arguments serve as input parameters that must be provided to the script during its execution. This functionality facilitates interaction with a command-line interface for the scripts. There are several methods to utilize command line arguments, some of which include:
1. Python sys Module
This fundamental module is included in the Python distribution starting from its earlier versions. It operates in a manner akin to the C library, utilizing argc/argv to handle command-line arguments. The sys module provides a straightforward list structure known as sys.argv for managing these command-line inputs.
Every item in the list corresponds to an individual argument. The initial element, sys.argv[0], signifies the name of the Python script. The subsequent elements, ranging from sys.argv[1] to sys.argv[n], represent the command line arguments from 2 to n. Spaces are utilized as delimiters between these arguments. If an argument value includes a space, it must be enclosed in quotes appropriately.
It saves command-line arguments in a list format, which can be accessed through sys.argv. This method is quite beneficial and provides an uncomplicated means of retrieving command-line arguments as strings.
Python sys Module Example
Let us consider an example to illustrate the functionality of the sys module in Python.
import sys
# Check the type of sys.argv
print(type(sys.argv)) # <class ' list '>
# Print the command line arguments
print(' The command line arguments are: ')
# Iterate over sys.argv and print each argument
for i in sys.argv:
print(i)
Output:
<class ' list '>
The command line arguments are:
script.py
arg1
arg2
2. Python getopt Module
The Python getopt module enhances the parsing of input strings by implementing parameter validation. Modeled after the C function getopt, it supports both short and long options, allowing for the assignment of values as well.
It closely resembles the C function getopt utilized for analyzing command line parameters. This function proves to be advantageous when it comes to interpreting command line inputs, especially when we require users to specify certain options.
Python getopt Module Example
To illustrate the functionality of the getopt module in Python, we will consider a practical example.
import getopt
import sys
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
print(opts)
print(args)
except getopt.GetoptError:
# Print a message or do something useful
print('Something went wrong!')
sys.exit(2)
Output:
[('-h', ''), ('-m', 'my_value'), ('--my_file', 'input.txt')]
['arg1', 'arg2']
3. Python argparse Module
It provides a command-line interface that generates standardized output, in contrast to the previous two solutions that require you to handle much of the work manually. The argparse library facilitates the validation of both fixed and optional arguments, allowing for name verification in either UNIX or GNU formats. It is widely regarded as the optimal method for parsing command-line arguments. Additionally, it offers numerous features, including positional arguments, default values for arguments, help messages, and the ability to specify the data type of each argument, among others.
It simplifies the process of creating user-friendly command-line interfaces. It automatically produces help and usage notifications and raises errors when a user provides incorrect arguments to the application. This facilitates communication between the program's developer and the end user without necessitating alterations to the code or modifications to the script. It also grants users the capability to input command-line arguments.
Python argparse Module Example
To illustrate the functionality of the argparse module in Python, let us consider a specific example.
import argparse
# Create an ArgumentParser object
parser = argparse.ArgumentParser(description = 'Example script using argparse')
# Add arguments
parser.add_argument('-f', '--file', help = 'Specify a file name')
parser.add_argument('-v', '--verbose', action = 'store_true', help = 'Enable verbose mode')
# Parse the command line arguments
args = parser.parse_args()
# Access the argument values
if args.file:
print(f "File name : {args.file} ")
if args.verbose:
print("Verbose mode is enabled")
Output:
python script.py -f myfile.txt -v
File name : myfile.txt
Verbose mode is enabled
The three mentioned above are the typical foundational modules for handling command line arguments in Python. Additionally, there are other straightforward modules in Python that facilitate command line arguments, including:
4. Docopt Module
Docopt serves the purpose of developing command line interfaces. It streamlines the task of interpreting command-line arguments and producing help documentation. Before utilizing docopt, it is necessary to install the library. You can accomplish this installation through pip:
Python Docopt Module Example
To illustrate the usage of the docopt module in Python, let us consider an 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 = 'Example 1')
print(arguments)
Output:
$ python script.py --option1 --option2=value argument_value
{
'--help': False,
'--option1': True,
'--option2': 'value',
'': ' argument_value ',
'--version': False
}
5. Fire Module
Python Fire facilitates the automatic creation of a command line interface with just a single line of code. In contrast to other libraries, it operates immediately. There is no requirement to specify any arguments, as all methods are interconnected by default. To install it, simply enter:
pip install fire
Define or use a class:
Python Fire Module Example
import fire
class Python(object):
def hello(self):
print("Hello")
def openfile(self, filename):
print(" Open file '" + filename + "'")
if __name__ == '__main__':
fire.Fire(Python)
Output:
$ python script.py hello
Hello
$ python script.py openfile my_file.txt
Open file 'my_file.txt'
Command Line arguments Modules
| Module | Use | Python version |
|---|---|---|
sys |
All arguments in sys.argv (basic) | All |
| argparse | Build a command line interface | >= 2.3 |
| docopt | Created command line interfaces | >= 2.5 |
fire |
Automatically generate command line interfaces (CLIs) | All |
| optparse | Deprecated | < 2.7 |