Python parsing command line read parameters argparse module usage

  • 2020-07-21 09:05:04
  • OfStack

In projects with multiple files or languages, python scripts often need to read parameters directly from the command line. The Universal python package comes with the argprase package to make this job simple and standard. PS: The optparse package is similar, except that it's a little more cumbersome to write.

If the script is simple or temporary and does not have multiple complex parameter options, you can take advantage of it directly sys.argv Read the arguments after the script in turn (the default is string format). Consider the following script named test.py:


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

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

1) General form of 1

In most cases, however, the script will probably require multiple parameters, each of which has a different type, so it is useful to add a label before the parameter indicating the type and purpose of the parameter. The argparse module is very convenient for this purpose.

Use the same script named ES30en.py for an example:


import argparse

parser = argparse.ArgumentParser(description="your script description")      # description The parameter can be used to insert information describing the purpose of the script, and can be empty 
parser.add_argument('--verbose', '-v', action='store_true', help='verbose mode')  #  add --verbose Tag, the tag alias can be -v Here, action Occurs when a parameter is read --verbose/-v when 
                                          #  Parameter dictionary verbose Set the corresponding value to be True And the help Parameters are used to describe --verbose The purpose or meaning of the parameter. 
args = parser.parse_args()                             #  Label variables - The value is stored in dictionary form args The dictionary 
if args.verbose:
  print "Verbose mode on!"
else:
  print "Verbose mode off!"

run python test.py verbose/ -v will output the former, but nothing will output the latter. An error is reported if a parameter other than --verbose/ -- v is entered: unrecognized arguments
The action parameter represents how the value is assigned to the key, using the bool type. If 'count' means the number of times the --verbose tag appears as the value of verbose; 'append' means to place the post-note value into the same array each time it appears. (Well, 1 generally, the latter two are used less than to say more)
PS: --help tags are automatically created when using the argparse module, so there is no need for us to actively define help information in general.


$ python test.py --help
usage: test.py [-h] [--verbose]

your script description

optional arguments:
  -h, --help    show this help message and exit
  --verbose, -v   verbose mode 

2) Required parameters

This pattern is used to ensure that some of the required parameters have input.

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

The required tag means that the verbose parameter is required and of type int, and input of any other type will give an error.

3) Location parameters (positional arguments)

The position argument is similar to the call to ES72en.argv. The argument does not have an explicit --xxx or -xxx tag, so the call property is the same as sys.argv.


parser.add_argument('filename')  #  Enter the first 1 The parameters are given a name filename The key of 
args = parser.parse_args()
print "Read in %s" %(args.filename)

The input python test.py test.txt Output Read in ES84en.txt

In addition, the nargs parameter can be used to limit the number of input position parameters, which defaults to 1. Of course, the nargs parameter can also be used for ordinary labeled parameters.
parser.add_argument('num', nargs=2, type=int) means that the script can read in two integers giving the num key (in this case, an array of values of two integers). nargs can also be used '*' to indicate that all subsequent inputs, if any, will be values for the position parameter; '+' means to read at least one of the location parameters. 'the & # 63; 'indicates that the position parameter either has none or only one. PS: USES 1 with the symbol for the regular expression.

Such as:


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

You can run python ES107en.py ES109en.txt 1 2

Because there is no label, you need to be careful when using position parameters.

4) Input type

As mentioned earlier, the type parameter allows you to specify an input parameter type. The type type can also represent the type of file operation to directly read and write the file.


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 value of parameters

1 Default parameters are usually set so that you don't need to enter some parameters that don't need to be changed every time. The default parameter can be used to achieve this.

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

At this point, run python text.py to get Read in text.txt without having to enter the file name.

6) Selection of candidate parameters

Indicates that the acceptable values for this parameter can only come from certain value candidates, otherwise an error will be reported, using the choices parameter. Such as:

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

Reference:

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

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

Here's what others have added:

1. Introduction:

argparse is the standard python module for parsing command-line arguments and options in place of the outdated optparse module. The argparse module is used to parse command-line arguments such as python parseTest. py input. txt output. txt --user=name --port=8080.

2. Steps:

1: import argparse

2: parser = argparse.ArgumentParser()

3: parser add_argument ()

4: parser parse_args ()

Explanation: First import the module; Then create a parse object; Then add the command-line arguments and options to the object, one for each add_argument method. Finally, the parse_args() method is called for resolution. Once the parsing is successful, it can be used. The following steps 2 and 3 are briefly explained.

3. 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, which are printed when calling parser.print_help () or when running the program because the parameters are incorrect (in this case, the python interpreter is actually calling the pring_help() method).

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

Among them:

name or flags: Command line argument name or option, as above address or -p,--port. Error if command line argument is not given and defualt is not set. But if it is an option, it is set to None

nargs: The number of command line arguments, usually represented by wildcards, where, '? 'means only one, '*' means zero to more, and '+' means at least one

default: Default

type: Type of parameter, default is string string, float, int, etc

help: The parameter function in ArgumentParser method is similar to that in ArgumentParser method

These are the most commonly used places, others can refer to the official documentation. Here is an example that basically covers common situations:


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 --port 10000 --delay 1.2 127.0.0.1 172.16.55.67 poetry/ ecstasy.txt

The output is:

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.


Related articles: