如何使python脚本在使用systemd服务关机之前显示图像?

2024-06-29 00:46:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Ubuntu16.04桌面的/lib/systemd/system/位置有下面的服务文件,其中包含lightdm显示管理器,用于显示python枕头库中的图像

[Unit]

Description=Python script to show image on starting shutdown
DefaultDependencies=no
Requires=graphical.target
#Requires=lightdm.service graphical.target
Before= halt.target poweroff.target shutdown.target

[Service]

Environment="XAUTHORITY=/home/devops/.Xauthority"
Environment="DISPLAY=:0"
User=devops
Type=simple
RemainAfterExit=yes
ExecStart=/bin/true
ExecStop=/usr/bin/python3 /home/devops/display_image.py
KillMode=none
TimeoutSec=300min

[Install]

WantedBy=graphical.target multi-user.target

下面给出了显示图像的python脚本

#!/usr/bin/python3


import time
from datetime import datetime
import psutil
from PIL import Image

start_time=datetime.now().strftime("%m/%d/%Y, %H:%M:%S")


#log to check if the script is started
with open("/home/devops/pylogs.txt", "a+") as text_file:
    print("Service script started on: {}".format(curr_time), file=text_file)

# open and show image
im = Image.open('/home/devops/shutdown_banner.jpg')
im.show()

# display image for 20 seconds before shutdown
time.sleep(20)

# hide image by killing the process
for proc in psutil.process_iter():
    if proc.name() == "display":
        proc.kill()


end_time=datetime.now().strftime("%m/%d/%Y, %H:%M:%S")

##log to check if the script is exited
with open("/home/devops/pylogs.txt", "a+") as text_file:
    print("Service exited on: {}".format(final_time), file=text_file)

脚本根据添加到日志文件的开始和停止时间条目执行。但是,图像不会显示,因为gui lightdm用户会话已被终止

Script execution as stop job

如上所示,关闭停止作业脚本由服务执行20秒,因为我包含了time.sleep(20),但图像没有显示

由于lightdm是默认的显示管理器,所以我尝试将此python脚本作为lightdm.service的ExecStopPre作业,但它根本不起作用

我是否应该使我的服务成为lightdm服务的BindPartof,以便在lightdm gui用户会话终止之前通过脚本显示图像

在遇到关机或重新启动之前,是否有方法使执行python脚本的my service文件在用户登录屏幕中显示一个图像


Tags: text图像imageimport脚本targethomedatetime