Why are Python 3 Line breaks \n not working wiith print and subprocess Popen stdout?

4363 views python-3.x

Python 3.7.1: Calling grep with subprocess.Popen to pull errors from a log file. When printing to screen, line breaks \n are not processed.


a = subprocess.Popen(["grep", "ERR", "errors.log"], stdout=subprocess.PIPE)


ERR 1 ret: 31113\nERR 2 ret: 35523\nERR 3 ret: 3810 (etc.)

Can't imagine why the line breaks are not processed. I would expect this:

ERR 1 ret: 31113
ERR 2 ret: 35523
ERR 3 ret: 3810

Been combing the 'net for answers, but no luck. Thx :^)


How would I specify a new line in Python?
Python Popen grep

answered question

Popen returns bytes. Have you tried a.stdout.read().decode()?

1 Answer


Specify an encoding to decode the subprocess output with. I can't tell you what your errors.log file is encoded with, but give "utf-8" a try:

a = Popen(["grep", "ERR", "errors.log"], stdout=subprocess.PIPE, encoding='utf-8')

posted this

Have an answer?


Please login first before posting an answer.