Detect Linux Runlevel

Tim Chase python.list at tim.thechases.com
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

https://gist.github.com/likexian/f9da722585036d372dca

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
runlevel.

Additional links I found helpful while searching:

https://casper.berkeley.edu/svn/trunk/roach/sw/busybox-1.10.1/miscutils/runlevel.c
https://github.com/garabik/python-utmp

-tkc





More information about the Python-list mailing list