argparse

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))

To use argparse

Make a parser

To use argparse, first create an ArgumentParser object.

parser = argparse.ArgumentParser(description='Process some integers.')

Add an argument

Call the add_argument () method on the ArgumentParser object Teach you how to take a command line string and turn it into an object.

parser.add_argument('intgers', 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 intgers (default: find the max)')

When you call parse_args (), you get two attributes, integers and accumulate. Returns the object it has.

The ʻintegers attribute is a list of one or more integers, and the ʻaccumulate attribute is If --sum is specified from the command line, the sum () function will be Otherwise it is a max () function.

Parse the arguments

ArgmumentParser parses its arguments with the parse_args () method. This method examines the command line, converts each argument to the correct type, Take the appropriate action.

In most cases this is from the command line parsing results Means to build a simple Namespace object.

In the script, parse_args () is usually called with no arguments ArgumentParser automatically gets command line arguments from sys.argv.

ArgumentParser object

class argparse.ArgumentParser(prog=None, usage=None, description=None,
 epilog=None, parents=[], formatter_class=argparse.helpFormatter,
 prefix_chars='-', fromfile_prefix_chars=None, argument_default=None,
 conflict_handler='error', add_help=true)

All arguments should be passed as keyword arguments.

argument Description
prog program name(Default:sys.argv[0])
usage A character string that describes how to use the program(Default:Generated from arguments added to the parser)
description The text that appears before the argument help(Default:none)
epilog The text that appears after the argument help(Default:none)
parents In the list of ArgumentParser objects, the arguments for this object are added
formatter_class Class for customizing help output
prefix_chars Character set that becomes the prefix of optional arguments(Default:'-')
fromfile_prefix_chars A character set that becomes the prefix of the file that reads the additional arguments(Default:None)
argument_default Global default value for arguments(Default:None)
conflict_handler How to resolve conflicting options(Usually not needed)
add_help -h/--Add help option to parser(Default:True)

prog

If you use argparse, the program name on the help message will be By default, it is obtained from sys.argv [0].

If you run a program called myprogram.py, the value of sys.argv [0] will be It becomes myprogram.py.

According to how the program starts on the command line This is the desired behavior in most cases because it creates a help message.

To change this default behavior, use the prog = argument of the ArgumentParser This can be achieved by specifying other values.

The program name was given with the prog = argument, even when taken from sys.argv [0] Even if you use the % (prog) s format specifier in the help message Available.

>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.add_argument('--foo', help='foo of the %(prog)s program')
>>> parser.print_help()
usage: myprogram [-h] [--foo FOO]

optional arguments:
  -h, --help  show this help message and exit
  --foo FOO   foo of the myprogram program

usage

usage: PROG [-h] [--foo [FOO]] bar [bar ...]

By default, usage is created automatically, ʻUsage =` Can be explicitly specified with the keyword argument.

parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
usage: PROG [options]

description

With the description = keyword argument, command line usage and arguments What the program does and how it works during the help message A short explanation about it is displayed.

parser = argparse.ArgumentParser(description='A foo that bars')
parser.print_help()
usage: argparse.py [-h]

A foo that bars

optional arguments:
  -h, --help show this help message and exit

epilog

Display an additional description of the program after the argument description.

>>> parser = argparse.ArgumentParser(
  description='A foo that bars',
  epilog="And that's how you'd foo a bar")
>>> parser.print_help()  
usage: argparse.py

A foo that bars

optional arguments:
  -h, --help  show this help message and exit

And that's how you'd foo a bar

parents

If you want to apply a common argument set to several parsers Parser with all common arguments as parents = argument Can be passed.

Specify add_help = False as the parent parser.

parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument('--parent', type=int)

foo_parser = argparse.ArgumentParser(parents=[parent_parser])
foo_parser.add_argument('foo')
foo_parser.parse_args(['--parent', '2', 'XXX'])

bar_parser = argparse.ArgumentParser(parents=[parent_parser])
bar_parser.add_argument('--bar')
bar_parser.parse_args(['--bar', 'YYY'])

add_argument () method

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const]
  [, default][, type][, choices][, required][, help][, metavar][, dest])
argument Description
name or flags Named or a list of optional strings
action Action when this argument is on the command line
nargs Number of command line arguments to consume
const Part ofactionWhennargsConstants used in combination of
default Value generated if there are no arguments on the command line
type The type to which command line arguments should be converted
choices Container of values allowed as arguments
required Whether command line options are optional
help A brief description of what the arguments are
metavar The name of the argument used in the usage message
dest parse_args()Attribute name added to the object returned by

name or flags

Is the specified argument an optional argument such as -f or --foo? Whether it is a positional argument such as a file name list, in the first argument of ʻadd_argument ()` give.

Create optional arguments as follows.

parser.add_argument('-f', '--foo')

Positional arguments are created as follows.

parser.add_argument('bar')

When parse_args () is called, optional arguments are prefixed with - It is identified and the other arguments are treated as positional arguments.

action

store

Simply stores the value of the argument. The default action.

store_const

Stores the value specified by the const keyword argument.

parser = argparse.ArgumentParser()
parser.add_argument('--foo', action='store_const', const=42)

42 is stored in a variable called foo.

store_true, store_false

Stores True and False respectively.

parser = argparse.ArgumentParser()
parser.add_argument('--foo', action='store_true')
parser.add_argument('--bar', action='store_false')

In the above case, foo stores True, and bar stores False.

append

Store the list and add the value of each argument to the list.

This action is useful for options where you want to allow multiple specifications.

parser = argparse.ArgumentParser()
parser.add_argument('--foo', action='append')
parser.parse_args('--foo 1 --foo 2'.splist())
Namespace(foo=['1', '2'])

append_const

Store the list and set the value given to the const keyword argument Add to that list.

parser = argparse.ArgumentParser()
parser.add_argument('--str', dest='types', action='append_const', const=str)
parser.add_argument('--int', dest='types', action='append_const', const=int)
parser.parse_args('--str --int'.split())
Namespace(types=[<class 'str'>, <class 'int'>])

count

Count the number of keyword arguments.

For example, it helps to raise the verbose level.

parser = argparse.ArgumentParser()
parser.add_argument('--versbose', '-v', action='count')
parser.parse_args('-vvv'.split())
Namespace(verbose=3)

nargs

Normally, the ArgumentParser object is Pass one command line argument to one action.

The nargs keyword argument is for one action and the number of others Command line arguments can be assigned.

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs=2)
>>> parser.add_argument('bar', nargs=1)
>>> parser.parse_args('c --foo a b'.split())
Namespace(bar=['c'], foo=['a', 'b'])

