f=open('a.txt','w')
import sys
old=sys.stdout #将当前系统输出储存到一个临时变量中
sys.stdout=f #输出重定向到文件
print('Hello world!',file=f) #测试一个打印输出
sys.stdout=old #还原原系统输出
f.close()
f1= open('a.txt','r')
print(f1.read())
f1.close()
注意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=0
f=FakeOut()
import sys
old=sys.stdout
sys.stdout=f
print 'Hello weird.'
print 'Hello weird too.'
sys.stdout=old
f.show()
# 输出:
# Out:[0] Hello weird.
# Out:[1]
# Out:[2] Hello weird too.
# Out:[3]
|