Exit Codes & Exceptions

Normal processes exit with exit code 0. This can be seen through a RunningCommand.exit_code:

output = ls("/")
print(output.exit_code) # should be 0

If a process terminates, and the exit code is not 0, an exception is generated dynamically. This lets you catch a specific return code, or catch all error return codes through the base class ErrorReturnCode:

try:
    print(ls("/some/non-existant/folder"))
except ErrorReturnCode_2:
    print("folder doesn't exist!")
    create_the_folder()
except ErrorReturnCode:
    print("unknown error")

See also

You can customize which exit codes indicate an error with _ok_code.

Signals

Signals are raised whenever your process terminates from a signal. The exception raised in this situation is SignalException, which subclasses ErrorReturnCode.

try:
    p = sh.sleep(3, _bg=True)
    p.kill()
except sh.SignalException_SIGKILL:
    print("killed")

Note

You can catch SignalException by using either a number or a signal name. For example, the following two exception classes are equivalent:

assert sh.SignalException_SIGKILL == sh.SignalException_9