Argparse is the recommended command-line parsing module in the Python standard library, which often requires parsing script parameters, which is a handy tool module to get rid of the manual system.argv. This article and everyone to share is python in the Argparse parsing script parameters related content, a look at it, I hope you learn Python help. Introduced Import Argparse Parser = Argparse. Argumentparser (description= ' description, can be used for help output description ', add_help=true) Parser.parse_args () Argumentparser Optional parameters are as follows: · prog– This script name (default: Sys.argv[0]) · usage– usage Notes (default: automatically generated based on parameters) · description– Script Description · Epilog– is also explained in the help output last · parents– Father parsers · formatter_class– customizing classes for output Help information · prefix_chars– Optional Prefix parameter number character (the parameter name is prefixed with this setting) · fromfile_prefix_chars– to read optional prefix parameter numbers from a file · argument_default– default values for all parameters · conflict_handler– Conflict Processor · add_help– whether to add help Common methods Add_argument () test.py Import Argparse Parser = Argparse. Argumentparser () Parser.add_argument ('-P ', '--param ') args = Parser.parse_args () print Args.param Run Python test.py-p value or Python test.py--param value. Add_argument Optional method parameters are as follows: · Name or flags-the names of the arguments. · Action-action when a parameter is encountered, the default value is store. Store_const, which indicates that the assignment is const;append, stores the encountered value as a list, that is, if the argument is repeated, it will save multiple values; Append_const, save a value defined in the parameter specification to a list, count, the number of times the store encounters, and also inherit the Argparse. Action custom parameter resolution; · Nargs-The number of arguments, can be a specific number, or is it? Number, use default for positional argument when no value is specified, const for Optional argument, or * for 0 or more arguments, or a + number for 1 or more parameters. · The constant values required by const-action and Nargs. · Default-defaults when parameters are not specified. · Type-types of parameters. such as int, str · Choices-The value allowed by the parameter. such as: [' A ', ' B ', ' C '] · Required-whether optional parameters can be omitted (for Optionals only). · Help-parameter helps when specified as Argparse. Suppress indicates that the help information for this parameter is not displayed. · Metavar-the parameter name in the usage description, default is the parameter name for the required parameter, and the default is the full uppercase parameter name for the optional parameter. · Dest-The parsed parameter name, by default, selects the longest name for the optional parameter, and the underscore is converted to an underscore. Add_mutually_exclusive_group () Set the conflict parameter and use this method when you need to set the specified input parameter to contain only one of them. test.py Parse = Argparse. Argumentparser () group = Parse.add_mutually_exclusive_group () group.add_argument ("-A", action= "Store_true") Group.add_argument ("-B", action= "Store_true") args = Parse.parse_args () In this case, the test.py input parameter can only contain a or B, and a, B cannot exist at the same time. Add_argument_group () Parameter grouping settings. When there are requirements for the Grouping command, the input parameters are attributed to the group under which they belong. Parse = Argparse. Argumentparser () Some_group = Parse.add_argument_group (' Publish plugin ') Some_group.add_argument ('-f ' type=str) Add_subparsers () Sub-command mode, like Git commit, git push, and other commands. Parse = Argparse. Argumentparser () Sub_parse = Parse.add_subparsers () # sub_parse opt ... Sample The following is a usage scenario. A script: publish.py, contains two functions: Publish and query, run the environment has test clothing and formal service, the release requires two account system password, query requires an account system password and version, channel parameters. So the script is as follows, see other notes: publish.py Import Argparse Def Get_args (): Parse = Argparse. Argumentparser (description= ' Publish tools. ', Add_help=true) # operation input, using mutex parameters and parameters must be entered and only one can be selected Group = Parse.add_mutually_exclusive_group (required=true) # Query Operations Group.add_argument ("-S", "--search", action= "Store_true") # Publish Action Group.add_argument ("-P", "--publish", action= "Store_true") # Run Environment parameters Parse.add_argument ('-e ', '--env ', type=str, help= ' Running environment ', choices=[' test ', ' product '], default= ' test ') # Required Account Information Parse.add_argument ('-a ', '--apiauth ', Required=true, Type=str, help= ' Username:password ') # Publish Group Command settings Publish_group = Parse.add_argument_group (' Publish ') Publish_group.add_argument ('-f ', '--ftpauth ', type=str, help= ' Username:password ') # Query grouping command settings Search_group = Parse.add_argument_group (' Search ') Search_group.add_argument ('-C ', '--channel ', type=str, help= ' channel ') Search_group.add_argument ('-V ', '--versoncode ', Type=int, help= ' Search verson code ') args = Parse.parse_args () return VARs (args) Args=get_args () print ' Opt search?: ', args[' search ', ' opt publish?: ', args[' publish '], ' \ n ', args Publish.py-h use Help as follows: usage:test.py [-h] (-s |-p) [-e {test,product}]-a apiauth [-f Ftpauth] [-C CHANNEL] [-V Hostversoncode] Publish tools. Optional arguments: -H,--help show this help message and exit -S,--search -P,--publish -e {test,product},--env {test,product} Running Environment -A apiauth,--apiauth Apiauth Username:password Publish plugin: -F Ftpauth,--ftpauth Ftpauth Username:password Search plugin: -C channel,--channel Channel Channel -V Versoncode,--versoncode Versoncode Search Verson Code Use the following: # 1 Publish Python publish.py-p-a u-f u# 2 search Python publish.py-s-a u-c channel-v 100
Source: Rocko ' s blog |