Python how to read output from pexpect child? Python how to read output from pexpect child? python python

Python how to read output from pexpect child?


In pexpect the before and after attributes are populated after an expect method. The most common thing used in this situation is waiting for the prompt (so you'll know that the previous command finished execution). So, in your case, the code might look something like this:

child = pexpect.spawn ('/bin/bash')child.expect("Your bash prompt here")child.sendline('ls')#If you are using pxssh you can use this#child.prompt()child.expect("Your bash prompt here")print(child.before)


Try the following:

import pexpectchild = pexpect.spawn('ls')print child.read() # not readline

The read() will give you the entire output of the ls.


#!/usr/bin/env pythonimport pexpectchild = pexpect.spawn("ssh root@172.16.0.120c -p 2222")child.logfile = open("/tmp/mylog", "w")child.expect(".*assword:")child.send("XXXXXXX\r")child.expect(".*\$ ")child.sendline("ls\r")child.expect(".*\$ ")

go to open your logfile:-go to terminal

$gedit /tmp/mylog

As Per https://pexpect.readthedocs.io/en/stable/api/pexpect.html#spawn-class

# In Python 3, we'll use the ``encoding`` argument to decode data# from the subprocess and handle it as unicode: child = pexpect.spawn('some_command', encoding='utf-8') child.logfile = sys.stdout