python2.7 - Python 2.7 stdout重定向的疑问
伊谢尔伦
伊谢尔伦 2017-05-18 10:48:16
0
2
639

先上代码

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'

问题:就如我注释里写的,调用TestWriter.write()的时候没有实现sys.stdout的重定向输出,但之后的print证明了标准输出已经重定向到了文件f对象。
断点跟踪的时候,self.stream也显示为f对象
求解惑!!!

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(2)
巴扎黑
def __init__(self, stream=sys.stdout)

Python在创建每个函数时,每个参数都会被绑定,默认值不会随着值的改变而重新加载

# 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

但如果绑定参数默认参数绑定的是地址,那就不一样,地址不变,内容可以变.

# 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]
阿神

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会顺序解释每条语句,所以TestWriter的构造器参数stdout没有被重定向。

以上都是我猜的

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

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)

运行结果

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!