f=open('a.txt','w')
import sys
old=sys.stdout #将当前系统输出储存到一个临时变量中
sys.stdout=f #输出重定向到文件
print 'Hello weird' #测试一个打印输出
sys.stdout=old #还原原系统输出
f.close()
print open('a.txt','r').read()
注意sys库的使用,文件位置默认位于你运行的源代码所在的位置。
同样可以自行编写一个类,这个类只要有write函数,以模拟file类型就可以将系统输出重定向到其上。