Batch mode and exit on error with code not 0
See original GitHub issueI need to be able to perform one or more commands directly from CLI call and exit on finish. I’ve resolved this need overriding the onecmd_plus_hooks method of my Cmd class to return True in some circumstances and adding a flag to the CLI to set the batch mode:
def onecmd_plus_hooks(self, line):
stop = Cmd.onecmd_plus_hooks(self, line)
if self.mode == self.MODE_BATCH:
# if there are commands in queue we exec all before stopping
if self.cmdqueue:
return stop
# queue is empty and we are in batch mode, exit
return True
else:
return stop
(This works pretty well so if you think is useful I can try to integrate it in the package)
There is a problem anyway… The expected behaviour of a CLI call in batch mode is that the exit code of the whole call is 0 if the command is successful and different from zero if there are exceptions in command execution or if the user press CTRL+C during the execution.
With the current implementation the command always exits with a 0 code. I’m a bit stuck on how to implement this behaviour. I’m trying modifying a little bit the exceptions handling in onecmd_plus_hooks and _cmdloop methods but I don’t know if it is the correct way to get a solution. Do you have any comment/suggestion?
If you think is worth I can push a branch with my attempt
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (5 by maintainers)

Top Related StackOverflow Question
The is some good discussion in PR #359 in relation to this issue.
I think the tentative resolution is that we will leave this issue open and revisit it after Issue #37 is complete and
cmd2’s underlying parsing logic has been refactored.We agree that some sort of standard way of returning a non-zero exit code to the shell is desirable, we just want to be careful about how it is implemented.
@albertored Hi Alberto,
We are finished with all of the refactoring we wanted to get done before revisiting this issue. Would you like to take another shot at a PR for this?