以幻灯片模式
自动切换windows terminal
的背景图片,可自定义包含图片的目录、切换频率等。python
使用命令python change_tty_image.py --help
查看使用帮助。shell
代码一共就162
行,核心功能代码事实上可能只有不到50
行,其余都是一些检查、日志等语句。感兴趣的能够download
脚本,自行定制一些功能。json
近期在折腾windows terminal
,于我而言这款终端软件也基本彻底替代xshell
,特别是win 10
内置了ssh, scp
等命令,用起来很是舒服和流畅。再和wsl
结合起来一块儿玩,简直爽到飞起。windows
windows terminal
能够自定义主题样式,自定义背景图片。做为一个伪二次元
爱好者,固然要把背景换成adroable
的小姐姐!安全
然而,每次终端只能设置一张图片,根本没法滿足敲命令的时候看不同的
二次元小姐姐的需求。联想到windows
能够设定图片目录,并选择幻灯片
模式动态切换桌面背景,因而去google
一番,发现windows terminal
的settings.json
好像没有这个选项。查阅[官方文档](Windows Terminal Appearance Profile Settings | Microsoft Docs)以下:app
要么给一个路径,要么就和桌面壁纸设置为同样。dom
因此,若是想要自动切换windows terminal
的背景图片,有一个折中方案:把backgroundImage
设置为desktopWallpaper
,而后桌面背景搞成幻灯片
模式,也就是下面这样子:ssh
这样就能自动切换。ui
可是像我这样壁纸
比较多的收藏家
,正愁壁纸多得无处安放,怎么能把desktop
和windows terminal
设置成同样的背景呢?这多不合适!this
因而,我花了1
个小时,用python
写了一个简单的脚本,支持设置壁纸目录
、更新频率
、随机更新
功能,每一个固定时间就为windows terminal
切换一张背景图片。
要实现这个功能其实很简单,不须要高大上的技术。整个开发需求主要包含两点:
windows terminal
的settings.json
中的backgroundImage
项,切换为指定目录下的图片路径,并进行轮循设置。针对两点需求,实现手段分别为:
time.sleep()
设置定时任务。这应该是简单的方式了,适合简单的定时任务触发。IO
操做,先读取指定目录的全部image
路径,而后取一个路径出来,替换掉backgroundImage
的值便可。实现起来很简单,也顺便帮我复习了一下python
操做文件和目录的一些接口。
time
模块获取时间,方便记录日志random
模块获取随机数,获得随机图片,显然,此处无需使用安全随机数生成器
os.walk()
遍历全部目录下全部的图片路径re
模块,正则匹配含有backgroundImage
的行,替换掉路径python change_tty_image.py -h
查看帮助settings.json
中已经预约义了一个路径10 min
,太快了不就蜻蜓点水pythonw
后台运行脚本关键操做都会记录日志,或在屏幕输出!
# -*- encoding: utf-8 -*- ''' @File : change_tty_image.py @Time : 2021/04/08 21:00:20 @Author : Roderick Chan @Email : ch22166@163.com @Desc : Change windows-terminal background image automatically ''' import os import sys import functools import random import re import time # key word to set image key_word = "\"backgroundImage\"" # help message help_msg = """ Usage: python change_tty_image.py [settings_path] [picture_directory] [update_frequency] [random] Function: Change windows-terminal background image automatically. Note: settings_path: [required] The absolute path of windows-terminal setting file. picture_directory: [required] A absolute directory path fulled with pictures, only support 'png', 'jpg', 'gif'. update_frequency: [required] The frequency to update image, should be more than 10, default value is 30, which represents 30min. random: [optional] Select image randomly or not. Default value: False. Tips: 1. Use `python` to run this script and output log-info on the screen. 2. Use `pythonw` to run this script in the background and output nothing, but your can use 'tasklist' and 'taskkill' to stop. 3. recommendation command: pythonw change_tty_image.py [settings_path] [picture_directory] [update_frequency] [random] > change_image.log 4. Use `python change_tty_image.py -h` to get help. """ def get_time(): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) def log(msg): print("\033[1;32mINFO\033[0m: {} \033[1;34mTime\033[0m: {}\n".format(msg, get_time())) # parse args # check args args = sys.argv arg_len = len(args) # show help if len(args) > 1 and (args[1] == "-h" or args[1] == "--help"): print(help_msg) sys.exit(0) if arg_len < 4 or arg_len > 5: print("\033[1;31m[-] Args Error!\033[0m\n") print(help_msg) sys.exit(-1) # validate args settings_path = args[1] picture_directory = args[2] update_frequency = args[3] random_enabled = False if arg_len == 5: random_enabled = bool(args[4]) assert os.path.exists(settings_path), "settings_path doesn't exist." assert os.path.isfile(settings_path), "settings_path is not a file path." assert os.path.exists(picture_directory), "picture_directory doesn't exist." assert os.path.isdir(picture_directory), "picture_directory is not a dir path." # process settings_path settings_dir, settings_full_name = os.path.split(settings_path) settings_name, setting_suffix = os.path.splitext(settings_full_name) backup_setting_path = os.path.join(settings_dir, settings_name + "_backup" + setting_suffix) tmp_setting_path = os.path.join(settings_dir, settings_name + "_tmpfile" + setting_suffix) # process update_frequency if update_frequency.isdecimal(): update_frequency = int(update_frequency) if update_frequency < 10: update_frequency = 30 else: update_frequency = 30 log('settings_path: {}'.format(settings_path)) log('backup_setting_path: {}'.format(backup_setting_path)) log('picture_directory: {}'.format(picture_directory)) log('update_frequency: {}'.format(update_frequency)) log('random_enabled: {}'.format(random_enabled)) # get all picture path all_picture_path = [] support_suffix = ('.jpg', '.png', '.gif') for r, dl, fl in os.walk(picture_directory,): for f in fl: is_ok = functools.reduce(lambda a, b : a or b, map(lambda x: f.endswith(x), support_suffix)) if not is_ok: continue # check size if len(all_picture_path) > 0x1000: continue; all_picture_path.append(os.path.join(r, f)) assert len(all_picture_path) > 0, 'no pictures appended, check your picture_directory.' # validate settings_path flag = False with open(file=settings_path, mode='r+', encoding='utf-8') as fd: for line in fd: if line.strip().startswith(key_word): flag = True break assert flag, "please initial your windows-terminal settings file first, add {} value at least.".format(key_word) log('all_picture_path : {}'.format(all_picture_path)) # back up if not os.path.exists(backup_setting_path): cmd = "copy {} {}".format(settings_path, backup_setting_path) os.popen(cmd) log("execute \"{}\"".format(cmd)) idx = -1 while True: if random_enabled: idx = random.randint(0, len(all_picture_path) - 1) else: idx += 1 idx %= len(all_picture_path) # replace '\' with '/' cur_picture_path = all_picture_path[idx].replace("\\", "/") log('cur_picture_path: {}'.format(cur_picture_path)) with open(file=settings_path, mode='r', encoding='utf-8') as fd_src: with open(file=tmp_setting_path, mode='w+', encoding='utf-8') as fd_bck: for line in fd_src: if not line.strip().startswith(key_word): fd_bck.write(line) continue res = re.sub(r"({}\s?:\s?)\".+\",".format(key_word), r'\1"{}",'.format(cur_picture_path), line) fd_bck.write(res) cmd = "copy {} {}".format(tmp_setting_path, settings_path) os.popen(cmd) log("execute \"{}\"".format(cmd)) cmd = "del {}".format(tmp_setting_path) os.popen(cmd) log("execute \"{}\"".format(cmd)) # sleep log("sleep start...") time.sleep(update_frequency * 60) log("sleep end...")
windows terminal profile setting
:<Windows Terminal Appearance Profile Settings | Microsoft Docs>