Several times in the past I needed to query sysctls from Python. I was unhappy that this was not possible because the Python standard library didn’t include a sysctl function. I even created a Python module just to do this. Of course, you may already be thinking “ctypes! ctypes! ctypes!”. Yes, that’s what I’m going to talk about.
ctypes is a Python module to access foreign C types and functions, namely sysctlbyname(3). It’s easy to work with, here’s an example:
from ctypes import *
libc = CDLL("libc.so")
size = c_uint(0)
libc.sysctlbyname("kern.ostype", None, byref(size), None, 0);
buf = create_string_buffer(size.value)
libc.sysctlbyname("kern.ostype", buf, byref(size), None, 0);
Python ctypes are available in Python 2.5 and up.