TAGS :Viewed: 21 - Published at: a few seconds ago

[ Can't write and read to stdin/stdout using Python ]

I'm working in Python 2.7 on MacOS 10.7.4. This is part of a longer script (not written by me) that essentially gives PHP some configuration options, writing them to PHP's stdin and then reading them from its stdout.

In practice, I don't seem to be able to read from stdout at all. The script below should write 'hello world', but all it writes is a blank line.

Could anyone suggest what's going wrong? I'm not very familiar with the way that stdin and stdout work in Python, or with PHP at all, so I'm struggling to debug this.

php_path = '/usr/bin/php'
args = [php_path]
child = subprocess.Popen(args,
      stdin=subprocess.PIPE,
      stdout=subprocess.PIPE,
      universal_newlines=True)
# Write to PHP stdin
print >>child.stdin, """
<?php
print "hello world\n";
# In reality we'd write some configuration options here,
# but in practice we can't even write 'hello world'. 
}
?>"""
child.stdin.close()
# Read from PHP stdout
line = True
while line:
    print 'line', line
    line = child.stdout.readline()
    print 'line from stdout', line
    if line == "hello world\n":
        break
else:
    raise Exception, "%s: failed to read options" % (php_path)

The output from this is:

line True
line from stdout 

line 

line from stdout Parse error: parse error in - on line 5

line Parse error: parse error in - on line 5

line from stdout 
Traceback (most recent call last):
  File "test.py", line 25, in <module>
    raise Exception, "%s: failed to read options" % (php_path)
Exception: /usr/bin/php: failed to read options

There is definitely a PHP at /usr/bin/php.

Answer 1


There seems to be an extra curly brace in the end of php script, that might cause the problem.

Answer 2


You're debugging the wrong thing. You send that string to PHP, and you're getting a PHP error back. PHP is complaining about a parse error in - on line 5 to me.

Now - is a special filename meaning stdin, so it's complaining about the 5th line you sent it, which seems to be a dangling }.