码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-01-22 18:34:39      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:other   必须   rac   choice   parent   imp   用法   rip   you   

介绍

平时我们想要了解一个命令的用法时,会使用『 --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')

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

标签:other   必须   rac   choice   parent   imp   用法   rip   you   

原文地址:https://www.cnblogs.com/mrdoghead/p/12228911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!