python Python用法示例的argparse模块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python用法示例的argparse模块相关的知识,希望对你有一定的参考价值。

## Demonstrate how to use argparse in Python 

import argparse 
parser = argparse.ArgumentParser(
	description= "description of the command",
	epilog = "something optional you want to print at the end of summary"
	)

## ------ .add_argument() method -----
# keyword arguments for this method:
# - action = store (default) | store_const | append | append_const | store_true | store_false
# - nargs : expected number of arguments that should be consumed. N | ? | * | + 
# - const: a const value required by some action or nargs
# - default: default value for the arg
# - type: string(default) | int | float |...
# - choices:  similar to ValidateSet() attrib in powershell 
# - required: true|false
# - help
# - dest
# - metavar: a display name for the arg in usage printout 

parser.add_argument('-foo',action='store_const', const = 42)
# then you will have parser.parse_args(['-foo']).foo == 42 
parser.add_argument('--verbose','-v',action='store_true',help="turn on verbose logging")
# NOTE on use of nargs:
# '?'. One argument will be consumed from the command line if possible, and produced as a single item. 
# If no command-line argument is present, the value from default will be produced. 
# Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. 
# In this case the value from const will be produced. 
parser.add_argument('--numbers',nargs='+', dest='numbers')
#type use
parser.add_argument('--max', type=int, help="max number to include in computation")
#choises
parser.add_argument('--sex', choices=['men','women'], required=True)

#---- start parsing args ----
args = parser.parse_args()

以上是关于python Python用法示例的argparse模块的主要内容,如果未能解决你的问题,请参考以下文章

python的argpare和click模块详解

Python 杂记:argparse 模块

python Python用法示例的argparse模块

python杂谈:Python中 的用法示例

Python格式化输出——format用法示例

Json Schema Validator用法(Python示例)