I am writing an internal log reading application in Python 3.12 and have run into a problem where code that works normally is not working inside of classes. I have one class that is reading the bytes of log files into a dictionary and stored as bytes similar to something like this:
class Logs:
def __init__(self, archive_file):
self.files = {'audit.log': b'1t2024-08-04 12:00:12tusertmessagen2t2024-08-04 12:00:13tusertmessage2n_etc.',
'system.log': b'1t2024-08-04 12:00:12tusertmessagen2t2024-08-04 12:00:13tusertmessagen_etc'}
I then have other classes that create the UI using tkinter and use that data. One of those is for actually viewing the log, but when I try to load and use the data at the beginning of the class I get an “Exception in Tkinter callback” and the variable is considered a noneType object. Here is the beginning of that class with the “data” variable being the dictionary above:
class logsNotebook(ttk.Notebook):
def __init__(self, data, parent, ui):
super().__init__(parent)
if ui.logs_button.cget("style") != "AccentButton":
ui.logs_button.configure(style="AccentButton")
ui.general_button.configure(style='')
ui.network_button.configure(style='')
ui.config_button.configure(style='')
tab1 = Frame(self)
tab2 = Frame(self)
self.add(tab1, text="System Log")
self.add(tab2, text="Audit Log")
self.pack(expand=True, fill="both")
### System Log ###############################################################
file = data.files['system.log'].decode('utf-8')
lines = []
for line in file.splitlines():
lines.append(line)
print(len(lines))
print(lines[-1])
The print statements never happen in the terminal. I receive the “Exception in Tkinter callback” first.
The files are in the right location, the tkinter code for the buttons and notebook work, and the data is read into memory successfully in the main program. In fact, if I just read the file in at the beginning of the class it works fine. If I replace the System Log section with this:
with open("system.log", "r") as f:
lines = f.readlines()
print(len(lines))
print(lines[-1])
then I don’t get the error. However, I am trying to avoid working with files on disk and just use them loaded into memory with the dictionary above.
If I write a test.py program that does the exact same thing it also works successfully:
import Logs
my_path = 'C:/Scripts/Python/testdata/system.log'
data = logs(my_path) #In the real code this is just grabbing the dictionary above
file = data.files['system.log'].decode('utf-8')
lines = []
for line in file.splitlines():
lines.append(line)
print(len(lines))
print(lines[-1])
There looks to be something that I am missing when passing the data between classes, but despite Google searches and the tests above trying to figure it out, I’m stumped.
user26635297 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.