python語法總結(五):argparse

轉自:https://blog.csdn.net/guoyajie1990/article/details/76739977
轉自:https://blog.csdn.net/ali197294332/article/details/51180628

在很多編程語言中,運行程序可以直接使用function(a,b,……)運行程序,但是在python中就無法實現,那麼我們如何在命令行中傳遞參數呢?在python的中,有一個argparse包,能夠實現。

     當遇到需要參數的情況時,有以下三種處理方法:

     1. 直接給定

               這種方法雖然實現起來方便,但是靈活性非常差,每次都需要打開python文件修改參數。

     2. 手動解析

               這種方法就是寫一個小代碼段用來對輸入的命令進行解析,例如:

               import sys

               def TestSys():

                      for arg in sys.argv[1: ] :        #對輸入的第二個參數到最後,arg[0] 爲第一個參數

                            print arg

                 這個方法也不錯,缺點就是每次輸入的格式必須正確,多一個少一個都不行。

       3. 自動解析

                  就是使用python中的包argparse來解析,下面用一個實例來說明其用法。

                  import argparse #導入包

                  parser = argparse.ArgumentParser()      #創建一個解析處理器

                  #下面設定需要處理的參數,格式如下:

                  #parser.add_argument('-shortname','--fullname',type=?,default=?)#參數數量可選

                  parser.add_argument('para')  #這種格式不滿足上述格式,但是是正確的,並且是最簡單的。它表示

                                                                 #para這個參數是必須有的

                  parser.add_argument('-shortname','--fullname')#存在簡稱和全程的格式在輸入時可有可無

                  parser.add_argument('--fullnage',type=?,default=?)#當然不使用簡稱也是可以的

                  ……

                  ……

                  #可以設置多個參數

                  #獲取參數值

                  args = parser.parse_args()

                  para = args.fullname


                  實例如下(可直接運行):

[python] view plain copy
  1. </pre></p><p><span style="font-size:18px;">                   </span><pre name="code" class="python">#!/usr/bin/env python  
  2.  # encoding: utf-8   
  3. from PIL import Image  
  4. import argparse  
  5.   
  6. parser = argparse.ArgumentParser()  
  7.   
  8. parser.add_argument('file')     #輸入文件  
  9. parser.add_argument('-ob''--output')   #輸出文件  
  10. parser.add_argument('--width', type = int,default=80#輸出字符畫寬  
  11. parser.add_argument('--height', type = int,default = 80#輸出字符畫高  
  12. args = parser.parse_args()  
  13. IMG = args.file  
  14. WIDTH = args.width  
  15. HEIGHT = args.height  
  16. OUTPUT = args.output  
  17.   
  18. print IMG  
  19. print WIDTH  
  20. print HEIGHT  
  21. print OUTPUT  
 

在命令行中輸入:


[python] view plain copy
  1. python c.py ascii_dora.png -o output.txt --width 100 --height 80  

其中 c.py 爲python文件名,ascii_dora.png爲圖片名稱(參數一),output.txt爲輸出文件名(參數二),後面爲長度和寬度兩個參數


結果如下:

ascii_dora.png  #獲得了文件名

100  #獲得了輸入值100

80   #獲得了默認值

output.txt   #獲得輸出文件名


Another example:

[python] view plain copy
  1. def main(argv):  
  2.   
  3.     parser = argparse.ArgumentParser()  
  4.     parser.add_argument('-m','--map')  
  5.     parser.add_argument('-d','--dir', nargs='+')  
  6.     parser.add_argument('-o','--output')  
  7.     args = parser.parse_args()  
  8.     mapfile = args.map  
  9.     srcdir = args.dir  
  10.     output  = args.output  

假設文件名爲a.py, 則示例命令爲:python  a.py -m b.map -d c d f -o outpt.txt

一、argparse模塊

python標準庫模塊argparse用於解析命令行參數,編寫用戶友好的命令行界面,該模塊還會自動生成幫助信息,並在所給參數無效時報錯。
首先看一個例子:

#arg_parse.py
#coding:utf-8
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',const=sum, default=max,
                      help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

將上述代碼保存爲arg_parse.py,在命令行運行該腳本。使用-h選項可以查看幫助信息

$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]
Process some integers.
positional arguments:
 N           an integer for the accumulator
optional arguments:
 -h, --help  show this help message and exit
 --sum       sum the integers (default: find the max)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

如果不指定–sum選項,則找出輸入參數中的最大值,否則求和。

$ python prog.py 1 2 3 4
4
$ python prog.py 1 2 3 4 --sum
10
  • 1
  • 2
  • 3
  • 4

如果給出無效的參數,會給出一個錯誤信息:

$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'
  • 1
  • 2
  • 3

二、ArgumentParser對象

使用argparse的第一步是創建一個 ArgumentParser對象,這個ArgumentParser對象中會保存所有將命令行參數轉爲python數據類型的必需信息。使用 argparse.ArgumentParser創建ArgumentParser對象。

argparse.ArgumentParser(prog=None, 
                        usage=None, 
                        epilog=None, 
                        parents=[], 
                        formatter_class=argparse.HelpFormatter, 
                        prefix_chars='-',                            
                        fromfile_prefix_chars=None,              
                        argument_default=None,
                        conflict_handler='error', 
                        add_help=True)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

下面介紹上述函數幾個常用的參數

1.prog

默認情況下, ArgumentParser對象根據sys.argv[0]的值(不包括路徑名)生成幫助信息中的程序名。

$ cat myprogram.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()

$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]  #注意程序名

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help
$ cd ..
$ python subdir\myprogram.py --help
usage: myprogram.py [-h] [--foo FOO] #注意程序名

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

