Python argparse用法

import argparse
import sys

parser = argparse.ArgumentParser(description='this is for test.')

parser.add_argument("-i", "--app_id", help="Custom app id")
parser.add_argument("-d", "--config_dir", help="Custom config directory")
parser.add_argument("-f", "--config_file", help="Custom config file name "
                    "(in config directory)")
args = parser.parse_args(sys.argv[1:])

# Set default parameters
app_id = 0000
config_dir = 'test_dir'
config_file = 'test_file'

if args.app_id:
    app_id = args.app_id

if args.config_dir:
    config_dir = args.config_dir

if args.config_file:
    config_file = args.config_file

print('APP_ID: {}, CONFIG_DIR: {}, CONFIG_FILE: {}.'.format(app_id, config_dir, config_file))

  

python.exe . est.py -h
usage: test.py [-h] [-i APP_ID] [-d CONFIG_DIR] [-f CONFIG_FILE]

this is for test.

optional arguments:
-h, --help show this help message and exit
-i APP_ID, --app_id APP_ID
Custom app id
-d CONFIG_DIR, --config_dir CONFIG_DIR
Custom config directory
-f CONFIG_FILE, --config_file CONFIG_FILE
Custom config file name (in config directory)

python.exe . est.py -i 123 -d dir -f file
APP_ID: 123, CONFIG_DIR: dir, CONFIG_FILE: file.

原文地址:https://www.cnblogs.com/zhangwei22/p/10766583.html