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

我只想在用户使用 2 个参数运行此脚本时,我的代码分别将它们分配给firstProductsecondProduct。但是它不起作用。有没有人告诉我为什么?提前致谢

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 的 answer之外,您还可以使用该metavar属性来使目标变量和帮助菜单中出现的变量名称不同,如此链接所示。

例如,如果您这样做:

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

您将获得可用的参数,args.firstProduct但将其列product_1在帮助中。

于 2015-11-30T19:01:29.387 回答