how do i use "tkinter.createfilehandler" with a regular c program?

Jim Segrave jes at nl.demon.net
Mon Nov 14 16:07:23 EST 2005


In article <dlai0f$ouh$1 at geraldo.cc.utexas.edu>,
Jo Schambach  <jschamba at physics.utexas.edu> wrote:
>I am trying to write a GUI with tkinter that displays the stdout from a
>regular C/C++ program in a text widget.
>The idea i was trying to use was as follows:
>
>1) use "popen" to execute the C/C++ program
>2) then use "tkinter.createfilehandler" to create a callback that  would
>be called when the C/C++ program creates output on stdout.
>
>Somehow, I can't get this to  work. here is what I have tried so  far:
>
>import sys,os
>from Tkinter import *
>
>root = Tk()
>mainFrame = Frame(root)
>textBox = Text(mainFrame)
>textBox.pack(fill=BOTH, expand=YES)
>mainFrame.pack(fill=BOTH, expand=YES)
>
>fh = os.popen('/homes/jschamba/tof/pcan/pcanloop')
>
>def readfh(filehandle, stateMask):
>    global textBox
>    newText = filehandle.read()
>    textBox.insert(END, newText)
>
>tkinter.createfilehandler(fh, tkinter.READABLE, readfh)
>root.mainloop()

Changingfilehandle.read() to filehandle.readline() and running a
separate output generator, this seems to work, although the Text
widget fills rapidly:

========= test generator - creates a pipe and writes the time once/second
#!/usr/local/bin/python
import os, time

try:
    pipe = os.mkfifo('./pipe', 0660)
except OSError, (errno):
    if errno == 17:
        pass

fh = open('./pipe', 'w')
rh = open('./pipe', 'r') # keep the pipe having a reader
while True:
    fh.write("%s\n" % time.asctime(time.localtime()))
    fh.flush()
    time.sleep(1)
    
========== read the output and put in a Text widget:
#!/usr/bin/python
import sys,os
from Tkinter import *

root = Tk()
mainFrame = Frame(root)
textBox = Text(mainFrame)
textBox.pack(fill=BOTH, expand=YES)
mainFrame.pack(fill=BOTH, expand=YES)

fh = os.popen('/bin/cat /tmp/pipe', 'r', 1)

def readfh(filehandle, stateMask):
    global textBox
    newText = filehandle.readline()
    textBox.insert(END, newText)

tkinter.createfilehandler(fh, tkinter.READABLE, readfh)
root.mainloop()

-- 
Jim Segrave           (jes at jes-2.demon.nl)




More information about the Python-list mailing list