【发布时间】:2021-10-20 10:18:06
【问题描述】:
我在 Python 中创建了一个自动化脚本,以使用 unsplash.com API 更改我桌面上的墙纸。它运行良好,除非我告诉它将文件保存为wallpaper.jpg,它会这样做一次,然后保存的每个文件都保存为wallpaper(1).jpg。为什么会这样?我希望将文件保存为wallpaper.jpg。
我解决了 change_wallpaper 函数中的问题,以便它检索 wallpaper(1).jpg 文件,但如果可能的话,我宁愿不必这样做。
# import dependencies
import os
import requests
import wget
import ctypes
import time
from config import UNSPLASH_ACCESS_KEY
def get_wallpaper():
# create API query and define parameters
url = 'https://api.unsplash.com/photos/random?client_id=' + UNSPLASH_ACCESS_KEY
params = {
"query": "HD Wallpapers",
"orientation": "landscape"
}
# create request, define json format, grab image url, and save to folder
response = requests.get(url, params=params).json()
image_url = response['urls']['full']
# download the image
image = wget.download(image_url, 'tmp/wallpaper.jpg')
return image
def change_wallpaper():
get_wallpaper()
# create path using cwd, current working directory, and use ctypes to update the designated image as the wallpaper.
path = os.getcwd()+'\\tmp\\wallpaper (1).jpg'
ctypes.windll.user32.SystemParametersInfoW(20,0, path,3)
def main():
try:
while True:
change_wallpaper()
time.sleep(10)
except KeyboardInterrupt:
print("\nThank you, come again!")
except Exception as e:
pass
if __name__ == "__main__":
main()
【问题讨论】:
-
wallpaper(1).jpg类型的文件名听起来像是在使用来自 Windows 操作系统的某种文件副本,它将重命名新文件,这样它就不会覆盖任何现有文件。可以先删除原文件吗? -
是的,所以即使我删除了这两个文件(wallpaper.jpg 和 wallpaper(1).jpg)并运行脚本,它也会创建一个 wallpaper.jpg 文件,然后是一个 wallpaper(1).jpg文件。
标签: python automation save wget wallpaper