Search code examples
pythonsystemd

sys.exit(1) not working, the script ends with code 0


I have the following code:

try:
    self._collect_persons_status()
except manager.AsteriskManagerError:
    # If it is not possible to continue with the collection of initial
    # person statuses via Asterisk Manager, end the program with an
    # error code.
    logger.debug('*** exit with 1!!')
    sys.exit(1)

This script is handled via systemd (runs as a daemon with a loop).

From the log I can see that *** exit with 1!! is printed, but the script ends with code 0, not 1 as expected:

script-exit-code

What am I doing wrong?


Solution

  • If you have something like this at script top-level, it will prevent sys.exit() from exiting the program:

    try:
        <invoke script entry point>
    except:
        <log the error>
    

    This is because sys.exit() is implemented by raising the SystemExit exception. You can fix the code by changing except: to except Exception which won't catch SystemExit (and some other low-level exceptions that you probably don't want to handle either).