簡體   English   中英

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

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

我正在使用pexpect將 output 與預期的字符串匹配。 我還想將命令的 output 打印到標准輸出。 我目前有這個:

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時,上述邏輯與 output 匹配,但我也想記錄我匹配的 output。 如果我添加print(cli.read().decode())行,我會看到 output 但是匹配失敗但是當我用 print 切換期望時, output 的打印不會發生。 關於如何解決這個問題的任何想法?

readexpect/expect_exact做不同的事情:

  • read最適合強制 output,例如繪圖,但沒有緩沖區大小,它將讀取直到遇到 EOF,有效地隱式關閉子項(請參閱pexpect.spawn.read )。
  • expectspawn或最后一個send/sendline線之后讀取所有 output ,用於打開的子進程 expect通常不會關閉孩子,除非它達到timeout (請參閱pexpect.spawn.exact )。

這是我的意思的一個例子:

注意- 在 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:

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

如您所見, read可能會被擊中或錯過。 對於進出 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:

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

祝你的代碼好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM