Tkinter/Python threading issue

Status
Not open for further replies.

Lysander

Smack-Fu Master, in training
80
Hello,

I'm using Ubuntu 10.04 and Python 2.6.5, and learning Tkinter, and I have an issue that I'd appreciate help with. I have a program that initializes a GUI (I'll call this the "GUI process"), then spawns another process that listens on a network via the TCP/IP protocol for incoming strings (I'll call this the "server process"). Everything works well up to this point.

What I want to happen next is for the server process to update a label in the GUI process when it receives a message from the network. First I tried passing a control variable for the label's text into the server process, but when I updated the control variable, nothing happened(no error messages, no feedback of any kind).

I tried piping the message from the server process into the GUI process using os.write() and os.read() - and this works, but not the way I need it to. I need the label to be updated automatically, without any intervention from the user (at the moment, it only works when the user clicks an "Update" button). I tried having the GUI process check the pipe for messages automatically, but when I do this it hangs when there's nothing in the pipe.

I've tried other avenues as well, but probably nothing worth mentioning. If you have any suggestions, I would be very grateful.
 
I don't know anything about Tkinter, but you don't have a threading issue. You're using multiple processes, which don't have access to each other's resources, requiring some form of IPC to communicate. You're on the right track with pipes - I'd probably use UNIX domain sockets, but have a look at http://docs.python.org/library/ipc.html for a list of the available options.

Also, note that in general, most GUI toolkits require that UI updates occur in the primary thread (e.g. BeginInvoke(), -performSelectorOnMainThread:withObject:), so even if you were using threads, you'd likely have to do a bit of work to marshal your label update action onto the main thread.
 

Lysander

Smack-Fu Master, in training
80
Thanks for the reply; everything that I mentioned is actually working, except for updating the label. The server process is receiving messages from the network just fine, and sending them back to the main program, but the main program can't receive them without causing the GUI to hang. I'll post some of the code so you can see what I'm talking about.
 

Lysander

Smack-Fu Master, in training
80
Code:
class MessageServer:
    '''Creates a message server object that listens for textual information
       and sends it back to the main program. Intended to be spawned as a
       separate process.
       '''
    
    def __init__(self, port_number, server_send, server_receive):
        '''@param server_send The pipe MessageServer uses to send text back to the main program.
           @param port_number The port the server listens on the network at.
           '''
    
        self.server_send = server_send
        self.server_receive = server_receive
        self.client_socket = None
        self.address = None

        self.error_logger = errorlogger.ErrorLogger(program_name=PROGRAM_NAME)

        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.bind(('localhost', port_number))
        self.server_socket.listen(1)

        self.listen()

    def listen(self):
        # listen for messages until process is killed
        # if a message is received, send it back to the main program
        (self.client_socket, self.address) = self.server_socket.accept()
        while True:
            input_stream = str(self.client_socket.recv(1024))
            if len(input_stream) != 0:
                os.write(self.server_send, input_stream)
                input_stream = None
 

Lysander

Smack-Fu Master, in training
80
Code:
    def check_message(self, spawn=True):
        '''Method for pulling message from server process.'''

        if spawn: self.pid2 = os.fork()
        if self.pid2 == 0:
            if verbose: print('message checker initialized')
            # repeat message check forever
            while True:
                incoming_data = os.read(self.client_receive, 1024)
                if verbose: print('Message receive successful')
                if verbose: print('Message: ' + incoming_data)
                self.update_messages(incoming_data)

Code:
    def update_messages(self, new_text=False):
        '''Adds new string to conversation box.
           @param new_text The string to be added.
           '''

        if not new_text: new_text = INCOMING_DATA
        try:
            current_text = self.chat_text.get()
            current_text += '\n' + new_text
            self.chat_text.set(current_text)
            
        except:
            error_details = 'Fatal Error. Message update failed. Program will now close.'
            tkMessageBox.showerror('Update Error', error_details)
            error_details += '\nINCOMING_DATA: ' + new_text
            error_details += '\ncurrent_text: ' + current_text
            stack_trace = traceback.format_stack()
            self.error_logger.log_error(stack=stack_trace, details=error_details)
            self.exit_program(force=True)
 
Calling os.read() will block until data or EOF is received (unless the fd is opened with os.O_NONBLOCK), leaving Tkinter unable to process any GUI events. You need to integrate with the toolkit's event loop.

A quick glance at the Tk docs indicates something like this should work:

Code:
# Somewhere in your app's initialization code
from Tkinter import *
app = Tk()

# Schedule the check_message() method to run as often as possible
app.after(0, check_message)
app.mainloop()

The after() method schedules the specified task to run exactly once, so call it again at the end of check_message(). Be sure to open the fd with os.O_NONBLOCK; if there is no data to read, it will return immediately, letting Tkinter process other events. If you don't need to spin as fast as possible watching for messages, increase the first parameter to after() as desired.
 

Lysander

Smack-Fu Master, in training
80
Yes, this is what I've been searching for. My original method used the GUI's event loop via the after method, but the event loop was disrupted when calling os.read() on the fd, causing the program to hang, which is why I tried solving the problem by spawning another process. I'll get rid of the extra process and try opening the fd with os.O_NONBLOCK...
 

Lysander

Smack-Fu Master, in training
80
No dice. After opening the pipe with fdopen() and passing it os.O_NONBLOCK, the event loop still hangs on check_message(). Here's the updated code:

Code:
        # setup the message server
        client_receive, server_send = os.pipe()
        self.client_receive = os.fdopen(client_receive, 'r', os.O_NONBLOCK)
        self.server_send = os.fdopen(server_send, 'w')
        self.pid = os.fork()
        if self.pid == 0:
            self.create_server()

Code:
    def check_message(self):
        '''Method for pulling message from server process.'''

        # repeat message check forever
        incoming_data = False
        incoming_data = self.client_receive.readline()
        if incoming_data:
            if verbose: print('Message receive successful')
            if verbose: print('Message: ' + incoming_data)
            self.update_messages(incoming_data)
            
        self.main_window.after(MSECS, self.check_message)

edit: typo
 
os.fdopen() doesn't take flags, only os.open() does.

os.fdopen(fd[, mode[, bufsize]])
Return an open file object connected to the file descriptor fd. The mode and bufsize arguments have the same meaning as the corresponding arguments to the built-in open() function.

Calling os.fdopen(client_receive, 'r', os.O_NONBLOCK) is actually setting bufsize to whatever the constant for os.O_NONBLOCK is (on my system, it's 4). Since you are using os.pipe(), you already have an fd, so you'll need to use fcntl to set options on it:

Code:
import fcntl
r, w = os.pipe()
if fcntl.fcntl(r, fcntl.F_SETFL, os.O_NONBLOCK) != 0:
  # handle error

# Call os.fdopen() on r, or just use os.read() like you did in your earlier code
 
On Linux, errno 11 is EAGAIN (it's 35 on Mac OS X, but that's what the errno module is for). From read(2):

[EAGAIN] The file was marked for non-blocking I/O, and no data were ready to be read.

Just trap that with a try/except block:

Code:
import errno

try:
  incoming_data = os.read(self.client_receive, 1024)
except OSError, e:
  if e.errno == errno.EAGAIN:
    # No data waiting
    pass
  else:
    raise
 
Status
Not open for further replies.