Search code examples
pythonlinuxstdoutstderr

How to capture the terminal log of script to a file?


I have a python script which runs succesfully from the Linux terminal. I am able to collect the terminal output to a file using a shell script when I run my python script.

Now I want to collect the terminal output from the python script itself. But unable to do so.

I want to do this using python only not using any shell or unix scripting

I have done like below in my python file:

class Tee(object):
    def __init__(self, f1, f2):
        self.f1, self.f2 = f1, f2
    def write(self, msg):
        self.f1.write(msg)
        self.f2.write(msg)

outfile = open('outfile', 'w')

sys.stdout = outfile
sys.stderr = Tee(sys.stderr, outfile)

This part of code in the python file prints both stderr and stdout to a outfile.

How can I capture the whole terminal output to a single file.


Solution

  • If you're okay with the requirement of having python in your PATH, then I'd call another python process to run your main script.

    In your top-level script, use the subprocess.Popen to start your desired script in a child process. Then use subprocess.Popen.communicate() to get the output streams from the process (and probably pass any command-line arguments into the process).

    You might even be able to redirect all std* output to files just with Popen, but this really depends on your needs and whatnot. communicate() seems pretty useful for what you might want to do.