Python | How to Parse Command-Line Options
Last Updated :
13 Sep, 2022
In this article, we will discuss how to write a Python program to parse options supplied on the command line (found in sys.argv).
Parsing command line arguments using Python argparse module
The argparse module can be used to parse command-line options. This module provides a very user-friendly syntax to define input of positional and keyword arguments.
Example: Sample program to take command line inputs using argparse module
Python3
'''
Hypothetical command-line tool for searching a
collection of files for one or more text patterns.
'''
import argparse
parser = argparse.ArgumentParser(description ='Search some files')
parser.add_argument(dest ='filenames', metavar ='filename', nargs ='*')
parser.add_argument('-p', '--pat', metavar ='pattern',
required = True, dest ='patterns',
action ='append',
help ='text pattern to search for')
parser.add_argument('-v', dest ='verbose',
action ='store_true', help ='verbose mode')
parser.add_argument('-o', dest ='outfile',
action ='store', help ='output file')
parser.add_argument('--speed', dest ='speed',
action ='store', choices = {'slow', 'fast'},
default ='slow', help ='search speed')
args = parser.parse_args()
The program mentioned above defines a command-line parser with the following usage:
usage: search.py [-h] [-p pattern] [-v] [-o OUTFILE]
[--speed {slow, fast}] [filename [filename ...]]
Search some files
positional arguments:
filename
optional arguments:
-h, --help show this help message and exit
-p pattern, --pat pattern
text pattern to search for
-v verbose mode
-o OUTFILE output file
--speed {slow, fast} search speed
Note: Generally, argparse defines a --help option to print out all accepted arguments and their details. It will print all details about accepted arguments if we execute the script as follows:
python script_name.py --help
Code: The following session shows how data shows up in the program.
usage: search.py [-h] -p pattern [-v] [-o OUTFILE]
[--speed {fast, slow}] [filename [filename ...]]
Input:
python3 search.py -v -p spam --pat = eggs foo.txt bar.txt
Output:
filenames = ['foo.txt', 'bar.txt']
patterns = ['spam', 'eggs']
verbose = True
outfile = None
speed = slow
- The argparse module is one of the largest modules in the standard library, and has a huge number of configuration options. This codes above show an essential subset that can be used and extended to get started.
- To parse options, you first create an ArgumentParser instance and add declarations for the options you want to support it using the add_argument() method.
- In each add_argument() call, the dest argument specifies the name of an attribute where the result of parsing will be placed.
- The metavar argument is used when generating help messages.
- The action argument specifies the processing associated with the argument and is often store for storing a value or append for collecting multiple argument values into a list.
Argument collects all the extra command-line arguments into a list. It’s being used to make a list of filenamesÂ
Python3
parser.add_argument(dest = 'filenames',
metavar = 'filename', nargs = '*')
Argument sets a Boolean flag depending on whether the argument was providedÂ
Python3
parser.add_argument('-v', dest = 'verbose',
action = 'store_true',
help = 'verbose mode')
Argument takes a single value and stores it as a string
Python3
parser.add_argument('-o', dest = 'outfile',
action = 'store', help = 'output file')
Similar Reads
How to Pass Optional Parameters to a Function in Python In Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar
5 min read
Pandas.get_option() function in Python Pandas have an options system that lets you customize some aspects of its behavior, display-related options being those the user is most likely to adjust. Let us see how to see the value of a specified option. get_option() Syntax : pandas.get_option(pat)Parameters :Â pat : Regexp which should match
2 min read
Optparse module in Python Optparse module makes easy to write command-line tools. It allows argument parsing in the python program. optparse make it easy to handle the command-line argument.It comes default with python.It allows dynamic data input to change the output Code: Creating an OptionParser object. Python3 import op
3 min read
Command Line Scripts | Python Packaging How do we execute any script in Python? $ python do_something.py $ python do_something_with_args.py gfg vibhu Probably that's how you do it. If your answer was that you just click a button on your IDE to execute your Python code, just assume you were asked specifically how you do it on command line.
4 min read
Pass list as command line argument in Python The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. One of them is sys module. sys Module A module is a file containing Python definiti
3 min read
Command-Line Option and Argument Parsing using argparse in Python Command line arguments are those values that are passed during the calling of the program along with the calling statement. Usually, python uses sys.argv array to deal with such arguments but here we describe how it can be made more resourceful and user-friendly by employing argparse module. Python
7 min read
Python | Execute and parse Linux commands Prerequisite: Introduction to Linux Shell and Shell Scripting Linux is one of the most popular operating systems and is a common choice for developers. It is popular because it is open source, it's free and customizable, it is very robust and adaptable. An operating system mainly consists of two par
6 min read
Command Line Interface Programming in Python This article discusses how you can create a CLI for your python programs using an example in which we make a basic "text file manager". Let us discuss some basics first. What is a Command Line Interface(CLI)? A command-line interface or command language interpreter (CLI), also known as command-line
7 min read
Pandas.describe_option() function in Python Pandas has an options system that lets you customize some aspects of its behavior, display-related options being those the user is most likely to adjust. Let us see how to see the description of a specified option. describe_option()  Syntax : pandas.describe_option(pat, _print_desc = False)Paramet
1 min read
Command Line Arguments in Python The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are: Table of ContentUsing sys.argvUsing getopt moduleUsing a
5 min read