Saturday, August 25, 2012

python-magic lets you implement the file command of UNIX

By Vasudev Ram


python-magic is a wrapper for libmagic, which is the library which the UNIX command-line tool called 'file' uses. The 'file' command guesses the type of a specified file in your UNIX system. It's typically used like this:

$ file some_file

or

$ file `which some_file`

The latter invocation can be used to check whether a file in one of the directories in your UNIX PATH environment variable, is executable (i.e. either a binary executable or a shell script or some other script) before attempting to run it.

The file command outputs a message saying what the type of the file is, such as "ASCII program text", "C program text", "PDF document, version 1.2", "FIFO", "directory", "socket", "block special file / block device file", etc. It works by reading / analysing the header(s) and content of the file and applying some heuristics as well. It usually gives the right results.

python-magic lets you do something similar in your Python programs.

- Vasudev Ram - Dancing Bison Enterprises



No comments: