8

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")
doon
  • 2,311
  • 7
  • 31
  • 52

2 Answers2

8

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()
Thomas K
  • 39,200
  • 7
  • 84
  • 86
  • 1
    Thanks. This should work but I am unable to validate this because of this http://stackoverflow.com/questions/21219158/pexpect-output-not-getting-generated. I will mark the answer as valid once I can get the exitcode to be printed. T – doon Jan 19 '14 at 16:08
  • Did the work for anyone? It should be the right answer however $? gets interpreted literally instead of being interpreted as a variable. So my echo output is literally '$?' – ateymour Sep 23 '20 at 21:26
7

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.

BenceL
  • 804
  • 6
  • 13