Extracting stderr from pexpect

pexpect, python

Solution

For posterity, and based on the comment by Thomas K, this seems to do what you want:

import os
import subprocess
from pexpect import fdpexpect

program = ['/path/to/command', '--arg1', 'value1', '--arg2', 'value2']
devNull = open(os.devnull, 'w')
command = subprocess.Popen(program, stdout=devNull,
                           stdin=subprocess.PIPE, stderr=subprocess.PIPE)
child = fdpexpect.fdspawn(command.stderr)
child.expect('hi')

Problem

My question is simple: Can I `expect()` to see certain output on stderr using pexpect? It seems `pexpect.spawn()` can only be used to expect output on stdout. Utopian example: `import pexpect child = pexpect.spawn(...) child.expect("hi", fd=pexpect.STDERR)` Or in prose, "expect the string 'hi' on stderr". I have not found any mention of such a facility in the docs, but I do note that the `child` instance has a `stderr` attribute... A hack which semi-achieves what I want is to redirect stderr to stdout in the spawn arguments, then we can use regular `expect()`. There must be a better way? Cheers

Original source