简体   繁体   English

PHP show从python脚本返回

[英]PHP show return from python script

I am unable to get php to show full results of my python script, only the last basic print statement is printed. 我无法获取php来显示我的python脚本的完整结果,仅打印了最后一个基本的打印语句。 What am I doing wrong here? 我在这里做错了什么? Why is the php not showing the output from the python script? 为什么PHP无法显示python脚本的输出?

php 的PHP

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

list.py 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"

the command line output for that python script is as below 该python脚本的命令行输出如下

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

stop

The php output from executing the python script is only 来自执行python脚本的php输出仅

stop

Thank you 谢谢

exec will always return the last line from the result of the command . exec始终 从命令结果返回最后一行 So, if you need to get every line of output from the command executed. 因此,如果您需要从执行的命令中获取每一行输出。 Then, you need to write as below : 然后,您需要编写如下内容:

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

As per exec documentation 根据执行文档

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. 如果存在output参数,则命令的输出的每一行都将填充指定的数组。 Trailing whitespace, such as \\n, is not included in this array. 尾随空格(例如\\ n)不包含在此数组中。 Note that if the array already contains some elements, exec() will append to the end of the array. 请注意,如果数组已经包含一些元素,则exec()将追加到数组的末尾。 If you do not want the function to append elements, call unset() on the array before passing it to exec(). 如果您不希望函数追加元素,请在将数组传递给exec()之前在数组上调用unset()。

You need to pass $result as a param into exec() otherwise you only get the last statement. 您需要将$result作为参数传递给exec()否则只会得到最后一条语句。

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

This will get an array of output, $result[0] will contain stop and $result[sizeof($result)-1] will contain stop and everything in between will contain the rest of your program output. 这将得到一个输出数组, $result[0]将包含stop$result[sizeof($result)-1]将包含stop ,介于两者之间的所有内容都将包含程序输出的其余部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM