Lucretiel / autocommand

Autocommand turns a python function into a CLI program
GNU Lesser General Public License v3.0
53 stars 9 forks source link

Trap KeyboardInterrupt #18

Closed jaraco closed 1 year ago

jaraco commented 6 years ago

Currently, if one creates a command in Python and one interrupts it with Ctrl+C, it prints a full traceback and exits with a status 1.

I'm inclined to think autocommand/automain should either always trap KeyboardInterrupt exceptions or offer an option/decorator to trap exceptions, e.g.:

@autocommand.autocommand(__name__)
@autocommand.trap_interrupt
def main():
    time.sleep(5)

As I think about it, other commands on interrupt will typically not render a traceback but will exit with a non-zero status.

$ sleep 1
^C
$ echo $?
130

So perhaps that's the functionality that autocommand.trap_interrupt should do.

I don't feel strongly about any of these ideas, but I thought I'd start the discussion to see what others recommend.

Lucretiel commented 6 years ago

While definitely would not want to make this the default behavior, I'd be happy to add a new decorator, and add a matching flag to the autocommand decorator.

jaraco commented 1 year ago

In jaraco.context 4.2, I added the on_interrupt decorator, which could be used in conjunction with autocommand:

@autocommand.autocommand(__name__)
@jaraco.context.on_interrupt('error')
def main(...):
   ...

It also could be used with other CLI entry points (abseil, simple).

Feel free to lift the implementation (or something similar) into autocommand, but for my purposes, I'll probably just use it from jaraco.context.

Lucretiel commented 1 year ago

I was actually curious if there was a third party library that handles this separately, and probably more featurefully than we could do here. Glad you found one!