Python命令模块argparse学习笔记
Posted Sch01aR#
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python命令模块argparse学习笔记相关的知识,希望对你有一定的参考价值。
首先是关于-h/--help参数的设置
description:位于help信息前,可用于描述help
prog:描述help信息中程序的名称
epilog:位于help信息后
usage:描述程序的用途
add_help:默认为True,设为False后,就不能显示help信息了,执行-h/--help将会报错
conflict_handler:解决参数冲突
prefix_chars:参数前缀,默认为"-"
fromfile_prefix_chars:设置前缀字符,放在文件名之前,对文件里的参数进行读取和执行
argument_default:参数的全局默认值
description/epilog
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import argparse parser = argparse.ArgumentParser(description="The Help Of Python") parser.add_argument("-t","--thread",help="Thread Run",action="store_true") args = parser.parse_args() if args.thread: print(args) else: print("Error")
执行参数-h
运行结果
prog/usage
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import argparse parser = argparse.ArgumentParser(description="The Help Of Python",epilog="End Of Help",usage="Python Run Thread") parser.add_argument("-t","--thread",help="Thread Run",action="store_true") args = parser.parse_args() if args.thread: print(args) else: print("Error")
运行结果
默认的为
如果没有设置prog和usage则显示默认的,prog和usage都设置的话,显示usage的
add_help
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import argparse parser = argparse.ArgumentParser(description="The Help Of Python",epilog="End Of Help",add_help=False) parser.add_argument("-t","--thread",help="Thread Run",action="store_true") args = parser.parse_args() if args.thread: print(args) else: print("Error")
运行结果
conflict_handler
当有参数重复的时候,程序会报错,把conflict_handler设置为resovle就可以解决
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import argparse parser = argparse.ArgumentParser(description="The Help Of Python",epilog="End Of Help") parser.add_argument("-t","--thread",help="Thread Run",action="store_true") parser.add_argument("-t","--thread",help="Thread Run(2)",action="store_true") args = parser.parse_args() if args.thread: print(args) else: print("Error")
运行,报错
给argparse.ArgumentParser()添加conflict_handler="resolve"
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import argparse parser = argparse.ArgumentParser(description="The Help Of Python",epilog="End Of Help",conflict_handler="resolve") parser.add_argument("-t","--thread",help="Thread Run",action="store_true") parser.add_argument("-t","--thread",help="Thread Run(2)",action="store_true") args = parser.parse_args() if args.thread: print(args) else: print("Error")
运行结果
原先的-t/--thread参数被覆盖
以上是关于Python命令模块argparse学习笔记的主要内容,如果未能解决你的问题,请参考以下文章