我在下面写了一些附加的注释,这些注释应该更清楚redirect_stdout
函数内部的情况:
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')
需要注意的重要一件事是,进程在启动时会从OS获取三个不同的文件描述符:
如评论中所述,上面的代码利用了stdout的文件描述符和文件描述符复制功能来欺骗C代码使用不同的stdout,同时仍保留对python代码中原始stdout的引用。打印。