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

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

scriptname stop 

and stop it (or something like that). Thus, he can call the shutdown method to save information and exit.

It currently works in the foreground in the terminal and cannot be stopped by keyboard interruption, so the only way to kill it is to close the terminal or kill python.

How can I do something like this?

+4
source share
2 answers

Use supervisord . It exists to control processes and provides a command interface for starting and stopping them.

When the supervisor kills the process, it sends a SIGTERM (or any other signal you choose). So, in order to disconnect, you must process this signal.

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

Processes can still listen to their own input channels and send output this way.

+3
source

If you are on Windows, then you are in the right place ...

Just rename your file: script.py to script.pyw and use it as usual.
Your Script will run in the background.

To close this script:
Go to the Task Manager , click the "Process" tab , pay attention to python , Finish the task .

If you need more information, I am ready to provide you ...
I am not sure about Linux or Ubuntu.
Thanks.

0
source

Source: https://habr.com/ru/post/1447297/


All Articles