Python句柄systemctl如何停止? [英] How Can Python Handle systemctl stop?
问题描述
我有一个作为服务运行的Python脚本.它写入磁盘.如果用户调用systemctl在服务上停止,我想以自己的方式处理该命令,以减少文件损坏的风险.
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.
如何捕获systemctl stop命令?
How can I catch the systemctl stop command?
我在/usr/lib/systemd/system中的文件是:
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
我的Python脚本是:
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()
推荐答案
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.
请参见另一个stackoverflow问题,以了解如何在Python程序中处理这些信号.
See another stackoverflow question to see how handle these signals in your Python program.
这篇关于Python句柄systemctl如何停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!