最简单常用的输出重定向方式是利用控制台命令。这种重定向由控制台完成,而与Python本身无关。
Windows命令提示符(cmd.exe)和Linux Shell(bash等)均通过">"或">>"将输出重定向。其中,">"表示覆盖内容,">>"表示追加内容。类似地,"2>"可重定向标准错误。重定向到"nul"(Windows)或"/dev/null"(Linux)会抑制输出,既不屏显也不存盘。
以Windows命令提示符为例,将Python脚本输出重定向到文件(为缩短篇幅已删除命令间空行):
E:\>echo print 'hello' >test.py
E:\>test.py >out.txt
E:\>type out.txt
hello
E:\>test.py >>out.txt
E:\>type out.txt
hello
hello
E:\>test.py >nul
注意,在Windows命令提示符中执行Python脚本时,命令行无需以"python"开头,系统会根据脚本后缀自动调用Python解释器。此外,type命令可直接显示文本文件的内容,类似Linux系统的cat命令。
Linux Shell中执行Python脚本时,命令行应以"python"开头。除">"或">>"重定向外,还可使用tee命令。该命令可将内容同时输出到终端屏幕和(多个)文件中,"-a"选项表示追加写入,否则覆盖写入。示例如下(echo $SHELL或echo $0显示当前所使用的Shell):
[wangxiaoyuan_@localhost ~]$ echo $SHELL
/bin/bash
[wangxiaoyuan_@localhost ~]$ python -c "print 'hello'"
hello
[wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" >out.txt
[wangxiaoyuan_@localhost ~]$ cat out.txt
hello
[wangxiaoyuan_@localhost ~]$ python -c "print 'world'" >>out.txt
[wangxiaoyuan_@localhost ~]$ cat out.txt
hello
world
[wangxiaoyuan_@localhost ~]$ python -c "print 'I am'" | tee out.txt
I am
[wangxiaoyuan_@localhost ~]$ python -c "print 'xywang'" | tee -a out.txt
xywang
[wangxiaoyuan_@localhost ~]$ cat out.txt
I am
xywang
[wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" >/dev/null
[wangxiaoyuan_@localhost ~]$
若仅仅想要将脚本输出保存到文件中,也可直接借助会话窗口的日志抓取功能。
注意,控制台重定向的影响是全局性的,仅适用于比较简单的输出任务。
import sysf = 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