Created
April 29, 2018 18:32
-
-
Save shengchiliu/b048f1fcc327f091c06ca8e3dfd9e295 to your computer and use it in GitHub Desktop.
Argparse 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
''' Python - Argparse ''' | |
# Calculate the Area of Circle | |
import math | |
import argparse | |
# 1. Without Argparse ----------------------------------------------------------- | |
# def circle_area(radius): | |
# return math.pi * (radius ** 2) | |
# | |
# if __name__ == "__main__": | |
# print(circle_area(3)) | |
''' | |
Execution Command | |
$ python argparse_demo.py | |
''' | |
# 2. Argparse - Basic ----------------------------------------------------------- | |
# parser = argparse.ArgumentParser(description="Calculate the Area of Circle") | |
# parser.add_argument("-r", "--radius", type=int, help="Radius of Circle") | |
# args = parser.parse_args() | |
# | |
# def circle_area(radius): | |
# return math.pi * (radius ** 2) | |
# | |
# if __name__ == "__main__": | |
# print(circle_area(args.radius)) | |
''' | |
Execution Command | |
$ python argparse_demo.py -r 7 | |
''' | |
# 3. Argparse - Advanced -------------------------------------------------------- | |
parser = argparse.ArgumentParser(description="Calculate the Area of Circle") | |
parser.add_argument("-r", "--radius", type=int, metavar="", required=True, help="Radius of Circle") | |
group = parser.add_mutually_exclusive_group() | |
group.add_argument("-q", "--quiet", action="store_true", help="Print Quiet") | |
group.add_argument("-v", "--verbose", action="store_true", help="Print Verbose") | |
args = parser.parse_args() | |
def circle_area(radius): | |
return math.pi * (radius ** 2) | |
if __name__ == "__main__": | |
area = circle_area(args.radius) | |
if args.quiet: | |
print(area) | |
elif args.verbose: | |
print("The area of the circle is %s" % area) | |
else: | |
print("The area = %s" % area) | |
''' | |
Execution Command | |
$ python argparse_demo.py -v -r 7 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment