Editing Gsettings unsuccesful when initiated from cron

The solution

It turned out the blind spot was a hole in my knowledge. The reason for not running specific commands in the python script (gsettings set) was because cron uses a very restricted set of environment variables.

To run a gsettings *set* command from cron (in general), it takes more than just running it from your personal cron file; the environment variable DBUS_SESSION_BUS_ADDRESS is needed for correct execution.

For reasons of convenience and flexibility, I solved it, inspired by- and based on the information in this post on stack overflow, by creating an "intermediate" script that both exports the variable and calls the actual script. The actual script edits gsettings. Since (normally) a process inherits the environment of its parent, now the script runs fine.

#!/bin/bash

PID=$(pgrep gnome-session)
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ|cut -d= -f2-);/path/to/script.py

(assuming script.py is executable)

Including the DBUS_SESSION_BUS_ADDRESS variable in a python script

To make editing gsettings possible by a python script, run by cron (and make an intermediate script unnecessary) the function below could be included in the script. It should be called before the gsettings set function in the script.

#!/usr/bin/env python3
import os
import subprocess

def set_envir():
    pid = subprocess.check_output(["pgrep", "gnome-session"]).decode("utf-8").strip()
    cmd = "grep -z DBUS_SESSION_BUS_ADDRESS /proc/"+pid+"/environ|cut -d= -f2-"
    os.environ["DBUS_SESSION_BUS_ADDRESS"] = subprocess.check_output(
        ['/bin/bash', '-c', cmd]).decode("utf-8").strip().replace("\0", "")