python pexpect在匹配输出之前或之后打印输出

2024-10-03 17:28:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pexpect将输出与期望的字符串匹配。我还想将命令的输出打印到stdout。我目前有:

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))

当我使用cliExpect时,上面的逻辑与输出匹配,但我还想记录匹配的输出。如果我添加 print(cli.read().decode())行,我将看到输出,但是匹配失败,但是当我将expect与print切换时,输出的打印不会发生。有没有关于如何解决这个问题的想法


Tags: tocmdclidefsystimeoutcommandpexpect