python subprocess.check_output函数使用

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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值