栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python subprocess.check

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python subprocess.check

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/529794.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号