Python-需要将控制台输出重定向到日志文件

时间:2015-09-29 12:19:40

标签: python python-2.7 logging

我正在执行多个" make"我的python脚本中的文件。示例脚本如下:

print("Calling make file")

call(["make"])

,输出结果为:

  

调用make文件

     

开始制作

     

cd src&&使distclean

     

make [1]:进入目录   ' /家/ Tejas的/ WLANrepo / src目录/的3rdParty / Redis的稳定/ src目录' rm -rf   redis-server redis-sentinel redis-cli redis-benchmark redis-check-dump   redis-check-aof * .o * .gcda * .gcno * .gcov redis.info lcov-html(cd   ../deps&&制造干净的'

我希望将整个输出重定向到日志文件。我试过了:

class Logger(object):

    def __init__(self):
        self.terminal = sys.stdout
        self.log = open("Buildexec_logfile.log", "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

但这只会重定向" print"下的那些语句。但是被调用的make文件的输出没有被重定向。

Python:python 2.7,操作系统:CentOS

2 个答案:

答案 0 :(得分:2)

您需要重定向python执行的进程输出(在您的情况下为make)。请参阅subprocess module的文档,特别是其方法的重定向参数(stdin=...stdout=...stderr=...)。根据您的需要,您可以完全丢弃子进程输出(DEVNULL),或将其收集到python进程(PIPE)内的变量或将其发送到另一个流。

答案 1 :(得分:0)

要捕获命令的常规输出,我们可以使用subprocess.check_output()函数。 强制同步是因为函数必须等待输出 被调用的子进程,但是如果它失败(返回你想要捕获的错误消息),你将需要处理被引发的CalledProcessError。幸运的是,CalledProcessError异常具有存储错误消息的output属性。

import subprocess
with open('logfile.log','w') as log:
    for makefile in multiple_makefiles:
        log.write("calling {}".format(makefile)
        try:
            log_info = subprocess.check_output(["make",makefile],stderr=STDOUT)
        except subprocess.CalledProcessError as e:
            log_info = e.output
        log.write(log_info)

当make实例干净地退出时,try将为log_info提供输出 并且except在错误时捕获错误。无论哪种方式,在log_info被写入log文件之前你都无法继续前进,因此同步应该没有问题

我还要补充一点,如果您出于实用性原因编写此脚本,例如:

  

荡。我现在真的需要这个编译,随附的makefile并不工作我需要收集输出来调试这个    然后继续以任何最有用或最快的方式完成它

BUT

如果你真的在做更多的事情:

  

我需要一个设置脚本来自动构建我的软件,并且在可预见的将来我将使用该软件发送它

然后停下来,不要重新发明你正在寻找的轮子cmake。 (并将为您记录输出)