redirect standard output problem

Hans Mulder hansmu at xs4all.nl
Fri Dec 21 08:42:09 EST 2012


On 21/12/12 06:23:18, iMath wrote:
> redirect standard output problem
> 
> why the result only print A but leave out 888 ?
> 
> import sys
> class RedirectStdoutTo:
> 
>     def __init__(self, out_new):
>         self.out_new = out_new
>     def __enter__(self):
>         sys.stdout = self.out_new
>     def __exit__(self, *args):
>         sys.stdout = sys.__stdout__
> 
> 
> print('A')
> with open('out.log', mode='w', encoding='utf-8') as a_file, RedirectStdoutTo(a_file):
> 
>     print('B')
>     print('C')
> 
> print(888)

On my machine it works as you'd expect.

If it doesn't work on your system, it might help to flush
sys.stdout in a few strategic places:

class RedirectStdoutTo:

    def __init__(self, out_new):
        self.out_new = out_new
    def __enter__(self):
        sys.stdout.flush()
        sys.stdout = self.out_new
    def __exit__(self, *args):
        sys.stdout.flush()
        sys.stdout = sys.__stdout__


print('A')
with open('out.log', mode='w', encoding='utf-8') as a_file,
RedirectStdoutTo(a_file):

    print('B')
    print('C')

print(888)
sys.stdout.flush()


Hope this helps,

-- HansM



More information about the Python-list mailing list