Detect Linux Runlevel

Tim Chase python.list at
Mon Dec 5 17:08:57 EST 2016

On 2016-12-05 14:58, Wildman via Python-list wrote:
> I there a way to detect what the Linux runlevel is from
> within a Python program?  I would like to be able to do
> it without the use of an external program such as 'who'
> or 'runlevel'.

You can use something like

to parse the /var/run/utmp contents.  Based on some source-code
scrounging, it looks like you want the first field to be "1" for the
"runlevel" account.  To extract the actual runlevel, you can take
the PID value from the second column ("53" in my example here) and
take it's integer value mod 256 (AKA "& 0xff") to get the character
value.  So chr(int("53") & 0xff) returns "5" in my case, which is my

Additional links I found helpful while searching:


More information about the Python-list mailing list