sysctlbyname(3) (and others) from Python

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("")
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);
>>> buf.value


Python ctypes are available in Python 2.5 and up.

One thought on “sysctlbyname(3) (and others) from Python

  1. Pingback: Accéder à sysctrl depuis python at FreeBSD-fr: Les nouvelles du géant en français

Comments are closed.