【问题标题】:Python script not work in crontabPython 脚本在 crontab 中不起作用
【发布时间】:2013-05-15 14:21:13
【问题描述】:

这是我的脚本(randomg.py):

#!/usr/bin/env python 
# -*- coding: utf8 -*-

import random
import subprocess
import os 


BACKGROUND = '/home/david/wallpaper/dell2312'
IGNORE_FILES = ['/home/david/wallpaper/dell2312/.directory']


def enumerate():
    global BACKGROUND
    file_collections = []
    for root, dirs, files in os.walk(BACKGROUND):
        for file in files:
            file_collections.append(os.path.join(root, file))
    return file_collections


def randombg():
    select_files = list(set(enumerate())-set(IGNORE_FILES))
    subprocess.call(['feh', '--bg-scale', random.choice(select_files)])


def main():
    while 1:
        randombg()


if __name__ == '__main__':
    main()

我已经运行 chmod a+x randombg.py 并且它与 python randombg.py 一起工作。假设它的路径是 /path/to/randombg.py. 另外,运行 /path/to/randombg.py 有效。

但是,当我将它添加到 crontab 时,如下所示:

1 * * * * /path/to/randombg.py 

01 * * * * python /path/to/randombg.py

01 * * * * /usr/bin/python /path/to/randombg.py

全部失败。

我想不通。谁能解释一下?

PS:ArchLinux


更多信息

当我运行ps aux|grep python 时,我找不到randombg.py,但有时它会出现。


来自 crontab 重定向标准错误的附加日志:

import: unable to open X server `' @   error/import.c/ImportImageCommand/361.
import: unable to open X server `' @ error/import.c/ImportImageCommand/361.
import: unable to open X server `' @ error/import.c/ImportImageCommand/361.
/home/david/dotfiles/randombg.py: line 9: BACKGROUND: command not found
/home/david/dotfiles/randombg.py: line 10: IGNORE_FILES: command not found
/home/david/dotfiles/randombg.py: line 13: syntax error near unexpected token `('
/home/david/dotfiles/randombg.py: line 13: `    def enumerate():'

【问题讨论】:

  • 您的while 循环将永远运行
  • 抱歉,我忘记删除了。
  • 你能把错误重定向到一个文件吗?
  • 我之前试过/path/to/randombg.py > /home/user/randombg.log,但是那个日志文件是空的。
  • 你也必须重定向stderr。

标签: python cron crontab


【解决方案1】:

尝试将您的subprocess.call 更改为

subprocess.call("export DISPLAY=:0; feh --bg-scale " + random.choice(select_files), shell=True)

这应该导出DISPLAY 变量,因为默认情况下从 crontab 运行的脚本无权访问环境变量。

【讨论】:

    猜你喜欢
    • 2013-01-12
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多