python parsing command line options

problem:

  • How the program can parse command-line options

solution

  • argparse Module can be used to parse command-line options

argparse Module

argparse Module is one of the largest in the standard library modules, with a large number of configuration options

dest Parameter specifies the analytical results is assigned to the name of the property

metavar Parameters are used to generate help

action Parameter specifies the attributes corresponding with the processing logic, the normal value  store , stored as a string, Action = 'the append'  for storing a value or more parameter values collected into a single list

 Once the parameters option is specified, you can perform the  parser.parse() way to go. It will process  sys.argv the value and returns a result instance. Each parameter value is set to this example  add_argument() method  dest attribute values specified by the parameters.

nargs role: the argument into a list

import argparse
parser = argparse.ArgumentParser(description='Search some files')

parser.add_argument(dest='filenames',metavar='filename', nargs='*')
args = parser.parse_args()
print(args.filenames)

 

Execute scripts

python test_nargs.py t.txt t1.txt t2.txt

 

 action = 'store_true'  to set the parameters according to the presence or absence of a  Boolean flag

import argparse
parser = argparse.ArgumentParser(description='Search some files')
parser.add_argument('-v', dest='verbose', action='store_true',
                    help='verbose mode')
args = parser.parse_args()
print(args.verbose)

Execute scripts

 

Action = 'Store'  to accept a single value and is stored as a string

import argparse
parser = argparse.ArgumentParser(description='Search some files')
parser.add_argument('-o', dest='outfile', action='store',
                    help='output file')
args = parser.parse_args()
print(args.outfile)

Execute scripts

 

Action = 'the append' appended to the received value list  

import argparse
parser = argparse.ArgumentParser(description='Search some files')
parser.add_argument('-o','--pat', dest='outfile', action='append',
                    help='output file')
args = parser.parse_args()
print(args.outfile)

Execute scripts  

python test_nargs.py -o hello --pat hello1

 

choices = { 'SLOW' , 'FAST' }, default = 'SLOW'   Parameter accepts a value, but it will be possible to select values and compared to detect its legitimacy

import argparse
parser = argparse.ArgumentParser(description='Search some files')
parser.add_argument('--speed', dest='speed', action='store',
                    choices={'slow','fast'}, default='slow',
                    help='search speed')
args = parser.parse_args()
print(args.speed)  

Execute scripts 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/crazymagic/p/11328266.html