【问题标题】:Live output to a file with PHP exec()?使用 PHP exec() 实时输出到文件?
【发布时间】:2016-05-01 19:03:34
【问题描述】:

在 Windows 上,我使用 PHP 执行 gulp 命令。

像这样:

<?php

     set_time_limit(0);

     exec("cd /projectpath");
     $results = exec("gulp");
?>

这行得通,但我只能在命令完成后才能得到命令的结果,大约需要 30 秒。

我想将结果写入一个文件,在它运行时,这样我就可以使用 Ajax 在间隔内轮询进度。

在正常的命令提示符下我可以做到

gulp > results.txt 2>&1

并且在命令运行时正在填充文本文件。

我也已经尝试过shell_exec()、system() 和passthru(),但我无法在 PHP 中使用它。

有什么想法吗?

【问题讨论】:

  • 也许popen 会有所帮助。

标签: php gulp shell-exec


【解决方案1】:

为什么不按照你提议的方式直接拨打exec()

<?php

     set_time_limit(0);

     exec("cd /projectpath");
     $results = exec("gulp > results.txt 2>&1");
?>

【讨论】:

  • 我当然试过了,但是该命令似乎立即停止并且什么也不做。不知道为什么。
【解决方案2】:

使用proc_open:

<?php
$cmd = 'for i in $(seq 20); do sleep 1; echo $i; done';
$cwd = '/';
$descriptors = array(
    0 => array('pipe', 'r'),
    1 => array('file', 'stdout', 'w'),
    2 => array('file', 'stderr', 'w'),
);

$handle = proc_open($cmd, $descriptors, $pipes, $cwd);
if (!$handle) {
    echo 'failed to run command';
} else {
    proc_close($handle); // wait for command to finish (optional)
}

【讨论】:

  • 我遇到了这个例子,但无法真正理解其中发生了什么。这将结果写入哪里?如何在我的示例中使用它?
  • $cwd 应设置为'/projectpath'$cmd = 'gulp';,然后将stdoutstderr 替换为您希望有stdout 和stderr 的文件名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多