Search code examples
pythonloopsdaemonshutdown

How can I create a Python script that runs in the background and can be stopped cleanly?


I have a python script that constantly runs (it has an infinite loop), but I want it to be able to still accept input while running. It will run in the background and then at any time I want to be able to type

scriptname stop

and stop it (or something like that). That way it can call a shutdown method to save information and quit.

Currently it runs in the foreground in the terminal, and can't be stopped by a keyboard interrupt, so the only way to kill it is to close the terminal or kill python.

How can I do something like this?


Solution

  • Use supervisord. It exists to manage processes, and provides a command interface to start and stop them.

    When supervisor kills a process, it sends SIGTERM (or any other signal you choose). So, to shutdown cleanly, you need to handle that signal.

    See this question on how to handle SIGTERM: Python - Trap all signals

    Processes can still listen on their own pipes for input, and send output that way.