首页 > 代码库 > python argparse模块
python argparse模块
python argparse 模块的功能是对命令行进行解析,检查命令行是否符合预定义的格式。
使用方法:
1、导入argparse模块 import argparse
2、创建argparse对象 parser = argparse.ArgumentParser()
3、添加命令行相关参数、选项 parser.add_argument("...")
4、解析 parser.parse_args()
例一:(删除指定的zabbix screen)
#!/usr/bin/env python2.7 #coding=utf-8 import sys import argparse import zabbixAuth import zabbixScreen if __name__ == "__main__": #if len(sys.argv) < 2 : # print "usage:",sys.argv[0],"screenName" # sys.exit(1) #if sys.argv[1] == "-h" or sys.argv[1] == "--help": # print "usage:",sys.argv[0],"screenName" # sys.exit() #以下三行的功能等效于以上的if 语句 parser = argparse.ArgumentParser() #创建argparse对象 parser.add_argument("screenName",help="Specifies the screen name of the is will be deleted") parser.parse_args() userAuth=zabbixAuth.zabbix_auth() token=userAuth.user_login() screenObj=zabbixScreen.zabbix_screen() screenidList=screenObj.screen_get(token,sys.argv[1]) if screenidList != None: print "screenID:",screenObj.screen_delete(token,screenidList[0]),"delete success" else: print "The screen:",sys.argv[1],"does not exists"
例二:(创建自定义的zabbix screen)
#!/usr/bin/env python2.7 #coding=utf-8 import sys import argparse import zabbixAuth import zabbixScreen if __name__ == "__main__": #if len(sys.argv) < 4 : # print "usage:",sys.argv[0],"screenName rows columns" # sys.exit(1) #if sys.argv[1] == "-h" or sys.argv[1] == "--help": # print "usage:",sys.argv[0],"screenName rows columns" # sys.exit() #if sys.argv[2].isdigit()==False or sys.argv[3].isdigit()==False: # print "Note: rows and columns is number" # sys.exit() #以上注释的if 语句等效于以下5行 parser = argparse.ArgumentParser() parser.add_argument("screenName",help="Given a string to set the screen name") parser.add_argument("rows",help="Given a number to set the lines",type=int) parser.add_argument("columns",help="Given a number to set the columns",type=int) parser.parse_args() if int(sys.argv[3])>3 : print "Note: columns must be less than 3" sys.exit() userAuth=zabbixAuth.zabbix_auth() token=userAuth.user_login() screenObj=zabbixScreen.zabbix_screen() screenidList=screenObj.screen_get(token,sys.argv[1]) if screenidList != None: print "screen already exists" else: print "screnn",sys.argv[1],"create success, screenid is",screenObj.screen_create(token,sys.argv[2],sys.argv[3],sys.argv[1])
本文出自 “WorkNote” 博客,请务必保留此出处http://caiyuanji.blog.51cto.com/11462293/1896437
python argparse模块
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。