2 Replies - 655 Views - Last Post: 14 October 2017 - 08:43 PM Rate Topic: -----

#1 Kharkiv   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 13-October 17

How can I set wallpaper via Python?

Posted 13 October 2017 - 11:37 PM

Hey, I'm writing this script that pulls a users' current time of day, and weather condition and sets their wallpaper accordingly.

E.g. Night-Snowy, it'll set a cool nighttime snow wallpaper.

I've got most of the code done up until setting the wallpaper.
https://github.com/M...ynamicWallpaper for the full project

heres the main code
'''This project changes my wallpaper'''
import requests
import json
import datetime
import urllib
import os

'''Additional libraries'''
    from bs4 import BeautifulSoup
except ModuleNotFoundError as e:
    print("Woops, It seems as if there is".title(), e)
    print("pip install the module!")

def get_weather_and_time():
        r = requests.get("http://freegeoip.net/json")
        json_string = r.json()
    except Exception:
        print("whoops there was some problem")
        ip = json_string['ip']
        country_code = json_string['country_code']
    #use the ip to find the rest of the info
        r = requests.get("http://ipinfo.io/json")
        data = r.json()
    except Exception:
        print("woops, there was some problem")
        city = data['city']
        coords = data['loc']
        coords = coords.split(",")
        lat, lon = coords[0], coords[1]
    location_info = {"country_code":country_code, "city":city, "lat":lat, "lon":lon}
    r =  requests.get("https://www.wunderground.com/weather/{0[country_code]}/{0[city]}/{0[lat]}%2C{0[lon]}".format(location_info))
    html = r.text
    #handle the data with beautifulsoup
    soup = BeautifulSoup(html, "html.parser")
    '''Here we will find the conditions, e.g. sunny, clear, rainy, etc'''
    result = soup.find("div", {"class":"condition-icon small-6 medium-12 columns"})
    condition = result.contents[3]
    get_condition = ""
    next_step = False
    for char in condition:
        if char == ">" or not next_step:
            while char != "<":
                next_step = True
    '''here we will find the temperature'''
    result = soup.find("span", {"class":"wu-value wu-value-to"})
    temp_faren = float(result.contents[0][:4])#unused
    temp_celcius = (temp_faren - 32) *.5556#unused

    user_wallpaper_info = Wallpaper_Info()

    #check and set time
    now_time = datetime.datetime.now()
    now_hour = now_time.hour

    if 0 <= now_hour <= 4: #8PM -> 4AM Nighttime
        user_wallpaper_info.set_time_of_day("night") #i could create a timeofday object with night, morning etc. but unecessary
    if 5 <= now_hour <= 11:
    if 13 <= now_hour <= 17:
    if 18 <= now_hour <= 20:
    if 21 <= now_hour <= 24:

    return user_wallpaper_info

def preset_wallpaper(info_to_parse):
    current_info = info_to_parse.return_instance()
    current_time_of_day = current_info["time_of_day"]
    current_condition = current_info["condition"]

    '''The above method allocates less system memory than what's here
    current_time_of_day = info_to_parse.return_instance()["time_of_day"]        
    current_condition = info_to_parse.return_instance()["condition"]

    #open the json file
    with open("wallpapers.json") as json_data:
        json_wallpaper = json.load(json_data)
    json_now_block = json_wallpaper[current_time_of_day]

    image_url = None
    for element in json_now_block:
        if element[0] == current_condition:
            image_url = element[1]
    if image_url is None:
        print("woops, we haven't created a wallpaper for that weather condition, feel free to add it in yourself !")

    current_running_path = os.path.realpath(__file__) #current path

    current_condition_filename = "".join(current_condition.split(" ")) #editing the name of conditions, e.g. Partly Cloudy -> PartlyCloudy
    file_name = current_time_of_day + "-" + current_condition_filename + ".jpg" #joining time of day and condition for a file name. night-PartyCloudy.jpg


    #after that all that is needed is a cron job and the script is done

    wallpaper_directory = os.chdir(os.getcwd() + "/wallpaper_images/")
    for filename in os.listdir(wallpaper_directory): #check if the wallpaper we need is already downloaded, if it is then just set it
        if filename == file_name:
            #set wallpaper
            return None

    print("Downloading Image...")
    f = open(file_name,'wb') #itll open
def set_wallpaper(filename):
    SCRIPT = """/usr/bin/osascript<<END
    tell application "Finder"
    set desktop picture to POSIX file "%s"
    end tell
    subprocess.Popen(SCRIPT%filename, shell=True)

class Wallpaper_Info(object):
    def __init__(self):
        self.info = {"time_of_day":None, "condition": None}
    def set_time_of_day(self, time_of_day):
        self.info["time_of_day"] = time_of_day

    def set_weather(self, condition):
        self.info["condition"] = condition
    def return_instance(self):
        for key, value in self.info.items():
            if value == None:
                print("Woops some information fell through check the code!")

if __name__ == "__main__":
    weather_and_time = get_weather_and_time()

I then store the wallpapers and data structures in a json file
                        ["Sunny", "URL"], ["Raining", "URL"], ["Partly Cloudy", "URL"]
                        ["Sunny", "URL"], ["Raining", "URL"], ["Partly Cloudy", "URL"]
                        ["Sunny", "URL"], ["Raining", "URL"], ["Partly Cloudy", "URL"]
                        ["Sunny", "URL"], ["Raining", "URL"], ["Partly Cloudy", "https://i.imgur.com/YBWm5aE.jpg"], ["Cloudy", "https://i.imgur.com/YBWm5aE.jpg"]

The images, are in a seperate folder called wallpaper_images, its in the code.
I can get up to the part where it downloads the image, if the image already isn't in the wallpaper_images directory. I just don't know how to set it on a users' desktop now.
Any advice?
I thought of using a batch file that'll get called by python and pass the image path as a param, and the batch file could possibly set it, but then I don't know a work around for mac users.

Is This A Good Question/Topic? 0
  • +

Replies To: How can I set wallpaper via Python?

#2 andrewsw   User is offline

  • head thrashing
  • member icon

Reputation: 6644
  • View blog
  • Posts: 27,191
  • Joined: 12-December 12

Re: How can I set wallpaper via Python?

Posted 13 October 2017 - 11:57 PM

There is information to be found with a search of "python change wallpaper", such as.

I don't know if you intend this to work cross-platform but I would first get it working for your current OS. If that is a mac then try "python change mac wallpaper", or "...background" if mac's don't use the term wallpaper. The os module can tell you what the current system is.
Was This Post Helpful? 1
  • +
  • -

#3 Kharkiv   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 13-October 17

Re: How can I set wallpaper via Python?

Posted 14 October 2017 - 08:43 PM

Thanks for your reply. Im fortunate to have a windows and OSX machine, so ultimately I'll try exploring how to accomplish this on my windows PC since i've been writing this script on my macbook.

Thanks again,

This post has been edited by andrewsw: 14 October 2017 - 11:16 PM
Reason for edit:: Removed previous quote, just press REPLY

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1