【问题标题】:How to see the output in pexpect?如何在 pexpect 中查看输出?
【发布时间】:2017-08-31 20:57:49
【问题描述】:

我已经写了这个程序:

[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 ~]$ 

但我看不到输出。我怎么看出来了。。当我执行它时,我什么也看不到。我怎么能看到输出?。

【问题讨论】:

    标签: python pexpect


    【解决方案1】:

    根据pexpect doc:

    logfile_read 和 logfile_send 成员可用于分别记录来自孩子的输入和 输出发送给孩子。有时你不想看到你写给孩子的所有东西。你只想要 记录孩子发回的内容。例如:

    child = pexpect.spawn('some_command')
    child.logfile_read = sys.stdout
    

    如果您使用的是 Python 3,则需要在上述代码中传递一个编码。
    要单独记录发送给孩子的输出,请使用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] #
    

    【讨论】:

      【解决方案2】:

      来自 pexpect 文档:

      每次调用expect() 后,before 和after 属性将设置为子应用程序打印的文本。 before 属性将包含符合预期字符串模式的所有文本。 after 字符串将包含与预期模式匹配的文本。

      因此,位于战略要地的print(child.before) 应该可以满足您的需求。

      【讨论】:

      【解决方案3】:

      您还可以将 pexpect 的输出记录到日志文件中:

      child.logfile = open("/tmp/mylog", "w")
      

      那么sendline的每一个响应都会被打印到日志中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-12
        • 2014-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-18
        • 2022-12-22
        • 2017-02-10
        相关资源
        最近更新 更多