Let's change the color scheme of iTerm2 automatically depending on the time zone

Tired of looking at the terminal screen with the same color scheme all the time, do you want to refresh your mood with a light theme during the day and a dark theme in the evening? However, it is troublesome to manually switch themes every morning and evening, so let Python do it.

Python API Starting with iTerm2 version 3.3.0 released in July 2019, the Python API is available (Is there an API called AppleScript before that?). You can also hit the API from outside iTerm2 by doing pip install iterm2.

-iTerm2 Python API Official Document

To use the API, check ** Enable Python API ** in ** Preferences> General> Magic **. Screen Shot 2020-03-31 at 20.42.58.png

If you want to prepare your own script, select ** Scripts> Manage> New Python Script ** and a guide will come up to create a template for you. The created Python code is saved in ~ / Library / Application Support / iTerm2 / Scripts, but if you want to load it automatically when the application is launched, the ʻAutoLaunch folder under the above Scripts` And store it there.

Actually, the automatic color scheme switching script does not need to be fully scratched, and the official Example Scripts is almost complete. There is.

In the original sample code, iTerm2 had to be started when switching the color scheme, so it has been changed so that it will switch with reference to the current time when starting the application. Save the following code as ~ / Library / Application Support / iTerm2 / Scripts / AutoLaunch / change_color.py.

change_color.py


#!/usr/bin/env python3.7

import asyncio
import datetime
import iterm2

# Clock time to change colors.
LIGHT_TIME = (7, 0)
DARK_TIME = (17, 0)

# Color presets to use
LIGHT_PRESET_NAME = "material"
DARK_PRESET_NAME = "onedark"

# Profiles to update
PROFILES = ["Default"]

def get_datetime(t, time):
    return datetime.datetime(t.year, t.month, t.day, time[0], time[1])

def datetime_after(t, time):
    today = get_datetime(t, time)
    if today > t:
        return today
    # Same time tomorrow
    return today + datetime.timedelta(1)


def next_deadline_after(t):
    light_deadline = datetime_after(t, LIGHT_TIME)
    dark_deadline = datetime_after(t, DARK_TIME)
    if light_deadline < dark_deadline:
        return (LIGHT_PRESET_NAME, light_deadline)
    return (DARK_PRESET_NAME, dark_deadline)


def get_duration():
    now = datetime.datetime.now()
    preset_name, deadline = next_deadline_after(now)
    duration = (deadline - now).seconds
    print("Sleep for {} seconds until {}".format(duration, deadline))
    return duration, preset_name


async def set_colors(connection, preset_name):
    print("Change to preset {}".format(preset_name))
    preset = await iterm2.ColorPreset.async_get(connection, preset_name)
    for partial in (await iterm2.PartialProfile.async_query(connection)):
        if partial.name in PROFILES:
            await partial.async_set_color_preset(preset)


async def main(connection):
    now = datetime.datetime.now()
    begin = get_datetime(now, LIGHT_TIME)
    end = get_datetime(now, DARK_TIME)
    if (now > begin and now < end):
        await set_colors(connection, LIGHT_PRESET_NAME)
    else:
        await set_colors(connection, DARK_PRESET_NAME)
    while True:
        duration, preset_name = get_duration()
        await asyncio.sleep(duration)
        await set_colors(connection, preset_name)
        await asyncio.sleep(1)


iterm2.run_forever(main)

The first five constants defined

--LIGHT_TIME = (7, 0): Time to switch to light theme (HH, MM) --DARK_TIME = (16, 0): Time to switch to dark theme (HH, MM) --LIGHT_PRESET_NAME = "..." : Light theme name (default theme is Light Background) --DARK_PRESET_NAME = "..." : Dark theme name (default theme is Dark Background) --PROFILES = ["..."] : Profile name to change the theme (multiple selections allowed)

Please change to your liking. Select the profile name from the profile list you have created, and select the theme preset name from the ** Color Presets ... ** menu at the bottom right. Screen Shot 2020-03-31 at 21.26.20.png

By the way, errors such as the standard output of print (...) or when you specify a preset name that does not exist will be output to ** Scripts> Manage> Console **. ![Screen Shot 2020-03-31 at 22.28.30-1.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274429/86fa67b6-3702-ebcc -8a86-ddd50ad7a7aa.png)

Boring things Psycho to let Python do ~ ~ ~ ~ ~

reference

ITerm2 has a status bar

Recommended Posts

Let's change the color scheme of iTerm2 automatically depending on the time zone
Let's execute the command on time with the bot of discord
Change the order of PostgreSQL on Heroku
[Linux] Difference in time information depending on the clock ID of the clock_gettime () function
Let's automatically display the lyrics of the song being played on iTunes in Python
In Python, change the behavior of the method depending on how it is called
Change the color of Fabric errors and warnings
Set the color on the poster side so that the color of the Youtube subtitles changes automatically.
At the time of python update on ubuntu
Change the resolution of Ubuntu running on VirtualBox
Change the time zone with Docker in Oracle Database
Difference in results depending on the argument of multiprocess.Process
[Python] Let's change the URL of the Django administrator site
Let's automatically display the lyrics of the song being played on iTunes in Python (improved version)
The return value of len or unichr may change depending on whether it is UCS-2 or UCS-4.
Source code of "Set the color on the poster side so that the color of Youtube subtitles changes automatically."
Change the theme of Jupyter
Change the style of matplotlib
How to change the color of just the button pressed in Tkinter
Let's measure the test coverage of pushed python code on GitHub.
On Linux, the time stamp of a file is a little past.
Django: Fluctuate the number of child forms depending on the number of input items