Skip to content

Instantly share code, notes, and snippets.

@shollingsworth
Created October 15, 2021 16:41
Show Gist options
  • Save shollingsworth/55e218942c90840af3fd7b4636670ccf to your computer and use it in GitHub Desktop.
Save shollingsworth/55e218942c90840af3fd7b4636670ccf to your computer and use it in GitHub Desktop.
docker run helper with fzf
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""docker run util."""
import os
import shlex
import subprocess
import textwrap
from typing import Dict
from pyfzf.pyfzf import FzfPrompt
def images() -> Dict[str, str]:
"""Grab list of images."""
cmd = shlex.split("docker image ls")
output = subprocess.check_output(cmd)
lines = output.splitlines()
header = lines.pop(0).split()
for line in lines:
spl = line.split()
if spl[0] == b"<none>":
continue
dval = dict(zip(header, spl))
name = b" ".join([dval[b"REPOSITORY"], dval[b"TAG"]]).decode()
img = dval[b"IMAGE"].decode()
yield f"{name} / {img}"
def run(name):
"""run job."""
repo, imgname, img = name.replace("/", "").split()
cmd = " ".join(
textwrap.dedent(
f"""
docker run
-v {os.getcwd()}:/data
--rm
-it
--name {repo}-{imgname}
--hostname {repo}-{imgname}
{img}
sh
"""
).split()
)
print("running")
print(cmd)
os.system(cmd)
def main():
"""Run main function."""
items = images()
prompt = FzfPrompt()
name = prompt.prompt(items)[0]
run(name)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment