redirecting stderr

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Michele Simionato

    #1

    redirecting stderr

    Maybe it is something obvious, but what is going on with this code?

    import sys
    myerr = file("myerr.txt ", "w")
    sys.stderr = myerr
    try:
    raise Exception, "some error"
    finally:
    myerr.close()
    sys.stderr = sys.__stderr__

    I would expect the error message to be written into "myerr.txt" , instead
    it is displayed on the console, on regular stderr (?) and "myerr.txt" is
    empty. I guess I misunderstood something ...

    Michele Simionato
  • Roland Heiber

    #2
    Re: redirecting stderr

    Michele Simionato wrote:[color=blue]
    > Maybe it is something obvious, but what is going on with this code?
    >
    > import sys
    > myerr = file("myerr.txt ", "w")
    > sys.stderr = myerr
    > try:
    > raise Exception, "some error"
    > finally:
    > myerr.close()
    > sys.stderr = sys.__stderr__
    >
    > I would expect the error message to be written into "myerr.txt" , instead
    > it is displayed on the console, on regular stderr (?) and "myerr.txt" is
    > empty. I guess I misunderstood something ...
    >
    > Michele Simionato[/color]

    Hi,

    os.close(2)
    os.dup2(myerr.f ileno(), 2)

    Works, but is dirty ...

    HtH, Roland

    Comment

    • Peter Otten

      #3
      Re: redirecting stderr

      Michele Simionato wrote:
      [color=blue]
      > Maybe it is something obvious, but what is going on with this code?
      >
      > import sys
      > myerr = file("myerr.txt ", "w")
      > sys.stderr = myerr
      > try:
      > raise Exception, "some error"
      > finally:
      > myerr.close()
      > sys.stderr = sys.__stderr__
      >
      > I would expect the error message to be written into "myerr.txt" , instead
      > it is displayed on the console, on regular stderr (?) and "myerr.txt" is
      > empty. I guess I misunderstood something ...[/color]

      I'd say you have to handle the exception before the original stderr is
      restored, e. g:

      import sys
      import traceback
      myerr = file("myerr.txt ", "w")
      sys.stderr = myerr
      try:
      try:
      raise Exception("some error")
      except:
      traceback.print _exc()
      finally:
      myerr.close()
      sys.stderr = sys.__stderr__

      As print_exc() allows you to specify a file parameter, you could of course
      entirely drop the try ... finally.

      Peter

      Comment

      Working...