How Can Python Handle systemctl stop?

*爱你&永不变心* 提交于 2019-12-01 19:30:41

问题


I have a Python script that is running as a service. It writes to disk. If a user calls systemctl stop on the service, I would like to handle the command in my own way to reduce the risk of file corruption.

How can I catch the systemctl stop command?

My file in /usr/lib/systemd/system is:

[Unit]
Description=foo

[Service]
Type=simple
ExecStart=/usr/bin/python /srv/go.py
User=jon
Restart=always

[Install]
WantedBy=graphical.target

My Python script is:

#!/usr/bin/python

import time
import datetime
import threading

def worker():
    while True:

        with open('/tmp/go.txt', 'a') as f:
            s = str(datetime.datetime.utcnow()) + '\n'
            f.write(s)
            print(s)

            time.sleep(1)


if __name__=='__main__':
    t = threading.Thread(target=worker)
    t.start()

回答1:


As described in systemd documentation, processes will receive SIGTERM and then, immediately, SIGHUP. After some time, SIGKILL will be send.

All signals, as well as strategy of sending them, can be changed in relevant service file.

See another stackoverflow question to see how handle these signals in your Python program.



来源:https://stackoverflow.com/questions/43711966/how-can-python-handle-systemctl-stop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!