【问题标题】:Python Script Open and Write into TerminalPython脚本打开并写入终端
【发布时间】:2017-10-09 02:44:15
【问题描述】:

我的 Raspberry Pi 3 Model B 上有一个 Python 脚本(OS NOOBS),它在运行时每分钟将 CPU 的温度记录到一个 .csv 文件中。

我想知道的是如何从 Python 脚本打开终端并在终端中输出温度而不是将其记录到 .csv 文件中?

这是我目前写的代码:

from gpiozero import CPUTemperature
from time import sleep, strftime, time

cpu = CPUTemperature()

def output_temp(temp):
    with open("cpu_temp.csv", "a") as log:
        log.write("{0}, {1}\n".format(strftime("%Y-%m-%d %H:&M:%S"),str(temp)))

while True:
    temp = cpu.temperature
    output_temp(temp)
    sleep(60)

我正计划使用我所要求的,所以当温度超过“x”度时,终端将打开,在那里打印温度,直到它再次降至“x”标记以下。但是,我会自己计算剩下的部分,因为我是一个仍在学习的新手。但是我卡在我想打开终端并在那里打印变量的部分。

我正在使用“Python 3 (IDLE)”软件来编写和运行这段代码。完成后我会集成它,以便它在启动时自动运行。

任何帮助将不胜感激! 真挚地, 乔克

【问题讨论】:

标签: python linux terminal output raspberry-pi3


【解决方案1】:

我无法在 raspberry 上对其进行测试,但 OS NOOBS 应该有 lxterminal 可用,并且以下代码应该可以工作。如果您的系统上没有 lxterminal,请安装它或尝试在下面的代码中将其替换为 xtermgnome-terminal 等。在 Ubuntu 16 上测试。

import os
import time
import subprocess


# create custom pipe file
PIPE_PATH = "/tmp/my_pipe"
if os.path.exists(PIPE_PATH):
    os.remove(PIPE_PATH)
    os.mkfifo(PIPE_PATH)

# open terminal that reads from your pipe file
a = subprocess.Popen(['lxterminal', '-e', 'tail --follow {0}'.format(PIPE_PATH)])

# write to file and it will be displayed in the terminal window
message = "some message to terminal\n"
with open(PIPE_PATH, "w") as p:
    p.write(message)

time.sleep(5)

# close the terminal
a.terminate()

您可以根据需要调整写入文件和睡眠。 :)

【讨论】:

  • 非常感谢!该解决方案是可以理解的并且有效,我非常感谢您的帮助! :)
猜你喜欢
  • 2020-05-14
  • 2015-07-04
  • 1970-01-01
  • 2022-12-11
  • 2020-01-16
  • 2017-04-26
  • 1970-01-01
  • 2020-08-28
  • 1970-01-01
相关资源
最近更新 更多