我尝试了解 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 个参数运行此脚本时,我的代码将它们分别分配给 firstProduct
和 secondProduct
。然而它不起作用。有没有人告诉我为什么?提前致谢
最佳答案
使用位置参数时省略 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')
关于python使用argparse.ArgumentParser方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18335687/