Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python using argparse.ArgumentParser method

Tags:

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

like image 373
caesar Avatar asked Aug 20 '13 12:08

caesar


People also ask

What does Argparse ArgumentParser () do?

ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() . Some important parameters to note for this method are name , type , and required .

How do you pass arguments to Argparse?

First, we need the argparse package, so we go ahead and import it on Line 2. On Line 5 we instantiate the ArgumentParser object as ap . Then on Lines 6 and 7 we add our only argument, --name . We must specify both shorthand ( -n ) and longhand versions ( --name ) where either flag could be used in the command line.

What command line argument does the ArgumentParser provide by default?

description– text to display before the argument help(default: none) epilog– text to display after the argument help (default: none) parents– list of ArgumentParser objects whose arguments should also be included. formatter_class– class for customizing the help output.


2 Answers

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')
like image 96
unutbu Avatar answered Sep 17 '22 19:09

unutbu


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.

like image 25
villaa Avatar answered Sep 19 '22 19:09

villaa