Skip to content

Instantly share code, notes, and snippets.

@stonecharioteer
Created November 23, 2022 08:03
Show Gist options
  • Save stonecharioteer/3a4dc2f6526abc0ae77f001290832b0f to your computer and use it in GitHub Desktop.
Save stonecharioteer/3a4dc2f6526abc0ae77f001290832b0f to your computer and use it in GitHub Desktop.
Safe exit for command line applications in python.
import sys
def cli_function():
"""This is a python function that offers a CLI or does some long running
task that you might want to interrupt"""
if __name__ == "__main__":
try:
cli_function()
except KeyboardInterrupt as e:
print("User interruption", file=sys.stderr)
sys.exit(1) # 1 = user interruption
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment