Python command-line parsing library Argparse

Source: Internet
Author: User
Tags vars

After 2.7, Python no longer extends the Optparse module, and the Python standard library recommends using the Argparse module to parse the command line.

1.example

There is an interview question: Write a script main.py, using the following methods:

Main.py-u http://www.sohu.com -d ' a=1,b=2,c=3 '-o/tmp/index.html

Feature Requirements: Open the page specified by-u, add the parameter a=1&b=2&c=3 after all the links in the page (you need to consider the problem that the specified parameter already exists in the link), and then save to the file specified by-O.

Import argparseimport urllibfrom pyquery import pyquery as Pqdef Getargs ():    parse=argparse. Argumentparser ()    parse.add_argument ('-u ', type=str)    parse.add_argument ('-d ', type=str)    parse.add_ Argument ('-o ', type=str)    Args=parse.parse_args ()    return VARs (args) def urladdquery (url,query):    query= Query.replace (', ', ' & ')      if '? ' in URL:        return url.replace ('? ', '? ') +query+ ' & ')    else:        return url+ '? ' +querydef gethref ():    Args=getargs ()    url=args[' u ']    query=args[' d '].strip ("\ '")    Filename=args [' O ']    DOC=PQ (Url=url)    with open (FileName, ' W ') as F: For        A in doc (' a '):            a=pq (a)            href=a.attr (' href ')            if href:                newurl=urladdquery (href,query)                f.write (newurl+ ' \ n ') if __name__== ' __main__ ':    Gethref ()
2. Create a parser
Import Argparseparser = Argparse. Argumentparser ()

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)

Creates an Argumentparser instance object, and the parameters of the Argumentparser object are the keyword parameters.

Prog: The name of the program, which defaults to sys.argv[0], is used to describe the name of the program in the Help information.

>>> parser = Argparse. Argumentparser (prog= ' MyProgram ') >>> parser.print_help () Usage:myprogram [-h]optional arguments:-H,--help  Show this help message and exit

usage: A string describing the purpose of the program

>>> 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: PROG [options]positional arguments:bar          Bar helpoptional arguments:-H,--help show this help   message and exit--f oo [foo]  foo Help

Description: The text before the help message.

Epilog: Information after help information

>>> parser = Argparse. Argumentparser (     ... description= ' A foo that bars ',...     Epilog= "and that's how you're ' d foo a bar") >>> parser.print_help () usage:argparse.py [-h]a foo that barsoptional arg Uments:-H,--help show this help message and Exitand that's how you  ' d foo a bar

parents: A list of Argumentparser objects whose arguments options are included in the new Argumentparser object.

>>> 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 ') >>> foo_parser.parse_ Args (['--parent ', ' 2 ', ' xxx ']) Namespace (foo= ' xxx ', parent=2)

formatter_class: The format of the Help information output,

prefix_chars: Parameter prefix, default to '-'

>>> parser = Argparse. Argumentparser (prog= ' prog ', prefix_chars= '-+ ') >>> parser.add_argument (' +f ') >>> parser.add_ Argument (' ++bar ') >>> Parser.parse_args (' +f x ++bar Y '. Split ()) Namespace (bar= ' Y ', f= ' X ')

fromfile_prefix_chars: prefix character, preceded by file name

