Python command line parameter parsing

1. Introduction of argparse module

  • argparse is a python standard library used to process command line parameters.
  • In most cases, scripts may need multiple parameters, and each parameter type has different uses. It is very useful to add labels before parameters to indicate the type and use of parameters. This can be easily achieved by using argparse module.

2. Use steps of argparse module

//If you are still confused in the world of programming,
//I don't know my future plan.
//Interested in python,
//Here I recommend my QQ group of learning and communication circles:895 797 751,
//It's all about learning python.
# Import module
import argparse

# This function is used to customize printing help information and to print with color by escaping symbols.
def print_help_description():
    print('\033[1;35m Here you can print your parameter rules\033[0m')
    print('\033[1;35m Examples of script execution: python server.py -s=nginx -a=running\033[0m')

# Instantiating parser parsing objects
parser = argparse.ArgumentParser(add_help=False) # False means no help information is displayed

# Binding parameters to parser objects
parser.add_argument('-h', "--help", help="\033[1;36m Display script help information\033[0m", action='store_true', )
parser.add_argument('-s', "--service",help="\033[1;36mmysql, httpd, nginx, redis, mongodb \033[0m", )
parser.add_argument('-a', "--application",help="\033[1;36mhealth, ping, running, \033[0m")


# Analytical parameters
args = parser.parse_args()

# Start judging the parameters passed by the script
if not args.service or not args.application: # If both conditions are False, the help information will be printed.
    parser.print_help() # print the help information
    print_help_description()  # Print custom functions
else:
    if args.service == 'mysql':
        if args.application == 'health':
            print('check health')
        elif args.application == 'ping':
            print('check ping')
        elif args.application == 'running':
            print('check running')
        else:
            parser.print_help()
            print_help_description()
    elif args.service == 'httpd':
        if args.application == 'health':
            print('check health')
        elif args.application == 'ping':
            print('check ping')
        elif args.application == 'running':
            print('check running')
        else:
            parser.print_help()
            print_help_description()
    else:
        parser.print_help()
        print_help_description()

  • import argparse imports module first.
  • parser = argparse.ArgumentParser () creates a parse object;
  • parser.add_argument() adds command line parameters and options to the object that you want to focus on.
  • parser.parse_args() is parsed.

3.ArgumentParser() method parameters

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);

  • prog: the name of the program (default: sys.argv[0]);
  • Usage: a string describing the usage of a program (default: generated from parser parameters);
  • description: The text before the parameter help information (default: empty);
  • epilog: text after parameter help information (default: empty);
  • parents: A list of ArgumentParser objects whose parameters should be included;
  • formatter_class: A class that customizes help information;
  • prefix_chars: prefix character set with optional parameters (default:'-');
  • fromfile_prefix_chars: The prefix character set of the file that additional parameters should read (default: None);
  • argument_default: Global default of parameters (default: None);
  • conflict_handler: A strategy for resolving optional parameters of a conflict (usually unnecessary);
  • add_help: Add the - h/- help option to the parser (default: True);

4.add_argument() method parameters

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

  • name or flags: Specify the form of parameters and write a few, but we usually write two, a short parameter and a long parameter, such as "- f" and "file";
  • action: When the command line encounters parameters, the default value is store.
  • nargs: specify how many value s follow this parameter;
  • const: Constants required by action and nargs;
  • Default: default value when no parameter is specified;
  • Type: The type that command line parameters should be converted to;
  • choices: A container of values allowed by parameters;
  • required: Can optional parameters be omitted (only for optional parameters);
  • Help: The help information of the parameter is not displayed when it is specified as argparse.SUPPRESS.
  • metavar: The parameter name in the usage specification defaults to the parameter name for the required parameter, and to the optional parameter defaults to the parameter name in full capitalization.
  • dest: The parsed parameter name, by default, for the longest name of the optional parameter, the underscore is converted to underscore.

Keywords: Python Nginx Programming Redis

Added by GreenUser on Mon, 22 Jul 2019 11:03:38 +0300