0

There are a number of questions and answers related to Python subprocess and reading of stdout during execution, but still I have not found a solution that fulfills these requirements:

  • Start a subprocess
  • Print stdout to terminal, while doing other processing e.g. writing to file
  • Print stderr to terminal, while doing other processing e.g. writing to file
  • stdout and stderr must be handled separately
  • Termination of process if output indicates error or due to some timeout
  • Linux must be supported, and if possible also Windows (XP/7)

One obstacle is for example that process stdout.read() and stdout.readline() are blocking if no stdout data is generated by the running process, thereby preventing process kill() for termination due to a timeout.

Code for a start:

# Python 3.3 syntax

import sys
import subprocess

def subproc(args, stdout):
    proc = subprocess.Popen(args, stdout=subprocess.PIPE, shell=False, universal_newlines=True)
    while True:  # while is broken by return 
        try:
            outs = ''  # Clear before communication attempt
            outs = proc.communicate(timeout=1)[0]  # Timeout every second to process stdout
        except subprocess.TimeoutExpired:
            pass
        # Processing termination using proc.kill is added later
        sys.__stdout__.write('Shows that proc communicate timeout works\n')
        if outs:
            stdout.write(outs)  # Allow stdout processing
        if proc.returncode is not None:  # Completed execution
            return proc.returncode  # End while and return

class StdHandle:
    def write(self, str):
        # Additional processing ...
        sys.__stdout__.write(str)
    def flush(self):
        pass

rc = subproc(('proc.sh'), stdout=StdHandle())
print('Return code:', rc)

# EOF
Morten Zilmer
  • 15,083
  • 3
  • 28
  • 47

0 Answers0