cae*_*sar 17 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
Run Code Online (Sandbox Code Playgroud)
我只是想,当用户运行此脚本有两个参数我的代码并将其分配给firstProduct和secondProduct分别.但它不起作用.有人告诉我为什么吗?提前致谢
unu*_*tbu 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)
Run Code Online (Sandbox Code Playgroud)
运行% test.py foo bar打印
('foo', 'bar')
Run Code Online (Sandbox Code Playgroud)
vil*_*laa 11
除了unutbu的答案之外,您还可以使用该metavar属性以使目标变量和帮助菜单中显示的变量名称不同,如此链接所示.
例如,如果你这样做:
myparser.add_argument("firstProduct", metavar="product_1", help="enter product1")
Run Code Online (Sandbox Code Playgroud)
您可以使用该参数,args.firstProduct但将其列product_1在帮助中.