PHP 显示 python 脚本中的 return

PHP show return from python script

我无法 php 显示我的 python 脚本的完整结果,只打印了最后的基本打印语句。我在这里做错了什么?为什么 php 不显示 python 脚本的输出?

php

$result = exec('python list.py');
echo $result;

list.py

import subprocess

print "start"

a = subprocess.Popen(["ls", "-a"], stdout=subprocess.PIPE)
a.wait()
result_str = a.stdout.read()
print result_str

print "stop"

python 脚本的命令行输出如下

start
...filename
...filename
...etc...etc

stop

执行 python 脚本的 php 输出仅为

stop

谢谢

exec始终 return 结果的最后一行命令。因此,如果您需要从执行的命令中获取每一行输出。然后,你需要这样写:

$result = exec('python list.py', $ouput);
print_r($output)

根据 exec 文档

string exec ( string $command [, array &$output [, int &$return_var ]] )

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

您需要将 $result 作为参数传递给 exec() 否则您只会得到最后一条语句。

exec('python list.py', $result);
print_r($result);

这将得到一个输出数组,$result[0] 将包含 stop$result[sizeof($result)-1] 将包含 stop,中间的所有内容将包含程序输出的其余部分.