argparse_cli
argparse_cli
com/2/argparse/
PyMOTW
Home argparse – Command Page Contents
1 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
import argparse
parser = argparse.ArgumentParser
Defining Arguments
argparse is a complete argument processing
library. Arguments can trigger different
actions, specified by the action argument to
add_argument() . Supported actions include
storing the argument (singly, or as part of a
list), storing a constant value when the
argument is encountered (including special
handling for true/false values for boolean
switches), counting the number of times an Now available for Python 3!
argument is seen, and calling a callback.
Simple Examples
2 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
import argparse
parser = argparse.ArgumentParser
parser.add_argument('-a', action
parser.add_argument('-b', action
parser.add_argument('-c', action
print parser.parse_args(['-a',
$ python argparse_short.py
import argparse
parser = argparse.ArgumentParser
parser.add_argument('--noarg',
parser.add_argument('--witharg'
parser.add_argument('--witharg2'
$ python argparse_long.py
import argparse
parser = argparse.ArgumentParser
3 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
parser.add_argument('count', action
parser.add_argument('units', action
print parser.parse_args()
Namespace(count=3, units='inches')
$ python argparse_arguments.py
Argument Actions
store
store_const
store_true / store_false
append
append_const
4 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
version
import argparse
parser = argparse.ArgumentParser
parser.add_argument('-s', action
help='Store a simple value'
parser.add_argument('-c', action
const='value-to-store'
help='Store a constant valu
parser.add_argument('-t', action
dest='boolean_switch'
help='Set a switch to true'
parser.add_argument('-f', action
dest='boolean_switch'
help='Set a switch to false
parser.add_argument('-a', action
default=[],
help='Add repeated values t
)
parser.add_argument('-A', action
const='value-1-to-append'
default=[],
help='Add different values
parser.add_argument('-B', action
const='value-2-to-append'
help='Add different values
parser.add_argument('--version'
results = parser.parse_args()
print 'simple_value =', results
print 'constant_value =', results
print 'boolean_switch =', results
print 'collection =', results
print 'const_collection =', results
$ python argparse_action.py -h
optional arguments:
-h, --help show this help message and e
-s SIMPLE_VALUE Store a simple value
-c Store a constant value
-t Set a switch to true
-f Set a switch to false
-a COLLECTION Add repeated values to a lis
-A Add different values to list
-B Add different values to list
--version show program's version numbe
5 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
simple_value = value
constant_value = None
boolean_switch = False
collection = []
const_collection = []
$ python argparse_action.py -c
simple_value = None
constant_value = value-to-store
boolean_switch = False
collection = []
const_collection = []
$ python argparse_action.py -t
simple_value = None
constant_value = None
boolean_switch = True
collection = []
const_collection = []
$ python argparse_action.py -f
simple_value = None
constant_value = None
boolean_switch = False
collection = []
const_collection = []
simple_value = None
constant_value = None
boolean_switch = False
collection = ['one', 'two', 'three']
const_collection = []
$ python argparse_action.py -B -A
simple_value = None
constant_value = None
boolean_switch = False
collection = []
const_collection = ['value-2-to-append', 'value
argparse_action.py 1.0
Option Prefixes
import argparse
6 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
parser = argparse.ArgumentParser
parser.add_argument('-a', action
help='Turn A off'
)
parser.add_argument('+a', action
help='Turn A on'
)
parser.add_argument('//noarg',
print parser.parse_args()
$ python argparse_prefix_chars.py -h
optional arguments:
-h, --help show this help message and
-a Turn A off
+a Turn A on
//noarg, ++noarg
$ python argparse_prefix_chars.py +a
Namespace(a=True, noarg=False)
$ python argparse_prefix_chars.py -a
Namespace(a=False, noarg=False)
Namespace(a=None, noarg=True)
Namespace(a=None, noarg=True)
7 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
Sources of Arguments
import argparse
from ConfigParser import ConfigParser
import shlex
parser = argparse.ArgumentParser
parser.add_argument('-a', action
parser.add_argument('-b', action
parser.add_argument('-c', action
config = ConfigParser()
config.read('argparse_witH_shlex.ini'
config_value = config.get('cli'
print 'Config :', config_value
argument_list = shlex.split(config_value
print 'Arg List:', argument_list
$ python argparse_with_shlex.py
Config : -a -b 2
Arg List: ['-a', '-b', '2']
Results : Namespace(a=True, b='2', c=None)
import argparse
from ConfigParser import ConfigParser
import shlex
parser = argparse.ArgumentParser
8 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
parser.add_argument('-a', action
parser.add_argument('-b', action
parser.add_argument('-c', action
print parser.parse_args(['@argparse_fromfile_pr
-a
-b
2
$ python argparse_fromfile_prefix_chars.py
Automatically Generated
Options
argparse will automatically add options to
generate help and show the version
information for your application, if configured
to do so.
import argparse
parser = argparse.ArgumentParser
parser.add_argument('-a', action
parser.add_argument('-b', action
parser.add_argument('-c', action
print parser.parse_args()
import argparse
parser = argparse.ArgumentParser
parser.add_argument('-a', action
parser.add_argument('-b', action
parser.add_argument('-c', action
print parser.parse_args()
9 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
$ python argparse_with_help.py -h
optional arguments:
-h, --help show this help message and exit
-a
-b B
-c C
$ python argparse_without_help.py -h
import argparse
parser = argparse.ArgumentParser
parser.add_argument('-a', action
parser.add_argument('-b', action
parser.add_argument('-c', action
print parser.parse_args()
$ python argparse_with_version.py -h
optional arguments:
-h, --help show this help message and exi
-v, --version show program's version number
-a
-b B
-c C
$ python argparse_with_version.py -v
1.0
1.0
10 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
Parser Organization
argparse includes several features for
organizing your argument parsers, to make
implementation easier or to improve the
usability of the help output.
import argparse
parser = argparse.ArgumentParser
parser.add_argument('--user',
parser.add_argument('--password'
import argparse
import argparse_parent_base
parser = argparse.ArgumentParser
parser.add_argument('--local-arg'
print parser.parse_args()
$ python argparse_uses_parent.py -h
optional arguments:
11 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
Conflicting Options
import argparse
parser = argparse.ArgumentParser
parser.add_argument('-a', action
parser.add_argument('-b', action
parser.add_argument('--long-b'
print parser.parse_args(['-h'])
$ python argparse_conflict_handler_resolve.py
optional arguments:
-h, --help show this help message
-a A
--long-b LONG_B, -b LONG_B
Long and short together
import argparse
parser = argparse.ArgumentParser
parser.add_argument('-a', action
parser.add_argument('--long-b'
parser.add_argument('-b', action
print parser.parse_args(['-h'])
$ python argparse_conflict_handler_resolve2.py
12 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
usage: argparse_conflict_handler_resolve2.py [-
[-
optional arguments:
-h, --help show this help message and e
-a A
--long-b LONG_B Long and short together
-b B Short alone
Argument Groups
import argparse
parser = argparse.ArgumentParser
parser.add_argument('--optional'
parser.add_argument('positional'
print parser.parse_args()
$ python argparse_default_grouping.py -h
positional arguments:
positional
optional arguments:
-h, --help show this help message and exit
--optional
import argparse
13 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
parser = argparse.ArgumentParser
group = parser.add_argument_group
group.add_argument('--user', action
group.add_argument('--password'
import argparse
import argparse_parent_with_group
parser = argparse.ArgumentParser
parser.add_argument('--local-arg'
print parser.parse_args()
$ python argparse_uses_parent_with_group.py -h
optional arguments:
-h, --help show this help message a
--local-arg
authentication:
--user USER
--password PASSWORD
import argparse
parser = argparse.ArgumentParser
group = parser.add_mutually_exclusive_group
group.add_argument('-a', action
group.add_argument('-b', action
print parser.parse_args()
$ python argparse_mutually_exclusive.py -h
14 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
optional arguments:
-h, --help show this help message and exit
-a
-b
$ python argparse_mutually_exclusive.py -a
Namespace(a=True, b=False)
$ python argparse_mutually_exclusive.py -b
Namespace(a=False, b=True)
$ python argparse_mutually_exclusive.py -a -b
Nesting Parsers
import argparse
parser = argparse.ArgumentParser
subparsers = parser.add_subparsers
# A list command
list_parser = subparsers.add_parser
list_parser.add_argument('dirname'
# A create command
create_parser = subparsers.add_parser
create_parser.add_argument('dirname'
create_parser.add_argument('--read-only'
help
)
# A delete command
delete_parser = subparsers.add_parser
delete_parser.add_argument('dirname'
delete_parser.add_argument('--recursive'
help
)
print parser.parse_args()
15 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
$ python argparse_subparsers.py -h
positional arguments:
{list,create,delete} commands
list List contents
create Create a directory
delete Remove a directory
optional arguments:
-h, --help show this help message
positional arguments:
dirname New directory to create
optional arguments:
-h, --help show this help message and exit
--read-only Set permissions to prevent writi
Namespace(dirname='foo', recursive=True)
Advanced Argument
Processing
The examples so far have shown simple
boolean flags, options with string or numerical
arguments, and positional arguments.
argparse supports sophisticated argument
specification for variable-length argument list,
enumerations, and constant values as well.
16 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
Value Meaning
import argparse
parser = argparse.ArgumentParser
parser.add_argument('--three',
parser.add_argument('--optional'
parser.add_argument('--all', nargs
parser.add_argument('--one-or-more'
print parser.parse_args()
$ python argparse_nargs.py -h
optional arguments:
-h, --help show this help message
--three THREE THREE THREE
--optional [OPTIONAL]
--all [ALL [ALL ...]]
--one-or-more ONE_OR_MORE [ONE_OR_MORE ...]
$ python argparse_nargs.py
17 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
Namespace(all=None, one_or_more=['with_value'],
Argument Types
import argparse
parser = argparse.ArgumentParser
parser.add_argument('-i', type
parser.add_argument('-f', type
parser.add_argument('--file',
try:
print parser.parse_args()
except IOError, msg:
parser.error(str(msg))
$ python argparse_type.py -i 1
18 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
$ python argparse_type.py -i a
import argparse
parser = argparse.ArgumentParser
parser.add_argument('--mode',
print parser.parse_args()
$ python argparse_choices.py -h
optional arguments:
-h, --help show this help message
--mode {read-only,read-write}
Namespace(mode='read-only')
File Arguments
19 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
import argparse
parser = argparse.ArgumentParser
parser.add_argument('-i', metavar
parser.add_argument('-o', metavar
try:
results = parser.parse_args
print 'Input file:', results
print 'Output file:', results
except IOError, msg:
parser.error(str(msg))
$ python argparse_FileType.py -h
optional arguments:
-h, --help show this help message and exit
-i in-file
-o out-file
Custom Actions
20 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
import argparse
class CustomAction(argparse.Action
def __init__(self,
option_strings
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False
help=None,
metavar=None):
argparse.Action.__init__
print
print 'Initializing CustomAction'
for name,value in sorted
if name == 'self'
continue
print ' %s = %r'
return
parser = argparse.ArgumentParser
parser.add_argument('-a', action
parser.add_argument('-m', nargs
parser.add_argument('positional'
21 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
results = parser.parse_args(['-a'
print
print results
$ python argparse_custom_action.py
Initializing CustomAction
dest = 'a'
option_strings = ['-a']
required = False
Initializing CustomAction
dest = 'm'
nargs = '*'
option_strings = ['-m']
required = False
Initializing CustomAction
dest = 'positional'
option_strings = []
required = True
See also:
argparse
The standard library documentation
for this module.
original argparse
The PyPI page for the version of
argparse from outside of the
22 of 23 07/03/25, 3:58 pm
argparse – Command line option and argument parsing. - Python Module... https://pymotw.com/2/argparse/
ConfigParser
© Copyright Doug Hellmann. | | Last updated on Jul 11, 2020. | Created using Sphinx. | Design based on
"Leaves" by SmallPark |
23 of 23 07/03/25, 3:58 pm