|FAQ Index - Search - Recent Changes - Everything - Add entry|
20.9. I don't want to use threading. What other options do I have?
- James Henstridge's post at [www.daa.com.au]
- David Mertz' Charming Python article `Implementing "weightless threads" with Python generators': [www-106.ibm.com]
- Guaranteed to work regardless of underlying thread support
- Much simpler to code and debug, no need for locks, semaphores etc.
- Allows extremely efficient scheduling. Thread creation/deletion overhead is minimal.
- Potentially long running or blocking operations (file.read etc) need to be handled specially.
For capturing the output of another process, or other file-based I/O, Danny Milosavljevic proposes using non-blocking I/O. This works like so:
- start the process via popen2.Popen4 (or use any other stuff that uses file descriptors, like pipes, ptys, whatever)
- set the file descriptor to non blocking mode (via fcntl F_SETFL O_NONBLOCK)
- use gtk.input_add to add a handler to be called a) on data or b) on process termination (gtk.gdk.INPUT_READ | gtk.gdk.INPUT_EXCEPTION)
- read()s what it can
- when reaching EOF that means the process terminated, and you can check the Popen4 object for the exit code
- when exception IOError with errno EAGAIN is fired, that means currently there is no (more) data available
- other IOErrors are fatal.
He has an example module available under the LGPL at [traveller.cvs.sourceforge.net] Check out about line 243. You should note he has deprecated this particular piece of code, and is using gobject.io_add_watch instead. The input_add functionality is commented still.