python pexpect 模块:将 stdout 保存到列表中

问题描述 投票:0回答:1

使用 python3 pexpect 模块时,如何将打印到 stdout 的所有内容保存到列表或变量中以便我以后查看?

这是一个非常基本的示例,我们只是等待“提示”,然后发送“foo”。之后我想检查 STDOUT 中的内容并根据它打印数据。似乎一旦你运行“p.read()”它就会清空并且不再可访问?即使在 p.close() 运行之后,如何保存整个 stdout 输出并稍后访问它?在此示例中,如果 if 语句为 true,则它可以工作,但如果为 false,您将无法再使用 p.read() 读取 stdout 中的内容。

import pexpect

p = pexpect.spawn(cmd)
p.expect("Prompt")
p.sendline("foo")


if "Command was successful" in p.read():
  print ("successful")
else:
  print (p.read())

p.expect(pexpect.EOF)
p.close()
python python-3.x pexpect
1个回答
0
投票

这是一个使用 io.StringIO 的简单示例。

文件:log-to-StringIO.py

import io
import pexpect

outbuf = io.StringIO()
proc = pexpect.spawn('bash --norc', encoding='utf8')

proc.logfile_read = outbuf

ps1re = 'bash-[.0-9]+[$#] $'
proc.expect(ps1re)

proc.sendline('echo hello world')
proc.expect(ps1re)

proc.sendline('exit')
proc.expect(pexpect.EOF)

# Now all the output is saved to outbuf and you can do whatever
# a StringIO instance can do.
outbuf.seek(0)
for line in outbuf:
    print(line, end='')

运行它:

# python3 log-to-StringIO.py
bash-5.2$ echo hello world
hello world
bash-5.2$ exit
exit
© www.soinside.com 2019 - 2024. All rights reserved.