Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.

New in Symfony 2.4: Flushing stdout and stderr on a Process

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

Contributed by
Juan Traverso Viagas
in #8288.

When running a command with the Process component, you can get back the output at the end of the process execution, or you can get it incrementally as the command is running:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use Symfony\Component\Process\Process;

$process = new Process('ls -lsa');
$process->start();

while ($process->isRunning()) {
    // get the incremental output since the last call
    echo $process->getIncrementalOutput();
}

// get the whole output at the end of the execution
echo $process->getOutput();

But when a command outputs a lot of data, and if you are using the incremental output getters, you don't need to keep around the whole output as you won't use the getOutput() method anyway. In this case, you might want to flush the output with these new methods available in 2.4:

1
2
3
4
5
6
7
while ($process->isRunning()) {
    // get the incremental output since the last call
    echo $process->getIncrementalOutput();

    // flushes the output buffer
    $process->flushOutput();
}

Everything also works for the stderr output, just use flushErrorOutput() instead.

Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

Comments

Awesome! :) I think we should rename the methods to "clear" instead of "flush" though: https://github.com/symfony/symfony/pull/9407
For reference, the PR in my previous comment has been merged. The methods are now called clearOutput() and clearErrorOutput().

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.