简体   繁体   中英

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. What am I doing wrong here? Why is the php not showing the output from the python script?

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"

the command line output for that python script is as below

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

stop

The php output from executing the python script is only

stop

Thank you

exec will always return the last line from the result of the command . 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. 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().

You need to pass $result as a param into exec() otherwise you only get the last statement.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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