*?-If possible, one argument is taken from the command line to create one item. If no command line arguments exist, a value of `default'is generated.

''-All command line arguments are collected in the list.

*'+'-All command line arguments are collected in the list, but at least Generate an error message if one command line argument does not exist.

type

By default, the ArgumentParser object takes command line arguments Read as a simple string.

If the command line string should be treated as a different type such as float, int, etc. Type checking with the type keyword argument of ʻadd_argument ()` Type conversion can be performed.

Common built-in data types and functions can be specified directly as the value of the type argument.

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.add_argument('bar', type=open)
>>> parser.parse_args('2 temp.text'.split())
Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)

choices

If you want the command line arguments to be chosen from several options Possible by passing the choices keyword argument.

When parsing the command line, the value of the argument is checked and the value is If it is not included in the options, an error message will be displayed.

>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser = add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock', 'paper', 'scissors')

required

To make optional arguments mandatory, specify True in therequired =keyword argument.

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', required=True)
>>> parser.parse_args(['--foo', 'BAR'])
Namespace(foo='BAR')
>>> parser.parse_args([])
usage: argparse.py [-h] [--foo FOO]
argparse.py: error: option --foo is required

help

For example, the user can specify -h or --help on the command line. When requesting help, this help description is displayed in each argument.

>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', action='store_true',
      help='foo the bars before frobbling')
>>> parser.add_argument('bar', nargs='+',
      help='one of the bars to be frobbled')
>>> parser.parse_args('-h'.split())
usage: frobble [-h] [--foo] bar [bar ...]

positional arguments:
  bar  one of the bars to be frobbled

optional arguments:
  -h, --help   show this help message and exit
  --foo        foo the bars before frobbling

metavar

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage: [-h] [--foo FOO] bar

positional arguments:
  bar

optional arguments:
  -h, --help  show this help message and exit
  --foo FOO

By default, the value of dest is used as it is for the positional argument. For optional arguments, convert the value of dest to uppercase and use it.

A positional argument with one dest ='bar' is referenced as bar. When one optional argument --foo requests one command line argument, Its argument is referenced as FOO.

An alternative name can be specified as metavar.

>>> parser = argparse.ArgumnetParser()
>>> parser.add_argument('--foo', metavar='YYY')
>>> parser.add_argument('bar', metavar='XXX')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage: [-h] [--foo YYY] XXX

positional arguments:
  XXX

optional arguments:
  -h, --help show this help message and exit
  --foo YYY

If you specify nargs, you can pass a tuple to metavar You can specify a different name for each argument.

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', nargs=2)
>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
>>> parser.print_help()
usage: PROG [-h] [-x X X] [--foo bar baz]

optional arguments:
  -h, --help    show this help message and exit
  -x X X
  --foo bar baz

dest

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-f', '--foo-bar', '--foo')
>>> parser.add_argument('-x', '-y')
>>> parser.parse_args('-f 1 -x 2'.split())
Namespace(foo_bar='1', x='2')
>>> parser.parse_args('--foo 1 -y 2'.split())
Namespace(foo_bar='1', x='2')

ArgumentParser selects the first long option string and replaces the leading -- By removing it, the value of dest is generated.

If no long option string is specified, start with the first short option string Generate a dest by removing the leading- character.

All - characters except the beginning are converted to _ so that they are valid attribute names.

To give a custom attribute name to dest, do as follows.

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', dest='bar')
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')

Recommended Posts

argparse
argparse part 1
argparse note
python argparse template
I tried using argparse
Complement argparse from docstrings