This is pretty lame, even for kragen-hacks.  But it might tell someone
how to do something actually useful at some point.

#!/usr/local/bin/python
# 'tkcat'
# How to handle asynchronous filehandle (stdin/stdout) I/O (on Unix)
# from the Tk event loop in Python --- mostly in the nature of an
# executable note to myself.

# Although it's kind of cool to use 'baud' and 'play-movie' from the
# movie package I posted to kragen-hacks a while back: baud 300 <
# sometextfile | play-movie | tkcat.

# Some information came from
# http://www.faqts.com/knowledge_base/view.phtml/aid/3728 by Fiona
# Czuczman, Rob Hooft, Grant Edwards, and Russell E. Owen

# According to
# http://mail.python.org/pipermail/python-list/1999-June/005884.html,
# a message from Matthew Cincera <[EMAIL PROTECTED]> on 25 Jun
# 1999 14:19:58 -0700, createfilehandler is not supported on Windows
# as of Tcl/Tk 8.0.

# Programmers who write libraries that do things from an event loop,
# but then require you to use their event loop instead of allowing you
# to use your own, should be drawn and quartered.  Using two such
# libraries in one program requires two threads.

import Tkinter, string, fcntl, FCNTL, sys, errno

mw = Tkinter.Tk()
# justify='left' makes lines of text attach to the left side of the
# widget.
# anchor='sw' means that when the window is subject to external sizing
# constraints and so can't assume its natural size, show the lower
# left-hand corner of it.
l = Tkinter.Label(mw, justify='left', anchor='sw', background='white', font='courier')

# expand means 'expand the widget's allocated space to fill available
# space if necessary'
# fill='both' means 'stretch the widget in both x and y to fill its
# allocated space'
l.pack(expand=1, fill='both')

text = ''

# doesn't differentiate between ' ' and '\n':
# _, _, _, _, oldtext = l.configure('text')
# also sometimes oldtext is a tuple and sometimes it's a string

def readappend(fh, _):
    try: mystr = sys.stdin.read()
    except IOError, (errnum, str):
        if errnum != errno.EAGAIN: raise
    if mystr == '': # EOF
        sys.exit(0)
    global text
    text = text + mystr
    l.configure(text=text)

def make_nonblocking(fh):
    if hasattr(fh, 'fileno'): fh = fh.fileno()
    fcntl.fcntl(fh, FCNTL.F_SETFL, 
                FCNTL.O_NONBLOCK | fcntl.fcntl(fh, FCNTL.F_GETFL))

make_nonblocking(sys.stdin)
Tkinter.tkinter.createfilehandler(sys.stdin, Tkinter.tkinter.READABLE,
                                  readappend)
mw.mainloop()



Reply via email to