How to write command-line arguments using argparse in python

If you want to run a .py python file from command line and you also want to pass the argument using command line you can use argparse library.

This can be done as below:

import argparse
# Command Line arguments
argp = argparse.ArgumentParser()

argp.add_argument('--my_var', dest="my_var", action="store", type=int, default=5)

params = argp.parse_args()

myvar= params.my_var
print(myvar)

Then you cal run this py file on command line as below

python predict.py –my_var 7

Thanks

Leave a Reply