473,698 Members | 2,616 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Catching stderr output from graphical apps


Here's a module to show stderr output from console-less Python
apps, and stay out of the way otherwise. I plan to make a ASPN
recipe of it, but I thought I'd run it by this group first.

To use it, import the module. That's it. Upon import it will
assign sys.stderr.

In the normal case, your code is perfect so nothing ever gets
written to stderr, and the module won't do much of anything.
Upon the first write to stderr, if any, the module will launch a
new process, and that process will show the stderr output in a
window. The window will live until dismissed; I hate, hate, hate
those vanishing-consoles-with-critical-information.
The code shows some arguably-cool tricks. To fit everthing in
one file, the module runs the Python interpreter on itself; it
uses the "if __name__ == '__main__'" idiom to behave radically
differently upon import versus direct execution. It uses TkInter
for the window, but that's in a new process; it does not import
TkInter into your application.

To try it out, save it to a file -- I call it "errorwindow.py " -
- and import it into some subsequently-incorrect code. For
example:

import errorwindow

a = 3 + 1 + nonesuchdefined

should cause a window to appear, showing the traceback of a
Python NameError.

--
--Bryan
----------------------------------------------------------------

"""

Import this module into graphical Python apps to provide a
sys.stderr. No functions to call, just import it. It uses
only facilities in the Python standard distribution.

If nothing is ever written to stderr, then the module just
sits there and stays out of your face. Upon write to stderr,
it launches a new process, piping it error stream. The new
process throws up a window showing the error messages.

"""

import sys
import os
import thread

if __name__ == '__main__':

from Tkinter import *
import Queue
queue = Queue.Queue(99)
def read_stdin(app) :
while 1:
data = os.read(sys.std in.fileno(), 2048)
queue.put(data)
if not data:
break
class Application(Fra me):
def __init__(self, master=None):
Frame.__init__( self, master)
self.master.tit le("Error Stream from run of %s" % sys.argv[-1])
self.pack(fill= BOTH, expand=YES)
self.logwidget = Text(self)
self.logwidget. pack(side=TOP, fill=BOTH, expand=YES)
# Disallow key entry, but allow copy with <Control-c>
self.logwidget. bind('<Key>', lambda x: 'break')
self.logwidget. bind('<Control-c>', lambda x: None)
self.after(200, self.start_thre ad, ())
def start_thread(se lf, _):
thread.start_ne w_thread(read_s tdin, (self,))
self.after(200, self.check_q, ())
def check_q(self, _):
go = True
while go:
try:
data = queue.get_nowai t()
if not data:
self.logwidget. configure(foreg round ='#0000AA')
data = "\n==== File Closed ====\n"
go = False
self.logwidget. insert(END, data)
self.logwidget. see(END)
except Queue.Empty:
self.after(200, self.check_q, ())
go = False
app = Application()
app.mainloop()

else:

class ErrorPipe(objec t):
def __init__(self):
self.lock = thread.allocate _lock()
self.empty = True
def on_first_write( self):
command = "%s %s %s" % (sys.executable , __file__, sys.argv[0])
self.pipe = os.popen(comman d, 'w')
def _write(self, data):
self.pipe.write (data)
os.fsync(self.p ipe)
def write(self, data):
self.lock.acqui re()
try:
if self.empty:
self.on_first_w rite()
self.empty = False
self._write(dat a)
finally:
self.lock.relea se()
sys.stderr = ErrorPipe()

Aug 10 '05 #1
9 2042
Bryan Olson wrote:
Here's a module to show stderr output from console-less Python
apps, and stay out of the way otherwise. I plan to make a ASPN
recipe of it, but I thought I'd run it by this group first.


For what it's worth, I believe you've basically duplicated the
functionality available in wxPython in the standard App object.

-Peter
Aug 10 '05 #2
Peter Hansen wrote:
Bryan Olson wrote:
Here's a module to show stderr output from console-less Python
apps, and stay out of the way otherwise. I plan to make a ASPN
recipe of it, but I thought I'd run it by this group first.


For what it's worth, I believe you've basically duplicated the
functionality available in wxPython in the standard App object.


I'm not a wxPython user, but what I've heard is that it tries to
write stderr to a regular window within the process. Crashing
apps vanish from the screen, taking their error windows with
them. Most any GUI toolkit has to return to its event-loop
before it will update the screen, preventing it from showing
messages of fatal errors.
--
--Bryan
Aug 10 '05 #3
gry
Python 2.3.3, Tkinter.__versi on__'$Revision: 1.177 $'

