pythonuptime

get system uptime with Python on a Raspberry Pi


This question refers to: uptime with Python

If I use the programm on a raspberry, I get the wrong time:

~ $ uname -a
Linux raspberry 5.4.72-v7+ #1356 SMP Thu Oct 22 13:56:54 BST 2020 armv7l GNU/Linux


pi@raspberry:~ $ uptime
15:14:33 up 20 min,  3 users,  load average: 0,00, 0,08, 0,09

But the output is:

20 0 1 # days, hours, minutes

I'm using:

import subprocess 
def uptime1(): # liefert Zeit in s
    raw = subprocess.check_output('uptime').decode("utf8").replace(',', '')
    days = int(raw.split()[2])
    if 'min' in raw:
        hours = 0
        minutes = int(raw[4])
    else:
        hours, minutes = map(int,raw.split()[4].split(':'))
    print(days, hours, minutes)    
    totalsecs = ((days * 24 + hours) * 60 + minutes) * 60
    return totalsecs

zeit=uptime1()

How can that be solved?


Solution

  • I found another solution: https://www.raspberrypi.org/forums/viewtopic.php?t=164276

    #!/usr/bin/python3
    
    import shlex, subprocess
    cmd = "uptime -p"
    args = shlex.split(cmd)
    p = subprocess.Popen(args, stdout=subprocess.PIPE)
    output = p.communicate()
    

    Thanks for your posted ideas. print (output)