Python脚本打开并写入终端

5
我在我的Raspberry Pi 3 Model B (OS NOOBS)上有一个Python脚本,运行时会将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)”编写和运行此代码。当完成后,我将集成它,以便在启动时自动运行。
如有任何帮助,将不胜感激! 诚挚地, Jocke

请查看此链接,了解如何在启动时打开终端窗口并执行Python脚本。希望对您有所帮助。 - return
1个回答

2

我无法在树莓派上进行测试,但是 OS NOOBS 应该可以使用 lxterminal,以下代码应该可以工作。如果您的系统中没有 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()

你可以根据需要调整写入文件和休眠时间。 :)

1
非常感谢!这个解决方案易于理解并且有效,我非常感谢您的帮助! :) - Jocke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接