python subprocess.check_output函数使用

最近拿到一块I2C OLED的屏幕,想到之前树莓派有个项目,可以通过I2C显示系统状态,顺手找了一下源码,配置好环境后上电测试,发现通过 top 得到的数据输出时都带有不必要的字符,本来考虑怎样把字符串切割出来。

后来发现主要是因为subprocess库的check_output函数的返回值可能不是正常字符串编码,查阅subprocess.check_output文档后得知:

By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level.

This behaviour may be overridden by setting text, encoding, errors, or universal_newlines to True as described in Frequently Used Arguments and run().

当使用encode转码后,再进行输出,就不会存在多余字符的问题:

    cmd = "hostname -I | cut -d\' \' -f1"
    IP = subprocess.check_output(cmd, shell = True )
    IP = IP.decode('UTF-8','strict')
    cmd = "top -bn1 | grep load | awk '{printf \"%.2f\",$(NF-2)}'"
    CPU = subprocess.check_output(cmd, shell = True )
    CPU = CPU.decode('UTF-8','strict')
    cmd = "free -m | awk 'NR==2{printf \"%s/%sMB %.2f%%\",$3,$2,$3*100/$2 }'"
    MemUsage = subprocess.check_output(cmd, shell = True )
    MemUsage = MemUsage.decode('UTF-8','strict')
    cmd = "df -h | awk '$NF==\"/\"{printf \"%d/%dGB %s\", $3,$2,$5}'"
    Disk = subprocess.check_output(cmd, shell = True )
    Disk = Disk.decode('UTF-8','strict')
    #decode output to format the coding data
    Date = time.asctime( time.localtime(time.time()) )
    
    draw.text((x, top),       "IP:" + str(IP),font=font,fill=255) 
    draw.text((x, top+8),     "CPU Load:"+str(CPU), font=font, fill=255)
    draw.text((x, top+25),    "Mem:"+str(MemUsage),  font=font, fill=255)
    draw.text((x, top+33),    "Disk:"+str(Disk),  font=font, fill=255)

Adafruit_SSD1306已停止更新,最新的库为Adafruit_CircuitPython_SSD1306

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