1. 程式人生 > >python的命令列解析argparse

python的命令列解析argparse

# -*- coding: utf-8 -*- import argparse args = "-f hello.txt -n 1 2 3 -x 100 -y b -z a -q hello @args.txt i_am_bar -h".split() # 使用@args.txt要求fromfile_prefix_chars="@" # args.txt檔案中應該一行一個引數,想改變行為參考convert_arg_line_to_args()
>>> with open('args.txt', 'w') as fp:
... fp.write('-f\nbar')
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('-f')
>>> parser.parse_args(['-f', 'foo', '@args.txt'])
Namespace(f='bar')
# ArgumentParser引數的簡單說明 ## description - 命令列幫助的開始文字,大部分情況下,我們只會用到這個引數 # epilog - 命令列幫助的結尾文字 # prog - (default: sys.argv[0])程式的名字,一般不需要修改,另外,如果你需要在help中使用到程式的名字,可以使用%(prog)s # prefix_chars - 命令的字首,預設是-,例如-f/--file。有些程式可能希望支援/f這樣的選項,可以使用prefix_chars="/" # fromfile_prefix_chars - (default: None)如果你希望命令列引數可以從檔案中讀取,就可能用到。例如,如果fromfile_prefix_chars='@',命令列引數中有一個為"@args.txt",args.txt的內容會作為命令列引數 # add_help - 是否增加-h/-help選項 (default: True),一般help資訊都是必須的,所以不用設定啦。 ##  parents - 型別是list,如果這個parser的一些選項跟其他某些parser的選項一樣,可以用parents來實現繼承,例如parents=[parent_parser]
>>> 
parent_parser = argparse.ArgumentParser(add_help=False) >>>parent_parser.add_argument('--parent',type=int)>>> foo_parser=argparse.ArgumentParser(parents=[parent_parser])>>> foo_parser.add_argument('foo')>>> foo_parser.parse_args(['--parent','2','XXX'])Namespace(foo='XXX', parent=2)
>>>bar_parser=argparse.ArgumentParser(parents=[parent_parser])>>>bar_parser.add_argument('--bar')>>> bar_parser.parse_args(['--bar','YYY'])Namespace(bar='YYY', parent=None)
## formatter_class - 自定義幫助資訊的格式(description和epilog)。預設情況下會將長的幫助資訊進行<自動換行和消除多個連續空白>。 #三個允許的值: # class argparse.RawDescriptionHelpFormatter 直接輸出description和epilog的原始形式(不進行自動換行和消除空白的操作) # class argparse.RawTextHelpFormatter 直接輸出description和epilog以及add_argument中的help字串的原始形式(不進行自動換行和消除空白的操作) ## class argparse.ArgumentDefaultsHelpFormatter 在每個選項的幫助資訊後面輸出他們對應的預設值,如果有設定的話。這個最常用吧! # argument_default - (default: None)設定一個全域性的選項的預設值,一般每個選項單獨設定,所以這個引數用得少,不細說 # usage - (default: generated)如果你需要修改usage的資訊(usage: PROG [-h] [--foo [FOO]] bar [bar ...]),那麼可以修改這個,一般不要修改。 # conflict_handler - 不建議使用。這個在極端情況下才會用到,主要是定義兩個add_argument中新增的選項的名字發生衝突時怎麼處理,預設處理是丟擲異常。 #註釋一行有##表示這幾個引數比較常用 parser = argparse.ArgumentParser(description="This is a description of %(prog)s", epilog="This is a epilog of %(prog)s", prefix_chars="-+", fromfile_prefix_chars="@", formatter_class=argparse.ArgumentDefaultsHelpFormatter) # ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]) # add_argument的引數是比較複雜的。。。 # name or flags - 指定引數的形式,想寫幾個寫幾個,不過我們一般就寫兩個,一個短引數,一個長引數,看下面的例子"-f", "--file" # 可選的選項,位置不固定,想怎麼寫就怎麼寫,預設是可選的 parser.add_argument("-f", "--file", help="test test test") # 位置固定的選項,例如"prog i_am_bar",這樣子的話,i_am_bar就是bar選項的值啦,預設是必須有的 parser.add_argument("bar", help="test test test") # nargs - 指定這個引數後面的value有多少個,例如,我們希望使用-n 1 2 3 4,來設定n的值為[1, 2, 3, 4] parser.add_argument("-n", "--num", nargs="+", type=int) # 這裡nargs="+"表示,如果你指定了-n選項,那麼-n後面至少要跟一個引數,+表示至少一個,?表示一個或0個,*0個或多個, # default - 如果命令列沒有出現這個選項,那麼使用default指定的預設值 parser.add_argument("+g", "++gold", help="test test test", default="test_gold")#需要prefix_chars包含"+" # type - 如果希望傳進來的引數是指定的型別(例如 float, int or file等可以從字串轉化過來的型別),可以使用 parser.add_argument("-x", type=int) # choices - 設定引數值的範圍,如果choices中的型別不是字串,記得指定type哦 parser.add_argument("-y", choices=['a', 'b', 'd']) # required - 通常-f這樣的選項是可選的,但是如果required=True那麼就是必須的了 parser.add_argument("-z", choices=['a', 'b', 'd'], required=True) # metavar - 引數的名字,在顯示 幫助資訊時才用到. parser.add_argument("-o", metavar="OOOOOO") # help - 設定這個選項的幫助資訊 # dest - 設定這個選項的值就是解析出來後放到哪個屬性中 parser.add_argument("-q", dest="world") args = parser.parse_args(args) # 如果你沒有args引數,那麼就使用sys.argv,也就是命令列引數啦。有這個引數,就方便我們除錯啊 # args.world就是-q的值啦 # action - The basic type of action to be taken when this argument is encountered at the command line.

ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parse_args(). The action keyword argument specifies how the command-line arguments should be handled. The supported actions are:

  • 'store' - This just stores the argument’s value. This is the default action. For example:

    >>> parser = argparse.ArgumentParser() 
  • >>> parser.add_argument('--foo') 
  • >>> parser.parse_args('--foo 1'.split()) Namespace(foo='1')
  • 'store_const' - This stores the value specified by the const keyword argument. (Note that the const keyword argument defaults to the rather unhelpful None.) The 'store_const'action is most commonly used with optional arguments that specify some sort of flag. For example:

    >>> parser = argparse.ArgumentParser() 
  • >>> parser.add_argument('--foo', action='store_const', const=42) 
  • >>> parser.parse_args('--foo'.split()) Namespace(foo=42)
  • 'store_true' and 'store_false' - These are special cases of 'store_const' using for storing the values True and False respectively. In addition, they create default values ofFalse and True respectively. For example:

    >>> parser = argparse.ArgumentParser() 
  • >>> parser.add_argument('--foo', action='store_true') 
  • >>> parser.add_argument('--bar', action='store_false') 
  • >>> parser.add_argument('--baz', action='store_false') 
  • >>> parser.parse_args('--foo --bar'.split()) Namespace(bar=False, baz=True, foo=True)
  • 'append' - This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. Example usage:

    >>> parser = argparse.ArgumentParser() 
  • >>> parser.add_argument('--foo', action='append') 
  • >>> parser.parse_args('--foo 1 --foo 2'.split()) Namespace(foo=['1', '2'])
  • 'append_const' - This stores a list, and appends the value specified by the constkeyword argument to the list. (Note that the const keyword argument defaults to None.) The'append_const' action is typically useful when multiple arguments need to store constants to the same list. For example:

    >>> parser = argparse.ArgumentParser() 
  • >>> parser.add_argument('--str', dest='types', action='append_const',const=str) 
  • >>> parser.add_argument('--int', dest='types', action='append_const',const=int) 
  • >>> parser.parse_args('--str --int'.split()) Namespace(types=[, ])
  • 'count' - This counts the number of times a keyword argument occurs. For example, this is useful for increasing verbosity levels:

    >>> parser = argparse.ArgumentParser() 
  • >>> parser.add_argument('--verbose', '-v', action='count') 
  • >>> parser.parse_args('-vvv'.split()) Namespace(verbose=3)
  • 'help' - This prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. SeeArgumentParser for details of how the output is created.

  • 'version' - This expects a version= keyword argument in the add_argument() call, and prints version information and exits when invoked:

    >>> import argparse 
  • >>> parser = argparse.ArgumentParser(prog='PROG') 
  • >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0') 
  • >>> parser.parse_args(['--version']) PROG 2.0

