2016-04-03 10 views
0

コマンドラインユーティリティの実行手段としてArgparseを使用しています。私は様々な議論が定義されている(それらのうちのいくつかは以下に示されている)。私は引数名、ヘルプ、それぞれの列にデータベースの型を格納するための要件が​​あります。Argparseのpyse.add_argumentから値を抽出する - python

これらの3つをそれぞれの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方法

によって定義された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_argumentactionパラメータに基づいて)Actionサブクラスを作成します。これを独自の変数に保存するか、パーサのリストの_actionsで見つけることができます。

これを印刷すると、その属性の一部が表示されますが、それを調べたり、さらに多くの属性を変更したりすることもできます。

あなたは多くの人がこれらの属性を理解することが argparse.pyファイル内のクラス定義を調べる必要が
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} 

+0

私がarg1.typeを実行すると、私はでintではありませんか? –

+0

私はそれを 'print(arg1.type)'で取得します。 'int'はクラスと整数を生成する関数の両方です。 – hpaulj

関連する問題