Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting stderr from pexpect

Tags:

python

pexpect

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

like image 358
Edd Barrett Avatar asked Nov 27 '14 22:11

Edd Barrett


People also ask

What does Pexpect expect return?

The important methods of pexpect. spawn class are expect(). This method waits for the child process to return a given string. The pattern specified in the except method will be matched all through the string.

What does Pexpect EOF mean?

expect(pexpect. EOF) The second form of spawn (where you pass a list of arguments) is useful in situations where you wish to spawn a command and pass it its own argument list. This can make syntax more clear.

What does Pexpect spawn do?

Pexpect is a Python module for spawning child applications and controlling them automatically. Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup scripts for duplicating software package installations on different servers.

How do you close Pexpect spawn?

spawn. close() would close the pty which in turn would send SIGHUP to the shell which in turn would terminate (kill) the shell unless the shell is ignoring SIGHUP . It's like you close the PuTTY (or gnome-terminal , ...) window when the shell is still running.


1 Answers

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')
like image 177
Lex Scarisbrick Avatar answered Sep 29 '22 01:09

Lex Scarisbrick