您的位置:首页 > 其它

argparse 命令含参数模块

2016-02-28 01:07 369 查看
argparse是python的一个命令行参数模块,可以解析命令行参数,生成帮助等。

你可以这样使用它:

Python代码


#!/usr/bin/python

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=2, type=int, help='the second argument')

p.add_argument('--docs-dir, default="./", help='document directory')

args = p.parse_args()

#可以打印出来查看

print args

#打印某一个参数

print args.one

print args.docs_dir #经过parse_args()函数后参数名称去掉了前面的"--",所有的"-"转换为"_"

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

./test.py

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

./test.py --help 或者 ./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

--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 tip

test.py: error: unrecognized arguments: ./test.py --p 235

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

这时程序可以这样写:

Python代码


#!/usr/bin/python

import sys

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=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 args

print remaining

再次运行程序:

./test.py --p 235

这个时候就会打印出:

命令行代码


Namespace(docs_dir='./', one=1, two=2)

['./test.py', '--p', '235']
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: