How to flush output of print function?

后端 未结 13 1611
旧时难觅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

    Dan's idea doesn't quite work:

    #!/usr/bin/env python
    class flushfile(file):
        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)
    
    print "foo"
    

    The result:

    Traceback (most recent call last):
      File "./passpersist.py", line 12, in 
        print "foo"
    ValueError: I/O operation on closed file
    

    I believe the problem is that it inherits from the file class, which actually isn't necessary. According to the docs for sys.stdout:

    stdout and stderr needn’t be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument.

    so changing

    class flushfile(file):
    

    to

    class flushfile(object):
    

    makes it work just fine.

提交回复
热议问题