Python to Set a Random Desktop Background with Full Source Code For Beginners

  • This script will download a random image from Unsplash and set it as the desktop background.
  • The image will be saved as “random.jpg” make sure that there are no files saved as “random.jpg” in the current directory

Requirements:

Linux

pip install requests

Run the script:

python background_linux.py
Code language: CSS (css)

(OR)

python background_windows.py
Code language: CSS (css)
  • Open on device using a python IDE
  • Run the script
python ussdtim.pyCode language: CSS (css)

Source Code:

background_windows.py

from requests import get
import os
import ctypes
import sys

url = "https://source.unsplash.com/random"
file_name = "random.jpg"

def is_64bit():
    return sys.maxsize > 2 ** 32


def download(url, file_name):
    '''
    downloading the file and saving it
    '''
    with open(file_name, "wb") as file:
        response = get(url)
        file.write(response.content)


def setup(pathtofile,version):
    name_of_file = pathtofile
    path_to_file = os.path.join(os.getcwd(), name_of_file)
    SPI_SETDESKWALLPAPER = 20
    if is_64bit():
        ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, path_to_file, 0)
    else:
        ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, path_to_file, 0)


if __name__ == "__main__":
    try:
        download(url, file_name)
        setup(file_name)
    except Exception as e:
        print(f"Error {e}")
        raise NotImplementedErrorCode language: PHP (php)

background_linux.py

from requests import get  # to make GET request
from os import system, getcwd, path


url = "https://source.unsplash.com/random"
filename = "random.jpg"


def download(url, file_name):
    '''
    downloading the file and saving it
    '''
    with open(file_name, "wb") as file:
        response = get(url)
        file.write(response.content)


def setup(pathtofile):
    '''
    setting the up file
    '''
    system("nitrogen --set-auto {}".format(path.join(getcwd(), pathtofile)))


if __name__ == "__main__":
    download(url, filename)
    setup(filename)Code language: PHP (php)

Leave a Comment