Python 2.7 在Ubuntu 12.04中使用Python2.7 Crontab设置背景

Python 2.7 在Ubuntu 12.04中使用Python2.7 Crontab设置背景,python-2.7,crontab,ubuntu-12.04,Python 2.7,Crontab,Ubuntu 12.04,我已经编写了以下简单的python脚本,我打算在Ubuntu12.04中将其设置为cron作业,每小时更改一次墙纸。当我从终端运行它时,脚本运行并更改墙纸。然而,当我设置cron作业时,我可以在syslog中看到cron作业已经运行,但是墙纸没有改变 #!/usr/bin/python import os import random directory = os.getcwd() + '/' files = os.listdir('.') random.shuffle(files) file

我已经编写了以下简单的python脚本,我打算在Ubuntu12.04中将其设置为cron作业,每小时更改一次墙纸。当我从终端运行它时,脚本运行并更改墙纸。然而,当我设置cron作业时,我可以在syslog中看到cron作业已经运行,但是墙纸没有改变

#!/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))

您必须更改脚本的工作目录。您可以从crontab调用它,如下所示:

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

my_path = os.path.abspath(__file__)
dir_name = os.path.dirname(my_path)
os.chdir(dir_name)
或者您可以在脚本中这样做:

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

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

在cron下运行gsettings似乎有问题。将os.system命令更改为包含DISPLAY=:0 GSETTINGS\u BACKEND=dconf可以实现这一目的


os.system(“DISPLAY=:0 GSETTINGS\u BACKEND=dconf GSETTINGS set org.gnome.desktop.background图片uri“%s'”(设置))

除了为背景图像文件提供正确路径和设置必要的环境变量外,您还可以从Python更改背景,而无需调用
os.system()

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

谢谢,我两次都试了,但都没用。背景没有改变。