Python命令行参数处理之argparse模块

介绍

平时我们想要了解一个命令的用法时,会使用『 --help 』或是『 --version 』参数,Python中也可以自定义命令行参数。

用法实例

先创建一个Python脚本test.py

import argparse

# 创建解析
parser = argparse.ArgumentParser(prog="This is a description.")

# 添加位置参数(必须参数)
parser.add_argument("name",         type = str,                  help = "Your name")
parser.add_argument("birth",        type = str,                  help = "birthday")
# 添加可选参数
parser.add_argument("-r",'--race',  type = str, dest = "race", help = u"民族")
# 可以限定范围
parser.add_argument("-a", "--age",  type = int, dest = "age",    help = "Your age", default = 0, choices=range(120))
parser.add_argument('-s',"--sex",   type = str, dest = "sex",    help = 'Your sex', default = 'male', choices=['male', 'female'])
parser.add_argument("-p","--parent",type = str, dest = 'parent', help = "Your parent", default = "None", nargs = '*')
parser.add_argument("-o","--other", type = str, dest = 'other',  help = "other Information",required = False, nargs = '*')

# 解析参数
args = parser.parse_args()

# 使用命令行传入的参数
print('my name is ',args.name)
print('my birthday is ',args.birth)
print(args)

然后用命令行运行

python test.py --help

python test.py doghead 2020.02.20
# my name is  doghead
# my birthday is  2020.02.20
 #Namespace(age=0, birth='2020.02.20', name='doghead', other=None, parent='None', race=None, sex='male')

python test.py doghead 2020.02.20 -r han -a 6 -s male -p Mom Dad -o 1 2 3 4 5
# my name is  doghead
# my birthday is  2020.02.20
# Namespace(age=6, birth='2020.02.20', name='doghead', other=['1', '2', '3', '4', '5'], parent=['Mom', 'Dad'], race='han', sex='male')
posted @ 2020-01-22 16:43  MrDoghead  阅读(386)  评论(0编辑  收藏  举报