【问题标题】:How to address differences between cron execution and terminal execution of a python script?如何解决 python 脚本的 cron 执行和终端执行之间的差异?
【发布时间】:2019-07-09 05:53:01
【问题描述】:

我正在尝试使用 cron 在 Arch linux 上定期执行一个简单的 python 脚本,但是当我在 cron 中运行它时,它的行为与我在终端中运行它的原因不同。

脚本从 NASA 当天的照片中下载一张壁纸,并使用“feh”程序将其设为我的壁纸。当我在终端中运行脚本时,一切都很好,但是当我在 cron 中运行它时,它会下载文件但不会使其成为墙纸。

任何帮助将不胜感激。

#!/usr/bin/env python

import time
import os
import requests
import tempfile
from bs4 import BeautifulSoup

WALLPAPER_LOCATION = "/home/user/.wallpaper.jpg"


def main():
    if os.path.exists(WALLPAPER_LOCATION):
        os.remove(WALLPAPER_LOCATION)
    website = "https://apod.nasa.gov/apod/astropix.html"
    html_txt = getHTML(website)
    img_url = get_image_URL(html_txt)
    downloadFile(img_url, WALLPAPER_LOCATION)
    os.system("/usr/bin/feh --bg-scale " + WALLPAPER_LOCATION)

def downloadFile(url, filepath):
    with open(filepath, 'wb') as handle:
        response = requests.get(url, stream=True)
        if not response.ok:
            print(response)
        for block in response.iter_content(1024):
            if not block:
                break
            handle.write(block)

def getHTML(url):
    html_txt = ""
    temp_html_file = tempfile.NamedTemporaryFile()
    downloadFile(url, temp_html_file.name)

    with open(temp_html_file.name, "r") as reader:
        html_txt = reader.read()
    return html_txt

def get_image_URL(html_doc):
    base_url = "https://apod.nasa.gov/apod/"

    soup = BeautifulSoup(html_doc, "html.parser")
    return base_url + soup.findAll('img')[0]["src"]



if __name__== "__main__":
  main()

【问题讨论】:

  • 查看cron tag wiki 了解常见问题,例如如何从 crontab 为 X11 运行选择显示器
  • 您在哪个用户下运行您的 cron 作业?我会冒险猜测你正在更改 root 的壁纸。

标签: python linux cron archlinux


【解决方案1】:

@thatotherguy 是对的。问题是 cron 不知道要使用什么显示器,以便 feh 可以设置墙纸。 @thatotherguy 提供的链接中提到了在 cron 中运行的 X11 程序的问题,在 arch wiki 中也可以找到。

我在我的 cron 工作开始时添加了 env DISPLAY=:0,现在一切正常。

【讨论】:

    猜你喜欢
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2015-07-04
    • 2018-11-07
    • 2018-06-27
    • 2017-07-18
    相关资源
    最近更新 更多