也可以人爲指定一個程序名

>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.print_help()
usage: myprogram [-h]        #注意程序名

optional arguments:
 -h, --help  show this help message and exit
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

在ArgumentParser對象的函數中,通過 %(prog)s可以引用程序名

>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.add_argument('--foo', help='foo of the %(prog)s program')
>>> parser.print_help()
usage: myprogram [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo of the myprogram program
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

##2.usage
默認情況下,ArgumentParser對象可以根據參數自動生成用法信息

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [-h] [--foo [FOO]] bar [bar ...]  #這是自動生成的usage信息

positional arguments:
 bar          bar help

optional arguments:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

同樣我們也可以指定usage

>>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [options]

positional arguments:
 bar          bar help

optional arguments:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

3.description

description 用於展示程序的簡要介紹信息,通常包括:這個程序可以做什麼、怎麼做。在幫助信息中 description位於用法信息與參數說明之間

>>> parser = argparse.ArgumentParser(description='A foo that bars')
>>> parser.print_help()
usage: argparse.py [-h]  #用法信息

A foo that bars          # description

optional arguments:      #參數說明 
 -h, --help  show this help message and exit
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

4.epilog

與description類似,程序的額外描述信息,位於參數說明之後

>>> parser = argparse.ArgumentParser(
...     description='A foo that bars',
...     epilog="And that's how you'd foo a bar")
>>> parser.print_help()
usage: argparse.py [-h]

A foo that bars

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

And that's how you'd foo a bar
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

5.parents

有時多個解析器可能有相同的參數集,爲了實現代碼複用,我們可以將這些相同的參數集提取到一個單獨的解析器中,在
創建其它解析器時通過parents指定父解析器,這樣新創建的解析器中就包含了相同的參數集。

>>> 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

要注意的一點是:創建父解析器時要指定 add_help=False,否則會報錯(ArgumentParser對象會找到兩個-h/–help選項)。

6.formatter_class

通過 formatter_class 可以定製幫助信息,通過以下幾種格式化類

class argparse.RawDescriptionHelpFormatter
class argparse.RawTextHelpFormatter
class argparse.ArgumentDefaultsHelpFormatter
class argparse.MetavarTypeHelpFormatter
  • 1
  • 2
  • 3
  • 4

RawDescriptionHelpFormatter 用於定製description和epilog,默認情況下description和epilog是自動換行的。

>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     description='''this description\n
...         was indented weird\n
...             but that is okay''',
...     epilog='''
...             likewise for this epilog whose whitespace will
...         be cleaned up and whose words will be wrapped
...         across a couple lines''')
>>> parser.print_help()
usage: PROG [-h]

