Skip to content

Commit

Permalink
Add on_interrupt decorator.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Nov 18, 2022
1 parent 2c3e624 commit cfd3997
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
v4.2.0
======

Added ``on_interrupt`` decorator.

v4.1.2
======

Expand Down
34 changes: 34 additions & 0 deletions jaraco/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,37 @@ class suppress(contextlib.suppress, contextlib.ContextDecorator):
... {}['']
>>> key_error()
"""


class on_interrupt(contextlib.ContextDecorator):
"""
Replace a KeyboardInterrupt with SystemExit(1)
>>> def do_interrupt():
... raise KeyboardInterrupt()
>>> on_interrupt('error')(do_interrupt)()
Traceback (most recent call last):
...
SystemExit: 1
>>> on_interrupt('error', code=255)(do_interrupt)()
Traceback (most recent call last):
...
SystemExit: 255
>>> on_interrupt('suppress')(do_interrupt)()
>>> with __import__('pytest').raises(KeyboardInterrupt):
... on_interrupt('ignore')(do_interrupt)()
"""

def __init__(self, action='error', /, code=1):
self.action = action
self.code = code

def __enter__(self):
return self

def __exit__(self, exctype, excinst, exctb):
if exctype is not KeyboardInterrupt or self.action == 'ignore':
return
elif self.action == 'error':
raise SystemExit(self.code) from excinst
return self.action == 'suppress'

0 comments on commit cfd3997

Please sign in to comment.