1

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.

martineau
  • 99,260
  • 22
  • 139
  • 249
User12345
  • 3,531
  • 10
  • 35
  • 83
  • 1
    What do you mean by "capture the whole terminal output"? The code above does already write everything to `outfile`. Although using `contextlib.redirect_(stdout|stderr)` would be easier. – YSelf Oct 23 '17 at 21:53
  • @YSelf My code prints only `print` statements into the file, I want all the logging that shows up on the `terminal` to be included as well – User12345 Oct 23 '17 at 22:05

2 Answers2

2

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.

ahogen
  • 589
  • 7
  • 18
0

You can use something like this in your code: os.system('pdv -t %s > 123.txt' % epoch_name) You could also look into this: Subprocess

Caden Grey
  • 19
  • 9