Python explains the argparse parameter module (command line parameters) in detail

help(argparse) View the documentation, "argparse - Command-line parsing library", we can know that it is a command-line parsing library and a module related to parameter parsing.

Example 1: Minimal parameter object

Let's start with a simple code, and quickly understand what this parameter is.
Save it as a file like t.py

import argparse
parser = argparse.ArgumentParser(description='easiest test')
parser.add_argument('--test', type=str, default='China')
args = parser.parse_args()
print(args.test)

Then we run this file in the command line

C:\Users\Tony>python t.py --test "I love China"
I love China

Let's analyze this code. First, create a parameter parsing object and assign it to the parser, and then use the add_argument method to add parameters and various options in the parser object. --test is the parameter, and the name of this parameter is customized according to its function. , type=str specifies that the input value type is a string, default='China' is the default value, that is to say, if no parameter is specified, the default value of China will be displayed
For the call after parser.parse_args() parses the parameters, it should be noted that if dest is not specified, it is to directly call the name with the dash removed. If specified, such as dest='showstr', then call the args.showstr attribute , if you still call test, it will report an error, you need to modify it to print(args.showstr)
AttributeError: 'Namespace' object has no attribute 'test'

Example 2: Summing Integers

If no argument is specified, the maximum of these integers is taken

#p.py
import argparse
#Create an ArgumentParser object for parsing
parser = argparse.ArgumentParser(description='handle some integers')
#Add parameters to objects
parser.add_argument('integers', metavar='N', type=int, nargs='+',help='cumulative integer')
parser.add_argument('--sum', dest='accumulate', action='store_const',const=sum, default=max,help='sum(default maximum value)')
#Parse parameters
args = parser.parse_args()
print(args.accumulate(args.integers))

When the parse_args() method is called, it will return two parameter attributes (integers and accumulate), the integers attribute is one or more integers, and the accumulate attribute is the sum() summation function. If there is no --sum parameter, it is the default max () maximum function, default=max
In addition, N can specify the number, nargs='+', which means one or more, it is very simple if you are familiar with regular expressions, it is a wildcard, and '?' means one, and '*' means 0 or more.

print(parser.parse_args(['--sum','1','33','5','6']))
'''
Namespace(accumulate=<built-in function sum>, integers=[1, 33, 5, 6])
'''

We can see a namespace appear where the accumulate property is a sum method and the integers property is a series of integers.
You can view the usage help instructions:

C:\Users\Tony>python p.py -h

usage: p.py [-h] [--sum] N [N ...]

handle some integers

positional arguments:
the accumulated integer

optional arguments:
  -h, --help  show this help message and exit
--sum sum (default maximum value)

Operation with participation without parameter

C:\Users\Tony>python p.py 1 33 5 6
33

C:\Users\Tony>python p.py -sum 1 33 5 6
or
C:\Users\Tony>python p.py 1 33 5 6 --sum
45

Of course, if it is not set according to the parameters, an error will be reported:

C:\Users\Tony>python p.py
#Requires input value N
usage: p.py [-h] [--sum] N [N ...]
p.py: error: the following arguments are required: N

C:\Users\Tony>python p.py 1 33 5.1 6
#If you need to input an integer, the floating point number will report an error
usage: p.py [-h] [--sum] N [N ...]
p.py: error: argument N: invalid int value: '5.1'

It can be seen that in addition to being convenient to use in the command line interface, this parameter object can also make some strict restrictions on it. For example, the type is limited, the type of example 2 is specified as int, it cannot be a floating-point number, if it can be a floating-point number, it is specified as type=float

Example 3: Whether the file has been tampered with

Let's take a look. Under the test directory (three text files are placed), the md5 value of each file is generated. If it is the same as the md5 provided by the official website, it means that the content has not been tampered with. After execution, the MD5 generated by each file will be displayed. value and generate a document named "directory suffix.txt" (the same content)

#m.py
import os
from hashlib import md5
import argparse

def parse_args():
    parser =argparse.ArgumentParser()
    parser.add_argument('--file_dir', type=str)
    return parser.parse_args()

def generate_md5(file_path):
    m =md5()
    file = open(file_path, 'rb')
    f = file.read()
    m.update(f)
    file.close()
    return m.hexdigest()

if __name__ == '__main__':
    args = parse_args()
    file_dir = args.file_dir
    log_path = args.file_dir + '.txt'
    log = open(log_path, 'w+')
    for root, _, files in os.walk(file_dir):
        for file in files:
            file_path = os.path.join(root, file)
            md5_value = generate_md5(file_path)
            print(file + " : " + md5_value)
            log.write(file + " : " + md5_value + '\n')

