[英]Python Script Open and Write into Terminal
I have a Python script on my Raspberry Pi 3 Model B (OS NOOBS) that when run, logs the temperature of the CPU into a .csv file every minute. 我在Raspberry Pi 3 Model B (OS NOOBS)上有一个Python脚本,该脚本在运行时每分钟将CPU的温度记录到一个.csv文件中。
What I'd like to know is how can I, from a Python script open a terminal and output the temperature in the terminal rather than log it into the .csv file? 我想知道的是如何从Python脚本打开终端并在终端中输出温度,而不是将其记录到.csv文件中?
This is the code that I've written so far: 这是我到目前为止编写的代码:
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)
I'm planning on using what I'm asking for so when the temperature goes above 'x' degrees, the terminal will open, print the temperature there until it drops down below the 'x' mark again. 我正在计划使用我要的东西,因此当温度超过“ x”度时,终端将打开,在此处打印温度,直到温度再次降至“ x”标记以下。 However I'll figure that remaining part on my own as I'm a newbie whom is still learning. 但是,我会认为剩下的部分是我自己,因为我还是一个正在学习的新手。 But I am stuck on the part where I want to open the terminal and print the variable there. 但是我卡在要打开终端并在其中打印变量的部分。
I'm using the software "Python 3 (IDLE)" to write and run this code. 我正在使用软件“ Python 3(IDLE)”来编写和运行此代码。 When it's completed I'll integrate it so it's automatically run on startup. 完成后,我将对其进行集成,以便在启动时自动运行。
Any assistance would be greatly appreciated! 任何帮助将不胜感激! Sincerely, Jocke 顺祝商祺
I can not test it on raspberry, but OS NOOBS should have lxterminal
available and the following code should work. 我无法在树莓派上对其进行测试,但是OS NOOBS应该具有可用的lxterminal
,并且以下代码应该可以工作。 If there is no lxterminal
on your system, install it or try replacing it in code below with xterm
or gnome-terminal
etc. Tested on Ubuntu 16. 如果您的系统上没有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()
You can adjust the writing to file and sleep according to your needs. 您可以根据需要调整写入文件并休眠。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.