• 技术文章 >Python技术 >Python基础教程

    python中getopt模块是什么

    小妮浅浅小妮浅浅2021-10-14 15:05:02原创4806

    1、Getopt模块是专门处理命令行参数的模块,用于获取命令行选项和参数。命令行选项使程序参数更加灵活,支持短选项模式(-)和长选项模式(-)。

    2、该模块提供了两种方法和一种异常处理来分析命令行参数。

    实例

    import sys
    import getopt
     
     
    def main(argv):
        input_file = ""
        output_file = ""
        # "hi:o:": 短格式分析串, h 后面没有冒号, 表示后面不带参数; i 和 o 后面带有冒号, 表示后面带参数
        # ["help", "input_file=", "output_file="]: 长格式分析串列表, help后面没有等号, 表示后面不带参数; input_file和output_file后面带冒号, 表示后面带参数
        # 返回值包括 `opts` 和 `args`, opts 是以元组为元素的列表, 每个元组的形式为: (选项, 附加参数),如: ('-i', 'test.png');
        # args是个列表,其中的元素是那些不含'-'或'--'的参数
        opts, args = getopt.getopt(argv[1:], "hi:o:", ["help", "input_file=", "output_file="])
     
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                print('script_2.py -i <input_file> -o <output_file>')
                print('or: test_arg.py --input_file=<input_file> --output_file=<output_file>')
                sys.exit()
            elif opt in ("-i", "--input_file"):
                input_file = arg
            elif opt in ("-o", "--output_file"):
                output_file = arg
        print('输入文件为:', input_file)
        print('输出文件为:', output_file)
     
        # 打印不含'-'或'--'的参数
        for i in range(0, len(args)):
            print('不含'-'或'--'的参数 %s 为:%s' % (i + 1, args[i]))
            
    if __name__ == "__main__":
        main(sys.argv)

    以上就是python中getopt模块的介绍,希望对大家有所帮助。更多Python学习指路:python基础教程

    专题推荐:python getopt
    品易云
    上一篇:python中sys.argv模块的介绍 下一篇:python中argparse库是什么

    相关文章推荐

    • python正则表达式如何匹配内容• python正则表达式查找和替换内容• python中if-elif-else语句的使用注意• python中删除文档的方法• python函数定义的规则• python匿名函数的命名规则• python中rindex函数是什么• python中TKinter组件的使用• python TKinter的消息传递机制• python中TKinter的绑定方法• python TKinter普通菜单的介绍• python TKinter弹出式菜单的使用• python canvas画布的介绍• python中sys.argv模块的介绍

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网