Created
February 7, 2025 15:22
-
-
Save shollingsworth/947e254d5edcf5a8605bb55c8ea04a31 to your computer and use it in GitHub Desktop.
script to automate creating asciinema gifs
This file contains hidden or 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 | |
"""Record terminal session to gif.""" | |
import argparse | |
import datetime | |
import shutil | |
from pathlib import Path | |
from subprocess import check_call | |
from tempfile import TemporaryDirectory | |
def verify_binaries(): | |
missing = [i for i in ["asciinema", "agg"] if not shutil.which(i)] | |
if missing: | |
msg = f"The following programs are missing, {','.join(missing)}" | |
raise SystemExit(msg) | |
def record(cast_file: Path): | |
cmd = [ | |
"asciinema", | |
"rec", | |
# max 2.5 second idle time | |
"-i", | |
"2.5", | |
str(cast_file), | |
] | |
check_call(cmd) | |
def to_gif(cast_file: Path, gif_file: Path): | |
cmd = [ | |
"agg", | |
str(cast_file), | |
str(gif_file), | |
] | |
check_call(cmd) | |
def do_stuff(args: argparse.Namespace): | |
dt = datetime.datetime.now(tz=datetime.timezone.utc) | |
dt_fmt = dt.strftime("%Y-%m-%d-%H%M%S") | |
bdir = Path(args.output_directory).expanduser() | |
name = f"asciinema-{dt_fmt}" if not args.name else f"{args.name}-{dt_fmt}" | |
dest_dir = bdir / name | |
with TemporaryDirectory() as _tdir: | |
tdir = Path(_tdir) | |
cast_file = tdir / "output.cast" | |
gif_file = tdir / "output.gif" | |
record(cast_file) | |
to_gif(cast_file, gif_file) | |
if not dest_dir.exists(): | |
print(f"Making Directory: {dest_dir}") | |
dest_dir.mkdir(parents=True) | |
for file in tdir.glob("*"): | |
dst_file = dest_dir / file.name | |
print(f"Copying {dst_file.name}") | |
shutil.copy(file, dest_dir) | |
def main() -> None: | |
"""Run main function.""" | |
parser = argparse.ArgumentParser( | |
formatter_class=argparse.RawDescriptionHelpFormatter, | |
description=__doc__, | |
add_help=True, | |
) | |
parser.add_argument( | |
"--name", | |
"-n", | |
help="name of recording", | |
default=None, | |
type=str, | |
) | |
parser.add_argument( | |
"--output-directory", | |
"-o", | |
help="output asciinema file/gif directory", | |
default="~/Documents/asciinema", | |
type=str, | |
) | |
# args = parser.parse_args() | |
args = parser.parse_args() | |
verify_binaries() | |
do_stuff(args) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment