4

I have a Python script which I want to spawn a child process with stdout and stderr redirected to a file. My current approach looks like this:

import subprocess

# Do some stuff.
p = subprocess.Popen("/path/to/something",
                     stdout=open("/var/log/something.log", "a+"),
                     stderr=subprocess.STDOUT)
# Do some more stuff.
# Terminate the parent process and leave the child running and logging output.

This appears to do what I want, but nothing is logged to the log file from stdout until the child process is interrupted. Without modifying the child process, is it possible to get the output to be flushed in a similar fashion as it is when stdout is displayed in the console? Stderr appears to flush normally.

I've tried using bufsize=1 as the docs say "1 means line buffered".

DanielGibbs
  • 9,910
  • 11
  • 76
  • 121
  • There are several good answers on SO: [How can I send python process output[(http://stackoverflow.com/questions/4227808/how-can-i-send-python-multiprocessing-process-output-to-a-tkinter-gui) or [Python def std_redirector()](http://stackoverflow.com/questions/4241234/having-a-console-in-a-single-threaded-python-script/4247395#4247395) – FoggyDay Jul 04 '14 at 18:02
  • I don't believe this is a duplicate as I can't seem to find how to redirect stdout/stderr to a file in the other questions. – DanielGibbs Jul 04 '14 at 18:07
  • I wouldn't have marked it "duplicate" so quickly, either. But please do look at the three links cited, and see if any of them help answer your question. – FoggyDay Jul 04 '14 at 18:16
  • They all look way more complicated that what I'm trying to do. I'll update the question. – DanielGibbs Jul 04 '14 at 18:20
  • This question asks about redirecting to a file after the parent ends which seems sufficiently different from all linked questions. – Nick T Apr 18 '16 at 18:26

0 Answers0