1

I have this python script which calls a shell script and processes the output.

$ cat cd-and-run.py
#!/usr/bin/env python

import sys, getopt
import subprocess

def run_mock_phantom (test_value):
        aid = 'unknown'
        proc = subprocess.Popen(['./mock-phanton.sh', test_value], stdout=subprocess.PIPE)
        for line in proc.communicate()[0]:
                print line
        return aid

def main(argv):
        app_id = run_mock_phantom ( 'test-one-two' )
        print "app is %s" % (app_id)


if __name__ == "__main__":
   main(sys.argv[1:])

Here is the shell script the above script calls:

$ cat mock-phanton.sh
#!/bin/sh

appid=$1

if [ -z $appid ]
then
        echo "oh man you didnt do it right ..."
        exit 0
fi

echo "APP_ID=$appid"

When I run the script I get this output:

$ ./cd-and-run.py
A
P
P
_
I
D
=
t
e
s
t
-
o
n
e
-
t
w
o


app is unknown

What I don't understand is why does each character get outputted on a separate line and not just ...

APP_ID=test-one-two

?

Red Cricket
  • 9,762
  • 21
  • 81
  • 166

1 Answers1

4

Try changing this:

for line in proc.communicate()[0]:
        print line

to this:

print proc.communicate()[0]

I think you're unintentionally iterating over a string.

EDIT:

As mentioned in this question, you can iterate over proc.communicate()[0].splitlines() for multiple lines of stdout. Perhaps a cleaner way to do it is like this, described in the same question:

for line in proc.stdout:
    print line
Community
  • 1
  • 1
Brian
  • 1,988
  • 1
  • 14
  • 29