擅长:python、mysql、java
<p>我在下面写了一些附加的注释,这些注释应该可以更清楚地说明<code>redirect_stdout</code>函数内部的情况:</p>
<pre><code>def redirect_stdout():
print "Redirecting stdout"
sys.stdout.flush() # < - important when redirecting to files
# Duplicate stdout (file descriptor 1)
# to a different file descriptor number
newstdout = os.dup(1)
# /dev/null is used just to discard what is being printed
devnull = os.open('/dev/null', os.O_WRONLY)
# Duplicate the file descriptor for /dev/null
# and overwrite the value for stdout (file descriptor 1)
os.dup2(devnull, 1)
# Close devnull after duplication (no longer needed)
os.close(devnull)
# Use the original stdout to still be able
# to print to stdout within python
sys.stdout = os.fdopen(newstdout, 'w')
</code></pre>
<p>需要注意的一点是,进程在启动时从操作系统得到三个不同的<a href="http://en.wikipedia.org/wiki/File_descriptor" rel="noreferrer">file descriptors</a>:</p>
<ul>
<li>标准输入:0</li>
<li>标准输出:1</li>
<li>标准:2</li>
</ul>
<p>正如注释中所解释的,上面的代码利用stdout的文件描述符和文件描述符复制函数来欺骗C代码使用不同的stdout,同时仍然在python代码中保留对原始stdout的引用,以便能够打印。在</p>