The Python standard library recommends using the Argparse module to parse the command line.
Creating a parser
Import Argparseparser = Argparse. Argumentparser ()
creates an Argumentparser instance object, and the parameters of the Argumentparser object are the keyword parameters.
Class 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)
Prog : The name of the program, the default is Sys.argv[0], is used to describe the name of the program in the Help information.
usage : A string that describes the purpose of the program.
Description : The text before the help message.
Epilog : Information after the help message.
Parents : A list of Argumentparser objects whose arguments options are included in the new Argumentparser object.
Formatter_class : The format of the Help information output.
Prefix_chars : The parameter prefix, which defaults to '-'.
Fromfile_prefix_chars : prefix character, placed before the file name.
Argument_default : The global default value of the parameter.
Conflict_handler : Resolves conflicting policies by default and errors occur.
Add_help : When set to false, the-H--help message is no longer displayed in the Help message.
#-*-coding:utf-8-*-import argparseparser = argparse. Argumentparser () "parser = Argparse. Argumentparser (prog= ' MyProgram ') parser.print_help () #输出 = = Usage:myprogram [-h] "" "parser = Argparse. Argumentparser (prog= ' prog ', usage= '% (Prog) s [Options] ') parser.add_argument ('--foo ', nargs= '? ', help= ' foo help ') Parser.add_argument (' Bar ', nargs= ' + ', help= ' Bar Help ') Parser.print_help () #usage: A string that describes the purpose of the program "" "Parser = Argparse. Argumentparser (description= ' a foo that bars ', epilog= "and that's how you ' d foo A bar") Parser.print_help () #description : The text before the help message. #epilog: Information after the help message. "'" 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 ') Print foo_parser.parse_args (['-- Parent ', ' 2 ', ' XXX ']) #parents: A list of Argumentparser objects whose arguments options are included in the new Argumentparser object. "'" parser = argparse. Argumentparser (prog= ' prog ', prefix_chars= '-+ ') parser.add_argument (' +f ') parsEr.add_argument (' ++bar ') Print parser.parse_args (' +f x ++bar y '. Split ()) # ' +f X ++bar y '. Split () is equivalent to [' +f ', ' X ', ' + + Bar ', ' Y '] #prefix_chars: parameter prefix, default to '-' "' #with as Context Manager # when there are too many arguments, you can put the parameter in the file read # example Parser.parse_args (['-F ', ' foo ', ' @ Args.txt ']) parsing will be read from the file args.txt, equivalent to ['-F ', ' foo ', '-f ', ' bar ']. With open (' Args.txt ', ' W ') as Fp:fp.write ('-f\nbar ') #将-F and Bar are written in the file parser = Argparse. Argumentparser (fromfile_prefix_chars= ' @ ') parser.add_argument ('-f ') Print parser.parse_args (['-F ', ' foo ', ' @ Args.txt ']) "" #禁止parse_args时的参数默认添加parser = Argparse. Argumentparser (Argument_default=argparse. Suppress) parser.add_argument ('--foo ') parser.add_argument (' Bar ', nargs= '? ') Print parser.parse_args (['--foo ', ' 1 ', ' BAR ']) Print parser.parse_args () #argument_default: The global default value of the parameter "" ' #conflict_handler: Conflict resolution policy, by default the conflict will occur error # normal parameter conflict will be reported argumenterror error, set conflict_handler= ' resolve ' after the conflict will automatically resolve parser = Argparse. Argumentparser (prog= ' prog ', conflict_handler= ' resolve ') parser.add_argument ('-f ', '--foo ', help= ' old foo ") parser.add_argument ('--foo ', help= ' new foo help ') Parser.print_help ()"
Add parameter Options
Add_argument (name or flags ...) [, Action] [, Nargs] [, Const] [, Default] [, type] [, Choices] [, Required] [, help] [, Metavar] [, Dest])
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=ma
Name or flags: There are two types of arguments, optional parameters and positional parameters.
Action: default to store
The action parameters can be: store_const, values are stored in const, Store_true, and store_false, values are stored as true or FALSE, append: Save As List, Append_const: Save As List, is added according to the const key parameter, Count: The number of times the statistic parameter appears, the HELP:HELP information, version: edition.
Nrgs: Number of parameters
The value can be an integer n (n), * (any number), + (one or more) , the value is? , the parameters are obtained from the command line first, if none are obtained from the const, and then obtained from the default.
Const : Save a constant
default : Default Value
type : Parameter Type
Choices : Values to choose from
Required : is required
Desk : Can be used as the name of the parameter
#添加可选参数parser. Add_argument ('-f ', '--foo ') #添加位置参数parser. Add_argument (' Bar ') #action: The default is Store#store_const, The value is stored in the const parser = Argparse. Argumentparser () >>> parser.add_argument ('--foo ', action= ' store_const ', const=42) #store_true和store_false, The value is stored as true or falseparser.add_argument ('--foo ', action= ' store_true ') parser.add_argument ('--bar ', action= ' Store_false ') #append: Save As List parser.add_argument ('--foo ', action= ' append ') Parser.parse_args ('--foo 1--foo 2 '. Split ()) #append_ Const: Saved as list, will be added according to const key parameters parser.add_argument ('--str ', dest= ' types ', action= ' append_const ', const=str) parser.add _argument ('--int ', dest= ' types ', action= ' append_const ', const=int) #count: Number of occurrences of statistical parameters parser.add_argument ('--verbose ' , '-V ', action= ' count ') #nrgs: The number of parameters # value can be an integer n (n), * (any number), + (one or more) parser.add_argument (' Bax ', nargs=5) parser.add_ Argument (' Bay ', nargs= ' + ') parser.add_argument (' Baz ', nargs= ' * ') #值为? , the parameter is obtained from the command line first, if none is obtained from the const, and then obtained from default parser.add_argument ('--foo ', nargs= '? ', const= ' C ', default= ' d ')
parsing Parameters
#参数有几种写法 # spaces Separate parser = Argparse. Argumentparser (prog= ' prog ') parser.add_argument ('-X ') parser.add_argument ('--foo ') print Parser.parse_args (' x x '). Split ()) Print Parser.parse_args ('--foo foo '. Split ()) #长选项用 = separate print Parser.parse_args ('--boo=boo '. Split ()) # Short options can be written together print Parser.parse_args ('-zz '. Split ()) The return value of the #parse_args () method is namespace, which can be built into a dictionary using the VARs () function parser.add_ Argument ('--doo ') args = Parser.parse_args (['--doo ', ' BAR ']) print VARs (args)
Python command-line parsing library Argparse