无法从控制台捕获新行并将其保存到文本文件中

Unable to capture new lines from a console and save them into a text file

以下源代码应该从控制台捕获输出并将其保存到文本文件中。

import sys
import subprocess
sys.stdout = open("my_app.txt", "w")
print(subprocess.check_output(
        ['./my_app', 
        '-length=7', 
        '-all', 
        '-file_names=tmpl.txt']        
        ), 
      '\n'
    )
sys.stdout.close()

以上源码预计输出结果如下:

1a62  A    4 THR H CCHHHHH 7.042 5.781 5.399 5.373 5.423  -9.118     
1a62  A    5 GLU H CHHHHHC 5.781 5.399 5.373 5.423 5.247   5.488   
1a62  A    6 LEU H HHHHHCC 5.399 5.373 5.423 5.247 5.485   5.166  

但是,我得到以下输出:

1a62  A    4 THR H CCHHHHH 7.042 5.781 5.399 5.373 5.423  -9.118\n1a62  A    5 GLU H CHHHHHC 5.781 5.399 5.373 5.423 5.247   5.488\n1a62  A    6 LEU H HHHHHCC 5.399 5.373 5.423 5.247 5.485   5.166  

换句话说,stdout 上的新行未正确 recognized/captured/parsed。

我该如何解决这个问题?

来自 docs:

For stdin, line ending characters '\n' in the input will be converted to the default line separator os.linesep. For stdout and stderr, all line endings in the output will be converted to '\n'. For more information see the documentation of the io.TextIOWrapper class when the newline argument to its constructor is None.

因为如果你使用 Python 3.7+,你应该添加 text=True 参数,否则 universal_newlines=TrueDocs.

print(subprocess.check_output([
    './my_app',
    '-length=7',
    '-all',
    '-file_names=tmpl.txt'
], text=True),
    '\n'
)