【发布时间】:2021-08-19 09:37:55
【问题描述】:
我创建了一个服务来运行 Python 程序,并添加了几行代码来创建一个锁以避免启动它两次。
不幸的是,我不知道如何配置服务以正确停止正在运行的程序。运行停止命令时它不会删除锁定,然后我无法再启动服务。如果我通过 CLI 自己执行程序并使用 Ctrl+C 退出,则锁定被删除。
我已阅读有关KillMode、ExecStop 和Signal 的手册。我的理解是默认配置是我需要的。
有什么帮助吗?
主程序
if __name__ == '__main__':
#Creating lock to avoid launching program twice
lock = pathlib.Path("program.lock")
if not lock.exists():
lock_acquired_on = datetime.now()
with open('program.lock', 'w') as lock:
lock.write(f'Lock acquired on {lock_acquired_on}')
logger.info('Added lock file to avoid running the program twice.')
try:
while True:
#Doing stuff here
except KeyboardInterrupt:
close_program() #Close other threads
#Removing the lock file
os.remove(pathlib.Path("program.lock"))
else:
with open('program.lock', 'r') as lock:
lock_acquisition_time = str(lock.readlines()[0])
logger.info('Programme Maquette Status is already running.')
logger.info(lock_acquisition_time)
服务
[Unit]
Description=Programme Maquette IoT End-to-End
After=multi-user.target
Conflicts=getty@tty1.service
[Service]
WorkingDirectory=/home/pi/Documents/ProductionMaquette
Type=simple
ExecStart=/usr/local/bin/python3.8 /home/pi/Documents/ProductionMaquette/Lo_main.py
StandardInput=tty-force
[Install]
WantedBy=multi-user.target
【问题讨论】:
标签: python linux loops exit systemd