Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple argparse example wanted: 1 argument, 3 results

The documentation for the argparse python module, while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. I don't need to do math on the command line or meddle with formatting lines on the screen or change option characters. All I want to do is "If arg is A, do this, if B do that, if none of the above show help and quit".

like image 228
matt wilkie Avatar asked Sep 15 '11 07:09

matt wilkie


People also ask

How do you add arguments in Argparse?

After importing the library, argparse. ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() .

What does Argparse return?

Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.


1 Answers

Here's the way I do it with argparse (with multiple args):

parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('-f','--foo', help='Description for foo argument', required=True) parser.add_argument('-b','--bar', help='Description for bar argument', required=True) args = vars(parser.parse_args()) 

args will be a dictionary containing the arguments:

if args['foo'] == 'Hello':     # code here  if args['bar'] == 'World':     # code here 

In your case simply add only one argument.

like image 86
Diego Navarro Avatar answered Oct 16 '22 03:10

Diego Navarro