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
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.
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.
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With