Python command-line argument parsing

Source: Internet
Author: User

This article is reproduced from my other blog, welcome you click to see, help me to add a bit popular ^_^ Impyy
Select module

As prompted by the Python reference manual, Optparse is obsolete and should be used Argparse

Tutorial Concepts

The Argparse module uses add_argument to add optional command-line arguments, which are prototyped as follows:

Argumentparser.add_argument (name or flags ...) [, Action] [, Nargs] [, Const] [, Default] [, type] [, Choices] [, Required] [, help] [, Metavar] [, Dest]) Define how a, command-line argument should be parsed. Each parameter have its own more detailed description below, but in short they are:name or flags-either a name or a l     Ist of option strings, e.g Foo Or-f,--foo.     Action-the basic type of action to being taken when this argument is encountered on the command line.     Nargs-the number of command-line arguments that should be consumed.     CONST-A constant value required by some action and Nargs selections.     Default-the value produced if the argument is absent from the command line.     Type-the type to which the command-line argument should is converted.     Choices-a container of the allowable values for the argument.     Required-whether or not the command-line option is omitted (Optionals only).     Help-a brief description of what the argument does.Metavar-a name for the argument in usage messages.  Dest-the name of the attribute to being added to the object returned by Parse_args ().

The above instructions actually do not need to look, look directly at the example good:

Just want to show some information
#-*-Coding:utf-8-*-"" "Argparse Tester" "" Import Argparseparser = Argparse. Argumentparser (description= ' argparse tester ') parser.add_argument ("-V", "--verbose", help= "increase output verbosity ",                    action=" store_true ") args = Parser.parse_args () If args.verbose:    print" Hello World "


It will output as follows:

$ python t.py$ python t.py-vhello world$ python t.py-husage:t.py [-h] [-v]argparse testeroptional arguments:-  H,-- Help     Show this help message and exit  -V,--verbose  increase output verbosity

Here-V is the shorthand for this option, and--verbose is a complete spelling.

Help is helpful information and does not explain

args = Parse_args () returns a namespace, so long as you add an option, such as verbose, it adds the verbose to args and can be accessed directly through Args.verbose.

If you want to give it an individual name, you need to add one more parameter dest= ' VB ' in Add_argument

So you can access it through Args.vb.

action= "Store_true" means that the option does not need to receive parameters, directly set Args.verbose = True,

Of course, if you don't specify-V, then Args.verbose is False.

But if you remove action= "Store_true", you have to specify a value for-V, such as-V 1

Make a summation procedure.
#-*-coding:utf-8-*-" "" Argparse Tester "" "Import Argparseparser = Argparse. Argumentparser (description= ' argparse tester ') parser.add_argument ("-V", "--verbose", help= "increase output verbosity ", action=" Store_true ") parser.add_argument (' numbers ', type=int, help=" numbers to calculate ", nargs= ' + ') parser.add_ Argument ('-s ', '--sum ', help= "sum all Numbers", action= ' store_true ', default=true) args = Parser.parse_args () print "  Input: ", Args.numbersprint" Result: "results = args.numbersif args.verbose:print" Hello world "if Args.sum:results = SUM (args.numbers) print "tsum:tt%s"% results 

The output is as follows:

[[email protected] test]$ python t2.py-husage:t2.py [-h] [-v] [-s] numbers [numbers ...] Argparse testerpositional arguments:  numbers        numbers to calculateoptional arguments:  -H,--help     Show This help message and exit  -V,--verbose  increase output verbosity  -S,--sum      sum all Numbers[[email prote CTED] test]$ python t2.py 1 2 3-sinput: [1, 2, 3]result:    Sum:        6

Note that this optional numbers no longer adds a "-" prefix because this is the location option

If you remove nargs= "+", you can enter only one number. Because it specifies the number of values for the numbers option

If Type=int is removed, then args.numbers is a string, not automatically converted to an integer

Note that the--sum option is also added with default=true, meaning that even if you do not specify-s on the command line, it is set to True by default.

Only 2 optional 1 options available
#-*-Coding:utf-8-*-"" "Argparse Tester" "" Import Argparseparser = Argparse. Argumentparser (description= ' argparse tester ') #group = Parser.add_mutually_exclusive_group () parser.add_argument ("- V ","--verbose ", help=" increase output verbosity ", action=" Store_true ") parser.add_argument (' numbers ', Type=int, help= "Numbers to calculate", nargs= ' + ') parser.add_argument ('-s ', '--sum ', help= "sum all Numbers", action= ' store_true ', default=true) parser.add_argument ('-f ', '--format ', choices=[' int ', ' float '], help= ' Choose result format ', default= ' int ') args = Parser.parse_args () print "Input:", Args.numbersprint "Result:" results = Args.numbersif args.verbose:print    "Hello World" if args.format = = ' int ': format = '%d ' Else:format = '%f ' If args.sum:results = SUM (args.numbers) print ' tsum:tt%s '% (format% results)

The output is as follows:

[[email protected] test]$ python t2.py 1 2 3-f floatinput: [1, 2, 3]result:    sum:        6.000000[[email protected] test] $ python t2.py 1 2 3-f doubleusage:t2.py [-h] [-v] [-S] [-f {int,float}] numbers [numbers ...] T2.py:error:argument-f/--format:invalid choice: ' Double ' (choose from ' int ', ' float ')

When the option-F is added, the choices=[' int ', ' float ' parameter is passed in, indicating that the option can only be selected from int or float 2 1

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Python command-line argument parsing

Related Article

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.