You can also specify an arbitrary action by passing an object that implements the Action API. The easiest way to do this is to extend argparse.Action, supplying an appropriate __call__method. The __call__ method should accept four parameters:

  • parser - The ArgumentParser object which contains this action.
  • namespace - The Namespace object that will be returned by parse_args(). Most actions add an attribute to this object.
  • values - The associated command-line arguments, with any type conversions applied. (Type conversions are specified with the type keyword argument to add_argument().)
  • option_string - The option string that was used to invoke this action. Theoption_string argument is optional, and will be absent if the action is associated with a positional argument.

An example of a custom action:

>>> class FooAction(argparse.Action): 
... def __call__(self, parser, namespace, values, option_string=None): 
... print '%r%r%r' % (namespace, values, option_string) 
... setattr(namespace, self.dest, values) 
... 
>>> parser = argparse.ArgumentParser() 
>>> parser.add_argument('--foo', action=FooAction) 
>>> parser.add_argument('bar', action=FooAction) 
>>> args = parser.parse_args('1 --foo 2'.split()) 
Namespace(bar=None, foo=None) '1' None Namespace(bar='1', foo=None) '2' '--foo' 
>>> args Namespace(bar='1', foo='2')
# const - A constant value required by some action and nargs selections. # 這兩個自己看幫助文件啦,比較複雜 # http://docs.python.org/library/argparse.html print args

這個複雜的程式碼,最後輸出的幫助資訊是(只要命令列有-h選項就會輸出幫助資訊並退出哦)

usage: argparse_sample.py [-h] [-f FILE] [-n NUM [NUM ...]] [+g GOLD] [-x X]                           [-y {a,b,d}] -z {a,b,d} [-o OOOOOO] [-q WORLD]                           bar This is a description of argparse_sample.py positional arguments:   bar                   test test test optional arguments:   -h, --help            show this help message and exit   -f FILE, --file FILE  test test test (default: None)   -n NUM [NUM ...], --num NUM [NUM ...]   +g GOLD, ++gold GOLD  test test test (default: test_gold)   -x X   -y {a,b,d}   -z {a,b,d}   -o OOOOOO   -q WORLD This is a epilog of argparse_sample.py 原地址:http://blog.iamzsx.me/show.html?id=100001 稍作修改。