473,792 Members | 3,400 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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.create filehandler" 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(fi ll=BOTH, expand=YES)
mainFrame.pack( fill=BOTH, expand=YES)

fh = os.popen('/homes/jschamba/tof/pcan/pcanloop')

def readfh(filehand le, stateMask):
global textBox
newText = filehandle.read ()
textBox.insert( END, newText)

tkinter.createf ilehandler(fh, tkinter.READABL E, readfh)
root.mainloop()
I don't see any of the stdout from my program appear in the textbox.

Does anyone have a short example that I could use as an inspiration for
this task?

I guess what my ultimate goal would be is to create something similar to
the "expectk" call "expect_backgro und", which does exactly what i just
described, i.e. wait for output from a shell/C/C++ program and then do
something in response to this output like insert it into a text widget.
In expect, the following program seems to work:

#!/usr/bin/expectk -f

# disable terminal output
log_user 0

spawn -noecho /homes/jschamba/tof/pcan/pcanloop
set shell $spawn_id
text .shell -relief sunken -bd 1 -width 90 -height 24 -yscrollcommand
{.scroll set}
scrollbar .scroll -command {.shell yview}
pack .scroll -side right -fill y
pack .shell -side bottom -expand true -fill both

expect_backgrou nd {
-i $shell -re "\[^\x0d]+" {
.shell insert end $expect_out(0,s tring)
.shell yview -pickplace insert
}
}
Jo
--
Dr Joachim Schambach
The University of Texas at Austin
Department of Physics
1 University Station C1600
Austin, Texas 78712-0264, USA
Phone: (512) 471-1303; FAX: (814) 295-5111
e-mail: js******@physic s.utexas.edu
Nov 22 '05 #1
3 3124
Compared to your program, I
* Made sure that the slave program actually flushed its stdout buffers
* didn't call read(), which will by default continue reading until
it reaches EOF, not merely read the available data

#!/usr/bin/env python
import sys, time, Tkinter, itertools, _tkinter, os

if '-slave' in sys.argv:
for i in itertools.count ():
time.sleep(1)
print "This is a line of output:", i
sys.stdout.flus h()
raise SystemExit

root = Tkinter.Tk()
root.wm_withdra w()

fh = os.popen('%s -slave' % sys.argv[0])

def reader(*args):
line = fh.readline()
if not line:
print "EOF from slave"
raise SystemExit
print "from slave: %r" % line

_tkinter.create filehandler(fh, Tkinter.READABL E, reader)
root.mainloop()

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDePR9Jd0 1MZaTXX0RAk6SAK CdYh2mbnbRk7Dc6 Q9hImCuiVrfXwCf dlgS
bVtpMT08YIylmRq KlPCZV6U=
=YPSK
-----END PGP SIGNATURE-----

Nov 22 '05 #2
In article <dl**********@g eraldo.cc.utexa s.edu>,
Jo Schambach <js******@physi cs.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.create filehandler" 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(f ill=BOTH, expand=YES)
mainFrame.pack (fill=BOTH, expand=YES)

fh = os.popen('/homes/jschamba/tof/pcan/pcanloop')

def readfh(filehand le, stateMask):
global textBox
newText = filehandle.read ()
textBox.insert( END, newText)

tkinter.create filehandler(fh, tkinter.READABL E, readfh)
root.mainloop( )


