开发者

Get PHP to update with every line returned from a shell command

开发者 https://www.devze.com 2023-03-31 09:05 出处:网络
Background: I\'m trying to write a shell script using php that will automatically checkout a couple of large SVN repos. I am also using the PEAR console progress bar class to display the progress of t

Background: I'm trying to write a shell script using php that will automatically checkout a couple of large SVN repos. I am also using the PEAR console progress bar class to display the progress of the checkout (not totally necessary, but the thing that prompted my question).

Question: Is there a way to run a loop that will update with every line output to STDIN on the commandline?

If I do

<?php shell_exec("svn co svn://my.repo.com/repo/trunk"); ?>

I get back all of the output from the command in a giant string. Trying a loop like

   <?php     $bar = new Console_ProgressBar('%fraction% [%bar%] %percent% | %elapsed% :: %estimate%', '=>', ' ', 80, $total);
    $bar->display(0);
    stream_set_blocking(STDIN, 0);
    $output = array();
    $return = '';
    exec("svn co $svnUrl $folder", $output, $return);
    while (!isset($r开发者_运维问答eturn))
    {
        $bar->update(count($output));
    }
    $bar->erase(); ?>

will display the bar but not update.

Any solutions?

========================= UPDATE =======================================

Here's the working code I came up with based on the answer (for future reference):

    <?php    
    $bar = new Console_ProgressBar('%fraction% [%bar%] %percent% | %elapsed% :: %estimate%', '=>', ' ', 80, $total);
    $handle = popen("/usr/bin/svn co $svnUrl $folder", 'r');
    $elapsed = 0;
    $bar->display($elapsed);

    while ($line = fgets($handle))
    {
        $elapsed++;
        $bar->update($elapsed);
    }
    pclose($handle);
    ?>


PHP is not multi-threaded. exec() and company will block your script until the exec'd task completes. There's no point in using the while() loop, because the loop will not even start running until the svn call has completed.

If you want to run multiple parallel svn's, you'll need to use popen() (or proc_open()), which gives you a filehandle from which you can read the external command's output, and have multiple such external commands at the same time.


Use Output Buffering

see:

  • http://php.net/manual/en/function.ob-start.php
  • http://php.net/manual/en/function.ob-flush.php
  • http://php.net/manual/en/function.ob-end-clean.php

and see some related:

  • PHP Output buffering on the command line
  • Kohana 3 Command line output buffering?


AS I understand your problem that php execute script synchronously. Thats mean cycle will be run only after exec command and output will not be changed because it already done. Try to use fork.

0

精彩评论

暂无评论...
验证码 换一张
取 消