Python Forum
Reading a file without blocking the main thread
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reading a file without blocking the main thread
#1
I'm following up from this question. I implemented the asyncio wrong, so I decided to correct it, use a threadpoolexecuitor and ask for feedback.

I have a text file parsed like this:

Ann Marie,Smith,[email protected]

There can over 100+ names in the text file.

Goal: When the program starts up, read in the text file using a thread, and load the data into a combobox. The main thread can continue loading other GUI components and isn't blocked by the method reading the text file.

import wx
import concurrent.futures


class MyDialog(wx.Frame):

    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(250, 270))

        self.panel = wx.Panel(self, size=(250, 270))
        self.combo = wx.ComboBox(self.panel, -1, pos=(60, 100))
        self.start_read_thread()

        # code to load other GUI components

        self.Centre()
        self.Show(True)

    def read_employees(self,read_file):
        emp_list = []
        with open(read_file) as f_obj:
            for line in f_obj:
                emp_list.append(line)
        wx.CallAfter(self.combo.Append, emp_list)

    def start_read_thread(self):
        filename = 'employees.txt'
        with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
            executor.submit(self.read_employees, filename)


app = wx.App(False)
frame = MyDialog(None, "Sample editor")
app.MainLoop()
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020