Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-Need to redirect the console output to a log file

I am executing multiple "make" files from my python script. A sample script is as follows :

print("Calling make file")

call(["make"])

and the output will be :

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)'

I want the entire output to be redirected to a log file. I tried :

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)

but this will redirect only those statements that are under "print". But the output of the make file that gets called is not getting redirected.

Python: python 2.7, OS: CentOS

like image 638
Tejas Avatar asked Oct 21 '25 14:10

Tejas


1 Answers

You need to redirect output of processes executed by python (in your case, make). See documentation for subprocess module and specifically, the redirection parameters (stdin=..., stdout=..., stderr=...) of its methods. Depending on your needs you may completely discard subprocess output (DEVNULL), or collect it to a variable inside python process (PIPE) or send it to another stream.

like image 93
user3159253 Avatar answered Oct 23 '25 02:10

user3159253



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!