python在后台运行时通知用户

时间:2017-07-13 14:47:19

标签: python subprocess

所以我有一个我正在尝试运行的代码,当它完成时它应该向用户显示一条消息,说明发生了什么变化。如果我在终端上运行它,这工作正常。但是当我将它添加到cronjob时没有任何反应并且没有显示错误。 在我看来,它正在失去显示会话,但无法弄清楚如何解决它。这是节目消息代码:

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

我也试过这个版本:

def sendmessage(message):
    Notify.init("Changes")
    n = Notify.Notification.new(message)
    n.show()
return

这给出了错误(仅在背景中):

  

无法打开显示:   已激活的服务'org.freedesktop.Notifications'失败:处理org.freedesktop.Notifications已退出状态

非常感谢任何帮助或替代方案。

1 个答案:

答案 0 :(得分:1)

我遇到了运行系统守护程序的类似问题,我希望用户收到有关超出网络带宽上传的通知。
该计划旨在systemd下运行,但也在upstart下推动。

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

systemd - bandwidth.service file

[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 - bandwidth.conf文件

#
# These are the scripts that run when a network appears.
# Use this on an upstart system in /etc/init
# test for systemd or upstart system with
# ps -p1 | grep systemd && echo systemd || echo upstart
# better
# ps -p1 | grep systemd >/dev/null && echo systemd || echo upstart
# Using upstart the script will need to daemonise which is a bugger
# so test for it and import Daemon_server.py
description "Bandwidth upstart events"

start on net-device-up     # Start a daemon or run a script
stop on net-device-down  # (Optional) Stop a daemon, scripts already self-terminate.
# Automatically restart process if crashed
respawn

# Essentially lets upstart know the process will detach itself to the background
expect fork

#Set environment variables
env DISPLAY=":0"
export DISPLAY
env XAUTHORITY="/home/#USER#/.Xauthority"
export XAUTHORITY 

script
# You can put shell script in here, including if/then and tests.
# replace #USER# with your name and ensure that you have .Xauthority in $HOME

/usr/sbin/bandwidth_logd
end script

您将注意到,在两个配置文件中,环境变为密钥,#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
相关问题