564543 发表于 2016-7-22 10:41:20

Python命令行模块argparse



#!/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 ]] [-p PORT]                     [--printbody] [--file FILE]optional arguments:-h, --help            show this help message and exit--address ]                        Mandatory, the address to connect-p PORT, --port PORTThe 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 --printbodythe address is: ['10.10.10.10']the port listened on is: 3868printbody existconfig file: config.cfgadd_argument()参数解释:(1)nargs:表示该选项可以多个,比如--address选项的help中显示 ],选项的值存储在列表中(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 输出版本信息然后退出。
页: [1]
查看完整版本: Python命令行模块argparse