Changingfilehan dle.read() to filehandle.read line() 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(ti me.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(fi ll=BOTH, expand=YES)
mainFrame.pack( fill=BOTH, expand=YES)

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

def readfh(filehand le, stateMask):
global textBox
newText = filehandle.read line()
textBox.insert( END, newText)

tkinter.createf ilehandler(fh, tkinter.READABL E, readfh)
root.mainloop()

--
Jim Segrave (je*@jes-2.demon.nl)

Nov 22 '05 #3
Thanks, that seems to work.
maybe one more question on this subject:

how can i use the callback function to the "createfilehand ler" call from
within a class?
in other words, what would be the signature of the callback function, if
I made it a member of a class?
The documentation says that the callback is called with the arguments:
callback(fileha ndle, stateMask)
but a class member function always has the "self" argument as is first
argument. So would the syntax be:

class GUI:
def __init__:
.....

def filehandlerCall back(self, filehandle, stateMask):
....
Jo
je****@unpython ic.net wrote:
Compared to your program, I
* Made sure that the slave program actually flushed its stdout buffers
* didn't call read(), which will by default continue reading until
it reaches EOF, not merely read the available data

#!/usr/bin/env python
import sys, time, Tkinter, itertools, _tkinter, os

if '-slave' in sys.argv:
for i in itertools.count ():
time.sleep(1)
print "This is a line of output:", i
sys.stdout.flus h()
raise SystemExit

root = Tkinter.Tk()
root.wm_withdra w()

fh = os.popen('%s -slave' % sys.argv[0])

def reader(*args):
line = fh.readline()
if not line:
print "EOF from slave"
raise SystemExit
print "from slave: %r" % line

_tkinter.create filehandler(fh, Tkinter.READABL E, reader)
root.mainloop()

--
Dr Joachim Schambach
The University of Texas at Austin
Department of Physics
1 University Station C1600
Austin, Texas 78712-0264, USA
Phone: (512) 471-1303; FAX: (814) 295-5111
e-mail: js******@physic s.utexas.edu
Nov 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1887
by: Psymaster | last post by:
Does anybody know where can I get the html version for offline browsing? It's cumbersome to use the pdf. I've got dial-up and I can't connect all the time to see the reference.
4
5242
by: Grzegorz Dostatni | last post by:
Good morning. I've got a Tkinter problem: File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 2310, in selection_present return self.tk.getboolean( TclError: expected boolean value but got "" Now a few weeks ago there was a similar problem with the boolean value. That's when the tcl started returning "???" for unknown fields in a
1
2674
by: Ivo | last post by:
Hi All, I would implement a tab viewing (like mozilla) using the Tkinter toolkit. Does anyone know if is it possible and where i can find doc about? Thanks, Ivo
0
1656
by: Miki Tebeka | last post by:
Hello All, The following script "hangs" on win32 system: from Tkinter import * from tkSimpleDialog import askstring root = Tk() root.withdraw() # <<< Problem here askstring("Yap", "What's up?")
6
2529
by: mortuno | last post by:
Hi My tkinter apps worked fine in debian linux (woody and sarge) I moved to ubuntu 5.10 I follow the 'hello world' test as seen in http://wiki.python.org/moin/TkInter import _tkinter # with underscore, and lowercase 't'
1
1744
by: notsonice51 | last post by:
I'm trying to install python2.5 on my computer(os Fedora 5). My problem is that I'm unable to get the tkinter module loaded into python. I've tried the solution here:"wiki.python.org/moin/TkInter" but am unsure as how to modify my setup.py script. I have installed the latest versions of tcl/tk (8.4.14) twice as well as installing python again. Everything is installed in the default location but still no luck. Does anyone have any ideas?...
3
30215
by: ElBeardo | last post by:
Hello, I´m new to Python.. so this is a newbee question. I´d like to put the value enterd in the entryfield in a variable. I´m trying to build a calculator with python and TKinter, coding it in just python works good. But making it with TK is a bit hard. This is my unfinished code, i have tryed get() in many ways,.but I cant make it work. I´m only need to get knowledge about using get() now,.. I now there is other thing undone in this...
27
4219
by: duli | last post by:
Hi: I would like recommendations for books (in any language, not necessarily C++, C, python) which have walkthroughs for developing a big software project ? So starting from inception, problem definition, design, coding and final delivery on a single theme or application. Most of the code I have written and books that I have read deal with toy programs and I am looking for something a bit more comprehensive. For example, maybe a...
1
2165
by: nicstel | last post by:
I don't understand the "argv" in TKinter module Can you tell me what argv means and do? Thank You
0
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9517
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10156
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6776
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4110
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.