1. 程式人生 > >Python命令模塊argparse學習筆記(一)

Python命令模塊argparse學習筆記(一)

efault desc bubuko mut 執行 nbsp () 技術分享 res

首先是關於-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學習筆記(一)