【问题标题】:PHP proc_open live command output not workingPHP proc_open 实时命令输出不起作用
【发布时间】:2022-08-03 14:46:43
【问题描述】:

我正在尝试使用 PHP 流式传输某些脚本的实时输出。 StackOverflow 上有很多关于此的问题。我遵循了这些答案:
PHP reading shell_exec live output
Bash script live output executed from PHP
Run process with realtime output in PHP
Live output to a file with PHP exec()?

但是,它们都不适合我。我总是在命令完成时获得整个输出。这是我使用的最终代码:

$cmd = \"/path/to/command\";

$descriptorspec = array(
   0 => array(\"pipe\", \"r\"),   // stdin is a pipe that the child will read from
   1 => array(\"pipe\", \"w\"),   // stdout is a pipe that the child will write to
   2 => array(\"pipe\", \"w\")    // stderr is a pipe that the child will write to
);
flush();
$process = proc_open($cmd, $descriptorspec, $pipes, realpath(\'./\'), array());
echo \"<pre>\";
if (is_resource($process)) {
    while ($s = fgets($pipes[1])) {
        print $s;
        flush();
    }
}
echo \"</pre>\";

平台:带有 Apache 的 Arch Linux

  • 实时过程输出是一个红鲱鱼。为了您自己的调试理智,这是您想要开始工作的general code。问题很可能是 PHP刷新,但是执行 PHP 的服务器可能正在缓冲。我建议在此答案中通读调整服务器的方法:stackoverflow.com/a/4978642/231316

标签: php


【解决方案1】:

我试图将 Python 程序作为外部命令运行。
我做了更多的研究,结果发现 Python 端有输出缓冲,所以 PHP 在 Python 解释器发出所有输出之前没有得到任何输出。
我在 python 命令中禁用了输出缓冲,现在它按预期工作。

要在 python 中禁用输出缓冲,只需添加 -u 开关: python -u my_prog.py

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 2021-08-12
    • 2013-12-06
    • 1970-01-01
    相关资源
    最近更新 更多