2016-04-03 79 views
0

我正在使用Argparse作爲命令行實用程序執行的一種手段。我定義了各種參數(如下所示)。我有一個要求存儲參數名稱,幫助,在他們各自的列中鍵入數據庫。在Argparse中從parse.add_argument中提取值-python,

我不知道如何從每個parse.add_argument中提取這三個並將其保存在某個數組/列表中。如果你可以分享任何投入,這將是有益的。

 parser.add_argument("num",help="The fibnocacci number to calculate:", type=int) # how to take the strings on the command line and turn them into objects 
    parser.add_argument("-f","--file",help="Output to the text file",action="store_true") 

回答

0

別人都認爲你想解析commandlline,從args命名空間中的值的結果。但我懷疑你想通過add_argument方法

定義在交互的shell的Action對象我可以定義一個解析器:

In [207]: parser=argparse.ArgumentParser() 

In [208]: arg1= parser.add_argument("num",help="The fibnocacci number to calculate:", type=int) 

In [209]: arg2=parser.add_argument("-f","--file",help="Output to the text file",action="store_true") 

In [210]: arg1 
Out[210]: _StoreAction(option_strings=[], dest='num', nargs=None, const=None, default=None, type=<type 'int'>, choices=None, help='The fibnocacci number to calculate:', metavar=None) 

In [211]: arg2 
Out[211]: _StoreTrueAction(option_strings=['-f', '--file'], dest='file', nargs=0, const=True, default=False, type=None, choices=None, help='Output to the text file', metavar=None) 

In [212]: parser._actions 
Out[212]: 
[_HelpAction(option_strings=['-h', '--help'], dest='help', nargs=0, const=None, default='==SUPPRESS==', type=None, choices=None, help='show this help message and exit', metavar=None), 
_StoreAction(option_strings=[], dest='num', nargs=None, const=None, default=None, type=<type 'int'>, choices=None, help='The fibnocacci number to calculate:', metavar=None), 
_StoreTrueAction(option_strings=['-f', '--file'], dest='file', nargs=0, const=True, default=False, type=None, choices=None, help='Output to the text file', metavar=None)] 

add_argument創建Action子類(基於action參數)。您可以將其保存在自己的變量中,或者在解析器的_actions列表中找到它。

打印時顯示了它的一些屬性,但你可以檢查,甚至更改它們。

In [213]: arg1.help 
Out[213]: 'The fibnocacci number to calculate:' 

In [214]: arg1.type 
Out[214]: int 

In [215]: arg1.dest 
Out[215]: 'num' 

In [217]: vars(arg1) 
Out[217]: 
{'choices': None, 
'const': None, 
'container': <argparse._ArgumentGroup at 0x8f0cd4c>, 
'default': None, 
'dest': 'num', 
'help': 'The fibnocacci number to calculate:', 
'metavar': None, 
'nargs': None, 
'option_strings': [], 
'required': True, 
'type': int} 

很多人需要檢查argparse.py文件中的類定義以瞭解這些屬性。

+0

當我做arg1.type我得到而不是int? –

+0

我用'print(arg1.type)'得到它。 'int'既是一個類又是一個產生整數的函數。 – hpaulj