Home  >  Q&A  >  body text

python2.7 - Questions about Python 2.7 stdout redirection

Code first

import sys


class TestWriter(object):
    def __init__(self, stream=sys.stdout):
        super(TestWriter, self).__init__()
        self.stream = stream

    def write(self, line):
        self.stream.write(line)

tmp = sys.stdout
f = open('d:\stdout.txt', 'w')
try:
    sys.stdout = f
    adpt = TestWriter() //如果这里我把f当参数传入,则执行结果如预期。
    adpt.write('asdfwe')  // 预期字符串写入文本,单事实上字符串输出到了屏幕。
    print 'this is import from print' //如预期的输入到了文本
except Exception, e:
    sys.stdout = tmp
    print e
finally:
    sys.stdout = tmp
    f.close()
print 'finish'

Problem: As I wrote in the comments, the redirected output of sys.stdout was not implemented when calling TestWriter.write(), but the subsequent print proved that the standard output has been redirected to the file f object.
When tracking breakpoints, self.stream is also displayed as an f object
Solve the doubts! ! !

伊谢尔伦伊谢尔伦2712 days ago649

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-05-18 10:50:16

    def __init__(self, stream=sys.stdout)
    

    When Python creates each function, each parameter will be bound, and the default value will not be reloaded as the value changes

    # coding: utf-8
    
    D = 2 
    class Test:
        def __init__(self, a=D):
            print a
    
    
    if __name__ == '__main__':
        D = 3 
        t = Test()
        print D
    
    inner function:  2
    outer function: 3
    

    But if the default parameter of the binding parameter is bound to the address, it is different. The address remains unchanged, but the content can change.

    # coding: utf-8
    
    D = [3] 
    class Test:
        def __init__(self, a=D):
            print "inner function: ", a
    
    
    if __name__ == '__main__':
        D[0] = 2
        t = Test()
        print "outer function:", D
       
    inner function:  [2]
    outer function: [2]
    

    reply
    0
  • 阿神

    阿神2017-05-18 10:50:16

    In contrast, in Python, execution begins at the top of one file and proceeds in a well-defined order through each statement in the file, ...

    http://stackoverflow.com/ques...

    python interprets each statement sequentially, so TestWriter的构造器参数stdout is not redirected.

    The above are all my guesses

    ==================================================== ====================

    import sys
    
    class A:
        def __init__(self, stream=sys.stdout):
            print(stream)
    
    f = open('test.txt', 'w')
    
    a = A()
    
    sys.stdout = f
    
    print(sys.stdout)
    

    Run results

    reply
    0
  • Cancelreply