0

I'm maintaining a Perforce server via a Unix executable which logs the errors in the terminal whenever something happens to it. What I would like to do is use Python to start the executable, and then have it watch for any errors being logged in the terminal window from the application it's executing.

The following code works for execution, but I have no idea how to get data back from the subprocess when it gets logged to the terminal via some form of callback.

import subprocess
subprocess.call(["./p4d"])
James Ives
  • 3,177
  • 3
  • 30
  • 63

2 Answers2

1

I usually do it this way

from subprocess import Popen, PIPE
proc = Popen(["./p4d"], stdout=PIPE, stderr=PIPE)
out, err = pipe.communicate()

pipe.communicate() will hang until the process is finished and then returns stdout and stderr

J. Darnell
  • 519
  • 7
  • 15
0

process.stdout and process.stdout are file-like objects that you can read from. Assuming things are logged to stdout:

proc = Popen(['./p4d'], stdout=PIPE, encoding='utf-8')  # Or whatever encoding suits
for line in proc.stdout:
    # Note that line will end in `\n`, unless it is the last line.
    line = line.rstrip('\n')

    # Do something depending on the line
Artyer
  • 31,034
  • 3
  • 47
  • 75