I am trying to add command line options to my script, using the following code:
import argparse
parser = argparse.ArgumentParser('My program')
parser.add_argument('-x', '--one')
parser.add_argument('-y', '--two')
parser.add_argument('-z', '--three')
args = vars(parser.parse_args())
foo = args['one']
bar = args['two']
cheese = args['three']
Is this the correct way to do this?
Also, how do I run it from the IDLE shell? I use the command 'python myprogram.py -x foo -y bar -z cheese' and it gives me a syntax error
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 .
The add_argument() method action - The basic type of action to be taken when this argument is encountered at the command line. nargs - The number of command-line arguments that should be consumed. const - A constant value required by some action and nargs selections.
The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.
That will work, but you can simplify it a bit like this:
args = parser.parse_args()
foo = args.one
bar = args.two
cheese = args.three
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With