Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

python - How to see the output in pexpect?

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?.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the pexpect doc:

The logfile_read and logfile_send members 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.stdout

You will need to pass an encoding to spawn in 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:

[STEP 105] # cat foo.py
import pexpect, sys

re_PS1 = 'bash-[.0-9]+[$#] $'

proc = pexpect.spawn('bash --norc')
if len(sys.argv) != 1:
    if sys.version_info[0] < 3:
        proc.logfile_read = sys.stdout
    else:
        proc.logfile_read = sys.stdout.buffer

proc.expect(re_PS1)

proc.sendline("echo hello world")
proc.expect(re_PS1)

proc.sendline('exit')
proc.expect(pexpect.EOF)
proc.close()
[STEP 106] # python foo.py
[STEP 107] # python foo.py foo
bash-4.4# echo hello world
hello world
bash-4.4# exit
exit
[STEP 108] #

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...