首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

argparse下令含参数模块

2012-09-24 
argparse命令含参数模块argparse是python的一个命令行参数模块,可以解析命令行参数,生成帮助等。?你可以这

argparse命令含参数模块

argparse是python的一个命令行参数模块,可以解析命令行参数,生成帮助等。

?

你可以这样使用它:

?

#!/usr/bin/pythonfrom argparse import ArgumentParserp = 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=2, type=int, help='the second argument')p.add_argument('--docs-dir, default="./", help='document directory')args = p.parse_args()#可以打印出来查看print args#打印某一个参数print args.oneprint args.docs_dir   #经过parse_args()函数后参数名称去掉了前面的"--",所有的"-"转换为"_"

?

?

这个文件的名称叫做test.py , 你可以这样运行它:

??????????????????????????????????????????????? ./test.py

想要查看是否有哪些参数可以:

????????????????????????????????????????????????./test.py --help? 或者? ./test.py -h

会打印出以下信息:

?

usage: it is usage tipthis is a testoptional arguments:  -h, --help  show this help message and exit  --one ONE   the first argument  --two TWO   the second argument  --docs-dir DOCS_DIR   document directory

?

?

?然后就可以带参数运行程序:

?

????????????????????????????????????? ./test.py --one 10 --two 20 --docs-dir /opt/docs/

?

?但是在这种情况下:“如果运行程序时带了一个不认识的参数”,就会报错:

?

????????????????????????????????????? ./test.py --p 235

?

usage: it is usage tiptest.py: error: unrecognized arguments: ./test.py --p 235

?

?

有时我们不希望这样,我们的需求是:只提取有用的参数,不认识的参数丢弃但并不需要报错".

这时程序可以这样写:

?

#!/usr/bin/pythonimport sysfrom argparse import ArgumentParserp = 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=2, type=int, help='the second argument')p.add_argument('--docs-dir, default="./", help='document directory')# 这个函数将认识的和不认识的参数分开放进2个变量中args, remaining = p.parse_known_args(sys.argv)#可以打印出来查看print argsprint remaining

?

?

再次运行程序:

?

????????????????????????????????????? ./test.py --p 235

?

这个时候就会打印出:

?

Namespace(docs_dir='./', one=1, two=2)['./test.py', '--p', '235']

?

?

热点排行