f = open('a.txt','w')
print >>sys.stdout,'hello,world'
hello,world
print >>f,'hello,world'
f.close()
输出到屏幕的内容重定向到文件,供参考。
另,print函数的源码
def print(stream):""" print(value, ..., sep=' ', end='\\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream) defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline. """
pass
print正常是要输出到屏幕上,如果你希望输出到其他地方比如文件,就需要使用>>来把输出导向到文件。空格的目的是要区分关键词,如果你输入的是print>>,电脑会把它当成一个单词,而无法知道是print函数。sys.stdout 默认就是输出到控制台(console),print 默认的输出也是 sys.stdout,所以输出到控制台。在 输入B 那,做了上下文切换with open
,也就是把默认的输出流指向到文件 out.log,
对应的代码是: sys.stdout = self.out_new,这里 out_new ->out.log,out_old = console
所以就print 指向文件,而不是控制台了
离开语句时,执行 sys.stdout = self.out_old =>sys.stdout = console,还原原来的默认输入流
于是后面就输出到默认的控制