如何将 pexpect 的输出复制到文件

How to copy the output of pexpect to a file

我期望的是:

  1. pexpect的输出可以实时显示在终端中,让我可以看到脚本执行的实时进度
  2. pexpect 的输出可以复制到一个文件,这样日志 可以自动管理。

我知道如何在终端上显示结果以及如何将结果重定向到文件,但我不知道如何同时实现这两个功能。

下面是我的示例代码:

# -*- coding: utf-8 -*-
# !/usr/bin/python3

import pexpect
import time
import sys

username = 'root'
server_ip_addr = '10.194.78.117'

loginPassword = '123456'


def main():
    cmd = "ssh -x -o StrictHostKeyChecking=no -l {} {}".format(username, server_ip_addr)
    t_spwan = pexpect.spawn(cmd, encoding='utf-8')
    t_spwan.logfile_read = sys.stdout
    t_spwan.expect("#", 30)

    t_spwan.sendline("")
    t_spwan.expect('#', 30)
    t_spwan.sendline("pwd")
    t_spwan.expect('#', 30)

    t_spwan.sendline("ls")
    t_spwan.expect('#', 30)

    t_spwan.sendline('exit')
    t_spwan.close()
    t_spwan.logfile_read = sys.stdout

if __name__ == "__main__":
    main()

下面是代码输出:

root@SSL-SAP:/home/test/Templates# python3 first.py
ONIE:~ #
ONIE:~ # pwd
/root
ONIE:~ # ls
al_tool          diag             sdk              smartctl.tar.xz
al_tool.tar.xz   driver           smartctl
ONIE:~ # root@SSL-SAP:/home/test/Templates#
root@SSL-SAP:/home/test/Templates#

提前致谢!

I know how to display the results on the terminal and how to redirect the results to a file, but I don’t know how to implement these two features at the same time.

如果你想在文件中保存stdout的信息(如cmd > output)但同时显示stdout,你可以使用tee

tee man

$ ls -l | tee -a output.txt
# stdout displayed at the screen
total 0
-rw-r--r--. 1 root root 0 Aug  4 13:12 1
-rw-r--r--. 1 root root 0 Aug  4 13:12 2
-rw-r--r--. 1 root root 0 Aug  4 13:12 3

$ cat output.txt
# here we can see same info as stdout
total 0
-rw-r--r--. 1 root root 0 Aug  4 13:12 1
-rw-r--r--. 1 root root 0 Aug  4 13:12 2
-rw-r--r--. 1 root root 0 Aug  4 13:12 3

在您的情况下,命令看起来像 first.py | tee -a output.txtpython3 first.py | tee -a output.txt

来自网络的另一个回答

import pexpect, sys

class MutliIO:
    def __init__(self, *fds):
        self.fds = fds

    def write(self, data):
        for fd in self.fds:
            fd.write(data)

    def flush(self):
        for fd in self.fds:
            fd.flush()

logfile = open('pexpect.log', 'w')

child = pexpect.spawnu('python3')
child.logfile_read = MutliIO(sys.stdout, logfile)

child.expect('>>> ')

child.sendline('print("Hello, world.")')
child.expect('>>> ')

child.sendline('exit()')
child.expect(pexpect.EOF)
child.wait()