python之命令行解析工具argparse

以前写python的时候都会自己在文件开头写一个usgae函数,用来加上各种注释,给用这个脚本的人提供帮助文档。

今天才知道原来python已经有一个自带的命令行解析工具argparse,用了一下,效果还不错。

argparse的官方文档请看 https://docs.python.org/2/howto/argparse.html#id1

from argparse import ArgumentParser

p = ArgumentParser(usage='it is usage tip', description='this is a test')
p.add_argument('--one', default=1, type=int,  help='the first argument')
args = p.parse_args()
print args

运行这个脚本test.py.

python test.py -h

输出:

usage: it is usage tip

this is a test

optional arguments:
  -h, --help  show this help message and exit
  --one ONE   the first argument

python test.py --one  8

 输出:

 Namespace(one=8)

可以看到argparse自动给程序加上了-h的选项,最后p.parse_args()得到的是你运行脚本时输入的参数。

如果我们需要用这些参数要怎么办呢,可以通过vars()转换把Namespace转换成dict。

from argparse import ArgumentParser

p = ArgumentParser(usage='it is usage tip', description='this is a test')
p.add_argument('--one', default=1, type=int,  help='the first argument')
p.add_argument('--two', default='hello', type=str, help='the second argument')

args = p.parse_args()
print args
mydict = vars(args)
print mydict
print mydict['two']

运行test.py.

python test.py --one 8  --two good

输出:

Namespace(one=8, two='good')
{'two': 'good', 'one': 8}
good

转载于:https://www.cnblogs.com/streakingBird/p/3928756.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值