python using argparse.ArgumentParser method

孤街浪徒 提交于 2019-12-10 01:21:29

问题


I've tried to learn how argparse.ArgumentParser works and I've write a couple lines for that :

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

I just want to that when User run this script with 2 parameters my code assign them to firstProduct and secondProduct respectively. However it doesn’t work. Is there anyone to tell me why? thanks in advance


回答1:


Omit the dest parameter when using a positional argument. The name supplied for the positional argument will be the name of the argument:

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)

Running % test.py foo bar prints

('foo', 'bar')



回答2:


In addition to unutbu's answer, you may also use the metavar attribute in order to make the destination variable and the variable name that appears in the help menus different, as shown in this link.

For example if you do:

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

You will have the argument available for you in args.firstProduct but have it listed as product_1 in the help.



来源:https://stackoverflow.com/questions/18335687/python-using-argparse-argumentparser-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!