Last active
April 26, 2018 06:09
-
-
Save albertofwb/7d5dedf4a78d230725b01ae8f741468d to your computer and use it in GitHub Desktop.
every time you execute this script will set your wallpaper to a random picture from bingwallpaper.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3d | |
import requests | |
from bs4 import BeautifulSoup | |
import os | |
import sys | |
import datetime | |
import random | |
import hashlib | |
def md5_str(my_string): | |
m = hashlib.md5() | |
m.update(my_string.encode('utf-8')) | |
return m.hexdigest() | |
def prepare_dir(): | |
root_dir = os.path.join(os.path.expanduser('~'), "Pictures", "bing") | |
if not os.path.exists(root_dir): | |
os.makedirs(root_dir) | |
return root_dir | |
def mac_pic_dir(root_dir): | |
today = datetime.datetime.now().strftime("%Y-%m-%d") | |
pic_dir = os.path.join(root_dir, today) | |
if not os.path.exists(pic_dir): | |
os.makedirs(pic_dir) | |
return pic_dir | |
# maybe support windows in someday | |
def make_cmd(file_path): | |
os_type = sys.platform | |
print("os_type: ", os_type) | |
cmd_base = "" | |
if os_type == "darwin": | |
cmd_base = 'osascript -e \'tell application "Finder" to set desktop picture to POSIX file "{path}"\'' | |
elif os_type.find("linux") > 0: | |
cmd_base = 'gsettings set org.gnome.desktop.background picture-uri http://file://{path}' | |
elif os_type == "win32": | |
cmd_base = '''reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v Wallpaper /t REG_SZ /d "{path}" /f | |
RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters''' | |
cmd = cmd_base.format(path=file_path) | |
return cmd | |
def execute_cmd(cmd): | |
os.system(cmd) | |
def get_pic_url(): | |
url = 'http://bingwallpaper.com/' | |
sc = requests.get(url) | |
soup = BeautifulSoup(sc.text, 'lxml') | |
image = soup.select('.cursor_zoom img') | |
random_index = random.randint(0, len(image)-1) | |
image_title = image[random_index].get('title') | |
image_url = image[random_index].get('src') | |
return image_title, image_url | |
def download_file(url, file_path): | |
res = requests.get(url) | |
with open(file_path, 'wb') as file: | |
file.write(res.content) | |
def get_picture(): | |
title, url = get_pic_url() | |
pic_dir = prepare_dir() | |
title = md5_str(title)[:5] | |
file_name = title + ".jpg" | |
pic_path = os.path.join(pic_dir, file_name) | |
if os.path.exists(pic_path): | |
print("ignore: ", title) | |
else: | |
print("download: ", title) | |
download_file(url, pic_path) | |
return pic_path | |
def set_pic_as_wallpaper(): | |
pic_file = get_picture() | |
cmd = make_cmd(pic_file) | |
execute_cmd(cmd) | |
if __name__ == '__main__': | |
set_pic_as_wallpaper() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment