如何在PHP中运行时打印Python输出
问题描述:
I want to display the output of the python script at runtime on the web browser through php. Can someone help upon this..??
I'm calling a simple python script through php here is the code: run.py:
import os
import subprocess
import sys
import time
print "<br> Hi from Python"
sys.stdout.flush()
for i in range(0,5):
time.sleep(1)
print "<br> Hi from Python"
sys.stdout.flush()
this is the php script:
<?php
$handle = popen("python run.py ", 'r');
while(!feof($handle)) {
$buffer = fgets($handle);
echo "$buffer<br/>
";
ob_flush();
}
pclose($handle);
?>
Can someone help upon this..??
答
use exec
instead
$res = NULL;
exec("python full/path/to/script.py 2>&1" ,$res); //2>&1 @comments.KEK
if(isset($res)){
foreach($res as $rowRes){
echo $rowRes;
}
}