Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the exit status code of a command send by pexpect

Tags:

pexpect

expect

In the following code snippet, how do I find the exit code of make? Specifically, I need to know if make has failed or succeeded. Thanks for any inputs.

process = pexpect.spawn("/bin/bash")
process.expect("make\r")
like image 827
doon Avatar asked Jan 17 '14 05:01

doon


People also ask

What does Pexpect do in Python?

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.

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.

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.

What is Sendline?

sendline() is just a convenience wrapper of send() . send() must be used if you don't want to press ENTER.


2 Answers

pexpect doesn't know about the make command - it is just sending text to bash. So you need to use bash's mechanism for determining exit code - the value of $?. So you want something like this:

process.sendline("make") # Note: issue commands with send, not expect
process.expect(prompt)
process.sendline("echo $?")
process.expect(prompt)
exitcode = process.before.strip()
like image 124
Thomas K Avatar answered Sep 21 '22 04:09

Thomas K


I had to use pexpect in my latest project and wanted to get the exit code, couldn't find the solution easily, as this is the top result in google I'm adding my solution to this.

process = pexpect.spawn(command, cwd=work_dir)
process.expect(pexpect.EOF)
output = process.before

process.close()
exit_code = process.exitstatus

I have the output saved as well, because I am running bash scripts and the exit code is saved in the exit_code variable.

like image 38
BenceL Avatar answered Sep 20 '22 04:09

BenceL