跳到内容

Process Helper

编辑此页

Process Helper 在进程运行时显示它们,并报告关于进程状态的有用信息。

要显示进程详情,请使用 ProcessHelper 并以非常详细的级别运行你的命令。例如,使用非常详细的级别(例如 -vv)运行以下代码

1
2
3
4
5
6
use Symfony\Component\Process\Process;

$helper = $this->getHelper('process');
$process = new Process(['figlet', 'Symfony']);

$helper->run($output, $process);

将产生如下输出

Console output showing two lines: "RUN 'figlet' 'Symfony'" and "RES Command ran successfully".

它将产生更详细的输出,并带有调试级别(例如 -vvv

In between the command line and the result line, the command's output is now shown prefixed by "OUT".

在进程失败的情况下,调试会更容易

The last line shows "RES 127 Command dit not run successfully", and the output lines show more the error information from the command.

注意

默认情况下,process helper 使用错误输出(stderr)作为其默认输出。可以通过传递 StreamOutput 的实例给 run() 方法来更改此行为。

参数

有三种方法可以使用 process helper

  • 使用命令行字符串

    1
    2
    // ...
    $helper->run($output, 'figlet Symfony');
  • 参数数组

    1
    2
    // ...
    $helper->run($output, ['figlet', 'Symfony']);

    注意

    当针对参数数组运行 helper 时,请注意这些参数将被自动转义。

  • 传递 Process 实例

    1
    2
    3
    4
    5
    6
    use Symfony\Component\Process\Process;
    
    // ...
    $process = new Process(['figlet', 'Symfony']);
    
    $helper->run($output, $process);

自定义显示

你可以使用 run() 方法的第三个参数来显示自定义错误消息

1
$helper->run($output, $process, 'The process failed :(');

自定义进程回调可以作为第四个参数传递。有关回调文档,请参阅 Process 组件

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

$helper->run($output, $process, 'The process failed :(', function (string $type, string $data): void {
    if (Process::ERR === $type) {
        // ... do something with the stderr output
    } else {
        // ... do something with the stdout
    }
});
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本