Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: subprocess.popen: read each line of output

I'm having trouble reading my subprocess output by line. The subprocess simply greps the contents of a file against another file. The output, which should be a two column file, prints to stdout just fine. But when I try to read each line, it reads each char followed by \n:

#!/usr/bin/python    

import sys
import getopt
import os
import subprocess
from subprocess import Popen, PIPE, STDOUT

inputfile = ''
target = ''

try:
        opts, args = getopt.getopt(sys.argv[1:],"s:t:",['servers=', 'target='])
except getopt.GetoptError:
        print 'getopt failure: exit'
        sys.exit()

for opt, arg in opts:
        if opt in ("-s", "--servers"):
                inputfile = arg
        if opt in ("-t", "--target"):
                boxwin = arg

p1 = subprocess.Popen(["grep -f " + inputfile + " " + target + " | awk '{print $2, $1}'"], stdout=subprocess.PIPE, shell=True)

output, error = p1.communicate()

print output # this prints normally

for line in output:
        print line # this prints each char of output followed by \n???

Expected output after reading by line:

abc 123
def 456
ghi 789

^^ this will print if I just "print output"

Actual output when using for loop to read each line:

a
b
c

1
2
3

d
e
f

...

Any ideas? Thanks.

like image 788
corneria Avatar asked Jan 29 '14 03:01

corneria


People also ask

How do you read a Popen output?

popen. To run a process and read all of its output, set the stdout value to PIPE and call communicate(). The above script will wait for the process to complete and then it will display the output.

How do I capture the output of a subprocess run?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.

What does subprocess Popen return?

Popen Function The function should return a pointer to a stream that may be used to read from or write to the pipe while also creating a pipe between the calling application and the executed command. Immediately after starting, the Popen function returns data, and it does not wait for the subprocess to finish.

What does subprocess Check_call return?

subprocess. check_call() gets the final return value from the script, and 0 generally means "the script completed successfully".


1 Answers

Try the following :

for line in output.splitlines():

instead of:

for line in output:
like image 171
jgritty Avatar answered Oct 23 '22 07:10

jgritty