20

私はどのようにargparse.ArgumentParser機能するかを学ぼうとしましたが、そのためにいくつかの行を書きました:

global firstProduct
global secondProduct 
myparser=argparse.ArgumentParser(description='parser test')
myparser.add_argument("product1",help="enter product1",dest='product_1')
myparser.add_argument("product2",help="enter product2",dest='product_2')

args=myparser.parse_args()

firstProduct=args.product_1
secondProduct=args.product_2

firstProductユーザーが2つのパラメーターを使用してこのスクリプトを実行すると、コードがそれぞれに割り当てられますsecondProduct。しかし、うまくいきません。理由を教えてくれる人はいますか?前もって感謝します

4

2 に答える 2

24

dest位置引数を使用する場合は、パラメーターを省略します。位置引数に指定された名前は、引数の名前になります。

import argparse
myparser = argparse.ArgumentParser(description='parser test')
myparser.add_argument("product_1", help="enter product1")
myparser.add_argument("product_2", help="enter product2")

args = myparser.parse_args()
firstProduct = args.product_1
secondProduct = args.product_2
print(firstProduct, secondProduct)

ランニング% test.py foo barプリント

('foo', 'bar')
于 2013-08-20T13:01:49.087 に答える
15

unutbu の回答に加えて、このリンクmetavarに示すように、宛先変数とヘルプ メニューに表示される変数名を異なるものにするために属性を使用することもできます。

たとえば、次のようにします。

myparser.add_argument("firstProduct", metavar="product_1", help="enter product1")

で引数を使用できますが、ヘルプのargs.firstProductようにリストされproduct_1ています。

于 2015-11-30T19:01:29.387 に答える