Forked from pknowledge/argparse_optional_argument.py
Created
December 4, 2021 18:50
-
-
Save andersonbosa/39ff726fce7976450216c4405a4918ef to your computer and use it in GitHub Desktop.
Python, argparse, and command line arguments example
This file contains 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 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