python 的重定向输出到一个文件

来源:互联网 发布:淘宝量子统计在哪里 编辑:程序博客网 时间:2024/05/01 13:39
f=open('a.txt','w')import sysold=sys.stdout #将当前系统输出储存到一个临时变量中sys.stdout=f  #输出重定向到文件print 'Hello weird' #测试一个打印输出sys.stdout=old #还原原系统输出f.close() print open('a.txt','r').read()

注意sys库的使用,文件位置默认位于你运行的源代码所在的位置。
同样可以自行编写一个类,这个类只要有write函数,以模拟file类型就可以将系统输出重定向到其上。

class FakeOut:    def __init__(self):        self.str=''        self.n=0    def write(self,s):        self.str+="Out:[%s] %s\n"%(self.n,s)        self.n+=1    def show(self): #显示函数,非必须        print self.str    def clear(self): #清空函数,非必须        self.str=''        self.n=0f=FakeOut()import sysold=sys.stdoutsys.stdout=fprint 'Hello weird.'print 'Hello weird too.'sys.stdout=oldf.show()# 输出:# Out:[0] Hello weird.# Out:[1]# Out:[2] Hello weird too.# Out:[3]
0 0