python argparse Command Line Parsing of Recommendation

  • 2021-11-13 08:09:24
  • OfStack

argparse is the standard module for python to parse command-line parameters and options.
Most of the time, you need to use a program that parses command line parameters, so that you can input training parameters and options in the terminal window.
The argparse module makes it easy to write a user-friendly command-line interface.
The program defines the parameters it needs, and then argparse will figure out how to parse those parameters from sys. argv. The argparse module will also automatically generate help and user manuals, and give an error message when the user passes in invalid parameters to the program.

test.py


# -*- coding: utf-8 -*-
import argparse

# (1)  Declaration 1 A parser Object that contains parsing the command line to  Python  All the information required for the data type. 
ap = argparse.ArgumentParser(description='Process some integers.')

# (2)  Add parameters 
ap.add_argument("first")  #  Position parameter, which represents the first 1 The parameters that occur are assigned to the first
ap.add_argument("--digit", type=int, help=" Enter a number ")  #  Declaration 1 A int Type parameter 
ap.add_argument("--name", help=" Name ", default="dog")  #  Ibid., default  Represents a default value 

# (3)  Read command line parameters 
args = ap.parse_args()

# (4)  Call these parameters 
print(args.first)
print(args.digit)
print("name = {}".format(args.name))

Call


python test.py position_arg --name qwe

ArgumentParser Object
(1) prog-Name of the program (default: sys. argv [0])
(2) usage-A string describing the purpose of the program (default: generated from arguments added to the parser)
(3) description-Text displayed after parameter help document (default: none)
(4) epilog-Text displayed after parameter help document (default: none)
(5) parents-A list of ap objects whose parameters should also be included
(6) formatter_class-Class for customizing the output format of help documents
(7) prefix_chars-Set of prefix characters for optional parameters (default: '-')
(8) fromfile_prefix_chars-Set of prefix characters used to identify the file name when additional parameters need to be read from the file (default: None)
(8) argument_default-Global Default for Parameter (Default: None)
(9) conflict_handler-Policy for conflict resolution options (usually unnecessary)
(10) add_help-Adds a-h/help option to the parser (default: True)
(11) allow_abbrev-Allow long abbreviation option if abbreviation is unambiguous (default: True)

add_argument () method
(1) name or flags-A list of 1 name or 1 option string. (E. G. foo or-f,-foo)
(2) action-Indicates the action to be performed by this option
(3) default-Default
(4) dest-Used to specify the location of the parameter, the name of the attribute added to the object returned by parse_args ().
(5) type-is the parameter type. (E. G. int)
(6) choices-used to select the range of input parameters. (E. G. choice = [1, 5, 10])
(7) help-Used to describe the effect of this option
(8) nargs-The number of command-line arguments that should be consumed.
(9) const-A constant selected by 1 action and 1 nargs.
(10) required-Whether this command-line option can be omitted (only options are available).
(11) metavar-Example of parameter values used in the usage method message.


import argparse
import logging

"""
" File Description:
" dump model && deploy
"
" Created by zz on 2021/6/22.
" Mail: zz@baidu.com
"""
logging.basicConfig(level=logging.DEBUG)


def parse_args():
	ap = argparse.ArgumentParser(prog="deploy tool", description='dump or calib model && deploy')
	ap.add_argument("deploy_path", type=str, help="deploy base path")
	ap.add_argument("exp_name", type=str, help="train exp name")
	subparser = ap.add_subparsers(title="model deploy subparser", dest="mode")

	# subparser
	model_deploy_parser = subparser.add_parser("model", help="model deploy")
	model_deploy_parser.add_argument("--default", default=False, type=bool, help="whether that's default model")

	calib_deploy_parser = subparser.add_parser("calib", help="offline calib deploy")
	calib_deploy_parser.add_argument("--input", required=True, type=str, help="model offline calib file")

	args = ap.parse_args()
	return args

# global args
args = parse_args()
mode = args.mode
deploy_path = args.deploy_path
exp_name = args.exp_name

def main():
	if mode == "model":
		_deploy_model()
	elif mode == "calib":
		_deploy_calib()
	else:
		logging.error( "Mode error")

if __name__ == '__main__':
	main()

Related articles: