Created
November 22, 2016 02:03
-
-
Save jovianlin/d69d8a0fed5f8e73a1a7e58899b4ab14 to your computer and use it in GitHub Desktop.
Python ArgParse
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 | |
import sys | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--x', type=float, default=1.0, | |
help='What is the first number?') | |
parser.add_argument('--y', type=float, default=1.0, | |
help='What is the second number?') | |
parser.add_argument('--operation', type=str, default='add', | |
help='What operation? Can choose add, sub, mul, or div') | |
args = parser.parse_args() | |
sys.stdout.write(str(calc(args))) | |
def calc(args): | |
if args.operation == 'add': | |
return args.x + args.y | |
elif args.operation == 'sub': | |
return args.x - args.y | |
elif args.operation == 'mul': | |
return args.x * args.y | |
elif args.operation == 'div': | |
return args.x / args.y | |
if __name__ == '__main__': | |
main() | |
# python argparse_example.py --x=5 --y=3 --operation=mul |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment