Python | How to Parse Command-Line Options
In this article, we will discuss how to write a Python program to parse options supplied on the command line (found in sys.argv). The argparse module can be used to parse command-line options.
Code #1 : Using argparse module
''' 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 –
bash % python3 search.py -h
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
Observe the output of the print() statements.
Code: The following session shows how data shows up in the program.
bash % python3 search.py foo.txt bar.txt
usage: search.py [-h] -p pattern [-v] [-o OUTFILE]
[--speed {fast, slow}] [filename [filename ...]]
search.py: error: the following arguments are required: -p/--pat
bash % python3 search.py -v -p spam --pat = eggs
foo.txt bar.txt
filenames = ['foo.txt', 'bar.txt']
patterns = ['spam', 'eggs']
verbose = True
outfile = None
speed = slow
bash % python3 search.py -v -p spam --pat = eggs
foo.txt bar.txt -o results
filenames = ['foo.txt', 'bar.txt']
patterns = ['spam', 'eggs']
verbose = True
outfile = results
speed = slow
bash % python3 search.py -v -p spam --pat = eggs
foo.txt bar.txt -o results \--speed = fast
filenames = ['foo.txt', 'bar.txt']
patterns = ['spam', 'eggs']
verbose = True
outfile = results
speed = fast
- 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.
Code : Argument collects all of the extra command-line arguments into a list. It’s being used to make a list of filenames
parser.add_argument(dest = 'filenames', metavar = 'filename', nargs = '*') |
Code : Argument sets a Boolean flag depending on whether or not the argument was provided
parser.add_argument('-v', dest = 'verbose', action = 'store_true', help = 'verbose mode') |
Code : Argument takes a single value and stores it as a string
parser.add_argument('-o', dest = 'outfile', action = 'store', help = 'output file') |
The following argument specification allows an argument to be repeated multiple times and all of the values append into a list. The required flag means that the argument must be supplied at least once.
Recommended Posts:
- Python | Execute and parse Linux commands
- Python | Parse a website with regex and urllib
- NLP | Using dateutil to parse dates.
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Index of Non-Zero elements in Python list
- Python | Convert list to Python array
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to Python Libraries
- Python | Add Logging to a Python Script
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Visualizing O(n) using Python
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- abs() in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



