Python parses the command line to read the parameter -- How to Use the argparse module, python -- argparse

Source: Internet
Author: User

Python parses the command line to read the parameter -- How to Use the argparse module, python -- argparse

In projects with multiple files or coordination between different languages, python scripts often need to read parameters directly from the command line. The omnipotent python comes with the aruplase package, which makes this work simple and standardized. PS: The optparse package is similar, but it is more troublesome to write.

If the script is simple or temporary, and there are no Complex Parameter options, you can directly usesys.argvRead the parameters after the script in sequence (the default read format is string format ). For example, the script named test. py is as follows:

import sysprint "Input argument is %s" %(sys.argv[0])

Run python test. py help in the shell script to obtain the result of Input argument is help.

1) General Form

However, in most cases, the script may need multiple parameters, and the type usage of each parameter is different, in this case, adding a label before the parameter indicates that the type and purpose of the parameter are very useful, and the argparse module can be used to conveniently achieve this purpose.

We also use a script named test. py to give you a question:

Import argparseparser = argparse. argumentParser (description = "your script description") # The description parameter can be used to insert information describing the purpose of the script. It can be empty. add_argument ('-- verbose', '-V', action = 'store _ true', help = 'verbose mode') # Add the -- verbose tag. The label alias can be-v, here, action indicates that when the read parameter -- verbose/-v appears # the verbose value of the parameter dictionary is True, the help parameter is used to describe the purpose or significance of the -- verbose parameter. Args = parser. parse_args () # store the variable in the dictionary of tag-value into the args dictionary if args. verbose: print "Verbose mode on! "Else: print" Verbose mode off! "

Runpython test.pyWhen verbose/-v is followed, the former is output. If nothing is output, the latter is output. If you enter a parameter other than -- verbose/-v, the following error occurs: unrecognized arguments.
A little bit, the way the value of the action parameter table is given to the key, here the bool type is used; if it is 'Count', The -- verbose tag appears as the verbose value; 'append' indicates that the value after this signature is saved to the same Array and then assigned a value. (Well, generally, the latter two methods are rarely used)
The PS: -- help Tag is automatically created when the argparse module is used. Therefore, we generally do not need to define the help information.

$ python test.py --helpusage: test.py [-h] [--verbose]your script descriptionoptional arguments:  -h, --help    show this help message and exit  --verbose, -v   verbose mode 

2) required parameters

This mode is used to ensure that some required parameters are input.

Parser. add_argument ('-- verbose', required = True, type = int)

The required label indicates that the -- verbose parameter is required and the type is int. If the input is of another type, an error is returned.

3) positional arguments)

The location parameter is similar to the sys. argv call. The parameter does not have an explicit -- xxx or-xxx tag. Therefore, the call attribute is the same as sys. argv.

Parser. add_argument ('filename') # assign the key named filename to args = parser. parse_args () print "Read in % s" % (args. filename)

Inputpython test.py test.txtRead in test.txt

In addition, you can use the nargs parameter to limit the number of input location parameters. The default value is 1. Of course, the nargs parameter can also be used for common parameters with tags.
Parser. add_argument ('num', nargs = 2, type = int) indicates that the script can read two integers and assign the num key (the value is an array of two integers ). Nargs can also '*' to indicate that all input values will be used as the parameter values for this location if the parameter is input; '+' indicates that at least one parameter is read. '? 'Indicates that either the location parameter does not exist or only one parameter is required. (PS: the usage of the regular expression is the same as that of the regular expression .)

For example:

parser.add_argument('filename')parser.add_argument('num', nargs='*)

You can run python test. py text.txt 1 2.

Because there are no tags, you need to be careful when using location parameters.

4) input type

As mentioned earlier, you can use the type parameter to specify the input parameter type. The type can also indicate the type of file operations to directly perform file read/write operations.

Parser. add_argument ('file', type = argparser. fileType ('R') # Read the file args = parser. parse_args () for line in args. file: print line. strip ()

5) default parameter values

In general, some default parameters are set so that you do not need to enter some parameters that do not need to be changed each time. You can use the default parameter.

