Python module Argparse usage examples detailed

Source: Internet
Author: User

Argparse is a python built-in module for quick creation of command lines. There is a third-party module Click can also implement this function, both have advantages and disadvantages, look at the individual needs.


Official website

Https://docs.python.org/3.5/library/argparse.html

Import argparse__verison__ = ' 1.1.1 ' parser = argparse. Argumentparser (description= ' hahahaaaa ') parser.add_argument ('-V ', '--version ', action= ' version ', version= '% (Prog) s ' +__version__ ' parser.add_argument ('--name ', '-n ', metavar= ' Namemma ', dest= ' name ', type=str,help= ' your name ', Nargs=1 ) parser.add_argument ('-i ', metavar= ' III ', action= ' store_const ', dest= ' IIII ', const= ' II ', help= ' dfafsdf ') parser.add_ Argument ("-Z", choices=[' a ', ' B ', ' d '],required=false) parser.add_argument (' foo ') args = Parser.parse_args () print ( Type (args)) print (Args.name,args.iiii,args.foo)

Simple description of the Argumentparser parameter

Epilog-end text for command line help

Prog-(default:sys.argv[0]) program name, generally do not need to modify, in addition, if you need to use in Help to the program's name, you can use% (Prog) s

Prefix_chars-Prefix of the command, default is-, for example-f/--file. Some programs may want to support options such as/F and can use prefix_chars= "/"

Fromfile_prefix_chars-(Default:none) If you want the command line arguments to be read from the file, you may use it. For example, if fromfile_prefix_chars= ' @ ', there is a "@args. txt" in the command-line arguments, the contents of Args.txt are used as command-line arguments

Add_help-whether to add-h/-help option (default:true), general help information is required, so do not set it.

Add_argument: Read in command-line arguments, the call has multiple parameters

Argumentparser.add_argument (name or flags ...) [, Action] [, Nargs] [, Const] [, Default] [, type] [, Choices] [, Required] [, help] [, Metavar] [, Dest])

Name or flags: is a required parameter that accepts the option parameter or is a positional parameter (a string of file names)


Parameters without '--'

You must enter a value when invoking a script

The order of the parameter inputs is consistent with the order defined in the program

Parameters of '-'

Do not enter Add_argument ("-A")

Similar to the '--' shortname, but the variable name in the program is defined as the parameter name

'--' parameter

Parameter aliases: 1 characters only, case sensitive

Add_argument ("-shortname", "--name", help= "params means"), but cannot use ShortName in code

Dest: Parameter in the program corresponding variable name add_argument ("a", dest= ' Code_name ')

Default: Parameter defaults

Help: Parametric action interpretation add_argument ("a", help= "params means")

Type: Default string Add_argument ("C", Type=int)

Metavar: The name of the parameter, which is used only when displaying the help information.

Action

Store: The default action mode, which stores the value to the specified variable.

Store_const: The stored value is specified in the const portion of the parameter and is used to implement non-Boolean command-line flags.

Store_true/store_false: boolean switch. You can have 2 parameters corresponding to one variable.

Append: Stores the value into the list, which can be reused.

Append_const: Stores the value to the list and stores the value specified in the const portion of the parameter.

Count: Number of shorthand inputs for statistical parameters add_argument ("-C", "--GC", action= "Count")

Version output release information and then exit.

Const: Used with action= "Store_const|append_const", default value

Choices: The range of input values Add_argument ("--GB", choices=[' A ', ' B ', ' C ', 0])

Required: Normally-f options are optional, but if required=true is required

The Nsrgs is used to specify the number of parameters, which can be .... or * or +

? 0 or one

* 0 or more

+ one or more


Create a child parse, each of which corresponds to its own input parameter

Import argparse# sub-command functionsdef subcmd_list (args):   print  " List "def subcmd_create (args):   print " create "def subcmd_delete (args):    print  "Delete" Parser = argparse. Argumentparser () subparsers = parser.add_subparsers (help= ' commands ') # a list  Commandlist_parser = subparsers.add_parser (' list ',  help= ' listcontents ') list_parser.add_argument (' dirname ',  action= ' store ', help= ' directory tolist ') list_parse.set_defaults (func=subcmd_list) # A  create commandcreate_parser = subparsers.add_parser (' Create ',  help= ' Create a  directory ') create_parser.add_argument (' dirname ', action= ' store ', help= ' new directoryto create ') Create_parser.add_argument ('--read-only ', default=false, action= ' store_true ', help= ' Setpermissions to  prevent writing to the directory ') create_parser . Set_defaults (Func=subcmd_create) # a delete commanddelete_parser = subparsers.add_ Parser (' delete ', help= ' remove a directory ') delete_parser.add_argument (' dirname ',  action= ' store ', help= ' The directory to remove ') delete_parser.add_argument ('--recursive ',  '-R ', default= False, action= ' store_true ', help= ' Remove thecontents of the directory, too ') Delete_parser .set_defaults (Func=subcmd_delete) Args = parser.parse_args () # call  Subcmdargs.fun (args)


Use Help

# python Args_subparse.py-h
usage:args_subparse.py [-h] {Create,list,delete} ...

Positional arguments:
{Create,list,delete} commands
List listcontents
Create Create a directory
Delete Remove a directory

Optional arguments:
-H,--help show this help message and exit

# python args_subparse.py create-h
usage:args_subparse.py create [-h] [--read-only] DirName

Positional arguments:
DirName New Directoryto Create

Optional arguments:
-H,--help show this help message and exit
--read-only SetPermissions to prevent writing to the directory

# python args_subparse.py delete-h
usage:args_subparse.py Delete [-h] [--recursive] DirName

Positional arguments:
DirName the directory to remove

Optional arguments:
-H,--help show this help message and exit
--recursive,-R Remove thecontents of the directory, too

# python args_subparse.py list-h
usage:args_subparse.py list [-h] dirname

Positional arguments:
DirName Directory ToList

Optional arguments:
-H,--help show this help message and exit


Multiple subparser Use the same defined parameters

# Add_help=false, must be specified, otherwise quote-H repeats the definition Parents_parser = argparse. Argumentparser (Add_help=false) parents_parser.add_argument ('--foo ', dest= "foo", action= ' store_true ') parents_ Parser.add_argument ('--bar ', dest= "bar", action= ' Store_false ') parents_parser.add_argument ('--baz ', dest= "Baz", action= ' store_false ') parser = Argparse. Argumentparser () Subparsers = parser.add_subparsers (help= ' commands ') M_parser = Subparsers.add_parser ("MySQL", Parents=[parents_parser], help= "MySQL method") m_parser.set_defaults (func=sub_mysql) O_parser = subparsers.add_ Parser ("Oracle", Parents=[parents_parser], help= "Oracle Method") o_parser.set_defaults (func=sub_oracle) args = Parser.parse_args ()


This article is from the "Baby God" blog, make sure to keep this source http://babyshen.blog.51cto.com/8405584/1887986

Python module Argparse usage examples detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.