nextdoordoc
nextdoordoc

Reputation: 1767

when using stdout, why changing to file object needed?

Below is the example of using stdout module.

#redirect.py

import sys

f = open('t.txt', 'w')        
stdout = sys.stdout   -----> first one
sys.stdout = f        -----> second one
print 'Sample output'
print 'Good'
print 'Good'
f.close()
sys.stdout = stdout   -----> third one

I could not understand why meaning of those three things above.

Thanks in advance =)

Upvotes: 0

Views: 44

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798546

print simply massages its arguments and then invokes sys.stdout.write(). Replacing sys.stdout allows you to capture the output of print and redirect it.

Upvotes: 1

Related Questions