[Python] Modifying the character representation of stdout Pipe values

Discussão em 'Python' iniciado por Stack, Agosto 23, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use subprocess.popen() to execute two Linux commands and then process their stdout streams to extract the CPU temperature and the average CPU load. Here is my code:

    #!/usr/bin/env python
    import subprocess
    Answers = ""
    IPs = ["192.168.70.13"]
    IPName = ["xxx"]
    for x in IPs:
    cmd = ['ssh', 'me@'+x, 'vcgencmd', ' measure_temp']
    cmd2 = ['top -n 1 | grep "%Cpu"']
    j = IPs.index(x)
    print(cmd2)
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    o, e = proc.communicate()
    print(IPName[j] + ': ' + o.decode('ascii'))
    Answers = Answers + IPName[j] + o.decode('ascii')
    proc.stdout.close()
    proc.stderr.close()
    proc2 = subprocess.Popen(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    o, e = proc2.communicate()
    TempCpu = o.decode('ascii')
    TempCpu = TempCpu.strip()
    print("lenght is " + str(len(TempCpu)))
    print("TempCpu = " + TempCpu)
    k = TempCpu.find('id')
    print("index of id = " + str(k))
    value = TempCpu[k-6:k]
    print(value)
    print(IPName[j] + ': ' + o.decode('ascii'))
    Answers = Answers + IPName[j] + ' == ' + o.decode('ascii')
    print('Answers were : /n' + Answers)


    The objective is to retrieve the CPU load and CPU temperatures of a Raspberry Pi running Debian Linux. The output was


    ['top -n 1 | grep "%Cpu"']

    xxx: temp=49.8'C

    lenght is 387

    TempCpu = %Cpu(s): 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st

    index of id = 169

    xxx: %Cpu(s): 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi,
    0.0 si, 0.0 st

    Answers were : /nRPStemp=49.8'C

    xxx == %Cpu(s): 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi,
    0.0 si, 0.0 st​

    If one visually examines the TempCpu value it is about 50 characters long and not the 387 which the length() function returns. Thus obviously the TempCpu variable is not the character value it is displaying. Which leads to other issues when I try to extract specific values, e.g. "id".

    Thus the question is how do I capture the output from the popen() function in a format which I can manipulate?

    Continue reading...

Compartilhe esta Página