繁体   English   中英

PHP CLI脚本中Shell命令的输出

[英]Output from shell command in PHP cli script

如何实时输出从php执行的shell脚本的内容?

假设我从脚本B调用了脚本A; 脚本完成前如何输出A的结果?

脚本A:

<?php
for ($i = 0; $i < 10000; $i++) {
  echo $i;
  sleep(1);
}

脚本B:

<?php
exec('php /path/to/scriptA.php', $output);

foreach ($output as $line) {
  // This will only output when script A completes.
  echo $line . "\n";
}

答案出奇地复杂。 而不是使用exec而是要查看proc_open

这为我工作:

<?php
ob_implicit_flush();

$command = "php /path/to/scriptA";

$descriptors = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("pipe", "w")
);

$pipes = [];
$process = proc_open($command, $descriptors, $pipes, dirname(__SCRIPT__), []);
if (is_resource($process)) {
  $char = '';
  while (($char = fgetc($pipes[1])) !== false) {
    echo $char;
    flush();
  }

  fclose($pipes[0]);
  fclose($pipes[1]);
  fclose($pipes[2]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM