Diveintopython第十章getopt.getopt学习

本文介绍了Python中的getopt模块,该模块用于处理命令行参数。通过示例代码详细解释了getopt函数的使用方法,包括如何解析命令行选项及非选项参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Diveintopython的第十章,用到getopt模块中getopt函数,getopt模块用来处理命令行参数。看了码源的__doc__感觉不是很清楚,度娘了一下,原来__doc__中"""The return value consists of two elements: the first is a list of (option, value) pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of the first argument). """

它的意思是:

在命令行输入: python test.py -i 127.0.0.1 -p 80 55 66

opts返回是个包含元祖的列表,每个元祖是分析出来的格式信息,比如 [('-i','127.0.0.1'),('-p','80')] ;
 args 是个列表,包含那些没有‘-’或‘--’的参数,比如:['55','66']
总结测试:
#!/usr/bin/env python

import sys;
import getopt;

def usage():
    print("Usage:%s [-h|-o|-t] [--help|--output] args...." %sys.argv[0]);


if "__main__" == __name__:
    
    try:
        opts,args = getopt.getopt(sys.argv[1:], "ho:t", ["help", "output="]);
    
        print("============ opts ==================");       
        print(opts);
    
        print("============ args ==================");
        print(args);
        
        #check all param
        for opt,arg in opts:
            if opt in ("-h", "--help"):
                usage();
                sys.exit(1);
            elif opt in ("-t", "--test"):
                print("for test option");
            else:
                print("%s  ==> %s" %(opt, arg));        
        
    except getopt.GetoptError:
        print("getopt error!");
        usage();
        sys.exit(1);
测试结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值