我在MacOS 10.7.4上使用Python 2.7。这是一个较长的脚本(不是我写的)的一部分,它基本上为PHP提供了一些配置选项,将它们写入PHP的stdin,然后从它的stdout中读取它们。无法使用Python对stdin/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, """
<?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)
的输出是这样的:
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
肯定是有在/usr/bin/php
一个PHP。
你应该使用'Popen.communicate',这样会简单得多,并自动避免死锁。答案中已经指出了真正的问题。 – schlamar 2012-07-19 12:02:42