python argparse(參數解析)模塊學習(一)


class ArgumentParser(_AttributeHolder, _ActionsContainer):
    """Object for parsing command line strings into Python objects.

    Keyword Arguments:
        - prog -- The name of the program (default: sys.argv[0])
        - usage -- A usage message (default: auto-generated from arguments)
        - description -- A description of what the program does
        - epilog -- Text following the argument descriptions
        - parents -- Parsers whose arguments should be copied into this one
        - formatter_class -- HelpFormatter class for printing help messages
        - prefix_chars -- Characters that prefix optional arguments
        - fromfile_prefix_chars -- Characters that prefix files containing
            additional arguments
        - argument_default -- The default value for all arguments
        - conflict_handler -- String indicating how to handle conflicts
        - add_help -- Add a -h/-help option
    """

取自argparse-1.4.0

1、prog 程序名(默認是sys.argv[0])

import argparse
parser = argparse.ArgumentParser()
arg = parser.parse_args()

運行結果:

argparse-learn]# python argparse-3.py -h
usage: argparse-3.py [-h]

optional arguments:
  -h, --help  show this help message and exit

顯示程序名為:argparse-3.py

可通過設置prog改變結果

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_3")
arg = parser.parse_args()

運行結果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h]

optional arguments:
  -h, --help  show this help message and exit

可見程序名已經修改為learn_argparse_3

 

2、usage 程序的使用用例,默認情況下回自動生成

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_3",usage="[-h] [--help] [...] [what you want???]")
arg = parser.parse_args()

運行結果:

argparse-learn]# python argparse-3.py -h
usage: [-h] [--help] [...] [what you want???]

optional arguments:
  -h, --help  show this help message and exit

這里可見learn_argparse_3沒有打印,故在自定義usage是要注意。

可用:

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_3",usage="%(prog)s [-h] [--help] [...] [what you want???]")
parser.add_argument('bar', nargs='+', help='bar help')
arg = parser.parse_args()

運行結果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???]

positional arguments:
  bar         bar help

optional arguments:
  -h, --help  show this help message and exit

 

3、description help參數之前顯示的信息

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_3",
                                 usage="%(prog)s [-h] [--help] [...] [what you want???]",
                                 description="A learn program")
arg = parser.parse_args()

運行結果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???]

A learn program

optional arguments:
  -h, --help  show this help message and exit

description經常會被調用用了簡單的描述這個程序的用途,默認在信息的前后會有換行

 

4、epilog 收場白,可在最后加入你想展示的信息

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_3",
                                 usage="%(prog)s [-h] [--help] [...] [what you want???]",
                                 description="A learn program",
                                 epilog="All for one, one for all")
arg = parser.parse_args()

結果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???]

A learn program

optional arguments:
  -h, --help  show this help message and exit

All for one, one for all

 

5、parents 有時候多個解析器共享一個參數,你可以將這個參數出遞給parent

import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int)

parser = argparse.ArgumentParser(prog="learn_argparse_3",
                                 usage="%(prog)s [-h] [--help] [...] [what you want???]",
                                 description="A learn program",
                                 epilog="All for one, one for all",
                                 parents=[parent_parser])
arg = parser.parse_args()

運行結果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???]

A learn program

optional arguments:
  -h, --help       show this help message and exit
  --parent PARENT

All for one, one for all

可見--parent 共享了

 

6、formatter_class 打印信息格式設定

    - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
        ArgumentDefaultsHelpFormatter -- Formatter classes which
        may be passed as the formatter_class= argument to the
        ArgumentParser constructor. HelpFormatter is the default,
        RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
        not to change the formatting for help text, and
        ArgumentDefaultsHelpFormatter adds information about argument defaults
        to the help.

摘自argparse-1.4.0

可見formatter_class有4個參數:HelpFormatter,RawDescriptionHelpFormatter,RawTextHelpFormatter,ArgumentDefaultsHelpFormatter

  • HelpFormatter 是默認參數
import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int)

parser = argparse.ArgumentParser(prog="learn_argparse_3",
                                 usage="%(prog)s [-h] [--help] [...] [what you want???]",
                                 description='''
                                 other men live ti eat, while i eat to live -- socrates
                                 love rules his kingdom without a sword -- herbert''',
                                 epilog='''
                                 All for one, one for all --                 dumas
                                 we soon believe what we desire --           chaucer
                                 the darkest hour is that before the dawn -- fuller''',
                                 parents=[parent_parser],
                                 formatter_class=argparse.HelpFormatter)
arg = parser.parse_args()

運行結果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???]

other men live ti eat, while i eat to live -- socrates love rules his kingdom
without a sword -- herbert

optional arguments:
  -h, --help       show this help message and exit
  --parent PARENT

All for one, one for all -- dumas we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller

可見HelpFormatter粗暴的去除了所有的'\s' '\n'

  • RawDescriptionHelpFormatter,description和epilog不做修改原樣輸出
import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int)

parser = argparse.ArgumentParser(prog="learn_argparse_3",
                                 usage="%(prog)s [-h] [--help] [...] [what you want???]",
                                 description='''
                                 other men live ti eat, while i eat to live -- socrates
                                 love rules his kingdom without a sword -- herbert''',
                                 epilog='''
                                 All for one, one for all --                 dumas
                                 we soon believe what we desire --           chaucer
                                 the darkest hour is that before the dawn -- fuller''',
                                 parents=[parent_parser],
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
arg = parser.parse_args()

運行結果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???]

                                 other men live ti eat, while i eat to live -- socrates
                                 love rules his kingdom without a sword -- herbert

