我在MacOS 10.7.4上使用Python 2.7。这是一个较长的脚本(不是我写的)的一部分,它基本上为PHP提供了一些配置选项,将它们写入PHP的stdin,然后从它的stdout中读取它们。
实际上,我似乎无法从stdout中读取任何内容。下面的脚本应该写'hello world',但是它写的只是一个空行。
任何人都可以提出什么问题?我不太熟悉stdin和stdout在Python或PHP中的工作方式,所以我很难调试它。
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, """
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)这个输出是:
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
raise Exception, "%s: failed to read options" % (php_path)
Exception: /usr/bin/php: failed to read options/usr/bin/php绝对有一个PHP。