Monday, January 25, 2010

Simple Errno Lookup with Python

Visual Studio has a tool [ERRLOOK] which looks up explanations of error codes. When you don't have the convenience of application code that automatically converts and reports this back to you it's nice to have.

I don't know of a similiar utility on Linux (or other Unix variants), but I know the library calls exist to write it (at least for well known system error codes).

Below is my first pass at writing this utility for Linux / Mac OS X using Python's CTypes.

#!/usr/bin/env python
import sys
import errno
import ctypes
try:
libc = ctypes.CDLL('libc.dylib')
except OSError:
libc = ctypes.CDLL('/lib/libc.so.6')
errorcode = int(sys.argv[1])
errmsg = ctypes.c_char_p(libc.strerror(errorcode)).value
print "%s (%d): %s" % (errno.errorcode[errorcode], errorcode, errmsg,)
view raw errnolookup.py hosted with ❤ by GitHub

The benifit of using python is that it doesn't need to be compiled (though this is a small benefit)— it's also an example of using CTypes to do FFI. Python also has the errno module which provides a mapping between a numeric error code and a symbolic name.

The calls to load libc.dylib or libc.so.1 might need to be tweaked depending on the system it's running on.

Example output:

> ./errnolookup.py 1
EPERM (1): Operation not permitted
> ./errnolookup.py 2
ENOENT (2): No such file or directory
> ./errnolookup.py 3
ESRCH (3): No such process
> ./errnolookup.py 42
ENOMSG (42): No message of desired type
view raw example.txt hosted with ❤ by GitHub
[Source for this post in Markdown mark-up]