Python子进程中的日志记录:获取按屏幕顺序出现的输出到日志文件
我有一个Python脚本(script1.py),它会生成一些子进程,代码如下:
print 'This is the main script'
status=os.system(command)
现在我执行这个脚本,并像这样重定向标准输出:
python script1.py > log.txt
在log.txt文件中,首先是子进程命令的输出(通过os.system调用),然后才是字符串'This is the main script'。我本来希望它们的顺序是相反的!
即使我用subprocess代替os.system,情况也是一样的:
print 'This is the main script'
p=subprocess.Popen(command,shell=True, stdout=None, stderr=subprocess.STDOUT)
status=p.returncode
那么我该如何将标准输出重定向到一个文件,并确保所有子进程的输出都按正确的顺序写入这个文件呢?注意,如果我不重定向标准输出,日志消息的顺序是正确的(就像在屏幕上显示的那样)!
更新
这个方法解决了我的问题(具体描述可以参考这里):
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
另外,也可以强制让打印的内容立即显示出来:
sys.stdout.flush()
不过,我觉得这样并不理想,因为每次打印后都需要这样做。所以我使用了第一种方法,这样的好处是我可以实时查看日志,而不需要等到计算结束后再写入文件中的缓冲输出。
1 个回答
7
使用logging模块。用打印(print)来输出信息并不太可靠。下面是一个例子:
import logging
rootLogger = logging.getLogger()
proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
logger.INFO('This is the main script. Here\'s the program output:')
logger.INFO(out)