简体   繁体   中英

Setting background with Python2.7 Crontab in Ubuntu 12.04

I've written the following simple python script which I intended to set as a cron job in Ubuntu 12.04 to change the wallpaper once an hour. The script runs and changes the wallpaper when I run it from a terminal perfectly. However when I set the cron job up I can see in syslog the cron job has run but the wallpaper doesnt change?

#!/usr/bin/python

import os
import random

directory = os.getcwd() + '/'
files = os.listdir('.')
random.shuffle(files)
files.remove('.project')
files.remove('.pydevproject')
files.remove('background.py')
background = files[0]
setup = 'file://' + directory + background

print setup

os.system("gsettings set org.gnome.desktop.background picture-uri '%s'" % (setup))

It seems its a problem with running gsettings under cron. Changing the os.system command to include DISPLAY=:0 GSETTINGS_BACKEND=dconf does the trick.

os.system("DISPLAY=:0 GSETTINGS_BACKEND=dconf gsettings set org.gnome.desktop.background picture-uri '%s'" % (setup))

You have to change working directory of Your script. You can do it by invoking it from crontab like this:

cd /path/of/your/script && python scriptname.py

or You can do it in your script doing something like this:

import os

my_path = os.path.abspath(__file__)
dir_name = os.path.dirname(my_path)
os.chdir(dir_name)

In addition to providing a correct path for the background image file and setting necessary environment variables you could change background from Python without os.system() call:

import os
import urllib
from gi.repository.Gio import Settings  # pylint: disable=F0401,E0611

def set_background(image_path, check_exist=True):
    """Change desktop background to image pointed by `image_path`.

    """
    if check_exist:  # make sure we can read it (at this time)
        with open(image_path, 'rb') as f:
            f.read(1)

    # prepare uri
    path = os.path.abspath(image_path)
    if isinstance(path, unicode):  # quote() doesn't like unicode
        path = path.encode('utf-8')
    uri = 'file://' + urllib.quote(path)

    # change background
    bg_setting = Settings.new('org.gnome.desktop.background')
    bg_setting.set_string('picture-uri', uri)
    bg_setting.apply() # might be unnecessary

from Automatic background changer using Python 2.7.3 not working, though it should

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