python基础:getopt命令行参数解析

本文介绍了Python中的getopt模块,用于处理脚本运行时接收到的命令行参数。通过实例展示了如何使用getopt进行参数解析,帮助用户更好地理解和应用这一功能。

用于解析脚本后指定的参数,例如:

./my.py --name bursto7 -l 10 -n -k

示例如下:

#!/usr/bin/python3
import getopt
import sys

print('参数个数为:', len(sys.argv), '个参数')
print('参数列表:', str(sys.argv))

"""
method: getopt.getopt(args, options[, long_options])
args: 要解析的命令行参数列表。
options: 以字符串的格式定义,options后的冒号(:)表示该选项必须有附加的参数,不带冒号表示该选项不附加参数;
long_options: 以列表的格式定义,long_options 后的等号(=)表示如果设置该选项,必须有附加的参数,否则就不附加参数;
该方法返回值由两个元素组成: 第一个是 (option, value) 元组的列表。 第二个是参数列表,包含那些没有'-'或'--'的参数;
"""


def test_getopt(argv):
    print('执行getopt...............')
    inputfile = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(argv, "hi:o:", ["ifile=", "ofile="])
        print("opts=|%s|" % opts)
        print("args=|%s|" % args)
    except getopt.GetoptError:
        print('usage:', sys.argv[0], ' -i <inputfile> -o <outputfile>')
        sys.exit(1)
    if len(args) > 1:
        print('usage:', sys.argv[0], ' -i <inputfile> -o <outputfile>')
        return
    for opt, arg in opts:
        if opt == '-h':
            print('test.py -i <inputfile> -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
    print('输入的文件为:', inputfile)
    print('输出的文件为:', outputfile)


def test_gnu_getopt(argv):
    """
    gnu_getopt解析命令行参数,选项和非选项可以混合在一起
    而getopt在碰到非选项的参数后,后续即使再碰到选项也不会解析了
    """
    print('执行gun_getopt...............')
    inputfile = ''
    outputfile = ''
    try:
        opts, args = getopt.gnu_getopt(argv, "hi:o:", ["ifile=", "ofile="])
        print("opts=|%s|" % opts)
        print("args=|%s|" % args)
    except getopt.GetoptError:
        print('usage:', sys.argv[0], ' file -i <inputfile> -o <outputfile>')
        sys.exit(1)
    if len(args) == 0:
        print('usage:', sys.argv[0], ' file -i <inputfile> -o <outputfile>')
        sys.exit(1)
    for opt, arg in opts:
        if opt == '-h':
            print('test.py -i <inputfile> -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
    print('输入的文件为:', inputfile)
    print('输出的文件为:', outputfile)


def main(argv):
    argv1 = ['-i', 'file1', '-o', 'file2']
    print("test 1: getopt:", str(argv1))
    test_getopt(argv1)
    argv2 = ['file3', '-i', 'file1', '-o', 'file2']
    print("test 2: getopt:", str(argv2))
    test_getopt(argv2)
    print("test 3: getopt:", str(argv2))
    test_gnu_getopt(argv2)


if __name__ == "__main__":
    main([])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值