如何解决python脚本的cron执行和终端执行之间的差异?

2024-05-15 20:51:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

该脚本从美国宇航局的每日图片下载了一张壁纸,并使用“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()

Tags: importtxt脚本urlifosmainresponse
1条回答
网友
1楼 · 发布于 2024-05-15 20:51:02

@另一个人是对的。问题是cron不知道使用什么显示器,这样feh就可以设置壁纸了。@thatotherguy提供的链接中提到了在cron中运行X11程序的问题,在arch wiki中也可以找到该链接

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

相关问题 更多 >