Progress Bar

Progress Bar

When executing longer-running commands, it may be helpful to show progress information, which updates as your command runs:

../../../_images/progressbar.gif

To display progress details, use the Symfony\Component\Console\Helper\ProgressBar, pass it a total number of units, and advance the progress as the command executes:

  1. use Symfony\Component\Console\Helper\ProgressBar;
  2. // creates a new progress bar (50 units)
  3. $progressBar = new ProgressBar($output, 50);
  4. // starts and displays the progress bar
  5. $progressBar->start();
  6. $i = 0;
  7. while ($i++ < 50) {
  8. // ... do some work
  9. // advances the progress bar 1 unit
  10. $progressBar->advance();
  11. // you can also advance the progress bar by more than 1 unit
  12. // $progressBar->advance(3);
  13. }
  14. // ensures that the progress bar is at 100%
  15. $progressBar->finish();

Tip

You can also regress the progress bar (i.e. step backwards) by calling $progress->advance() with a negative value. For example, if you call $progress->advance(-2) then it will regress the progress bar 2 steps.

Instead of advancing the bar by a number of steps (with the [advance()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Helper/ProgressBar.php "Symfony\Component\Console\Helper\ProgressBar::advance()") method), you can also set the current progress by calling the [setProgress()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Helper/ProgressBar.php "Symfony\Component\Console\Helper\ProgressBar::setProgress()") method.

Tip

If your platform doesn’t support ANSI codes, updates to the progress bar are added as new lines. To prevent the output from being flooded, use the [minSecondsBetweenRedraws()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Helper/ProgressBar.php "Symfony\Component\Console\Helper\ProgressBar::minSecondsBetweenRedraws()") method to limit the number of redraws and the [setRedrawFrequency()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Helper/ProgressBar.php "Symfony\Component\Console\Helper\ProgressBar::setRedrawFrequency()") method to redraw every N iterations. By default, redraw frequency is 100ms or 10% of your max.

New in version 4.4: The minSecondsBetweenRedraws() and maxSecondsBetweenRedraws() methods were introduced in Symfony 4.4.

If you don’t know the exact number of steps in advance, set it to a reasonable value and then call the setMaxSteps() method to update it as needed:

  1. // start with a 50 units progressbar
  2. $progressBar = new ProgressBar($output, 50);
  3. // a complex task has just been created: increase the progressbar to 200 units
  4. $progressBar->setMaxSteps(200);

Another solution is to omit the steps argument when creating the Symfony\Component\Console\Helper\ProgressBar instance:

  1. $progressBar = new ProgressBar($output);

The progress will then be displayed as a throbber:

  1. # no max steps (displays it like a throbber)
  2. 0 [>---------------------------]
  3. 5 [----->----------------------]
  4. 5 [============================]
  5. # max steps defined
  6. 0/3 [>---------------------------] 0%
  7. 1/3 [=========>------------------] 33%
  8. 3/3 [============================] 100%

Whenever your task is finished, don’t forget to call [finish()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Helper/ProgressBar.php "Symfony\Component\Console\Helper\ProgressBar::finish()") to ensure that the progress bar display is refreshed with a 100% completion.

Note

If you want to output something while the progress bar is running, call [clear()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Helper/ProgressBar.php "Symfony\Component\Console\Helper\ProgressBar::clear()") first. After you’re done, call [display()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Helper/ProgressBar.php "Symfony\Component\Console\Helper\ProgressBar::display()") to show the progress bar again.

If the progress information is stored in an iterable variable (such as an array or a PHP generator) you can use the [iterate()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Helper/ProgressBar.php "Symfony\Component\Console\Helper\ProgressBar::iterate()") method, which starts, advances and finishes the progress bar automatically:

  1. use Symfony\Component\Console\Helper\ProgressBar;
  2. $progressBar = new ProgressBar($output);
  3. // $iterable can be array
  4. $iterable = [1, 2];
  5. foreach ($progressBar->iterate($iterable) as $value) {
  6. // ... do some work
  7. }
  8. // or a generator
  9. function iterable() { yield 1; yield 2; ... };
  10. foreach ($progressBar->iterate(iterable()) as $value) {
  11. // ... do some work
  12. }

The previous code will output:

  1. 0/2 [>---------------------------] 0%
  2. 1/2 [==============>-------------] 50%
  3. 2/2 [============================] 100%

