Created
July 20, 2020 10:28
-
-
Save bala-codes/a04df8cfe32cdb3466faca0a6ecf42f0 to your computer and use it in GitHub Desktop.
# Simple Demonstration of Python Argparser with positional and optional arguments
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
# Simple Demonstration of Python Argparser in command line arguments with positional and optional arguments | |
import argparse | |
from distutils.util import strtobool | |
def add_and_display(args): | |
print(args) | |
print() | |
if args.permissions : | |
if args.operation == "add": | |
print("Adding two numbers :", args.number_1 + args.number_2 + args.number_3 + args.number_4) | |
else: | |
print("Subract two numbers :", args.number_1 - args.number_2 - args.number_3 - args.number_4) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description='Trying out some argparsers.') | |
# --permission (Long notation) & -p (Short notation) | |
parser.add_argument('-p','--permissions', type=strtobool, default=False, required=True, | |
help="Whether to display the output") | |
parser.add_argument('-o','--operation', type=str, required=True, choices=["add", "subtract"], | |
help="Operation to be performed") | |
parser.add_argument("-n1","--number_1", type=int, default=0, required=True, | |
help="Placeholder for the first number") | |
parser.add_argument("-n2","--number_2", type=int, default=0, required=False, | |
help="Placeholder for the second number") | |
# number_3 and number_4 are positional arguments and required by default. | |
parser.add_argument("number_3", type=int, help="Placeholder for the third number") | |
parser.add_argument("number_4", type=int, help="Placeholder for the fourth number") | |
# Below code aggregates the data specified in the previous placeholders | |
args = parser.parse_args() | |
add_and_display(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment