Created
March 5, 2018 08:08
-
-
Save davidnvq/87971c1a0e4e2fc15ab7658cfc29bc2c to your computer and use it in GitHub Desktop.
Argparse Python Tutorial
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
# The recommended command-line parsing module in the Python standard library | |
# Read the document here | |
# https://docs.python.org/2/howto/argparse.html | |
"""Tutorial of using Argparse""" | |
import argparse | |
parser = argparse.ArgumentParser() | |
## Positional argument | |
parser.add_argument("square", help="display a square of a given number") | |
## Optional argument | |
# --verbose used like a flag | |
parser.add_argument("--verbose", help="increase output verbosity", | |
action="store_true") | |
# Short option | |
# parser.add_argument("-v", "--verbose", help="increase output verbosity", | |
# action="store_true") | |
args = parser.parse_args() | |
print(args.square ** 2) | |
if args.verbose: | |
print("Verbosity is turned on") | |
## Running on command-line | |
$ python prog.py --help | |
usage: prog.py [-h] [-v] | |
optional arguments: | |
-h, --help show this help message and exit | |
-v, --verbose increase output verbosity | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment