Skip to content Skip to sidebar Skip to footer

Is It Possbile To Let Pexpect Output The Texts It Matches?

I am familiar with expect script so I feel a bit odd when I first use pexpect. Take this simple script as an example, #!/usr/bin/expect set timeout 10 spawn npm login expect 'Usern

Solution 1:

With the comment I got I finally made it work

#! /usr/bin/env python3

import pexpect
import sys
print('npm login',timeout = 10)
child = pexpect.spawn('npm login')
child.logfile_read = sys.stdout.buffer // use sys.stdout.buffer for python3
child.expect('Username:')
child.sendline('qiulang2000')
child.expect('Password:')
child.sendline('xxxx')
child.expect('Email:')
child.sendline('qiulang@gmail.com')
child.expect('Logged in as')

If I need to call child.interact(), then it is important that I call child.logfile_read = None before it, otherwise sys.stdout will echo everything I type.

The answer here How to see the output in pexpect? said I need to pass an encoding for python3, but I found that if I use encoding='utf-8' it will cause TypeError: a bytes-like object is required, not 'str' If I don't set encoding at all, everything works fine.

So a simple ssh login script looks like this

#!/usr/bin/env python3import pexpect
import sys
child = pexpect.spawn('ssh qiulang@10.0.0.32')
child.logfile_read = sys.stdout.buffer
child.expect('password:')
child.sendline('xxxx')
#child.expect('Last login')  don't do that
child.logfile_read = None# important !!!
child.interact()

One problem remains unresolved, I had added one last expect call to match the ssh login output after sending the password, e.g. child.expect('Last login')

But if I added that, that line would show twice. I have gave up trying, like one comment said "pexpect's behavior is kind of counter intuitive".

Welcome to Ubuntu 16.04 LTS (GNU/Linux 4.4.0-141-generic x86_64)

 * Documentation:  https://help.ubuntu.com/33 packages can be updated.
0 updates are security updates.

Last login: Fri Sep 1111:44:192020from10.0.0.132
: Fri Sep 1111:44:192020from10.0.0.132

Post a Comment for "Is It Possbile To Let Pexpect Output The Texts It Matches?"