您的位置:首页 > 编程语言 > Python开发

Python命令行模块argparse

2016-07-21 11:15 399 查看
先看下面代码:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--address', nargs = '*', default='localhost', help =  "Mandatory, the address to connect")
parser.add_argument('-p', '--port', type=int, help = "The port to listen on. Default is 3868", default=3868)
parser.add_argument('--printbody', action='store_true', default = False, help="Optional. If print body of response")
parser.add_argument('--file', action = 'store', dest='file', help = "Default configuration file")args = parser.parse_args()
print("the address is:", args.address)print("the port listened on is:", args.port)
if(args.printbody):
print("printbody exist")
else:
print("printbody not exist")print("config file:", args.file)

程序help输出如下:
C:\>python argparse_t.py --helpusage: argparse_t.py [-h] [--address [ADDRESS [ADDRESS ...]]] [-p PORT] [--printbody] [--file FILE]optional arguments: -h, --help show this help message and exit --address [ADDRESS [ADDRESS ...]] Mandatory, the address to connect -p PORT, --port PORT The port to listen on. Default is 3868 --printbody Optional. If print body of response --file FILE Default configuration file
执行输出; C:\>python argparse_t.py --addres 10.10.10.10 --port 3868 --file config.cfg --printbody
the address is: ['10.10.10.10']the port listened on is: 3868printbody existconfig file: config.cfg

add_argument()函数参数解释:
(1)nargs:表示该选项可以多个,比如--address选项的help中显示 [ADDRESS [ADDRESS ...]],选项的值存储在列表中
(2)default:选项默认值
(3)type:制定选项的类型,当输入类型不符合要求时报错,比如程序中指定port为in类型,当输入字符时,报错入下:python argparse_t.py --port d,argparse_t.py: error: argument -p/--port: invalid int value: 'd'
(4)help:--help中的输出信息
(5)action store:默认action模式,存储值到指定变量;
  store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag;
  store_true / store_false:布尔开关。可以2个参数对应一个变量;
  append:存储值到列表,该参数可以重复使用;
  append_const:存储值到列表,存储值在参数的const部分指定;
  version 输出版本信息然后退出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  命令行 python argparse