Created
July 30, 2023 10:40
-
-
Save gdyrrahitis/dab547c8d3b52ccca29c552a4fb243b0 to your computer and use it in GitHub Desktop.
Python minimal program setup
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
def main(cli_args: List[str] = None) -> int: | |
""" | |
`cli_args` makes it possible to call this function command-line-style | |
from other Python code without touching sys.argv. | |
""" | |
try: | |
# Parsing with `argparse` and additional processing | |
# is usually lenghty enough to extract into separate functions. | |
raw_config = _parse_cli( | |
sys.argv[1:] if cli_args is None else cli_args) | |
config = _validate_and_sanitize(raw_config) | |
# Same exception raising idea as the simple approach | |
do_real_work(config.foo, config.bar) | |
except KeyboardInterrupt: | |
print('Aborted manually.', file=sys.stderr) | |
return 1 | |
except Exception as err: | |
# (in real code the `except` would probably be less broad) | |
# Turn exceptions into appropriate logs and/or console output. | |
# non-zero return code to signal error | |
# Can of course be more fine grained than this general | |
# "something went wrong" code. | |
return 1 | |
return 0 # success | |
# __main__ support is still here to make this file executable without | |
# installing the package first. | |
if __name__ == '__main__': | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From https://softwareengineering.stackexchange.com/questions/418600/best-practice-for-python-main-function-definition-and-program-start-exit