Python 脚本打开并写入终端
Python Script Open and Write into Terminal
我的 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)" 编写和 运行 这段代码。完成后,我将集成它,以便它在启动时自动 运行。
如有任何帮助,我们将不胜感激!
真挚地,
乔克
我无法在 raspberry 上测试它,但是 OS NOOBS 应该有 lxterminal
可用并且下面的代码应该可以工作。如果您的系统上没有 lxterminal
,请安装它或尝试在下面的代码中将其替换为 xterm
或 gnome-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()
您可以根据需要调整写入文件和休眠。 :)
我的 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)" 编写和 运行 这段代码。完成后,我将集成它,以便它在启动时自动 运行。
如有任何帮助,我们将不胜感激! 真挚地, 乔克
我无法在 raspberry 上测试它,但是 OS NOOBS 应该有 lxterminal
可用并且下面的代码应该可以工作。如果您的系统上没有 lxterminal
,请安装它或尝试在下面的代码中将其替换为 xterm
或 gnome-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()
您可以根据需要调整写入文件和休眠。 :)