Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to read output from pexpect child?

Tags:

python

pexpect

child = pexpect.spawn ('/bin/bash') child.sendline('ls') print(child.readline()) print child.before, child.after 

All I get with this code in my output is

ls  ls  

But when my code is

child = pexpect.spawn('ls') print(child.readline()) print child.before, child.after 

Then it works, but only for the first 2 prints. Am I using the wrong send command? I tried send, write, sendline, and couldn't find anymore.

like image 976
user2579116 Avatar asked Jul 13 '13 16:07

user2579116


People also ask

What does Pexpect EOF mean?

If you wish to read up to the end of the child's output without generating an EOF exception then use the expect(pexpect. EOF) method. TIMEOUT. The expect() and read() methods will also timeout if the child does not generate any output for a given amount of time. If this happens they will raise a TIMEOUT exception.

What is the use of Pexpect 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.

How does Pexpect expect work?

Pexpect works like Don Libes' Expect. Pexpect allows your script to spawn a child application and control it as if a human were typing commands. Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc.


1 Answers

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) 
like image 173
Catalin Luta Avatar answered Sep 18 '22 23:09

Catalin Luta