python之命令行解析工具argparse

时间:2023-03-09 05:48:10
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