this description was indented weird but that is okay

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

likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

利用RawDescriptionHelpFormatter實現description和epilog換行

>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.RawDescriptionHelpFormatter,
...     description=textwrap.dedent('''\
...         Please do not mess up this text!
...         --------------------------------
...             I have indented it
...             exactly the way
...             I want it
...         '''))
>>> parser.print_help()
usage: PROG [-h]

Please do not mess up this text!
--------------------------------
   I have indented it
   exactly the way
   I want it

optional arguments:
 -h, --help  show this help message and exit
RawTextHelpFormatter maintains whitespace for all sorts of help text, including argument descriptions.

ArgumentDefaultsHelpFormatter automatically adds information about default values to each of the argument help messages:
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

7.prefix_chars

一般情況下,我們使用’-‘作爲選項前綴,ArgumentParser也支持自定義選項前綴,通過prefix_chars

>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
>>> parser.add_argument('+f')
>>> parser.add_argument('++bar')
>>> parser.parse_args('+f X ++bar Y'.split())
Namespace(bar='Y', f='X')
  • 1
  • 2
  • 3
  • 4
  • 5

8.add_help

是否禁用-h –help選項

>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> parser.add_argument('--foo', help='foo help')
>>> parser.print_help()
usage: PROG [--foo FOO]

optional arguments:
 --foo FOO  foo help
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

三、add_argument()方法

rgumentParser.add_argument(name or flags...[,action][,nargs][,const][,default]
                           [,type][,choices][,required][,help][,metavar][,dest])
  • 1
  • 2

1.name 或 flags

指定一個可選參數或位置參數

>>> parser.add_argument('-f', '--foo')  #指定一個可選參數
>>> parser.add_argument('bar')          #指定一個位置參數
  • 1
  • 2

可選參數是以’-‘爲前綴的參數,剩下的就是位置參數

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-f', '--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args(['BAR'])
Namespace(bar='BAR', foo=None)
>>> parser.parse_args(['BAR', '--foo', 'FOO'])
Namespace(bar='BAR', foo='FOO')
>>> parser.parse_args(['--foo', 'FOO'])
usage: PROG [-h] [-f FOO] bar
PROG: error: too few arguments
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.action

action參數指定應該如何處理命令行參數,預置的操作有以下幾種:
action=’store’ 僅僅保存參數值,爲action默認值

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args('--foo 1'.split())
Namespace(foo='1')
  • 1
  • 2
  • 3
  • 4

action=’store_const’ 與store基本一致,但store_const只保存const關鍵字指定的值

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_const', const=42)
>>> parser.parse_args('--foo'.split())
Namespace(foo=42)
>>> parser.parse_args('--foo 34'.split())
usage: arg_parse.py [-h] [--foo]
arg_parse.py: error: unrecognized arguments: 34
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

action=’store_true’或’store_false’ 與store_const一致,只保存True和False

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
>>> parser.parse_args('--foo --bar'.split())
Namespace(bar=False, foo=True)
  • 1
  • 2
  • 3
  • 4
  • 5

action=’append’ 將相同參數的不同值保存在一個list中

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])
  • 1
  • 2
  • 3
  • 4

action=’count’ 統計該參數出現的次數

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--verbose', '-v', action='count')
>>> parser.parse_args('-vvv'.split())
Namespace(verbose=3)
  • 1
  • 2
  • 3
  • 4

action=’help’ 輸出程序的幫助信息

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='help')
>>> parser.parse_args('--foo'.split()) 
usage: arg_parse.py [-h] [--foo]

optional arguments:
  -h, --help  show this help message and exit
  --foo
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

action=’version’ 輸出程序版本信息

>>> 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
  • 1
  • 2
  • 3
  • 4
  • 5

除了上述幾種預置action,還可以自定義action,需要繼承Action並覆蓋callinit方法。

>>> class FooAction(argparse.Action):
...     def __init__(self, option_strings, dest, nargs=None, **kwargs):
...         if nargs is not None:
...             raise ValueError("nargs not allowed")
...         super(FooAction, self).__init__(option_strings, dest, **kwargs)
...     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')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

