#!/usr/bin/env python import sys, os import argparse, json import random, re, subprocess, time """ " CLI """ parser = argparse.ArgumentParser( prog='wallpaper', description='Cycle through wallpapers' ) parser.add_argument( '--config', required=True, help='{"": { "find": "", "exclude": "" }, "":...}' ) parser.add_argument( '--interval', default=600 ) args = parser.parse_args() config = json.loads(args.config) """ " Program """ running_bg_process = None while True: probability_number = random.randrange(start=1, stop=100, step=1) # select config to use based on args.config # see https://stackoverflow.com/questions/16489449/select-element-from-array-with-probability-proportional-to-its-value/16490300#16490300 selected_config = {} accumulative = 0 for weight, wallpaper_path in config.items(): lower_bound = accumulative accumulative += int(weight) upper_bound = accumulative if lower_bound <= probability_number and probability_number <= upper_bound: selected_config = wallpaper_path break # build list of file paths to choose from found_file_paths = [] for dirpath, dirnames, filenames in os.walk(os.path.expandvars(wallpaper_path['find'])): for filename in filenames: found_file_paths.append(f'{dirpath}/{filename}') if 'exclude' in selected_config.keys(): found_file_paths = list(filter( lambda file_path: (not re.match(os.path.expandvars(wallpaper_path['exclude']), file_path)), found_file_paths )) # run swaybg swaybg_cmd = ['swaybg', '-i', random.choice(found_file_paths), '-m', 'fill'] replacing_process = subprocess.Popen(swaybg_cmd) # wait until new instance of swaybg has booted up properly time.sleep(5) # kill the previous process # the new swaybg process takes its place automatically if running_bg_process: running_bg_process.terminate() # set running process for next iteration running_bg_process = replacing_process # wait $INTERVAL seconds time.sleep(int(args.interval))