Created
December 27, 2013 14:33
-
-
Save sdvcrx/8147713 to your computer and use it in GitHub Desktop.
arg parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
➜ ~ 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