Embedded python: printing exceptions to a file?

Kitty Munson Cooper KittyMCooper at zianet.com
Sun Jan 5 13:48:23 EST 2003


If you search the python newsgroup archives (available on the saerch
function from python.org) for redirecting sys.stderr, you will find many
useful discussions of problems similar to yours.

> - Is there any easy & recommended way to let sys.stderr point to another
> open file object?

YES, use "=",  here is a working example:

import sys

try:
  logfile = open ('logfile.txt',"w",0)  #the 0 means unbuffered so we get it
all on a failure
except Exception, why:
  print "Open of logfile failed:", why
else:
  try:
    sys.stderr = logfile
  except why:
    print "** FAILED ** Could not redirect errors -- ",why
  else:
    ## code to force an error
    print "testing logging"
    print "force an error"
    a = 0
    b = 3
    print b/a
    ## end of code to force an error
## restore  stderr
try:
  sys.stderr = standardset

except Exception , why:
  print "**FAILED** ",why

logfile.close()



--
---------------------------------------------------------------
Kitty Munson Cooper, web designer  -- KittyMCooper at zianet.com
Holiday Greetings at http://www.kittymunson.com/Xmas/2002.html
more information at http://www.kittycooper.com/resume.html


"Gernot Hillier" <ghillie at suse.de> wrote in message
news:av9com$nrl$1 at Fourier.suse.de...
> Hi!
>
> I use embedded python in my application and I'm really enthusiastic about
it
> - the API is really well designed, thx. :-)
>
> But now I have a small problem - I want to log errors from python scripts
> running in the embedded interpreter to a log file.
>
> All I found so far is PyErr_Print() which prints to sys.stderr.
>
> I looked at its implementation - hoping to find a small function where I
> just could change sys.stderr to some open file and copy it to my
> application - but it seems to be rather complex so I think it's not wise
to
> copy and modify all this code... :-((
>
> So I see two ways:
>
> - Perhaps there's a function provided which already provides an
alternative
> to PyErr_Print()?
>
> - Is there any easy & recommended way to let sys.stderr point to another
> open file object?
>
> <OT>
> I just wonder if it would be wise to splitup this newsgroup into some more
> specific subjects like (just suggestions)
> - Python main (questions regarding the core Python functionality)
> - Python-Newbie (installing, troubleshooting simple scripts, ...)
> - Embedding/Extending python questions
> - Additional modules
> - ...
>
> I really would like to read this group more actively - but it contains
> simply too much mails and too much things I'm not interested in...
> </OT>
>
> TIA!
>
> --
> Ciao,
>
> Gernot






More information about the Python-list mailing list