python使用argparse.ArgumentParser方法

时间:2013-08-20 12:57:30

标签: python command-line argparse

我试图了解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。但它不起作用。有人告诉我为什么吗?提前谢谢

2 个答案:

答案 0 :(得分:17)

使用位置参数时省略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')

答案 1 :(得分:9)

除了unutbu's answer之外,您还可以使用metavar属性,以使目标变量和帮助菜单中显示的变量名称不同,如this link所示。

例如,如果你这样做:

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

您可以在args.firstProduct中找到可用的参数,但在帮助中将其列为product_1