我试着学习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
和secondProduct
。但是它不起作用。有人告诉我为什么吗?提前谢谢
除了unutbu's answer,您还可以使用
metavar
属性使目标变量和出现在帮助菜单中的变量名不同,如this link。例如,如果您这样做:
您将在
args.firstProduct
中获得参数,但在帮助中将其列为product_1
。使用位置参数时省略
dest
参数。为位置参数提供的名称将是参数的名称:正在运行
% test.py foo bar
打印相关问题 更多 >
编程相关推荐