Skip to content

Instantly share code, notes, and snippets.

@Kentzo
Last active October 16, 2022 06:38
Show Gist options
  • Save Kentzo/42f7e3a7476baef2b42dbf1eab5bc1c8 to your computer and use it in GitHub Desktop.
Save Kentzo/42f7e3a7476baef2b42dbf1eab5bc1c8 to your computer and use it in GitHub Desktop.

Revisions

  1. Kentzo revised this gist Oct 16, 2022. 1 changed file with 1 addition and 2 deletions.
    3 changes: 1 addition & 2 deletions file.py
    Original file line number Diff line number Diff line change
    @@ -33,11 +33,10 @@ def file_proc():
    @contextlib.contextmanager
    def file_typer():
    proc = file_proc()
    proc.send(None)

    def getter(path):
    posix_type = proc.send(path.as_posix())
    proc.send(None)
    posix_type = proc.send(path.as_posix())
    return posix_type

    with contextlib.closing(proc):
  2. Kentzo revised this gist Oct 12, 2022. No changes.
  3. Kentzo created this gist Oct 12, 2022.
    48 changes: 48 additions & 0 deletions file.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    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()
    proc.send(None)

    def getter(path):
    posix_type = proc.send(path.as_posix())
    proc.send(None)
    return posix_type

    with contextlib.closing(proc):
    yield getter


    with file_typer() as typer:
    typer('/usr/bin/python')