Command line progress bar in PHP

后端 未结 4 520
温柔的废话
温柔的废话 2020-12-23 01:51

I am currently trying to add a progress bar to a command line script and I\'ve tried various solutions (including Zend and Console_ProgressBar). The problem they both have i

4条回答
  •  遥遥无期
    2020-12-23 02:29

    Other answers seem overly complex. My solution is to simply echo \033[0G escape sequence before the next update and it moves the cursor back to the beginning.

    function progressBar($done, $total) {
        $perc = floor(($done / $total) * 100);
        $left = 100 - $perc;
        $write = sprintf("\033[0G\033[2K[%'={$perc}s>%-{$left}s] - $perc%% - $done/$total", "", "");
        fwrite(STDERR, $write);
    }
    

    Calling the function for the first time outputs the progress bar and each subsequent call overwrites the last line with a new progress bar.

    EDIT: I have changed echoing \r to the escape sequence \033[0G and this should now work on OSX as well as Linux/Unix.

    EDIT 2: Fixed possible error on line 3 as per @tbjers suggestion.

    EDIT 3: Updated with new version that prints to STDERR and now also on GitHub: https://github.com/MacroMan/PHPTerminalProgressBar

    EDIT 4: Now with composer: composer require macroman/terminal-progress-bar

    use TerminalProgress\Bar;
    
    $pg = new Bar(1000);
    
    for ($i = 0; $i < 1000; $i++) {
        usleep(10000);
        $pg->tick();
    }
    

提交回复
热议问题