Python command line parameter parsing package argparse

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')
args = parser.parse_args()
print(args.echo)

Mainly three steps

1. Create a parser

parser = argparse.ArgumentParser()

An ArgumentParser  object contains all the information needed to parse the command line into Python data types.

2. Add parameters

parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')

 Adding program argument information  to an  ArgumentParser is  done by calling the add_argument() method.

3. Parsing parameters

>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

ArgumentParser parses arguments  through  the parse_args()  method.

Official documentation:

Argparse Tutorial — Python 3.11.3 documentation

argparse — Parser for command-line options, arguments and sub-commands — Python 3.11.3 documentation

Mistake made: The file name is the same as the package name. . . It will report the error that the module does not exist.

add_argument()

add_argument() parameters fall into two categories:

1. Positional parameters

Add parameters directly with double quotes "argment_name".

2. Optional parameters Optional arguments

Adding parameters is represented by "--argment_name".

With the help option, you can view all the parameters.

action

store: Store parameter values, the default behavior.

store_const: used with the key parameter const

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

Namespace(foo=42)

store_true and store_false: If it is passed, it will be True and False itself, if it is not passed, it will be the opposite

append: The parameter value forms a list

parser = argparse.ArgumentParser()
parser.add_argument('--dataset',
                       action='append',
                       nargs=2,
                       metavar=('DATASET_NAME', 'DATASET_PATH'),
                       required=True,
                       help='')

parser.parse_args('--dataset twitter15 --dataset ./twitter15.json'.split())

Namespace(dataset=['twitter15', './twitter15.json'])

append_const : this stores a list and appends the value specified by the const keyword argument to the 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 occurrences of the parameter

parser = argparse.ArgumentParser()
parser.add_argument('--verbose', '-v', action='count', default=0)
parser.parse_args(['-vvv'])
Namespace(verbose=3)

nrgs

N: an integer, the command lines are gathered into a list.
'?': Will take an argument from the command line, if possible, and generate it as a single item. If no command-line arguments are present, the values ​​in Defaults will be generated. Note that for optional arguments, there is an additional case - the option string is present, but no command-line arguments follow. In this case, the value in const will be generated.

parser = argparse.ArgumentParser()
parser.add_argument('--foo', nargs='?', const='c', default='d')
parser.add_argument('bar', nargs='?', default='d')
parser.parse_args(['XX', '--foo', 'YY'])
# Namespace(bar='XX', foo='YY') 有值传一个参则单项生成
parser.parse_args(['XX', '--foo'])
# Namespace(bar='XX', foo='c')  存在选择字符foo传参,则赋值const的值
parser.parse_args([])
# Namespace(bar='d', foo='d')  无值传参则则使用默认值


*: Indicates zero or more parameters passed
+: All command line parameters are collected into a list. Reports an error if at least one parameter does not exist.

parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('foo', nargs='+')
print(parser.parse_args(['a','b']))
# Namespace(foo=['a', 'b'])

const

There are two usages of const
1. action='store_const' or action='append_const 
2. nargs='?' If the selection character exists but the parameter does not exist, use const, followed by default.

default

The default value if not assigned, or None if there is no default value.

type

can be customized

def hyphenated(string):
    return '-'.join([word[:4] for word in string.casefold().split()])

parser = argparse.ArgumentParser()
_ = parser.add_argument('short_title', type=hyphenated)
parser.parse_args(['"The Tale of Two Cities"'])

# Namespace(short_title='"the-tale-of-two-citi')

dest

Namespace name setting

For positional arguments, dest is provided as the first argument to the function.

For optional argument operations, the value of dest is generated by taking the first long option string and dropping the initial "--". If no long option string is provided, dest will be derived from the first short option string by stripping the initial-character. Any internal characters will be converted to _ characters to ensure the string is a valid property name.

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') 同样的条件,选择前面一个

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

metavar

parser = argparse.ArgumentParser()
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

# options:
#  -h, --help  show this help message and exit
#  --foo YYY

Guess you like

Origin blog.csdn.net/qq_41458274/article/details/130388568