I have write this program:
[mik@mikypc ~]$ cat ftp.py
#!/usr/bin/env python
# This connects to the rediris ftp site
#
import pexpect
child = pexpect.spawn('ftp ftp.rediris.es')
child.expect('Name .*: ')
child.sendline('anonymous')
child.expect('ftp> ')
child.sendline('[email protected]')
child.expect('ftp> ')
child.sendline('lcd /tmp')
child.expect('ftp> ')
child.sendline('pwd')
child.expect('ftp> ')
child.sendline('bye')
[mik@mikypc ~]$ ./ftp.py
[mik@mikypc ~]$
[mik@mikypc ~]$
[mik@mikypc ~]$
But I cannot see the output. How could I see it?. I don't see anything when I execute it. How could I see the output?.
According to the pexpect doc:
The
logfile_readandlogfile_sendmembers can be used to separately log the input from the child and output sent to the child. Sometimes you don’t want to see everything you write to the child. You only want to log what the child sends back. For example:child = pexpect.spawn('some_command') child.logfile_read = sys.stdoutYou will need to pass an
encodingtospawnin the above code if you are using Python 3.To separately log output sent to the child use
logfile_send:child.logfile_send = fout
See following example:
# cat foo.py
import pexpect, sys
pat_ps1 = 'bash-[.0-9]+[$#] $'
if sys.version_info[0] < 3:
# python2
proc = pexpect.spawn('bash --norc')
else:
# python3
proc = pexpect.spawn('bash --norc', encoding='utf8')
if len(sys.argv) != 1:
proc.logfile_read = sys.stdout
proc.expect(pat_ps1)
proc.sendline("echo hello world")
proc.expect(pat_ps1)
proc.sendline('exit')
proc.expect(pexpect.EOF)
proc.wait()
$ python3 foo.py
$ python3 foo.py 1
bash-5.2$ echo hello world
hello world
bash-5.2$ exit
exit
$
From the pexpect docs:
After each call to
expect()thebeforeandafterproperties will be set to the text printed by child application. Thebeforeproperty will contain all text up to the expected string pattern. Theafterstring will contain the text that was matched by the expected pattern.
So, a print(child.before) in strategic places should fulfill your need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With