Detect Linux Runlevel

Wildman best_lay at yahoo.com
Tue Dec 6 13:10:52 EST 2016


On Mon, 05 Dec 2016 16:08:57 -0600, Tim Chase wrote:

> 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

I went back to the code from the above link to try to
get it to work with Python3, just to see if I could.
The problem was that the output was in bytes or partly
in bytes like this:

['1', '53', "b'~\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\
x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\ (...)

I was trying to convert the bytes to strings and that
is what I never got to work right.  It didn't occur
to me that all I needed was the first two fields and
they were already strings.

The 'print output' part of the original code was this
which printed everything.  Over kill for my use:

data = read_xtmp('/var/run/utmp')
for i in data:
    print i

I changed it to this and it works:

data = read_xtmp('/var/run/utmp')
for i in data:
    if i[0] == "1":
        print("Runlevel: " + chr(int(i[1]) & 0xFF))
        break

The output:  Runlevel: 5

If I had tried this in the beginning, it would have
save you a lot of work.

Since both versions of the code works, which one do
you recommend?  Or does it matter?

-- 
<Wildman> GNU/Linux user #557453
The cow died so I don't need your bull!


More information about the Python-list mailing list