【问题标题】:Saving output from pexpect to a text file with sys.stdout使用 sys.stdout 将 pexpect 的输出保存到文本文件
【发布时间】:2015-08-13 08:49:14
【问题描述】:

我正在使用 pexpect 在某些输入文件上运行外部应用程序,并且我想将输出保存到日志文件中。我通常设法做到这一点,但是这个应用程序运行迭代计算并且当它超过大约。 20 个周期我的输出被切断了。

我确信我的计算一直运行到最后。

我的代码:

sys.stdout = open(logfile_path , 'a') child = pexpect.run('app input_files' , logfile=sys.stdout , cwd=path_cwd)

有没有更合适的方法来做这个,所以我可以保存所有的输出?

【问题讨论】:

    标签: python stdout pexpect


    【解决方案1】:

    可能会发生超时。检查退出状态,在这种情况下它应该是非零的。通过timeout=None 禁用超时,通过withexitstatus=True 获取退出状态:

    #!/usr/bin/env python
    import subprocess
    import sys
    import pexpect  # $ pip install pexpect
    
    N = 10**7
    command = [sys.executable, '-c', r"print('\n'*%d)" % N]
    subprocess_output = subprocess.check_output(command, universal_newlines=True)
    assert len(subprocess_output) == (N + 1), repr(subprocess_output[:30])
    output, status = pexpect.runu(command[0], args=command[1:], withexitstatus=1,
                                  timeout=None)
    assert not status, (status, repr(output.strip()))
    print(repr(output[:30]))
    assert subprocess_output.splitlines() == output.splitlines()
    assert len(output) == 2*(N + 1) # \n -> \r\n
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2014-11-02
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多