dqqs64238
2016-05-03 13:15
浏览 223

如何在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..??

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douhan8581 2016-05-03 13:24
    已采纳

    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;
        }
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题