Extracting stderr from pexpect

5.1k Views Asked by At

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

1

There are 1 best solutions below

1
On

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')