How to flush output of print function?

后端 未结 13 1569
旧时难觅i
旧时难觅i 2020-11-21 05:15

How do I force Python\'s print function to output to the screen?

This is not a duplicate of Disable output buffering - the linked question is attempting unbuffe

13条回答
  •  余生分开走
    2020-11-21 05:36

    Using the -u command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the -u option. I usually use a custom stdout, like this:

    class flushfile:
      def __init__(self, f):
        self.f = f
    
      def write(self, x):
        self.f.write(x)
        self.f.flush()
    
    import sys
    sys.stdout = flushfile(sys.stdout)
    

    ... Now all your print calls (which use sys.stdout implicitly), will be automatically flushed.

提交回复
热议问题