>>> with open (' Args.txt ', ' W ') as FP: ...    Fp.write ('-f\nbar ') >>> parser = Argparse. Argumentparser (fromfile_prefix_chars= ' @ ') >>> parser.add_argument ('-f ') >>> Parser.parse_args ([' -F ', ' foo ', ' @args. txt ']) Namespace (f= ' bar)

When there are too many parameters, the parameters can be read in the file, in the example Parser.parse_args (['-F ', ' foo ', ' @args. txt ') parsing will be read from the file Args.txt, equivalent to ['-F ', ' foo ', ' -F ', ' bar '.

Argument_default: The global default value of the parameter. For example, to disallow Parse_args when a parameter is added by default, we can:

>>> parser = Argparse. Argumentparser (Argument_default=argparse. Suppress) >>> parser.add_argument ('--foo ') >>> parser.add_argument (' Bar ', nargs= '? ') >>> Parser.parse_args (['--foo ', ' 1 ', ' Bar ']) Namespace (bar= ' bar ', foo= ' 1 ') >>> Parser.parse_args () Namespace ()

Foo and bar are not resolved automatically when Parser.parse_args ().

conflict_handler: Resolves a conflicting policy, by default the error occurs:

>>> parser = Argparse. Argumentparser (prog= ' prog ') >>> parser.add_argument ('-f ', '--foo ', help= ' old foo-help ') >>> Parser.add_argument ('--foo ', help= ' new foo help ') Traceback (most recent call last): ... Argumenterror:argument--foo:conflicting option String (s):--foo

We can set the conflict resolution policy:

>>> parser = Argparse. Argumentparser (prog= ' prog ', conflict_handler= ' resolve ') >>> parser.add_argument ('-f ', '--foo ', help= ' old Foo help ') >>> parser.add_argument ('--foo ', help= ' new foo help ') >>> parser.print_help () Usage:prog [- h] [-f FOO] [--foo foo]optional arguments:-H,--help show this help  message and exit-f FOO old      FOO help--foo FO O   new Foo Help

 add_help: When set to false, the-H--help message is no longer displayed in the Help message.

3. Add Parameter Options
>>> 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=max,...                     help= ' Sum the integers (default:find the max)

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

name or flags: There are two types of arguments, optional parameters and positional parameters.

To add an optional parameter:

>>> parser.add_argument ('-f ', '--foo ')

Add Location Parameters:

>>> parser.add_argument (' Bar ')

The Parse_args () runtime uses '-' to authenticate the optional parameters, and the rest is the positional parameters.

>>> parser = Argparse. Argumentparser (prog= ' prog ') >>> parser.add_argument ('-f ', '--foo ') >>> parser.add_argument (' Bar ') >>> Parser.parse_args ([' Bar ']) Namespace (bar= ' bar ', Foo=none) >>> Parser.parse_args ([' Bar ', '--foo ', ' FOO ']) Namespace (bar= ' bar ', foo= ' foo ') >>> Parser.parse_args (['--foo ', ' foo ']) Usage:prog [-h] [-F FOO] BarPROG:error:too few arguments

Parsing without positional parameters will be an error.

action: default to store

Store_const, the value is stored in the const:

>>> parser = Argparse. Argumentparser () >>> parser.add_argument ('--foo ', action= ' store_const ', const=42) >>> Parser.parse _args ('--foo '. Split ()) Namespace (foo=42)

Store_true and Store_false, with a value of true or False

>>> parser = Argparse. Argumentparser () >>> parser.add_argument ('--foo ', action= ' store_true ') >>> parser.add_argument ('- -bar ', action= ' Store_false ') >>> parser.add_argument ('--baz ', action= ' store_false ') >>> Parser.parse_args ('--foo--bar '. Split ()) Namespace (Bar=false, Baz=true, Foo=true)

Append: Save As List

>>> parser = Argparse. Argumentparser () >>> parser.add_argument ('--foo ', action= ' append ') >>> Parser.parse_args ('--foo 1- -foo 2 '. Split ()) Namespace (foo=[' 1 ', ' 2 '))

Append_const: Saved as a list, it is added according to the const key parameters:

>>> parser = Argparse. Argumentparser () >>> parser.add_argument ('--str ', dest= ' types ', action= ' append_const ', const=str) >> > parser.add_argument ('--int ', dest= ' types ', action= ' append_const ', const=int) >>> Parser.parse_args ('-- Str--int '. Split ()) Namespace (Types=[<type ' str ';, <type ' int ';])

Count: Number of occurrences of statistical parameters

>>> parser = Argparse. Argumentparser () >>> parser.add_argument ('--verbose ', '-V ', action= ' count ') >>> Parser.parse_args ( '-VVV '. Split ()) Namespace (verbose=3)

Help:help Information

Version: Versions

>>> Import argparse>>> parser = Argparse. Argumentparser (prog= ' prog ') >>> parser.add_argument ('--version ', action= ' version ', version= '% (Prog) S 2.0 ') >>> Parser.parse_args (['--version ']) PROG 2.0

Nrgs: Number of parameters

The value can be an integer n (n), * (any number), + (one or more)

>>> parser = Argparse. Argumentparser () >>> parser.add_argument ('--foo ', nargs= ' * ') >>> parser.add_argument ('--bar ', nargs= ' * ') >>> parser.add_argument (' Baz ', nargs= ' * ') >>> Parser.parse_args (' a b--foo x y--bar 1 2 '. Split ()) Namespace (bar=[' 1 ', ' 2 '], baz=[' A ', ' B '], foo=[' x ', ' Y '])

Value is? , the parameters are obtained from the command line first, if none are obtained from the const, and then obtained from the default:

>>> parser = Argparse. Argumentparser () >>> parser.add_argument ('--foo ', nargs= '? ', const= ' C ', default= ' d ') >>> Parser.add _argument (' Bar ', nargs= '? ', default= ' d ') >>> Parser.parse_args (' xx--foo YY '. Split ()) Namespace (bar= ' xx ', foo = ' YY ') >>> Parser.parse_args (' xx--foo '. Split ()) Namespace (bar= ' xx ', foo= ' C ') >>> Parser.parse_args (". Split ()) Namespace (bar= ' d ', foo= ' d ')

A more common scenario is to allow the parameter to be a file

>>> parser = Argparse. Argumentparser () >>> parser.add_argument (' infile ', nargs= '? ', Type=argparse. FileType (' R '),...                     Default=sys.stdin) >>> parser.add_argument (' outfile ', nargs= '? ', Type=argparse. FileType (' W '),...                     Default=sys.stdout) >>> Parser.parse_args ([' Input.txt ', ' output.txt ']) Namespace (infile=<open file ' Input.txt ', mode ' r ' at 0x...>,          outfile=<open file ' output.txt ', Mode ' W ' at 0x...>) >>> Parser.pars E_args ([]) Namespace (infile=<open file ' <stdin> ', mode ' r ' at 0x...>,          outfile=<open file ' <stdout > ', Mode ' W ' at 0x...>)

Const: Saving a constant

Default: Defaults

Type: Parameter types

choices: Values to choose from

>>> parser = Argparse. Argumentparser (prog= ' doors.py ') >>> parser.add_argument (' door ', Type=int, Choices=range (1, 4)) >>> Print (Parser.parse_args ([' 3 ')]) Namespace (door=3) >>> Parser.parse_args ([' 4 ']) usage:doors.py [-h] Doors.py:error:argument door:invalid Choice:4 (choose from 1, 2, 3)

Required: is required

Desk: Can be used as the name of the parameter

>>> parser = Argparse. Argumentparser () >>> parser.add_argument ('--foo ', dest= ' bar ') >>> Parser.parse_args ('--foo XXX '). Split ()) Namespace (bar= ' XXX ')
4. Parsing parameters

The parameters are written in several ways:

The most common spaces are separated:

>>> parser = Argparse. Argumentparser (prog= ' prog ') >>> parser.add_argument ('-X ') >>> parser.add_argument ('--foo ') > >> Parser.parse_args (' x x '. Split ()) Namespace (Foo=none, x= ' x ') >>> Parser.parse_args ('--foo foo '). Split ()) Namespace (foo= ' foo ', X=none)

Long option with = separate

>>> Parser.parse_args ('--foo=foo '. Split ()) Namespace (foo= ' foo ', X=none)

The short options can be written together:

>>> Parser.parse_args ('-xx '. Split ()) Namespace (Foo=none, x= ' x ')

The return value of the Parse_args () method is namespace and can be built into a dictionary with the VARs () function:

>>> parser = Argparse. Argumentparser () >>> parser.add_argument ('--foo ') >>> args = Parser.parse_args (['--foo ', ' BAR ']) >>> VARs (args) {' foo ': ' BAR '}

  

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.