在后台运行python时通知用户

2024-04-28 21:35:15 发布

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

所以我有一个我正在尝试运行的代码,当它完成时,它应该向用户显示一条消息,告诉用户发生了什么变化。如果我在终端上运行的话,这个很好。但是当我把它添加到cronjob中时,什么都不会发生,也不会显示错误。 在我看来,它正在失去显示会话,但不知道如何解决它。以下是显示消息代码:

def sendmessage(message):
    subprocess.Popen(['notify-send', message])
return

我也试过这个版本:

^{pr2}$

这就产生了错误(也只有在后台):

cannot open display: Activated service 'org.freedesktop.Notifications' failed: Process org.freedesktop.Notifications exited with status

非常感谢您的帮助和选择。在


Tags: 代码用户org终端消息messagedef错误
1条回答
网友
1楼 · 发布于 2024-04-28 21:35:15

我在运行系统守护程序时遇到了一个类似的问题,我希望用户收到超过网络带宽上载的通知。
该程序设计为在systemd下运行,但同时也在upstart下运行。在

您可以从我的配置文件中获得一些好处:

systemd-带宽.服务文件

[Unit]
Description=Bandwidth traffic monitor
Documentation=man:bandwidth(7)
After=graphical.target

[Service]
Type=simple
Environment="DISPLAY=:0" "XAUTHORITY=/home/#USER#/.Xauthority"
PIDFile=/var/run/bandwidth.pid
ExecStart=/usr/bin/dbus-launch /usr/sbin/bandwidth_logd
ExecReload=/bin/kill -HUP $MAINPID
User=root

[Install]
WantedBy=graphical.target

upstart-带宽.conf文件

^{pr2}$

您会注意到,在这两个配置文件中,环境都变为key,而#USER#将被其$HOME目录中具有有效.Xauthority文件的真实用户名替换。
在python代码中,我使用以下代码发出消息(import notify2)。在

def warning(msg):
    result = True
    try:
        notify2.init("Bandwidth")
        mess = notify2.Notification("Bandwidth",msg,'/usr/share/bandwidth/bandwidth.png')
        mess.set_urgency(2)
        mess.set_timeout(0)
        mess.show()
    except:
        result = False
    return result

相关问题 更多 >