Python command line Parsing Library argparse, pythonargparse

Source: Internet
Author: User
Tags vars

Python command line Parsing Library argparse, pythonargparse

Python no longer extends the optparse module after 2.7. We recommend that you use the argparse module to parse the command line in the python standard library.

1. example

There is an interview question: compile a script main. py, which is used as follows:

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

Function requirements: Open the page specified by-u, add the parameter a = 1 & B = 2 & c = 3 after all links on the page (you need to consider the problem that the specified parameter already exists in the link ), then save it 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)

Create an ArgumentParser instance object. Parameters of the ArgumentParser object are all keyword parameters.

Prog: Program name. The default value is sys. argv [0]. It is used to describe the program name 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: String that describes 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 --foo [FOO]  foo help

Description: Text before help information.

Epilog: Information after help

>>> parser = argparse.ArgumentParser(...     description='A foo that bars',...     epilog="And that's how you'd foo a bar")>>> parser.print_help()usage: argparse.py [-h]A foo that barsoptional arguments: -h, --help  show this help message and exitAnd that's how you'd foo a bar

Parents: A list composed of ArgumentParser objects. Their 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: Help information output format,

Prefix_chars: Parameter prefix. The default value is '-'

>>> 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, before 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, you can put them in the file for reading. In this example, parser. parse_args (['-F', 'foo', '@args.txt'will be read from args.txt, which is equivalent to ['-F', 'foo', '-F', 'bar'].

Argument_default: Global default value of the parameter. For example, if you want to disable parse_args from being added by default, you 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()

When parser. parse_args (), foo and bar are not automatically parsed.

Conflict_handler: Conflict resolution policy. By default, an error occurs in the conflict:

>>> 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 a 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 FOO   new foo help

 Add_help: If it is set to False, the-h -- help information is no longer displayed in the help information.

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 parameters: optional parameters and location parameters.

Add optional parameters:

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

Add location parameters:

>>> parser.add_argument('bar')

When parse_args () is running, '-' is used to authenticate the optional parameter, and the rest is the location parameter.

>>> 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

If there is no location parameter during parsing, an error will be reported.

Action:The default value is store.

Store_const, whose values are stored in 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. The value is 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: Save As a list and add it according to key const 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 times the parameter appears

>>> parser = argparse.ArgumentParser()>>> parser.add_argument('--verbose', '-v', action='count')>>> parser.parse_args('-vvv'.split())Namespace(verbose=3)

Help: help information

Version: version

>>> 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 of 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? First, obtain the parameter from the command line. If not, obtain the parameter from the const, and then get the parameter 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 case 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.parse_args([])Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,          outfile=<open file '<stdout>', mode 'w' at 0x...>)

Const: Save a constant

Default: Default Value

Type: Parameter type

Choices: Available values

>>> 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] {1,2,3}doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)

Required: Required

Desk: Can be used as a parameter name

>>> parser = argparse.ArgumentParser()>>> parser.add_argument('--foo', dest='bar')>>> parser.parse_args('--foo XXX'.split())Namespace(bar='XXX')
4. parsing Parameters

Parameters can be written in the following ways:

The most common space separation:

>>> 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 Options are separated by =

>>> parser.parse_args('--foo=FOO'.split())Namespace(foo='FOO', x=None)

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. You can use the vars () built-in function to convert it into a dictionary:

>>> parser = argparse.ArgumentParser()>>> parser.add_argument('--foo')>>> args = parser.parse_args(['--foo', 'BAR'])>>> vars(args){'foo': 'BAR'}

  


How does python get the content in the cmd command box?

Use popen to run the process and open the pipeline to perform input and output operations through the pipeline. See the subprocess documentation for an example:
Data = subprocess. Popen (cmd, stdout = subprocess. PIPE, stderr = subprocess. PIPE, shell = True) li = data. stdout. readline ()

How does python clear command lines?

In the idle interaction environment, ctrl + f6 can clear the impact of previous command lines in the interaction environment.
Windows command line, no way, only exit () first, then cls clear
I don't know what you want to do to clear the command line?

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.