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参数被覆盖

posted @ 2018-01-21 22:32  Sch01aR#  阅读(607)  评论(0编辑  收藏  举报