473,474 Members | 1,822 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Catch stderr in non-console applications


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.

To try it out, you can use something like:

import errorwindow
x = undefined_variable_name
I've tried this version on Microsoft Windows 2000 and XP, and
on a couple versions of Linux. I'd be happy to hear how it does
on other systems.

Thanks to George (g...@ll.mit.edu) for testing a previous version.
Thanks to Robert Kern for pointing me to a bug solution.
--Bryan

---------------- cut -------------------
#!/usr/bin/env python

# Python module "errorwindow.py", by Bryan Olson, 2005.
# This module is free software and may be used, distributed,
# and modified under the same terms as Python itself.

"""

Importing this module redirects sys.stderr so that error
output, if any, will appear in a new window.

Notes on the module:

It is particularly handy for graphical applications that
do not otherwise have a stderr stream. It mitigates most
silent failures.

It uses only this file plus facilities in the Python
standard distribution.

There are no functions to call; just import it.

Import it early; it cannot catch prior errors.

It can catch syntax errors in modules imported after
it, but not in '__main__'.

Importing it more than once is harmless.

When there is no error output, it is highly efficient,
because it does nothing.

Upon output to sys.stderr, it runs a new process and
pipes the error output.

It does not import any graphical library into your
program. The new process handles that.
"""

import sys
import os
import thread
if __name__ == '__main__':

from threading import Thread
from Tkinter import *
import Queue
queue = Queue.Queue(99)
def read_stdin(app):
while 1:
data = os.read(sys.stdin.fileno(), 2048)
queue.put(data)
if not data:
break
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master.title("Error stream from %s" % sys.argv[-1])
self.pack(fill=BOTH, expand=YES)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
xscrollbar = Scrollbar(self, orient=HORIZONTAL)
xscrollbar.grid(row=1, column=0, sticky=E+W)
yscrollbar = Scrollbar(self)
yscrollbar.grid(row=0, column=1, sticky=N+S)
self.logwidget = Text(self, wrap=NONE,
xscrollcommand=xscrollbar.set,
yscrollcommand=yscrollbar.set)
self.logwidget.grid(row=0, column=0, sticky=N+S+E+W)
xscrollbar.config(command=self.logwidget.xview)
yscrollbar.config(command=self.logwidget.yview)
# 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_thread, ())
def start_thread(self, _):
t = Thread(target=read_stdin, args=(self,))
t.setDaemon(True)
t.start()
self.after(200, self.check_q, ())
def check_q(self, _):
go = True
while go:
try:
data = queue.get_nowait()
if not data:
Label(self, text="Stream closed.", relief=
"sunken").grid(row=2, sticky=E+W)
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(object):
def __init__(self):
self.lock = thread.allocate_lock()
self.command = " ".join([sys.executable, __file__,
sys.argv[0]])
def write(self, data):
self.lock.acquire()
try:
if not hasattr(self, 'pipe'):
self.rawpipe = os.popen(self.command, 'w')
fd = os.dup(self.rawpipe.fileno())
self.pipe = os.fdopen(fd, 'w', 0)
self.pipe.write(data)
finally:
self.lock.release()

sys.stderr = ErrorPipe()
Nov 4 '05 #1
0 2016

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

Similar topics

6
by: Tsai Li Ming | last post by:
Dear all, I have a problem with a redirecting stdout and stderr. I am a top level module and has no control over the imported modules that are making system calls such as os.system or popen2.* ....
4
by: Random Task | last post by:
How do i run exec and catch stdio and stderr in a local string vairable (not a file) ... Thanks very very much, Jim
4
by: ChokSheak Lau | last post by:
Hi, using popen() doesn't seem to give me any way to capture the stderr of the child process. does anyone know whether there is any way to capture these: 1. stdout 2. stderr 3. exitcode
11
by: Pohihihi | last post by:
I was wondering what is the ill effect of using try catch in the code, both nested and simple big one. e.g. try { \\ whole app code goes here } catch (Exception ee) {}
2
by: =?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7z | last post by:
Please see the follow code, I can not catch the exception " IOError" raised from shutil.copyfile() , why? try: if (DEST_TYPE & TYPE_FTP): fn = oname ftpc.UploadFile(f, fn) else: fn =...
37
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...
2
by: Guillaume Dargaud | last post by:
Hello all, a while ago I was pointed towards freopen as a way to redirect stderr to a log file. It works great, but apparently the app also writes a few lines to stdout. Now I could redirect to 2...
1
by: Lincoln Yeoh | last post by:
Hi, I've just started to learn python (I've been using perl for some years). How do I redirect ALL stderr stuff to syslog, even stderr from external programs that don't explicitly change their...
1
by: RC | last post by:
By default the print statement sends to stdout I want to send to stderr Try print "my meeage", file=sys.stderr I got I try
2
by: khalidanwar123 | last post by:
i am getting the following error while updating a clob field. ERROR java.sql.SQLException: Data size bigger than max size forthis type: 4003 19:28:27,499 ERROR at...
0
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,...
0
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...
1
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
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...
0
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...
0
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 ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.