cmd2 icon indicating copy to clipboard operation
cmd2 copied to clipboard

Per-command clean-up registration

Open anselor opened this issue 3 years ago • 1 comments

Currently the only way to handle a SIGINT is overriding sigint_handler() in the cmd2.Cmd main class.

We now have CommandSets, allowing different sets of functionality to be written in relative isolation from each other. What would be useful would be a way to optionally register a custom cleanup function for a command in the event of an interrupt.

Thinking an optional decorator on a command that points to another method or function that can perform custom cleanup. This allows the cleanup for a command in a CommandSet to be located in the CommandSet.

anselor avatar Feb 01 '22 04:02 anselor

On a related note, cmd2 does provide a way for SIGINT protection during sections of code that need to fully run to avoid putting the app in an unstable state.

Using self.sigint_protection you can do stuff like:

try:
    # Get SIGINT protection while we set up the environment
    with self.sigint_protection:
        setup_step1()
        setup_step2()
        setup_step3()

    # Do stuff now that the environment is set up
     ...
finally:
    # Get SIGINT protection while we tear down the environment
    with self.sigint_protection:
        teardown_step1()
        teardown_step2()
        teardown_step3()

See cmd2.py for actual uses.

When self.sigint_protection is set, cmd2.Cmd.sigint_handler() won't raise a KeyboardInterrupt.

kmvanbrunt avatar Feb 28 '22 21:02 kmvanbrunt