parser.add_argument('filename', default='text.txt')

In this case, you can directly run python text. py to get Read in text.txt without entering the file name.

6) candidate Parameter Selection

This parameter indicates that the acceptable values of this parameter can only come from a few candidate values. In addition, an error is reported. Use the choices parameter. For example:

parser.add_argument('filename', choices=['test1.txt', 'text2.txt'])

Refer:

Https://mkaz.tech/python-argparse-cookbook.html

Https://docs.python.org/2/howto/argparse.html

The following is a supplement from other netizens:

I. Introduction:

Argparse is a standard module used by python to parse command line parameters and options. It is used to replace outdated optparse modules. The argparse module is used to parse command line parameters, such as python parseTest. py input.txt output.txt -- user = name -- port = 8080.

Ii. Procedure:

1: import argparse

2: parser = argparse. ArgumentParser ()

3: parser. add_argument ()

4: parser. parse_args ()

Explanation: first import the module, then create a parsing object, and then add the command line parameters and options you want to pay attention to the object, each add_argument method corresponds to a parameter or option that you want to pay attention to. Finally, the parse_args () method is called for resolution. After the resolution is successful, it can be used. The following describes steps 2 and 3.

Iii. Method 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)

These parameters have default values when calling parser. print_help () or when the program is running, because the parameters are incorrect (in this case, the python interpreter actually calls the pring_help () method), these descriptions are printed. Generally, you only need to pass the description parameter, as shown above.

Iv. Method add_argument (name or flags... [, action] [, nargs] [, const] [, default] [, type] [, choices] [, required] [, help] [, metavar] [, dest])

Where:

Name or flags: name or option of the command line parameter. If the command line parameter is not specified and defualt is not set, an error occurs. However, if it is an option, set it to None.

Nargs: Number of command line parameters, which are generally expressed by wildcards ,'? 'Indicates only one,' * 'indicates 0 to multiple, and' + 'indicates at least one

Default: default Value

Type: parameter type. The default value is string, float, int, and other types.

Help: similar to parameters in the ArgumentParser method, they appear in the same way.

These are the most commonly used parts. For more information, see the official documentation. The following is an example of a common situation:

import argparse def parse_args():  description = usage: %prog [options] poetry-file This is the Slow Poetry Server, blocking edition.Run it like this:  python slowpoetry.py <path-to-poetry-file> If you are in the base directory of the twisted-intro package,you could run it like this:  python blocking-server/slowpoetry.py poetry/ecstasy.txt to serve up John Donne's Ecstasy, which I know you want to do.    parser = argparse.ArgumentParser(description = description)     help = The addresses to connect.  parser.add_argument('addresses',nargs = '*',help = help)   help = The filename to operate on.Default is poetry/ecstasy.txt  parser.add_argument('filename',help=help)   help = The port to listen on. Default to a random available port.  parser.add_argument('-p',--port', type=int, help=help)   help = The interface to listen on. Default is localhost.  parser.add_argument('--iface', help=help, default='localhost')   help = The number of seconds between sending bytes.  parser.add_argument('--delay', type=float, help=help, default=.7)   help = The number of bytes to send at a time.  parser.add_argument('--bytes', type=int, help=help, default=10)   args = parser.parse_args();  return args if __name__ == '__main__':  args = parse_args()     for address in args.addresses:    print 'The address is : %s .' % address     print 'The filename is : %s .' % args.filename  print 'The port is : %d.' % args.port  print 'The interface is : %s.' % args.iface  print 'The number of seconds between sending bytes : %f'% args.delay  print 'The number of bytes to send at a time : %d.' % args.bytes</path-to-poetry-file>

Run the Script: python test. py -- port 10000 -- delay 1.2 127.0.0.1 172.16.55.67 poetry/ecstasy.txt

Output:

The address is: 127.0.0.1.
The address is: 172.16.55.67.
The filename is: poetry/ecstasy.txt.
The port is 10000.
The interface is: localhost.
The number of seconds between sending bytes: 1.200000
The number of bytes to send at a time: 10.

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.