import contextlib import subprocess def file_proc(): args = [ '/usr/bin/file', '--brief', '-E', '--no-dereference', '--no-buffer', '--preserve-date', '-00', '--mime-type', '--files-from', '-' ] with contextlib.ExitStack() as stack: proc = subprocess.Popen(args, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, preexec_fn=None, text=True) stack.callback(proc.kill) while True: file_path = yield proc.stdin.write(file_path + '\n') proc.stdin.flush() file_type = '' while (c := proc.stdout.read(1)) != '\0': file_type += c yield file_type.splitlines()[0] @contextlib.contextmanager def file_typer(): proc = file_proc() def getter(path): proc.send(None) posix_type = proc.send(path.as_posix()) return posix_type with contextlib.closing(proc): yield getter with file_typer() as typer: typer('/usr/bin/python')