单行/动态上的简单更新字符串



我是Python的新手,从此以后我想发展我对这门语言的知识!

所以最近我得到了一个Raspberry Pi B +,今天我正在用python编写一个脚本,该脚本将更新终端中CPU的温度,就像在顶部htop实用程序中更新CPU使用率百分比一样

/opt/vc/bin/vcgencmd measure_temp

在控制台/ssh中输入并点击返回上述代码,以以下形式打印CPU的温度:

temp=34.2'C

所以我的主要目标是让上面的行不断自动更新,也许是一个

time.sleep(2)

延迟更新时间。

如果你能摆脱"temp="会更好,我相信我们可以通过使用.replace()

来完成

感谢您的任何帮助!

每两秒运行一次命令并打印34.2°C部分:

import subprocess
import sys
import time
while True:
    time.sleep(2 - time.time() % 2) # lock with the timer, to avoid drift
    output = subprocess.check_output(["/opt/vc/bin/vcgencmd", "measure_temp"])
    t = output.rpartition('=')[2] # extract the part after the last '='
    sys.stderr.write("r%6s" % t.strip())

如果要更改输出格式,则应在脚本measure_temp中执行此操作。现在你需要的是:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import time
while 1:
    os.system('/opt/vc/bin/vcgencmd measure_temp')
    time.sleep(2)

希望对您有所帮助。

我知道

这不在范围内,但是您是否查看了监视命令。如果没有必要,为什么要重新发明轮子。

watch --help
Usage:
 watch [options] command
Options:
  -b, --beep             beep if command has a non-zero exit
  -c, --color            interpret ANSI color sequences
  -d, --differences[=<permanent>]
                         highlight changes between updates
  -e, --errexit          exit if command has a non-zero exit
  -g, --chgexit          exit when output from command changes
  -n, --interval <secs>  seconds to wait between updates
  -p, --precise          attempt run command in precise intervals
  -t, --no-title         turn off header
  -x, --exec             pass command to exec instead of "sh -c"
 -h, --help     display this help and exit
 -v, --version  output version information and exit
For more details see watch(1).

尝试观看 ls -l 或观看日期

如果您只想在=后显示文本,最好使用字符串切片而不是替换。如果你的行在一个名为 line 的字符串变量中,你想显示line[5:],即从字符 5 到末尾 - python 字符串从字符 0 开始(在你的例子中是 t)。

最新更新