简体   繁体   English

python pexpect 打印 output 之前或之后匹配 output

[英]python pexpect print output before or after matching the output

I am using pexpect to match the output with the expected string.我正在使用pexpect将 output 与预期的字符串匹配。 I also want to print the output of the command to stdout.我还想将命令的 output 打印到标准输出。 I currently have this:我目前有这个:

def cliExecute(cmd):
    try:
        print("Running:", cmd)
        cli = pexpect.spawn(cmd)
        return cli
    except:
        print("Failed to execute command:", str(cmd), sys.exc_info()[0])
        print("Stopping test due to error")
        sys.exit(1)

def cliExpect(cli, expectation, timeout=30):
    try:
        # print(cli.read().decode()) Doing this will print o/p but the next command fails
        cli.expect(expectation, timeout=timeout)
    except:
        raise cliExpectFail("Failed to find: ", expectation,
            "\nLast exec line:" + str(cli.before))

The above logic matches the output when I use cliExpect but I also want to log the output I am matching to.当我使用cliExpect时,上述逻辑与 output 匹配,但我也想记录我匹配的 output。 If I add the print(cli.read().decode()) line, I will see the output but the matching fails but when I switch the expect with print, the print of output doesn't happen.如果我添加print(cli.read().decode())行,我会看到 output 但是匹配失败但是当我用 print 切换期望时, output 的打印不会发生。 Any thoughts on how to fix this?关于如何解决这个问题的任何想法?

read and expect/expect_exact do different things: readexpect/expect_exact做不同的事情:

  • read is best for forcing output, such as plots, but without a buffer size, it will read until it encounters and EOF, effectively closing the child implicitly (see pexpect.spawn.read ). read最适合强制 output,例如绘图,但没有缓冲区大小,它将读取直到遇到 EOF,有效地隐式关闭子项(请参阅pexpect.spawn.read )。
  • expect reads all output after a spawn or the last send/sendline , for an open child process . expectspawn或最后一个send/sendline线之后读取所有 output ,用于打开的子进程 expect will not usually close a child, unless it reaches a timeout (see pexpect.spawn.exact ). expect通常不会关闭孩子,除非它达到timeout (请参阅pexpect.spawn.exact )。

Here's an example of what I mean:这是我的意思的一个例子:

NOTE - Tested on Ubuntu 20.04, using Python 3.8注意- 在 Ubuntu 20.04 上测试,使用 Python 3.8

import pexpect

# This child executes a single command and closes implicitly
cli = pexpect.spawn("ls -l")
# I use expect_exact when using symbols like $ (also used by expect's regex)
index = cli.expect_exact(["$", pexpect.EOF, ])
if index == 0:
    print("First child still open, so use *before*:\n", cli.before)
    cli.close()
else:
    # This will happen
    print("First child closed, so use *read*:\n", cli.read())

# The child stays open after this command. You should close this child explicitly
cli = pexpect.spawn("/bin/bash")
index = cli.expect_exact(["$", pexpect.EOF, ])
if index == 0:
    # This will happen
    cli.sendline("ls -l")
    cli.expect_exact("$")
    print("Next child still open, so use *before*:\n", cli.before)
    cli.close()
else:
    print("Next child closed, so use *read*:\n", cli.read())

Output: Output:

First child closed, so use *read*:
 b''
Next child still open, so use *before*:
 b'ls -l\r\ntotal 28\r\n-rw-rw-r-- 1 ***** ***** 3393 Dec  1 15:52 *****.py\r\n-rw-rw-r-- 1 ***** ***** 1071 Dec  1 21:54 cli.py\r\n-rw-rw-r-- 1 ***** *****  793 Nov 29 19:46 *****.py\r\n-rw-rw-r-- 1 ***** *****  796 Nov 29 19:37 *****.py\r\n-rw-rw-r-- 1 ***** ***** 1118 Nov 29 16:05 *****.py\r\n-rw-rw-r-- 1 ***** *****  709 Nov 29 16:21 *****.py\r\n-rw-rw-r-- 1 ***** *****  376 Nov 22 19:47 *****.log\r\n

As you can see, read can be hit or miss.如您所见, read可能会被击中或错过。 For in-and-out CLI commands, I recommend pexpect.run instead:对于进出 CLI 命令,我建议改为使用pexpect.run

import pexpect

list_of_commands = ["ls -l", ]
for c in list_of_commands:
    command_output, exitstatus = pexpect.run(c, withexitstatus=True)
    if exitstatus != 0:
        raise RuntimeError("Unable to {0}: {1}".format(c, command_output.strip()))
    print(command_output.strip().decode())

Output: Output:

total 28
-rw-rw-r-- 1 ***** ***** 3393 Dec  1 15:52 *****.py
-rw-rw-r-- 1 ***** ***** 1071 Dec  1 21:54 cli.py
-rw-rw-r-- 1 ***** *****  793 Nov 29 19:46 *****.py
-rw-rw-r-- 1 ***** *****  796 Nov 29 19:37 *****.py
-rw-rw-r-- 1 ***** ***** 1118 Nov 29 16:05 *****.py
-rw-rw-r-- 1 ***** *****  709 Nov 29 16:21 *****.py
-rw-rw-r-- 1 ***** *****  376 Nov 22 19:47 *****.log

Good luck with your code!祝你的代码好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM