简体   繁体   English

使用sys.stdout将输出从pexpect保存到文本文件

[英]Saving output from pexpect to a text file with sys.stdout

I am using pexpect to run external application on some input files and I want to save the output to a logfile. 我正在使用pexpect在某些输入文件上运行外部应用程序,我想将输出保存到日志文件中。 I generally manage to do this, but this application run iterative calculations and when it makes more than approx. 我通常设法做到这一点,但是此应用程序会运行迭代计算,并且当它的计算结果超过大约时。 20 cycles my output is cut. 我的输出被削减了20个周期。

I am sure that my calculations are running past this point up to the end. 我确信我的计算已经超过了这一点,直到最后。

My code: 我的代码:

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

Is there any more proper way to do this, so I could save all the output? 有没有更合适的方法可以做到这一点,所以我可以保存所有输出?

Perhaps a timeout happens. 也许发生超时。 Check exit status, it should be non-zero in this case. 检查退出状态,在这种情况下应为非零值。 Pass timeout=None to disable the timeout, pass withexitstatus=True to get the exit status: 通过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

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

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