Argparse Module
Argparse is the library used in the Python standard library to handle command-line arguments.
Basic usage
Import Argparseparser = Argparse. Argumentparser () Parser.parse_args ()
Output results
Xxx>python Arg_example.pyxxx>python arg_example.py-husage:arg_example.py [-h]optional arguments:- H,-- Help Show this help message and Exitxxx>python arg_example.py ausage:arg_example.py [-h]arg_example.py:error:un Recognized arguments:axxx>
- First one without any output and error
- The second test is for printing help information, and Argparse automatically generates the Help document
- The third test is an undefined a parameter, and an error occurs
Positional arguments
Positional arguments for the English definition, the Chinese name has the translation as the positional parameter, uses does not have the belt-can be used
Import Argparseparser = Argparse. Argumentparser () parser.add_argument ("echo") args = Parser.parse_args () print (Args.echo) output: Xxx>python arg_ example.py Aaxxx>python arg_example.py Echoechoxxx>python arg_example.pyusage:arg_example.py [-h] Echoarg_ Example.py:error:the following arguments is Required:echo
Defines a named echo parameter, which is required by default
- The first test is normal usage, echoing the input string a
- The second test is without parameters, because the
echo parameter is empty, so error, and give usage (usage) and error message
Optional arguments
Chinese is called optional parameter, there are two ways:
- One is
- to specify the short parameters by one, such as -h ;
- One is
-- to specify a long parameter, such as--help
Import Argparseparser = Argparse. Argumentparser () parser.add_argument ("-V", "--verbo", help= "Verbo usage") args = Parser.parse_args () if Args.verbo: print ("Verbo turned on%s"% Args.verbo) output: Xxx>python arg_example.py-v Helloverbo turned on Helloxxx>python arg_example.py--verbo Helloverbo turned on Helloxxx>python arg_example.py-husage:arg_example.py [-h] [-V VERBO]opti Onal arguments: -H,--help show this help message and Exit-v Verbo,--verbo verbo verbo Usagexxx>pyth On arg_example.py ausage:arg_example.py [-h] [-V verbo]arg_example.py:error:unrecognized arguments:a
An optional parameter is defined -v or --verbo , after parsing, its value is saved in the args.verbo variable
- In test 1, the parameter value is specified by-V
- In Test 2, the parameter value is specified by--verbos
- In Test 3, print help information by-H
- In Test 4, the parameter value is not specified for-V, so an error is given
action= ' Store_true '
Specifying when parameters are definedaction="store_true",可以像-h那样,不需要指定参数值
Import Argparseparser = Argparse. Argumentparser () parser.add_argument ("-V", "--verbo", help= "Verbo usage", action= "store_true") args = Parser.parse_ Args () if Args.verbo: print ("Verbo turned on%s"% Args.verbo) output: Xxx>python Arg_example.py-vverbo turned on True Xxx>python arg_example.py-husage:arg_example.py [-h] [-v]optional arguments: -H,--help show this help Message and exit -V,--verbo verbo usagexxx>python arg_example.py-v hellousage:arg_example.py [-h] [-v]arg_ Example.py:error:unrecognized Arguments:hello
- Test 1,-V does not specify any parameters can also, in fact, the existence of true and false, if present, its value is true, otherwise false
- In Test 2, print help information by-H
- Test 3,-V to specify the parameter value, will error, because specify Ture or False
Argparse Configuration Parameters
The parameters that can be configured are the following:
- Dest: Can decide after parsing, the value of the property name, especially suitable for a number of equivalent parameters. When not specified, the option is not added-the string.
- Type: The value type of the option, the default type of the value is the string, where the value is specified as a different type.
- Default: Defaults. No default value is set for none.
- Help: An option that has an-H to print the information.
- Metavar: Represents the default value displayed to the Help options;
- Choices: This value needs to be set when type is set to choices.
Action: Used to control the handling of options and parameters, like parameterless option processing, can be set to the following string:
- "Store": stores the value to dest the specified attribute, forcing the request to provide the parameters later;
- "Store_true": When this option is used, the following dest will be set to true, not with the arguments.
- "Store_false": When this option is used, the subsequent dest will be set to false. Used when the same dest is used in conjunction with another "store_true" option. Not with parameters.
- "Append": Stores the value to dest the specified property, and is in the form of an array, which must be followed by the parameter.
- "Store_const": Used to store the value set by the const parameter to the Dest specified property. Commonly used when dest is 2 or more options with the same name. Not with parameters.
- "Append_const": Used to store an array of parameters that are const set to the Dest specified property. Not with parameters.
- "Count": After use, the stored value to dest the specified attribute value plus 1, you can count the number of occurrences in the parameter. Not very useful. Not with parameters.
- "Callback": After specifying the callback function name (without parentheses), the corresponding opt and args are passed to the callback function.
- "Help", "version": corresponds to the aid and version. be used in addition to your own design.
Default
Import Argparseparser = Argparse. Argumentparser () parser.add_argument ("-V", "--verbo", help= "Verbo usage", default=1) args = Parser.parse_args () if Args.verbo: print ("Verbo turned on%s"% Args.verbo)
Type
Import Argparseparser = Argparse. Argumentparser () parser.add_argument ('-X ', Type=int, help= "square") args = Parser.parse_args () answer = args.x * * 2print ( Answer
Choices
Import Argparseparser = Argparse. Argumentparser (description= "Calculate X to the power of Y") parser.add_argument ("Square", Type=int, help= "display a Square of a given number ") Parser.add_argument ("-V ","--verbosity ", Type=int, Choices=[0, 1, 2], default=1, help=" Increase output verbosity ") args = Parser.parse_args () answer = args.square**2if Args.verbosity = = 2: print (" the Square of {} equals {} ". Format (Args.square, answer)) elif args.verbosity = = 1: print (" {}^2 = = {} ". Format (Args.square, Answer) Else: print (answer)
Output results
Xxx>python arg_example.py 3-v 13^2 = 9xxx>python arg_example.py 3-v 2the square of 3 equals 9xxx>python ARG_EX ample.py 33^2 = = 9xxx>python arg_example.pyusage:arg_example.py [-h] [-v {0,1,2}] squarearg_example.py:error:the fol lowing arguments is Required:squarexxx>python arg_example.py-husage:arg_example.py [-h] [-v {0,1,2}] Squarecalcula Te X to the power of ypositional arguments: square display a square of a given numberoptional arguments: -H,- -help Show this help message and exit -v {0,1,2},--verbosity {0,1,2} increase output verbosity
Case FTP client command line
Import Argparseparser = Argparse. Argumentparser ( description= "FTP client, using-s 127.0.0.1-p 9988-u hh-p 123") Parser.add_argument ("-S", "--server", type =str, default= ' 127.0.0.1 ', dest= "Server", help= "ftp server Ip_addr") parser.add_argument ("-P", "--port ", Type=int, dest=" Port ", help=" FTP server port ") parser.add_argument ("-U ", "--username ", TYPE=STR, choices=[' Alex ', ' Egon ', ' Eva '], dest= "username", help= "username info") parser.add_ Argument ("-P", "--password", dest= "password", help= "password info") args = Parser.parse_args () print (' server:{} port:{} username:{} password:{} '. Format (Args.server, Args.port, Args.username, Args.password))
Output Results
Xxx>python arg_example.py-husage:arg_example.py [-h] [-s server] [-P server] [-u {Alex,egon,eva}] [-P PASSWORD]FTP client, using-s 127.0.0.1-p 9988-u hh-p 123optional arguments:-H,--help show this help message and exit-s server,--server server FTP server ip_addr-p server,--port server FTP server Port-u {Alex,egon,eva},--username {Alex,egon,eva} username info-p PASSWORD, --password password Password infoxxx>python arg_example.py-s 127.0.0.1-p 9988-u en-p 123usag e:arg_example.py [-h] [-s SERVER] [-P PORT] [-u {Alex,egon,eva}] [-P Password]arg_example.py:error: Argument-u/--username:invalid choice: ' en ' (choose from ' Alex ', ' Egon ', ' Eva ') Xxx>python arg_example.py-s 127.0.0.1 -P 9988-u alex-p 123server:127.0.0.1 port:9988 username:alex password:123xxx>python arg_example.py-s 127.0.0.1- P 9988-u alex-p 123456server:127.0.0.1 port:9988 Username:alex password:123456
Reference http://yarving.historytale.com/
Python argparse module