Hmm, the error window pops up with appropriate title, but contains no
text.
I stuck an unbuffered write to a log file in ErrorPipe.write and got
only one line: Traceback (most recent call last):$

Any idea what's wrong?

-- George

Aug 10 '05 #4
gr*@ll.mit.edu wrote:
Python 2.3.3, Tkinter.__versi on__'$Revision: 1.177 $'

Hmm, the error window pops up with appropriate title, but contains no
text.
I stuck an unbuffered write to a log file in ErrorPipe.write and got
only one line: Traceback (most recent call last):$

Any idea what's wrong?


Darn. Are you on Windoze/Mac/Unix/, and what version?

If you can spare the time, could you please try:
import errorwindow
import sys

sys.stderr.writ e("Hello\nWorld .\n")

x = 7 + nosuchvariable
and tell me what happens?

Thanks.
--
--Bryan
Aug 10 '05 #5
gry
Linux -2.4.20 (x86), Python 2.3.3.
I did exactly as you suggested.
After the stderr.write, a window pops up with title "Error Stream from
run of errorwindow.pyc ".
The window is otherwise blank.
Nothing more happens when I do the "x=7+nosuchvari able", I just get
the next python ">>>" prompt, but no error messages.
When I try to exit the python, e.g. sys.exit(), it hangs and I have to
Control-C.
After the control-C, the "Error Stream..." window goes away.

Any more suggestions? Perhaps we should take this to email, instead of
newsgroup?
This *is* something I would like to be able to use, if we can get it
working.

-- George

Aug 12 '05 #6

Thanks.

Yeah, guess I was naive to test on Windows and expect that kind
of process stuff to be portable. I'll be away from Linux for a
week or so, so this will take me a while.

Further bulletins as events warrant.

--
--Bryan
Aug 12 '05 #7
Bryan Olson wrote:

Thanks.

Yeah, guess I was naive to test on Windows and expect that kind
of process stuff to be portable. I'll be away from Linux for a
week or so, so this will take me a while.

Further bulletins as events warrant.


If you can get a cross-platform solution, please re-annoucne it; this
sounds like a really neat module to have handy for graphical programs.
Aug 12 '05 #8
Christopher Subich wrote:
Bryan Olson wrote:
Thanks.

Yeah, guess I was naive to test on Windows and expect that kind
of process stuff to be portable. I'll be away from Linux for a
week or so, so this will take me a while.

Further bulletins as events warrant.


If you can get a cross-platform solution, please re-annoucne it; this
sounds like a really neat module to have handy for graphical programs.


Look at py.io[1]. It seems to have implemented a probably-cross-platform
solution. Please check it out and let c.l.py and the py mailing list
know if it works on Windows.

[1] http://codespeak.net/py/current/doc/home.html

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 13 '05 #9
Robert Kern wrote:
Christopher Subich wrote:
If you can get a cross-platform solution, please re-annoucne it; this
sounds like a really neat module to have handy for graphical programs.

Look at py.io[1]. It seems to have implemented a probably-cross-platform
solution. Please check it out and let c.l.py and the py mailing list
know if it works on Windows.

[1] http://codespeak.net/py/current/doc/home.html


Thanks guys. I found I had a bootable Linux system. With some
stuff from py.io, and *without* the fsync(), this one worked on
Windows and Linux in my not-so-extensive testing.

--
--Bryan

"""

Import this module into graphical Python apps to provide a
sys.stderr. No functions to call, just import it. It uses
only facilities in the Python standard distribution.

If nothing is ever written to stderr, then the module just
sits there and stays out of your face. Upon write to stderr,
it launches a new process, piping it error stream. The new
process throws up a window showing the error messages.

"""

import sys
import os
import thread

import time

if __name__ == '__main__':

from Tkinter import *
import Queue
queue = Queue.Queue(99)
def read_stdin(app) :
fd = os.dup(sys.stdi n.fileno())
infile = os.fdopen(fd, 'r', 0)
while 1:
data = os.read(infile. fileno(), 2048)
queue.put(data)
if not data:
break
class Application(Fra me):
def __init__(self, master=None):
Frame.__init__( self, master)
self.master.tit le("Error Stream from run of %s" % sys.argv[-1])
self.pack(fill= BOTH, expand=YES)
self.logwidget = Text(self)
self.logwidget. pack(side=TOP, fill=BOTH, expand=YES)
# Disallow key entry, but allow copy with <Control-c>
self.logwidget. bind('<Key>', lambda x: 'break')
self.logwidget. bind('<Control-c>', lambda x: None)
self.after(200, self.start_thre ad, ())
def start_thread(se lf, _):
thread.start_ne w_thread(read_s tdin, (self,))
self.after(200, self.check_q, ())
def check_q(self, _):
go = True
while go:
try:
data = queue.get_nowai t()
if not data:
self.logwidget. configure(foreg round ='#0000AA')
data = "\n==== File Closed ====\n"
go = False
self.logwidget. insert(END, data)
self.logwidget. see(END)
except Queue.Empty:
self.after(200, self.check_q, ())
go = False
app = Application()
app.mainloop()

