0

For my current project I need to find a way to write a stdout-dependent version or at least a formatted stdout to a logfile. Currently I'm just using subprocess.Popen(exec, stdout=log), which writes it to a file, unformatted.

The best idea I've got was formatting the output in on-the-fly, by intercepting the stdout, rerouting it to a custom module and let it write own strings to the log by using a combination of if's and elif's. But I couldn't find any way on how to do this in Python 3 in the docs. The most fitting answer I could find was in this question, the accepted answer is already kind of near.

But I just fail to understand on how exactly I should build the class that should be used as stdout=class. Which one of these methods receives the input (and how is it formatted)? Which of these methods are necessary? Or might there even be a way easier method to accomplish what I want to do?

Community
  • 1
  • 1
Big-Blue
  • 429
  • 9
  • 22
  • 1
    Have you considered using the logging module instead? You set sys.stdout to any file descriptor you want, without spawning a subproc. `sys.stdout = open('somefile', 'a')` – jordanm May 10 '12 at 15:52
  • Well, the logging module doesn't fit my project, as it is basically just a script calling a pre-compiled executable, which is why I want to alter/format the stdout. Opening the executable as a subprocess proven more reliable to me, and the stdout is currently already going to a file (the log), but - as mentioned - unformatted. – Big-Blue May 10 '12 at 16:00

1 Answers1

1

You can use the sarge project to allow a parent process to capture the stdout (and/or stderr) of a subprocess, read it line by line (say) and do whatever you like with the read lines (including writing them, appropriately formatted, to a log file).

Disclosure: I'm the maintainer of the sarge project.

Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191
  • That is exactly what I need, thanks! But what strikes me is the limited cross-compatibility and the size of sarge, as my script is barely 200 lines long and a single file. So I guess it would be the best to write my own *Capture*-class, as lightweight as possible. I'll try to learn a bit from your source and understand how exactly the output is processed to achieve something similar. If that actually works, I will spend you and your project a line in the header. :) – Big-Blue May 11 '12 at 17:18