Lookslikerain75
Posts: 11
Joined: Wed Jul 17, 2019 6:29 pm

Read log file as lines are added into guizero textbox

Wed Nov 13, 2019 11:31 am

I am trying to read a log file as lines are added, after a button is pressed in a GUIZERO window. I am struggling to read the log file line by line into a gui textbox. This code locks the window as it seems to be stuck running def LogWindow() if i force close the program the the textbox shows whatever the last line was in the log file. So it is reading the lines just doesn't know when to stop and isn't showing all lines just the last one. I think I am way off on reading this log file as new lines are added, but this is all i have so far. Any help much appreciated as always.

Code: Select all

from guizero import App, Text, PushButton, TextBox
import os, psutil, subprocess, time

# Set up the app
app = App(title="System Updater", height="560", width="580", layout="grid")

def action():
    subprocess.Popen(['sudo ./autoupdate.sh > /updatelog.log'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
    LogWindow()
    textshow.value = "Update Complete"
    reval()

def follow(thefile):
    thefile.seek(0, os.SEEK_END) # End-of-file
    while True:
         line = thefile.readline()
         if not line:
             time.sleep(0.1) # Sleep briefly
             continue
         yield line      
     
def LogWindow():
    filepath = open('updatelog.log')
    loglines = follow(filepath)
    input_box.enable()
    input_box.visible=True
    for line in loglines:
        input_box.value=line
    filepath.close()
    #input_box.disable()

button1 = PushButton(app, action, text="Click to Update", grid=[0,0], align="left")
button1.text_color="Black"

app.display()

scotty101
Posts: 3863
Joined: Fri Jun 08, 2012 6:03 pm

Re: Read log file as lines are added into guizero textbox

Wed Nov 13, 2019 12:24 pm

I'm not near a Pi to test/try and fixes but there are a few issues.

Your LogWindow function can potentially take a number of seconds if not longer to complete so while it is running, guizero can't update the GUI. Rather than doing this, use the .repeat method in gui to schedule reading of the file periodically. See https://lawsie.github.io/guizero/blocking/

Rather than using the > redirect to a log file, you can redirect stdout and stderr to a file.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Lookslikerain75
Posts: 11
Joined: Wed Jul 17, 2019 6:29 pm

Re: Read log file as lines are added into guizero textbox

Wed Nov 13, 2019 2:05 pm

Thanks for the advice I looked up the .repeat function and that is working. I will also take a look at the stdout and stderr options also.

Thanks again

Return to “Python”