Wednesday, May 12, 2010

python:标准输出重定向并复原

示例如下:    
    o=os.dup(sys.stdout.fileno())        #将标准输出备份
#将文件dup到标准输出,并关闭标准输出
    p=open('./test.html','wb+')
    os.dup2(p.fileno(), sys.stdout.fileno())
#此后所有的print将直接打印到文件
    print "hello,world\n"
    print "hello,world\n"
    print "hello,world\n"
    print "hello,world\n"
    print "hello,world\n"
#将标准输出复原,
    os.dup2(o, sys.stdout.fileno())
    print "hahaxix"

No comments: