Forked from pknowledge/argparse_optional_argument.py
Created
October 12, 2019 19:09
-
-
Save geo5555/7887082f47717bc7800707c493356009 to your computer and use it in GitHub Desktop.
Python, argparse, and command line arguments example
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 | |
if __name__ == '__main__': | |
# Initialize the parser | |
parser = argparse.ArgumentParser( | |
description="my math script" | |
) | |
# Add the parameters positional/optional | |
parser.add_argument('-n','--num1', help="Number 1", type=float) | |
parser.add_argument('-i','--num2', help="Number 2", type=float) | |
parser.add_argument('-o','--operation', help="provide operator", default='+') | |
# Parse the arguments | |
args = parser.parse_args() | |
print(args) | |
result = None | |
if args.operation == '+': | |
result = args.num1 + args.num2 | |
if args.operation == '-': | |
result = args.num1 - args.num2 | |
if args.operation == '*': | |
result = args.num1 * args.num2 | |
if args.operation == 'pow': | |
result = pow(args.num1, args.num2) | |
print("Result : ", result) | |
# Run script with following command | |
#python argparse_optional_argument.py -n=84 -i=70 -o=+ | |
#--------------------OR----------------- | |
#python argparse_optional_argument.py --num1 80 --num2 45 --operation - |
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 | |
if __name__ == '__main__': | |
# Initialize the parser | |
parser = argparse.ArgumentParser( | |
description="my math script" | |
) | |
# Add the parameters positional/optional | |
parser.add_argument('num1', help="Number 1", type=float) | |
parser.add_argument('num2', help="Number 2", type=float) | |
parser.add_argument('operation', help="provide operator", default='+') | |
# Parse the arguments | |
args = parser.parse_args() | |
print(args) | |
result = None | |
if args.operation == '+': | |
result = args.num1 + args.num2 | |
if args.operation == '-': | |
result = args.num1 - args.num2 | |
if args.operation == '*': | |
result = args.num1 * args.num2 | |
if args.operation == 'pow': | |
result = pow(args.num1, args.num2) | |
print("Result : ", result) | |
# Run script with following command | |
# python argparse_positional_argument.py 84 41 + |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment