Skip to main content
 首页 » 编程设计

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

2024年10月24日12虾米哥

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

print("Calling make file") 
 
call(["make"]) 

输出将是:

Calling make file

Starting make

cd src && make distclean

make[1]: Entering directory '/home/tejas/WLANrepo/src/3rdparty/redis-stable/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 && make distclean)'

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

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) 

但这只会重定向那些在“打印”下的语句。但是被调用的 make 文件的输出没有被重定向。

Python:python 2.7,操作系统:CentOS

请您参考如下方法:

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