else:

class ErrorPipe(objec t):
def __init__(self):
self.lock = thread.allocate _lock()
self.pipe = None
def on_first_write( self):
command = "%s %s %s" % (sys.executable , __file__, sys.argv[0])
self.rawpipe = os.popen(comman d, 'w')
fd = os.dup(self.raw pipe.fileno())
self.pipe = os.fdopen(fd, 'w', 0)
def write(self, data):
self.lock.acqui re()
try:
if not self.pipe:
self.on_first_w rite()
self.pipe.write (data)
finally:
self.lock.relea se()
sys.stderr = ErrorPipe()
# sys.stdout = ErrorPipe()
Aug 13 '05 #10

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

Similar topics

6
4438
by: Farshid Lashkari | last post by:
Hi, My application has python embedded into it. I noticed that when I run any python code the output is buffered and doesn't get flushed until my application exits. To fix this I simply flush sys.stdout and sys.stderr every once in while by using the following code: //Get handle to python stdout file and flush it PyObject *pyStdout = PySys_GetObject("stdout"); if(pyStdout && PyFile_Check(pyStdout)) {
21
639
by: clusardi2k | last post by:
/* The below code on SGI will wait for you to enter 2 things, but on Linux it will only wait the first time. I can make the code work by replacing the scanf with: char data ; fgets (data,5,stdin); the_number = atoi (data);
0
2026
by: Bryan Olson | last post by:
New and improved! Love Python's stack-tracing error messages, but hate the way GUI applications throw the messages away and crash silently? Here's a module to show Python error messages that would otherwise be lost in console-less programs. Graphical applications should not require console windows, but they do need a workable destination for sys.stderr.
7
11641
by: Andre | last post by:
Hi, I have a program that sends some output to stdout and some to stderr. I need to separate the two using the command-line so that I direct stderr output to a file, say fileA.txt, and stdout output to a file, say fileB.txt. I'm trying to implement a program that would then take the two files and use them separately. By the way, I'm on Linux. Thanks! -Andre
5
2472
by: Philip Hölzenspies | last post by:
Hi All, I have been crunching my brains on this one all day. I use this library that creates output I want, but it can only write it to a file or the stdout. The problem is that I don't want to use the filesystem (permissions, latency through NFS, etc, etc), but a memory buffer. I've been looking for a way to redirect stdout to a buffer that I manage myself. Obviously I considered setbuf (from stdio.h), but then I'ld still have to...
37
5061
by: nobody | last post by:
I am writing a framework that other developers will write plug-ins for. I would like for one of the features of the framework to be to intercept all text written to stdout/stderr and prepend timestamps on each line. I would like for this to work for all the printf-line functions (fprintf, etc...) as well as C++ I/O streams (cout and cerr). The key here is that I would like to get these timestamps on the lines of text written to...
3
3366
by: Fuzzyman | last post by:
Hello all, Before I ask the question a couple of notes : * This question is for implementing a script inside the Wing IDE. For some reason using the subprocess module doesn't work so I need a solution that doesn't use this module. * The platform is Windows and I'm happy with a Windoze only solution. :-)
37
5053
by: Vince C. | last post by:
Hi all. I've installed Bloodshed Dev-C++ on a Windows 2000 SP4 machine. I'm using MinGW 3.4.2. I'd like to temporarily disable standard functions to write to stderr, i.e. for instance redirect stderr to a temporary file (or /dev/null but is there an equivalent under Windows? Is it "nul:") and then to *restore* the default stderr so that standard library functions that write to stderr produce output again.
8
6606
by: r0g | last post by:
Hi There, I'm trying to migrate a locally hosted page from windows to a private Ubuntu development server and one of the key bits of functionality (which used to work fine in Windows) was the ability for the page to start a file browser via PHP's exec() function. I can't get this working under Ubuntu though e.g. <?php exec('nautilus /var/www'); ?>
0
8683
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
8610
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
9031
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
8902
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
6528
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
5862
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();...
0
4372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4623
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
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

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.