-
-
Save daeh/2323b89b63e12a09261c17feea68ef80 to your computer and use it in GitHub Desktop.
Python script template
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
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
"""pyscript.py | |
Simple python script template. | |
""" | |
import argparse | |
import os | |
import sys | |
from typing import Any, Dict, Optional | |
def main(arga: Optional[str], argb: int = 1, argc: str = "something", **kwargs) -> str: | |
"""Main script where stuff happens. | |
Args: | |
arga (Optional[str]): Argument a. | |
argb (int, optional): Argument b. Defaults to 1. | |
argc (str, optional): Argument c. Defaults to 'something'. | |
Returns: | |
str: Summary of the arguments. | |
""" | |
summary = f"arga: {arga}\nargb: {argb}\nargc: {argc}\n" | |
return summary | |
def _cli() -> Dict[str, Any]: | |
"""Command-line interface parser. | |
Returns: | |
Dict[str, Any]: Parsed command-line arguments. | |
""" | |
parser = argparse.ArgumentParser( | |
description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter, argument_default=argparse.SUPPRESS | |
) | |
parser.add_argument("arga", nargs="?", default=None, help="This is argument a") | |
parser.add_argument("-b", "--argb", default=0, type=int, help="This is argument b") | |
parser.add_argument("-c", "--argc", default="nothing", type=str, help="This is argument c") | |
parser.add_argument("-f", "--f", nargs="?", default=os.path.realpath(__file__), type=str, help="This is argument f") | |
args = parser.parse_args() | |
return vars(args) | |
if __name__ == "__main__": | |
print(f"\n-- Received {sys.argv} from shell --\n") | |
exit_status = 1 | |
try: | |
output = main(**_cli()) | |
except Exception as e: | |
print(f"Got exception of type {type(e).__name__}: {e}") | |
print("Not sure what happened, so it's not safe to continue -- crashing the script!") | |
print("\n-- SOME ISSUE, EXITING --") | |
exit_status = os.EX_SOFTWARE | |
else: | |
print(f"Output: \n{output}") | |
print("\n-- SCRIPT COMPLETED SUCCESSFULLY --") | |
exit_status = os.EX_OK | |
finally: | |
sys.exit(exit_status) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment