0

I am using python sys to save my stdout to a text file.

sys.stdout=open('OLSYield.txt','w')

However I only want a portion of the stdout to go to the text. How do I stop writing to txt file and redirect back to the terminal or console?

So it should look something like

sys.stdout=open('OLSYield.txt','w')
print "helloWorld appears in text file"

sys.stdout=close('OLSYield.txt','w')
print "helloWorld appears in console"

Im not sure what command I should use to close stdout=open

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
galucero
  • 353
  • 1
  • 4
  • 9

2 Answers2

6

to change the output back to the console you need to keep a reference to the original stdout:

orig_stdout = sys.stdout
sys.stdout=open('OLSYield.txt','w')
print "helloWorld appears in text file"

sys.stdout.close()
sys.stdout=orig_stdout 
print "helloWorld appears in console"
James Kent
  • 5,763
  • 26
  • 50
0

You can stop writing to your file and revert to the console like this:

sys.stdout = open("file.txt", "w")
print "in file"

sys.stdout.close()
sys.stdout = open("/dev/stdout", "w")

print "in console"
Jess
  • 3,097
  • 2
  • 16
  • 42
  • 3
    the problem with this solution is that it's platform specific, so it doesn't work on windows – James Kent Jan 21 '16 at 14:47
  • You're 100% right. As soon as I read your answer I thought that. On the other hand, if you're running in some env (e.g. CI?) and your original stdout isn't what you want, you're also stuck. – Jess Jan 21 '16 at 14:58
  • 1
    Meh. No. Reverting to original stdout seems cleanest/safer – Jess Jan 21 '16 at 15:02
  • i figure its the most predicable way of doing it as it will resume the previous behavior, I know I've done things where i redirect the output for logging/debugging purposes, my method above would at least resume that. – James Kent Jan 21 '16 at 15:40
  • Yeah especially if you're running in some container/application or other cross platform situation. – Jess Jan 21 '16 at 16:36