使用proc_open的多个流选择从慢进程接收响应

时间:2014-05-30 00:44:02

标签: php python sockets stream proc-open

我使用proc_open从WP插件调用慢速python脚本作为子进程(echonest remix code),并在this question找到一些代码的变体。

(python)脚本需要大约一分钟的时间来处理(一堆音频),并且我希望找到一种方法来显示从python脚本打印到浏览器的输出。就目前而言,直到proc_open和stream_select进程结束,我的整个函数的输出才会显示。这甚至包括函数开头的echo语句。

<?php
echo "Why wait before printing me out?";

$description = array (     
    0 => array("pipe", "r"),  // stdin
    1 => array("pipe", "w"),  // stdout
    2 => array("pipe", "w")   // stderr
);

$application_system = "python ";
$application_name .= "glitcher/glitchmix.py";
$application = $application_system.$application_name.$separator;

$argv1 = 'a variable';
$argv2 = 'another variable';
$separator = " ";

$pipes = array();

$proc = proc_open ( $application.$separator.$argv1.$separator.$argv2, $description , $pipes, glitch_player_DIR);

// set all streams to non blockin mode
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);

// get PID via get_status call
$status = proc_get_status($proc);
// status check here if($status === FALSE)

$pid = $status['pid'];
// now, poll for childs termination
while(true) {
    // detect if the child has terminated - the php way
    $status = proc_get_status($proc);
    //  retval checks : ($status === FALSE) and ($status['running'] === FALSE)

    // read from childs stdout and stderr
    // avoid *forever* blocking through using a time out (1sec)
    foreach(array(1, 2) as $desc) {
        // check stdout for data
        $read = array($pipes[$desc]);
        $write = NULL;
        $except = NULL;
        $tv = 1;
        $n = stream_select($read, $write, $except, $tv);
        if($n > 0) {
            do {
                $data = fgets($pipes[$desc], 8092);
                echo $data . "\n<br/>";
            } while (strlen($data) > 0);
        }
    }
}
?>

是否可以使用stream_select的多个调用来回显子进程输出?

显然我是套接字编程的新手,并期待S.O.的更多见解。社区。

1 个答案:

答案 0 :(得分:0)

这很有趣也很简单。请参阅Python的 -u 选项。我在同一个问题上浪费了2天。当我用bash替换python并测试bash脚本的一些输出时 - 它会立即收到它。