简体   繁体   中英

Python - send KDE knotify message with cron job on linux?

I'm trying to send a notification to KDE's knotify from a cron job. The code below works fine but when I run it as a cron job the notification doesnt appear.

#!/usr/bin/python2
import dbus
import gobject

album = "album"
artist = "artist"
title = "title"
knotify = dbus.SessionBus().get_object("org.kde.knotify", "/Notify")
knotify.event("warning", "kde", [], title, u"by %s from %s" % (artist, album), [], [], 0, 0, dbus_interface="org.kde.KNotify")

Anyone know how I can run this as a cron job?

You need to supply an environment variable called DBUS_SESSION_BUS_ADDRESS .

You can get the value from a running kde session.

$ echo $DBUS_SESSION_BUS_ADDRESS
unix:abstract=/tmp/dbus-iHb7INjMEc,guid=d46013545434477a1b7a6b27512d573c

In your kde startup (autostart module in configuration), create a script entry to run after your environment starts up. Output this environment variable value to a temp file in your home directory and then you can set the environment variable within your cron job or python script from the temp file.

#!/bin/bash
echo $DBUS_SESSION_BUS_ADDRESS > $HOME/tmp/kde_dbus.session

As of 2019 KDE5, it still works but is slightly different results:

$ echo $DBUS_SESSION_BUS_ADDRESS 
unix:path=/run/user/1863/bus

To test it, you can do the following:

$ qdbus org.freedesktop.ScreenSaver /ScreenSaver SimulateUserActivity

You may need to use qdbus-qt5 if you still have the old kde4 binaries installed along with kde5. You can determine which one you should use with the following:

export QDBUS_CMD=$(which qdbus-qt5 2> /dev/null || which qdbus || exit 1)

I run this with a sleep statement when I want to prevent my screensaver from engaging and it works. I run it remotely from another computer beside my main one.

For those who want to know how I lock and unlock the remote screensaver, it's a different command...

loginctl lock-session 1

or

loginctl unlock-session 1

That is assuming that your session is the first one. You can add scripts to the KDE notification events for screensaver start and stop. Hope this information helps someone who wants to synchronize their screen savers across more than one computer.

I know this is long answer, but I wanted to provide an example for you to test with and a practical use case where I use it today.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM