Python+getopt实现命令行带参数

管理员 pythonPython+getopt实现命令行带参数已关闭评论28,1085字数 887阅读2分57秒阅读模式

python中 getopt 模块,该模块是专门用来处理命令行参数的

函数getopt(args, shortopts, longopts = [])文章源自运维生存时间-https://www.ttlsa.com/python/python-getopt-command-args/

参数args一般是sys.argv[1:],shortopts 短格式 (-), longopts 长格式(--)文章源自运维生存时间-https://www.ttlsa.com/python/python-getopt-command-args/

命令行中输入:文章源自运维生存时间-https://www.ttlsa.com/python/python-getopt-command-args/

# python test.py -i 127.0.0.1 -p 80 55 66
# python test.py --ip=127.0.0.1 --port=80 55 66

下面的代码:文章源自运维生存时间-https://www.ttlsa.com/python/python-getopt-command-args/

#!/usr/bin/python

import getopt
import sys


def usage():
    print ' -h help \n' \
          ' -i ip address\n' \
          ' -p port number\n' \
          ''

if __name__ == '__main__':
    try:
        options, args = getopt.getopt(sys.argv[1:], "hp:i:", ['help', "ip=", "port="])
        for name, value in options:
            if name in ('-h', '--help'):
                usage()
            elif name in ('-i', '--ip'):
                print value
            elif name in ('-p', '--port'):
                print value
    except getopt.GetoptError:
        usage()

options,args = getopt.getopt(sys.argv[1:],"hp:i:",["help","ip=","port="])文章源自运维生存时间-https://www.ttlsa.com/python/python-getopt-command-args/

“hp:i:”短格式

h 后面没有冒号:表示后面不带参数,p:和 i:后面有冒号表示后面需要参数文章源自运维生存时间-https://www.ttlsa.com/python/python-getopt-command-args/

["help","ip=","port="]长格式

help后面没有等号=,表示后面不带参数,其他三个有=,表示后面需要参数文章源自运维生存时间-https://www.ttlsa.com/python/python-getopt-command-args/

返回值 options 是个包含元祖的列表,每个元祖是分析出来的格式信息,比如 [('-i','127.0.0.1'),('-p','80')] ;文章源自运维生存时间-https://www.ttlsa.com/python/python-getopt-command-args/

args 是个列表,包含那些没有‘-’或‘--’的参数,比如:['55','66']文章源自运维生存时间-https://www.ttlsa.com/python/python-getopt-command-args/

注意:定义命令行参数时,要先定义带'-'选项的参数,再定义没有‘-’的参数文章源自运维生存时间-https://www.ttlsa.com/python/python-getopt-command-args/ 文章源自运维生存时间-https://www.ttlsa.com/python/python-getopt-command-args/

weinxin
我的微信
微信公众号
扫一扫关注运维生存时间公众号,获取最新技术文章~
管理员
  • 本文由 发表于 26/08/2016 15:30:25
  • 转载请务必保留本文链接:https://www.ttlsa.com/python/python-getopt-command-args/