Skip to content

Instantly share code, notes, and snippets.

@Kentzo
Last active October 16, 2022 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kentzo/42f7e3a7476baef2b42dbf1eab5bc1c8 to your computer and use it in GitHub Desktop.
Save Kentzo/42f7e3a7476baef2b42dbf1eab5bc1c8 to your computer and use it in GitHub Desktop.
Guess file type from python on macOS, no dependencies
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')
@Kentzo
Copy link
Author

Kentzo commented Oct 12, 2022

#libmagic #python-magic #file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment