Skip to content

Instantly share code, notes, and snippets.

@b1two
Created November 27, 2022 12:21
Show Gist options
  • Save b1two/5d5fb26d086c8df989d52cfacef0432a to your computer and use it in GitHub Desktop.
Save b1two/5d5fb26d086c8df989d52cfacef0432a to your computer and use it in GitHub Desktop.
Kitty terminal kitten to log last command and command output to file.
import sys
from kitty.boss import Boss
def main(args):
return sys.stdin.read()
class Output:
def __init__(self):
self.prompt = []
self.output = []
def is_prompt(line):
info = line.split(":")[-1]
return info in [
"\x1b[32mprompt \x1b[39m",
"\x1b[32msecondary_prompt \x1b[39m"
]
def is_output(line):
info = line.split(":")[-1]
#print(repr(info))
return info == "\x1b[33moutput \x1b[39m"
def is_empty(line):
info = line.split(":")[-1]
return info in ["\n", " \x1b[39m", "continued ", "dirty "]
class LastData:
def __init__(self):
self.cur_output = None
self.prev_output = None
self.next = None
def parse(self, line):
if is_prompt(line):
self.next = "prompt"
self.prev_output = self.cur_output
self.cur_output = Output()
return
if is_output(line):
self.next = "output"
return
if is_empty(line):
# We keep the last next
return
# This is a line that contains actual data
getattr(self.cur_output, self.next).append(line)
from kittens.tui.handler import result_handler
@result_handler(type_of_input="output")
def handle_result(args, answer, target_window_id, boss):
data = LastData()
boss.window_id_map.get(target_window_id).screen.dump_lines_with_attrs(data.parse)
command, output = None, None
if len(data.cur_output.output) != 0:
command, output = data.cur_output.prompt, data.cur_output.output
else:
command, output = data.prev_output.prompt, data.prev_output.output
with open("/tmp/test", "w") as f:
f.write("\n".join(command))
f.write("\n")
f.write("\n".join(output))
f.write("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment