Skip to content

Instantly share code, notes, and snippets.

@gdyrrahitis
Created July 30, 2023 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdyrrahitis/dab547c8d3b52ccca29c552a4fb243b0 to your computer and use it in GitHub Desktop.
Save gdyrrahitis/dab547c8d3b52ccca29c552a4fb243b0 to your computer and use it in GitHub Desktop.
Python minimal program setup
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