optional arguments:
  -h, --help       show this help message and exit
  --parent PARENT

                                 All for one, one for all --                 dumas
                                 we soon believe what we desire --           chaucer
                                 the darkest hour is that before the dawn -- fuller

然源碼中好像在line之間加入了個indent,不明所以,有知道的小伙伴可以指導下嗎?

  • RawTextHelpFormatter  會保留預定意的幫助信息中的空格
  • ArgumentDefaultsHelpFormatter會在HelpFormatter的基礎上打印默認值給參數(測試發現在add_argument中無help參數也不會顯示default)
import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int,default=[1, 2, 3, 4, 5, 6])

parser = argparse.ArgumentParser(prog="learn_argparse_3",
                                 usage="%(prog)s [-h] [--help] [...] [what you want???]",
                                 description='''
                                 other men live ti eat, while i eat to live -- socrates

                                 love rules his kingdom without a sword -- herbert''',
                                 epilog='''
                                 All for one, one for all --                 dumas
                                 we soon believe what we desire --           chaucer
                                 the darkest hour is that before the dawn -- fuller''',
                                 parents=[parent_parser],
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
arg = parser.parse_args()

運行結果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???]

                                 other men live ti eat, while i eat to live -- socrates

                                 love rules his kingdom without a sword -- herbert

optional arguments:
  -h, --help       show this help message and exit
  --parent PARENT

                                 All for one, one for all --                 dumas
                                 we soon believe what we desire --           chaucer
                                 the darkest hour is that before the dawn -- fuller

default值並沒有打印出來

import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int,default=[1, 2, 3, 4, 5, 6,],help='parent')

parser = argparse.ArgumentParser(prog="learn_argparse_3",
                                 usage="%(prog)s [-h] [--help] [...] [what you want???]",
                                 description='''
                                 other men live ti eat, while i eat to live -- socrates

                                 love rules his kingdom without a sword -- herbert''',
                                 epilog='''
                                 All for one, one for all --                 dumas
                                 we soon believe what we desire --           chaucer
                                 the darkest hour is that before the dawn -- fuller''',
                                 parents=[parent_parser],
                                 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
arg = parser.parse_args()

運行結果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???]

other men live ti eat, while i eat to live -- socrates love rules his kingdom
without a sword -- herbert

optional arguments:
  -h, --help       show this help message and exit
  --parent PARENT  parent (default: [1, 2, 3, 4, 5, 6])

All for one, one for all -- dumas we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller

7、prefix_chars 自定義前綴,默認'-'

import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int,default=[1, 2, 3, 4, 5, 6,],help='parent')

parser = argparse.ArgumentParser(prog="learn_argparse_3",
                                 usage="%(prog)s [-h] [--help] [...] [what you want???]",
                                 description='''
                                 other men live ti eat, while i eat to live -- socrates

                                 love rules his kingdom without a sword -- herbert''',
                                 epilog='''
                                 All for one, one for all --                 dumas
                                 we soon believe what we desire --           chaucer
                                 the darkest hour is that before the dawn -- fuller''',
                                 parents=[parent_parser],
                                 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                 prefix_chars='=')
arg = parser.parse_args()

這是不能用“python argparse-3.py -h”,會報錯

運行結果:

argparse-learn]# python argparse-3.py =h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???]

other men live ti eat, while i eat to live -- socrates love rules his kingdom
without a sword -- herbert

optional arguments:
  =h, ==help       show this help message and exit
  --parent PARENT  parent (default: [1, 2, 3, 4, 5, 6])

All for one, one for all -- dumas we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller

 

8、fromfile_prefix_chars 有時候將從文件中讀取參數,如果設置fromfile_prefix_chars參數的話,解析器會將帶有這個前綴的參數當作文件處理

 

import argparse
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument('-f')
print parser.parse_args(['-f', 'foo', '@args.txt'])

 

9、argument_default 給所有沒有默認值的參數設置默認值。

import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int,default=[1, 2, 3, 4, 5, 6,],help='parent')
parser = argparse.ArgumentParser(prog="learn_argparse_3",
                                 usage="%(prog)s [-h] [--help] [...] [what you want???]",
                                 description='''
                                 other men live ti eat, while i eat to live -- socrates

                                 love rules his kingdom without a sword -- herbert''',
                                 epilog='''
                                 All for one, one for all --                 dumas
                                 we soon believe what we desire --           chaucer
                                 the darkest hour is that before the dawn -- fuller''',
                                 parents=[parent_parser],
                                 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                 prefix_chars='-',
                                 fromfile_prefix_chars='$',
                                 argument_default='The default value for all arguments')
parser.add_argument('--argument_default')
print parser.parse_args()

運行結果:

Namespace(argument_default='The default value for all arguments', parent=[1, 2, 3, 4, 5, 6])

 

10、conflict_handler argumentparser對象不允許傳入倆個相同的參數,否則會報錯,通過設置conflict_handler為resolve,可以用新的參數覆蓋舊的同名參數

 

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_4",
                                 conflict_handler='resolve')
parser.add_argument('-b','--boy',help='boy')
parser.add_argument('--boy',help='girl')
parser.print_help()

運行結果:

argparse-learn]# python argparse-4.py
usage: learn_argparse_4 [-h] [-b BOY] [--boy BOY]

optional arguments:
  -h, --help  show this help message and exit
  -b BOY      boy
  --boy BOY   girl

 

11、add_help默認情況下ArgumentParser對象對自動添加-h/--help選項,可設置add_help=False取消

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_4",
                                 add_help=False)
parser.add_argument('boy',help='good boy help')
parser.print_help()

運行結果:

argparse-learn]# python argparse-4.py
usage: learn_argparse_4 boy

positional arguments:
  boy  good boy help

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: