Skip to content

Instantly share code, notes, and snippets.

@sdvcrx
Created December 27, 2013 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdvcrx/8147713 to your computer and use it in GitHub Desktop.
Save sdvcrx/8147713 to your computer and use it in GitHub Desktop.
arg parser
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count", default=0,
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity >= 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity >= 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer
➜ ~ python test.py 4 -v 1
4^2 == 16
➜ ~ python test.py 4 -v 2
the square of 4 equals 16
➜ ~ python test.py 4 -v 3
16
➜ ~ python test.py -h
usage: test.py [-h] [-v {1,2,3}] square
positional arguments:
square display a square of a given number
optional arguments:
-h, --help show this help message and exit
-v {1,2,3}, --verbosity {1,2,3}
increase output verbosity
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment