Friday 16 January 2015

printing - How to flush output of Python print?, disable print statement from terminal in python or “print” for Debugging | Python : Flushing stdout

printing - How to flush output of Python print?, disable print statement from terminal in python or “print” for Debugging

----------------------------------------------------------------------------------------------------------------
include below lines in your code, before print statements (or at starting point of code)  ...
----------------------------------------------------------------------------------------------------------------
import sys
sys.stdout = open('file.txt', 'w')

--------------------------------------------------------------------------------

Python : Flushing stdout

Many a times I need to redirect the output of a program to a file. For example

#> python temp.py > outfile 

(Ubuntu command prompt)
However, the problem with this is that stdout is not flushed on each print command and some of the statements can still be in the buffer which can be painful at times based on the level of anxiety.

We shall now see one of the quickest way to ensure that stdout is flushed. I have not seen a case where it didn't work (at least in Linux) and do not know how one can verify if this works at all times.

For example if your file is as follows:
  • def test():
    • j = True
    • while j:
      • time.sleep(1)
      • print("Welcome"+str(j))
    • print "Bye"
  • if __name__ == "__main__":
    • func()


Just add the following line to your code
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

This can be done as follows:
  • if __name__ == "__main__":
    • import os, sys
    • sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
    • func()

No comments: