argparse
The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages. The module will also issue errors when users give the program invalid arguments.reference here link
argparse.ArgumentParser()
parser = argparse.ArgumentParser(
prog='ProgramName',
description='What the program does',
epilog='Text at the bottom of help')
Example
ArgumentParser.add_argument
method attaches individual argument specifications to the parser. It supports positional arguments, options that accept values, and on/off flags:
Quick Links for add_argument()
Name |
Description |
Values |
---|---|---|
Specify how an argument should be handled |
|
|
Limit values to a specific set of choices |
|
|
Store a constant value |
||
Default value used when an argument is not provided |
Defaults to |
|
Specify the attribute name used in the result namespace |
||
Help message for an argument |
||
Alternate display name for the argument as shown in help |
||
Number of times the argument can be used |
|
|
Indicate whether an argument is required or optional |
|
|
Automatically convert an argument to the given type |
Example 1
import argparse
parser = argparse.ArgumentParser(description='Here are the Camera Settings')
parser.add_argument('--imgdir', help = 'Folder to store images in',default='Pics')
parser.add_argument('--resolution',help = 'Desired resloution',default='1280x720')
args = parser.parse_args()
print(args.imgdir)
print(args.resolution)
Example 2
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Assuming the above Python code is saved into a file called prog.py
, it can be run at the command line and it provides useful help messages:
$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]
Process some integers.
positional arguments:
N an integer for the accumulator
options:
-h, --help show this help message and exit
--sum sum the integers (default: find the max)
When run with the appropriate arguments, it prints either the sum or the max of the command-line integers:
$ python prog.py 1 2 3 4
4
$ python prog.py 1 2 3 4 --sum
10
If invalid arguments are passed in, an error will be displayed:
$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'