python: argparse模块

在shell环境的python参数处理模块

import argparse
#description(可选参数):在shell环境下,调用'python test.py -h'时显示在开关的注释
parser = argparse.ArgumentParser(description='describe the functionality of this funtion')
parser.add_argument("echo",#必须输入的参数,有多个这样的参数的话,注意输入顺序
                    help='echo the string you use here')#在shell环境下,调用'python test.py -h'时显示的注释

parser.add_argument('--square', #可选输入参数
                    type=int,   #输入参数的类型,默认为字符char类型
                    help='display a square of a given number')

parser.add_argument('-r','--radius',#可选输入参数的简化形式,即用-r代替--radius
                    type=int,
                    default=3,  #当没指定此输入参数时,取默认值为3
                    help='dispaly the radius')

parser.add_argument('--verbose',
                    action='store_true'#当提到这个参数时,取值为True,否则为False; 
                    help='a switch with default being true') #感兴趣的可以试试action='store_false'

parser.add_argument('--switch',
                    type=int,
                    choices=[0, 1, 2],#限定输入参数的可取范围
                    help='I dont know what to say')

parser.add_argument('-i','--iov',
                    action='count',#当没提到-i时,为None; 提到-i时,为1; 提到-ii时,为2, 依此类推。
                    help='increase output verbosity')

#group中的参数,在此的话即,-y -n(或者-ny:-y -n的合并形式) 不能同时提到
group = parser.add_mutually_exclusive_group()
group.add_argument('-y','--yes',action='store_true')
group.add_argument('-n','--no',action='store_true')

args = parser.parse_args()#将参数全部赋给args
print args.echo           #args.参数名: 得到相应参数值
print args                #输出所有参数

感兴趣的话可在shell下分别运行下列命令(假设此python文件名为test.py,而且处在该文件所在目录):
python test.py its_echo
python test.py its_echo –square=1
python test.py its_echo –square 1(square与1中间可以是=号或者空格键)
python test.py its_echo –square=1 -r=4
python test.py its_echo –square=1 -r=4 –verbose
python test.py its_echo –square=1 -r=4 –verbose –switch=1
python test.py its_echo –square=1 -r=4 –verbose –switch=3 (会提示错误)
python test.py its_echo –square=1 -r=4 –verbose –switch=1 -i
python test.py its_echo –square=1 -r=4 –verbose –switch=1 -iii
python test.py its_echo –square=1 -r=4 –verbose –switch=1 -iii -y
python test.py its_echo –square=1 -r=4 –verbose –switch=1 -iii -yn(会提示错误)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值