python - 如何在预期中看到输出?

标签 python pexpect

我写了这个程序:

[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('noah@example.com')
 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 ~]$ 

但是我看不到输出。我怎么会看到它?我执行它时什么也看不到。我怎样才能看到输出?

最佳答案

根据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 

请看下面的例子:

[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] #

关于python - 如何在预期中看到输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45989975/

相关文章:

python - 将python正则表达式代码拆分为多行

python - 将时间戳转换为槽。 Python。 Pandas

python - 递归生成器

python - 预期方法不起作用

python - 似乎无法让 pexpect 从命令打印数据

python - 运行命令并像在终端中一样近乎实时地分别获取其标准输出、标准错误

python - 使用 pexpect python 模块的 SFTP

python - pandas df.ix[number, column] 访问与 df[column].ix[number] 不同的标量类型

python - 如何让 Fabric 自动(而不是用户交互地)与 shell 命令交互?与 pexpect 结合?

python - 为什么在 Python 中对一些大整数进行除法和乘法会返回奇怪的结果?