【发布时间】: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