Python Script Open and Write to Terminal

I have a Python script on my Raspberry Pi 3 Model B (OS NOOBS) that logs the cpu temperature in a .csv file every minute on startup.

What I would like to know is how can I, with a Python script, open a terminal and output the temperature in the terminal, and not write it to a .csv file?

This is the code I have 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 am planning to use what I ask, so when the temperature is above "x" degrees the terminal will open, print the temperature there until it goes below the "x" mark. However, I will show that the remainder is on its own as I am a beginner still learning. But I am stuck on the part where I want to open a terminal and print the variable there.

I am using "Python 3 (IDLE)" software to write and run this code. When it's complete, I will integrate it so that it starts automatically on startup.

Any help would be greatly appreciated! Regards, Jocke

+3


source to share


1 answer


I can't test it on raspberries, but OS NOOBS should have lxterminal

and the following code should work. If not on your system lxterminal

, install it or try replacing it in the code below xterm

or gnome-terminal

etc. Tested on 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 customize file recording and sleep according to your needs. :)

+1


source







All Articles