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

Time:02-22

The following source code is supposed to capture output from the console and save that 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()

The above source code is expected to output the following output:

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  

However, I am getting the following output:

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  

In other words, the new lines on stdout are not being recognized/captured/parsed properly.

How can I resolve this issue?

CodePudding user response:

From 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.

Since that you should add text=True parameter if you are using Python 3.7 , universal_newlines=True else. Docs.

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