Published on 2020-10-27, by Javed Shaikh
This post has been updated to include changes to support Linux operating system as well. So you can use this code to change desktop background in both linux and windows computers π.
In this fun tutorial we are going to download a random wallpaper from pexels and set it to our desktop background every minute using Python. While it sounds like fun project, but we are going to learn some important concepts like how to make http request, how to download a file and save it to your local machine and most importantly how to set the wallpaper using Windows's system function.
Visit my GitHub page for complete codes at https://github.com/jaqsparow/change-desktop-wallpaper
Note: All these code snippets are tested on windows 10 and Ubuntu 20.04 LTS, with Python v3.9.0
We are going to build a CLI app using Python to change desktop wallpaper every given number of minutes. Every wallpaper downloaded from internet will be unique and our app will change the wallpaper based on the time we set.
First of all, we need an api key to make HTTP request and download image. For this tutorial, I am going to use pexels. Follow these steps to get the api key
Visit this link and then click "Join" link. Provide your name and email details in the text provided and create an account https://www.pexels.com/join-consumer/
Once you registered and confirmed your email visit https://www.pexels.com/api/ and click "Get Started" and it will take you to new page for applications. Click new application and provide your application details.
After above step you should be provided with an api key which we are going to use in the next step. So save this api key somewhere in your machine.
Note - Do not abuse the Pexels api. They are providing 200 requests per hour with a free account. So respect π
To make an http request, we need a module requests . so lets install this module
1pip install requests
2
Now we have everything setup and lets go to next step to start coding π».
First we need to import all the modules we need to make this app. So lets get started.
1import argparse
2import os
3import time
4import random
5import requests
6import ctypes
7import platform
8
Lets create a function named get_wallpaper() and generate a random number inside this function, which we will use to make random http request URL.
1def get_wallpaper():
2 #Random number
3 num = random.randint(1,99)
4
Now lets save our api key inside the function as shown below. Replace your api keys in the field and also set the url for pexel request as shown below
1 #Set your api key here
2 payload = {'Authorization': '<Your api key goes here>'}
3 #Search query
4 query = 'flower'
5 #URL for PEXELS
6 url = 'https://api.pexels.com/v1/search?per_page=1&page=' + str(num) + '&query=' + query
7
With above codes, we are creating a random URL with page parameter and query =flower π. Change the query depending on what type of wallpaper you want to download like nature, mountain, airplane or anything you want. I am downloading wallpaper with query flower So we have the url, now lets make the http request to that url with get method
1 res= requests.get(url, headers=payload)
2
In above code, we are making http request to Pexels with api key in the headers. Also note that we have saved the response in res variable which we are going to use in our next step. Now its time to download the image. Lets do that using below code
1 #Get the url of the image from the response
2 if res.status_code == 200:
3 img_url = res.json().get('photos')[0]['src']['original']
4 #Make request to get the image
5 img = requests.get(img_url)
6 #Write and save the imgae locally with name temp.jpg
7 with open('temp.jpg', 'wb') as f:
8 f.write(img.content)
9 else:
10 print('error in making http request')
11
Lets understand the above code. In the very first line we are checking the status code from our http request in the last step. Please note that for every http request, we will get the response with status_code. If the status code is 200, that means the request was successful and a good response object should be returned. We are converting the response content into json object so that we can use it parse the image url.
In the second line we got the image_url after parsing the JSON response object. We are making another http request to download the image and finally we are saving the image in our local system using write method. Please note that we are saving the file using wb mode so that a new file will be downloaded and replaced the old one. We are saving the wallpaper as "temp.jpg"
Finally we are printing 'error message' if the status code returned is not 200
In this section we are going to create a new function set_wallpaper() as follow
1def set_wallpaper():
2 get_wallpaper()
3 #Check the operating system
4 system_name = platform.system().lower()
5 path = ''
6 if system_name =='linux':
7 path = os.getcwd()+'/temp.jpg'
8 command = "gsettings set org.gnome.desktop.background picture-uri file:" + path
9 os.system(command)
10 elif system_name == 'windows':
11 path = os.getcwd()+'\\temp.jpg'
12 ctypes.windll.user32.SystemParametersInfoW(20,0,path,0)
13
Lets take a look what we did above. In the first line inside set_wallpaper() we are calling the function get_wallpaper() to download the image and save it to temp.jpg file. In the next line, we are assigning path variable with the complete path of the image that we just downloaded.
Please note we are using platform.system() function to identify the operating system and based on system we are running respecting command to change the desktop wallpaper.
The next line shown below is interesting. With the help of ctypes module, we are calling Windows's system C++ function SystemParametersInfoW() to change the wallpaper. Lets see different parameters of this function.
1ctypes.windll.user32.SystemParametersInfoW(20,0,path,0)
2
Syntax
1BOOL SystemParametersInfoW(
2 UINT uiAction,
3 UINT uiParam,
4 PVOID pvParam,
5 UINT fWinIni
6);
7
uiAction: this is systemwide parameter (such as desktop/icon/menu..)to be set or retrieved.
We are using SPI_SETDESKWALLPAPER or 0x0014 to set this parameter. Please note 0x0014 is nothing but 20 in decimal which are sending in above code.
If the above function execution succeeds, the return value will be nonzero else it will be zero
With this we are done with the coding to change and set the wallpaper. Now its time to call this function every minute
Here we will be calling from the main function based on the user input. Since this is CLI app, we are going to ask user for what would be the frequency to change the wallpaper? every minute, or every 5 minutes or any other value?
1if __name__ == "__main__":
2
3 parser = argparse.ArgumentParser()
4 parser.add_argument("-t", "--time", help="Enter time in minutes")
5
6 args = parser.parse_args()
7 minute = int(args.time)
8 while(True):
9 time.sleep(minute*60)
10 set_wallpaper()
11
With the above code we are setting up the entry point of our app. First two lines are to setup CLI arguments where we are setting up input argument -t which will take number minutes we will be calling set_wallpaper(). We have used sleep() method to delay execution and call set_wallpaper() every n number of minutes as per user input.
Ok. All done now lets run the app π
Run in the CMD as shown below. To run every minute
1C:\Users\jaqsp>wallpaper.py -t 1
2
Or if you want to change wallpaper every 5 minutes
1C:\Users\jaqsp>wallpaper.py -t 5
2
Hope this post will help you understand some important concepts like how we made http requests and downloaded an image to our local system. Also how we used Windows's system function or(linux's gnome setting) and called it from Python program to change the wallpaper. There are many other parameters available for this system function that we can use to perform some other interesting cases. Visit the link below to know more about this function.
Visit my GitHub repository to see complete codes. Thanks for reading:)
There are many ways to monitor and set alerts for your web server using third party apps but they don't come with free, be it Pingdom or Amazon's CloudWatch. In this post I am going to show how we can write and setup our own alert tool with just few lines of code
2020-10-29
In this post we are going to see how we can use Python to find the size of any file and folder. We will check how many files we have inside a folder and how many of them are empty files and how to delete those empty files.
2020-10-26
Monitoring CPU and memory usage are one of the top todo checklist for a backend engineer. Sometimes you wont even notice when your server is down due to high CPU usage unless you login and manually check the system.
2020-11-04
A process in computer term is a program being executed currently by a computer. Each process is unique and can be identified by its PID or process ID.
2020-10-24