5

我编写了以下简单的 python 脚本,打算在 Ubuntu 12.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))
4

3 回答 3

2

在 cron 下运行 gsettings 似乎有问题。更改 os.system 命令以包含 DISPLAY=:0 GSETTINGS_BACKEND=dconf 就可以了。

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

于 2012-10-03T12:22:37.563 回答
1

您必须更改脚本的工作目录。您可以通过像这样从 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)
于 2012-10-03T11:31:03.913 回答
0

除了为背景图像文件提供正确的路径和设置必要的环境变量之外,您还可以在不os.system()调用 Python 的情况下更改背景:

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

来自使用 Python 2.7.3 的自动背景更换器不起作用,尽管它应该

于 2012-10-03T14:44:05.067 回答