command line execution

C:\Users\Tony>python m.py --file_dir "C:/Users/Tony/test"
1.txt : 81dc9bdb52d04dc20036dbd8313ed055
2.txt : d84b0391f5ce6b011e4086ed73d9dd9b
3.txt : 2b3b15ac34d69fa01e851d483e61f029

As can be seen from this code, the md5 value of all files under the directory can be obtained by specifying a parameter of a file directory. Of course, you can also make some explanations like in Example 2: parser.add_argument('--file_dir', type=str,help='specify the directory where the file is located') Add a description of the help parameter.

C:\Users\Tony>python m.py -h
usage: m.py [-h] [--file_dir FILE_DIR]

optional arguments:
  -h, --help           show this help message and exit
--file_dir FILE_DIR specifies the directory where the file is located

parser = argparse.ArgumentParser('Batch generation of files MD5 value')
parser.add_argument('--file_dir',dest='fdir',type=str,help='Specify the directory where the file is located')
print(parser.print_help())

'''
usage: Batch generation of files MD5 value [-h] [--file_dir FDIR]

optional arguments:
  -h, --help       show this help message and exit
  --file_dir FDIR  Specify the directory where the file is located
None
'''

custom type

In addition to basic types, you can also customize types, as follows to define a type that can only be a value of a perfect square number

#d.py
import argparse
import math

def perfect_square(s):
    v=int(s)
    vs=math.sqrt(v)
    if vs!=int(vs):
        msg="%r not a perfect square" %s
        raise argparse.ArgumentTypeError(msg)
    return v

parser=argparse.ArgumentParser(description='custom type')
parser.add_argument('hi',type=perfect_square,help='only perfect squares')
args = parser.parse_args()
print(args.hi)

Command line run:

C:\Users\Tony>python d.py 3
usage: d.py [-h] hi
d.py: error: argument hi: '3' is not a perfect square

C:\Users\Tony>python d.py -h
usage: d.py [-h] hi

custom type

positional arguments:
hi can only be a perfect square

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

It can be seen that the hi parameter is a positional argument (positional parameter), that is to say, it is required, unlike the optional arguments (optional parameter) with a dash in front of it.

choices option limitation

In addition to the above type restrictions and customizable types, it can also be limited to some custom scopes

#c.py
parser=argparse.ArgumentParser(description='custom options')
parser.add_argument('sel',type=int,choices=range(1,9),help='please enter[1-9)range of integers')
args = parser.parse_args()
print(args.sel)

command line execution
C:\Users\Tony>python c.py 10
usage: c.py [-h] {1,2,3,4,5,6,7,8}
c.py: error: argument sel: invalid choice: 10 (choose from 1, 2, 3, 4, 5, 6, 7, 8)

required Required parameters

We can also specify optional parameters as required, if not specified:

parser=argparse.ArgumentParser(description='custom options')
parser.add_argument('--sel',type=int,choices=range(1,9),help='please enter[1-9)range of integers')
print(parser.parse_args([]))

In this example, we know that the sel parameter is optional, so there will be no error, the result: Namespace(sel=None)
If you add a required=True

parser.add_argument('--sel',required=True,type=int,choices=range(1,9),help='please enter[1-9)range of integers')
#Execution will report an error:
usage: ipykernel_launcher.py [-h] --sel {1,2,3,4,5,6,7,8}
ipykernel_launcher.py: error: the following arguments are required: --sel
An exception has occurred, use %tb to see the full traceback.
#At this time, the parameter sel is a required parameter.
print(parser.parse_args(['--sel','2']))
Namespace(sel=2)

subcommand

mainly set_defaults The purpose of the method is important when there are multiple parsers.
#s.py
def f(v):
     r=v.x + v.y + v.z
     print('x+y+z=',r)
    
parser = argparse.ArgumentParser(description='Find the sum of three input values')
subparsers = parser.add_subparsers(help='Subcommand usage')
parser_a = subparsers.add_parser('add', help='addition operation')
parser_a.add_argument('--x', type=int)
parser_a.add_argument('--y', type=int)
parser_a.add_argument('--z', type=int)
parser_a.set_defaults(func=f)#parser_a sets the default function to f
args = parser.parse_args()
args.func(args)#run function

Command line execution:

C:\Users\Tony>python s.py add --x 11 --y 2 --z 9
x+y+z= 22

To learn about the usage of some other parameters, you can read the official documentation: argparse

Tags: Python argparse

Posted by skripty on Wed, 13 Jul 2022 02:22:22 +0530