Xavier
Xavier

Reputation: 51

Python script running as service : KeyboardInterrupt crashes if it contains a call to os.system()

I have a Python script which runs as a service. I have specified KillSignal=SIGINT in the .service file, so that KeyboardInterrupt is called when stopping the service, which executes some cleanup code. Everything worked fine until I added a few os.system() calls in the KeyboardInterrupt. This causes the service to no longer stop (until it times out : "stop-sigterm timed out. Killing.") I tried using subprocess.run() instead, to no avail. No problem when running this code in a terminal instead of as a service. Any suggestions on how to solve this?

(This code is running on an embedded Linux system - I need to turn off an LED to indicate the service is not running)

    try:
        while True:
           ...
    except KeyboardInterrupt:
        ...
        os.system('/usr/local/bin/set_led 2 OFF')

Upvotes: 0

Views: 155

Answers (2)

Xavier
Xavier

Reputation: 51

Sorry, my mistake! After all it was not the KeyboardInterrupt which caused the issue. It were other os.system() calls in the service code itself which apparently prevented the KeyboardInterrupt to be called, and caused a hanging service (as already mentioned in os.system() disabling keyboard interrupt signal). Replacing os.system() with subprocess.run() on all places solved it.

Upvotes: 0

Alex Grounds
Alex Grounds

Reputation: 264

Make sure to re-raise the error after you've done your cleanup work, like so:

try:
   while True:
       ...
except KeyboardInterrupt:
    ...
    os. system('/usr/local/bin/set_led 2 OFF')
    raise

If you don't re-raise the error, it's simply gone. Your program no longer knows that it occurred. By re-raising, it will exit as usual after doing the work in the except block.

Upvotes: 1

Related Questions