New in version 4.3: The iterate() method was introduced in Symfony 4.3.

Customizing the Progress Bar

Built-in Formats

By default, the information rendered on a progress bar depends on the current level of verbosity of the OutputInterface instance:

  1. # OutputInterface::VERBOSITY_NORMAL (CLI with no verbosity flag)
  2. 0/3 [>---------------------------] 0%
  3. 1/3 [=========>------------------] 33%
  4. 3/3 [============================] 100%
  5. # OutputInterface::VERBOSITY_VERBOSE (-v)
  6. 0/3 [>---------------------------] 0% 1 sec
  7. 1/3 [=========>------------------] 33% 1 sec
  8. 3/3 [============================] 100% 1 sec
  9. # OutputInterface::VERBOSITY_VERY_VERBOSE (-vv)
  10. 0/3 [>---------------------------] 0% 1 sec/1 sec
  11. 1/3 [=========>------------------] 33% 1 sec/1 sec
  12. 3/3 [============================] 100% 1 sec/1 sec
  13. # OutputInterface::VERBOSITY_DEBUG (-vvv)
  14. 0/3 [>---------------------------] 0% 1 sec/1 sec 1.0 MB
  15. 1/3 [=========>------------------] 33% 1 sec/1 sec 1.0 MB
  16. 3/3 [============================] 100% 1 sec/1 sec 1.0 MB

Note

If you call a command with the quiet flag (-q), the progress bar won’t be displayed.

Instead of relying on the verbosity mode of the current command, you can also force a format via setFormat():

  1. $progressBar->setFormat('verbose');

The built-in formats are the following:

  • normal
  • verbose
  • very_verbose
  • debug

If you don’t set the number of steps for your progress bar, use the _nomax variants:

  • normal_nomax
  • verbose_nomax
  • very_verbose_nomax
  • debug_nomax

Custom Formats

Instead of using the built-in formats, you can also set your own:

  1. $progressBar->setFormat('%bar%');

This sets the format to only display the progress bar itself:

  1. >---------------------------
  2. =========>------------------
  3. ============================

A progress bar format is a string that contains specific placeholders (a name enclosed with the % character); the placeholders are replaced based on the current progress of the bar. Here is a list of the built-in placeholders:

  • current: The current step;
  • max: The maximum number of steps (or 0 if no max is defined);
  • bar: The bar itself;
  • percent: The percentage of completion (not available if no max is defined);
  • elapsed: The time elapsed since the start of the progress bar;
  • remaining: The remaining time to complete the task (not available if no max is defined);
  • estimated: The estimated time to complete the task (not available if no max is defined);
  • memory: The current memory usage;
  • message: used to display arbitrary messages in the progress bar (as explained later).

For instance, here is how you could set the format to be the same as the debug one:

  1. $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');

Notice the :6s part added to some placeholders? That’s how you can tweak the appearance of the bar (formatting and alignment). The part after the colon (:) is used to set the sprintf format of the string.

Instead of setting the format for a given instance of a progress bar, you can also define global formats:

  1. ProgressBar::setFormatDefinition('minimal', 'Progress: %percent%%');
  2. $progressBar = new ProgressBar($output, 3);
  3. $progressBar->setFormat('minimal');

This code defines a new minimal format that you can then use for your progress bars:

  1. Progress: 0%
  2. Progress: 33%
  3. Progress: 100%

Tip

It is almost always better to redefine built-in formats instead of creating new ones as that allows the display to automatically vary based on the verbosity flag of the command.

When defining a new style that contains placeholders that are only available when the maximum number of steps is known, you should create a _nomax variant:

  1. ProgressBar::setFormatDefinition('minimal', '%percent%% %remaining%');
  2. ProgressBar::setFormatDefinition('minimal_nomax', '%percent%%');
  3. $progressBar = new ProgressBar($output);
  4. $progressBar->setFormat('minimal');

When displaying the progress bar, the format will automatically be set to minimal_nomax if the bar does not have a maximum number of steps like in the example above.

Tip

A format can contain any valid ANSI codes and can also use the Symfony-specific way to set colors:

  1. ProgressBar::setFormatDefinition(
  2. 'minimal',
  3. '<info>%percent%</info>\033[32m%\033[0m <fg=white;bg=blue>%remaining%</>'
  4. );

Note

A format can span more than one line; that’s very useful when you want to display more contextual information alongside the progress bar (see the example at the beginning of this article).

