代码之家  ›  专栏  ›  技术社区  ›  brienna

如何使用pexpect将整个stdout保存到变量

  •  0
  • brienna  · 技术社区  · 4 年前

    我正在使用pexpect运行一个终端命令,该命令在终端中运行时会输出相对较长的文本块。问题是如何将完整的stdout保存到变量中,以便在命令结束后在CLI程序中处理它。

    我尝试过:

    output = pexpect.run("[command]")
    print(output.decode("utf-8"))
    

    这只输出命令中的一行。

    我还尝试过:

    child = pexpect.spawn("[command]", 
                timeout=None,
                encoding="utf-8")
    child.expect(pexpect.EOF)
    with open('test.txt', 'w') as o: 
        o.write(child.before)
    

    打印的输出是一些小于全文长度的空白换行符,但却是生成的文件 test.txt 包含看起来像时间戳的内容和每行上类似数组的字符串:

    [1m[36m⠏[0m [the line's output][0m
    

    我不想要这些时间戳或类似数组的格式。如何将纯文本stdout格式化为字符串并保存为变量?

    0 回复  |  直到 4 年前
        1
  •  0
  •   Rob G    4 年前

    这些是 ANSI escape codes .我想你的指挥部正试图用粗体字打印一些东西( [1m ),第一个字符为青色( [36m ),然后使用 [0m 的来清除格式。尝试删除序列:

    注释 -使用Ubuntu 20.04和Python 3.8进行测试

    import re
    
    import pexpect
    
    test = b'\x1b[32mwhich ls: /usr/bin/ls\x1b[0m\r\n\x1b[32mwhoami: stack\x1b[0m\r\n\x1b[31;1mCannot execute command find foo: /usr/bin/find: \xe2\x80\x98foo\xe2\x80\x99: No such file or directory\x1b[0m\r\n\x1b[32mdate: Sun 30 Jan 2022 11:53:37 PM EST\x1b[0m\r\n'
    
    # Show raw output
    print(test)
    # Show formatted output
    print(test.decode('utf-8'))
    # Remove ANSI escape sequences and print
    remove_ansi = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]')
    print(remove_ansi.sub('', str(test.decode('utf-8'))))
    
    # Your script goes here
    command_output = pexpect.run('[command')
    print(remove_ansi.sub('', str(command_output.decode('utf-8'))))