Last active
December 22, 2022 19:39
-
-
Save prutya/cbf77d4b9ddb4d530bd494905ff4ef6d to your computer and use it in GitHub Desktop.
Automatically switch theme on iTerm2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import asyncio | |
import iterm2 | |
def log(string): | |
print(string) | |
async def update(connection, theme): | |
# Themes have space-delimited attributes, one of which will be light or dark. | |
parts = theme.split(" ") | |
if "dark" in parts: | |
preset = await iterm2.ColorPreset.async_get(connection, "Tango Dark") | |
else: | |
preset = await iterm2.ColorPreset.async_get(connection, "Tango Light") | |
# Update the list of all profiles and iterate over them. | |
profiles = await iterm2.PartialProfile.async_query(connection) | |
for partial in profiles: | |
# Fetch the full profile and then set the color preset in it. | |
profile = await partial.async_get_full_profile() | |
await profile.async_set_color_preset(preset) | |
async def monitor_variable(connection): | |
async with iterm2.VariableMonitor(connection, iterm2.VariableScopes.APP, "effectiveTheme", None) as mon: | |
while True: | |
theme = await mon.async_get() | |
log("theme switched to " + theme) | |
await update(connection, theme) | |
async def monitor_app(connection, monitor_variable_task): | |
while True: | |
log("monitor_app: falling asleep") | |
await asyncio.sleep(5) | |
log("monitor_app: waking up") | |
app = await iterm2.async_get_app(connection, create_if_needed = False) | |
if app is None: | |
log("monitor_app: None") | |
break | |
else: | |
log("monitor_app: App") | |
async def main(): | |
connection = await iterm2.Connection.async_create() | |
# Initial theme update | |
app = await iterm2.async_get_app(connection) | |
await update(connection, await app.async_get_variable("effectiveTheme")) | |
monitor_variable_task = asyncio.create_task(monitor_variable(connection)) | |
await monitor_app(connection, monitor_variable_task) | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment