前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python getopt模块函数用法小

Python getopt模块函数用法小

作者头像
py3study
发布2020-01-09 16:55:05
7200
发布2020-01-09 16:55:05
举报
文章被收录于专栏:python3python3

官方模块说明:https://docs.python.org/2/library/getopt.html#module-getopt

    shell中几乎所有的命令输入的时候都可以携带合适的参数来扩展其功能,例如:ls -l,cp -f,mkdir -p,ping -c 10等。

   前段时间看到同事写了个添加IP的shell脚本,里面使用了高大上的getopt函数,于是就简单琢磨了下,好记性不如烂笔头,索性就做个笔记总结记录一下,也是好久都不写文字性的东西了,开头都不知道该从何写起了。

Python中getopt模块

说明:该模块是用来在终端执行程序时处理命令行参数时使用的。

函数用法格式:getopt.getopt(argsoptions[, long_options])

args:命令行参数,一般是sys.argv[1:],0为脚本本身的名字;

options:shortopts 短格式(“-”)

long_options:longopts 长格式(“--”)

命令行示例:

python config.py -h -d 13 -c allow --help

代码语言:javascript
复制
#!/bin/env python
#coding:utf-8
#

import getopt,sys

def usage():
	"""
The output  configuration file contents.

Usage: config.py [-d|--domain,[number|'m']] [-c|--cache,[allow|deny]] [-h|--help] [-v|--version] [output, =[argument]]

Description
	        -d,--domain	Generate domain configuration,take 13 or 19 number,"m" is the second - tier cities.
	        -c,--cache	Configure cache policy. "allow" or "deny".
	        -h,--help    Display help information.
	        -v,--version  Display version number.
for example:
	python config.py -d 13
	python config.py -c allow
	python config.py -h
	python config.py -d 13 -c allow
"""

def getopttest():
    try:
        options,args = getopt.getopt(sys.argv[1:],"d:c:hv",["domain=","cache=","help","version"])
    except getopt.GetoptError as err:
        print str(err)
      print usage.__doc__
      sys.exit(1)
    for o,a in options:
    #for b in args: # Value other than args agruments for getopt format.

       if o in ("-d","--domain") and a in ("13"):
          ttt.domain(int(a))
      elif o in ("-d","--domain") and a in ("19"):
        ttt.domain(int(a))
      elif o in ("-c","--cache") and a in ("allow"):
        ttt.cache("allow")
      elif o in ("-h","--help"):
          print usage.__doc__
        sys.exit()
      elif o in ("-v","--version"):
          version = xxx
      else:
           print "Using the wrong way,please view the help information."
if __name__ == "__main__":
    getopttest()

代码说明:

    注:ttt.domain为我学习时候随便写的一个类方法,测试的话可以修改为print xxx方式。上面代码是我随便写的供测试说明该模块参数作用的示例,不够严谨,有错误的地方大家就自己改改吧。

    getopt.GetoptError为getopt模块函数异常错误,这里捕获该异常并打印出相关信息等。

    sys.argv[1:]为获取到的命令行参数,赋值给options,options变量在getopt分析完后实际包含两个值,参数和参数值,args值为不属于getopt函数分析内的参数和参数值,例如python config.py -d 13 aaa,则aaa为args变量。

    “d:c:hv”: 此为短格式,“:”表示该参数后面需要加参数值,不加冒号使用时则无需添加参数值,例如:-d 13。

    ["domain=","cache=","help","version"]: 此为长格式,长格式参数后面跟随等号即“=”表示该长格式参数后面需要添加参数值,不加等号则使用时无需添加参数值,例如:--cache allow。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档