Skip to content

Instantly share code, notes, and snippets.

@pknowledge
Created September 26, 2018 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pknowledge/21573f2b7d43f5d128b9bdb2a106def9 to your computer and use it in GitHub Desktop.
Save pknowledge/21573f2b7d43f5d128b9bdb2a106def9 to your computer and use it in GitHub Desktop.
Python, argparse, and command line arguments example
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 -
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