3.nargs

默認情況下 ArgumentParser對象將參數與一個與action一一關聯,通過指定 nargs可以將多個參數與一個action相關聯。nargs支持值如下:
N (整數) N個命令行參數被保存在一個list中

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs=2)
>>> parser.add_argument('bar', nargs=1)
>>> parser.parse_args('c --foo a b'.split())
Namespace(bar=['c'], foo=['a', 'b'])
  • 1
  • 2
  • 3
  • 4
  • 5

‘?’ 如果存在該參數且給出了參數值,則從命令行取得該參數,如果存在該參數但未給出參數值,則從const關鍵字中取得參數值,如果不存在該參數,則將生成默認值。可能表述地不到位,還是看結合代碼理解吧

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='?', const='c', default='d')
>>> parser.add_argument('bar', nargs='?', default='d')
>>> parser.parse_args('XX --foo YY'.split())
Namespace(bar='XX', foo='YY')
>>> parser.parse_args('XX --foo'.split())
Namespace(bar='XX', foo='c')
>>> parser.parse_args(''.split())
Namespace(bar='d', foo='d')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

‘*’命令行參數被保存在一個list中

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='*')
>>> parser.add_argument('--bar', nargs='*')
>>> parser.add_argument('baz', nargs='*')
>>> parser.parse_args('a b --foo x y --bar 1 2'.split())
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

‘+’命令行參數被保存在一個list中,要求至少要有一個參數,否則報錯

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', nargs='+')
>>> parser.parse_args('a b'.split())
Namespace(foo=['a', 'b'])
>>> parser.parse_args(''.split())
usage: PROG [-h] foo [foo ...]
PROG: error: too few arguments
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

argparse.REMAINDER 其餘的命令行參數保存到一個list中

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo')
>>> parser.add_argument('command')
>>> parser.add_argument('args', nargs=argparse.REMAINDER)
>>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4.default

如果參數可以缺省,default指定命令行參數不存在時的參數值。

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=42)
>>> parser.parse_args('--foo 2'.split())
Namespace(foo='2')
>>> parser.parse_args(''.split())
Namespace(foo=42)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

5.type

默認情況下,ArgumentParser對象將命令行參數保存爲字符串。但通常命令行參數應該被解釋爲另一種類型,如 float或int。通過指定type,可以對命令行參數執行類型檢查和類型轉換。通用的內置類型和函數可以直接用作type參數的值:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.add_argument('bar', type=open)
>>> parser.parse_args('2 temp.txt'.split())
Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
  • 1
  • 2
  • 3
  • 4
  • 5

6. choices

將命令行參數的值限定在一個範圍內,超出範圍則報錯
Example 1

>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Example 2

>>> parser = argparse.ArgumentParser(prog='doors.py')
>>> parser.add_argument('door', type=int, choices=range(1, 4))
>>> print(parser.parse_args(['3']))
Namespace(door=3)
>>> parser.parse_args(['4'])
usage: doors.py [-h] {1,2,3}
doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

7.required

指定命令行參數是否必需,默認通過-f –foo指定的參數爲可選參數。

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', required=True)
>>> parser.parse_args(['--foo', 'BAR'])
Namespace(foo='BAR')
>>> parser.parse_args([])
usage: argparse.py [-h] [--foo FOO]
argparse.py: error: option --foo is required
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

8.dest

dest 允許自定義ArgumentParser的參數屬性名稱
Example 1

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('bar')
>>> parser.parse_args('XXX'.split())
Namespace(bar='XXX')
  • 1
  • 2
  • 3
  • 4

Example 2

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-f', '--foo-bar', '--foo')
>>> parser.add_argument('-x', '-y')
>>> parser.parse_args('-f 1 -x 2'.split())
Namespace(foo_bar='1', x='2')
>>> parser.parse_args('--foo 1 -y 2'.split())
Namespace(foo_bar='1', x='2')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Example 3

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', dest='bar')
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')
  • 1
  • 2
  • 3
  • 4
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章