Friday, 29 April 2016

Easy way to parse command line arguments in python using argparse

Here is the easiest way to parse command line arguments in python.

import argparse

args = argparse.ArgumentParser(description='Description of the script.')
args.add_argument('-i', '--input', help='Input file name', required=True)
args.add_argument('-o', '--output', help='Output file', required=True)
args = args.parse_args()

input = args.input
output = args.output

print "Input:" + input
print "Ouput:" + output

Rahuls-MacBook-Pro:exception rahuldiyewar$ python -h
usage: [-h] -i INPUT -o OUTPUT

Description of the script.

optional arguments:
  -h, --help            show this help message and exit
  -i INPUT, --input INPUT
                        Input file name
  -o OUTPUT, --output OUTPUT
                        Output file

Rahuls-MacBook-Pro:exception rahuldiyewar$ python -i myinput -o myoutput 

No comments:

Post a Comment