Bar Settings

Among the placeholders, bar is a bit special as all the characters used to display it can be customized:

  1. // the finished part of the bar
  2. $progressBar->setBarCharacter('<comment>=</comment>');
  3. // the unfinished part of the bar
  4. $progressBar->setEmptyBarCharacter(' ');
  5. // the progress character
  6. $progressBar->setProgressCharacter('|');
  7. // the bar width
  8. $progressBar->setBarWidth(50);

Caution

For performance reasons, Symfony redraws screen every 100ms. If this is too fast or to slow for your application, use the methods [minSecondsBetweenRedraws()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Helper/ProgressBar.php "Symfony\Component\Console\Helper\ProgressBar::minSecondsBetweenRedraws()") and [maxSecondsBetweenRedraws()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Helper/ProgressBar.php "Symfony\Component\Console\Helper\ProgressBar::maxSecondsBetweenRedraws()"):

  1. $progressBar = new ProgressBar($output, 50000);
  2. $progressBar->start();
  3. // this redraws the screen every 100 iterations, but sets additional limits:
  4. // don't redraw slower than 200ms (0.2) or faster than 100ms (0.1)
  5. $progressBar->setRedrawFrequency(100);
  6. $progressBar->maxSecondsBetweenRedraws(0.2);
  7. $progressBar->minSecondsBetweenRedraws(0.1);
  8. $i = 0;
  9. while ($i++ < 50000) {
  10. // ... do some work
  11. $progressBar->advance();
  12. }

New in version 4.4: The minSecondsBetweenRedraws and maxSecondsBetweenRedraws() methods were introduced in Symfony 4.4.

Custom Placeholders

If you want to display some information that depends on the progress bar display that are not available in the list of built-in placeholders, you can create your own. Let’s see how you can create a remaining_steps placeholder that displays the number of remaining steps:

  1. ProgressBar::setPlaceholderFormatterDefinition(
  2. 'remaining_steps',
  3. function (ProgressBar $progressBar, OutputInterface $output) {
  4. return $progressBar->getMaxSteps() - $progressBar->getProgress();
  5. }
  6. );

Custom Messages

Progress bars define a placeholder called message to display arbitrary messages. However, none of the built-in formats include that placeholder, so before displaying these messages, you must define your own custom format:

  1. ProgressBar::setFormatDefinition('custom', ' %current%/%max% -- %message%');
  2. $progressBar = new ProgressBar($output, 100);
  3. $progressBar->setFormat('custom');

Now, use the setMessage() method to set the value of the %message% placeholder before displaying the progress bar:

  1. // ...
  2. $progressBar->setMessage('Start');
  3. $progressBar->start();
  4. // 0/100 -- Start
  5. $progressBar->setMessage('Task is in progress...');
  6. $progressBar->advance();
  7. // 1/100 -- Task is in progress...

Messages can be combined with custom placeholders too. In this example, the progress bar uses the %message% and %filename% placeholders:

  1. ProgressBar::setFormatDefinition('custom', ' %current%/%max% -- %message% (%filename%)');
  2. $progressBar = new ProgressBar($output, 100);
  3. $progressBar->setFormat('custom');

The setMessage() method accepts a second optional argument to set the value of the custom placeholders:

  1. // ...
  2. // $files = ['client-001/invoices.xml', '...'];
  3. foreach ($files as $filename) {
  4. $progressBar->setMessage('Importing invoices...');
  5. $progressBar->setMessage($filename, 'filename');
  6. $progressBar->advance();
  7. // 2/100 -- Importing invoices... (client-001/invoices.xml)
  8. }

Displaying Multiple Progress Bars

When using Console output sections it’s possible to display multiple progress bars at the same time and change their progress independently:

  1. $section1 = $output->section();
  2. $section2 = $output->section();
  3. $progress1 = new ProgressBar($section1);
  4. $progress2 = new ProgressBar($section2);
  5. $progress1->start(100);
  6. $progress2->start(100);
  7. $i = 0;
  8. while (++$i < 100) {
  9. $progress1->advance();
  10. if ($i % 2 === 0) {
  11. $progress2->advance(4);
  12. }
  13. usleep(50000);
  14. }

After a couple of iterations, the output in the terminal will look like this:

  1. 34/100 [=========>------------------] 34%
  2. 68/100 [===================>--------] 68%

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.