Re: Intercepting printed strings

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gabriel Genellina

    Re: Intercepting printed strings

    En Fri, 19 Sep 2008 10:37:00 -0300, Robert Dailey <rcdailey@gmail .com>
    escribió:
    On Fri, Sep 19, 2008 at 4:21 AM, Gabriel Genellina
    <gagsl-py2@yahoo.com.a r>wrote:
    >
    >En Thu, 18 Sep 2008 19:24:26 -0300, Robert Dailey <rcdailey@gmail .com>
    >escribió:
    >>
    >>
    > I'm currently using Python 3.0 b3 and I'm curious as to how I can go
    >about
    >>interceptin g things send to print() for some intermediate processing
    >>before
    >>they're actually sent to sys.stdout. Right now I've thought of the
    >>following:
    >>>
    >>Replace sys.stdout with a class named PrintStream. PrintStream is
    >>defined
    >>as
    >>follows:
    >>>
    >>class PrintStream:
    >> def write( self, message ):
    >> sys.__stdout__. write( '\t{0}'.format( message ) )
    >>>
    >>Will this work? Basically I want to add a tab character in front of
    >>every
    >>message printed. Thanks.
    >>>
    >>
    >Why don't you try it yourself?
    >You may replace builtins.print with your own function too. It's not
    >exactly
    >the same thing, but given your request "intercepti ng things send to
    >print()
    >before they're sent to sys.stdout" it may be more adequate.
    >
    >
    I did try the code I posted and it doesn't work.
    Works for me:

    p3class PrintStream:
    .... def write( self, message ):
    .... sys.__stdout__. write( '\t{0}'.format( message ) )
    ....
    p3sys.stdout = PrintStream()
    p3print("Hello world!")
    Hello world!
    p3print(1, 2, 3)
    1 2 3

    (note the double spacing between elements)
    You may want to replace the print() function instead (this was not so easy
    in previous versions):

    p3sys.stdout = sys.__stdout__
    p3def _print(*args): # simplified print() signature
    .... sys.stdout.writ e('\t' + ' '.join(str(arg) for arg in args) + '\n')
    ....
    p3import builtins
    p3builtins.prin t = _print
    p3print("Hello world!")
    Hello world!
    p3print(1, 2, 3)
    1 2 3
    p3>

    --
    Gabriel Genellina

Working...