【问题标题】:Displaying Console Ouput in Browser while the Perl Script is still runningPerl 脚本仍在运行时在浏览器中显示控制台输出
【发布时间】:2010-12-14 08:53:25
【问题描述】:

这是我正在测试的非常简单的程序

#!/usr/bin/perl

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "Script Testing Done\n";

现在 PHP 应该每隔 10 秒或 5 秒或每当 php 在控制台上看到输出时输出一次脚本输出(将输出到控制台)。

我有数百个 perl 脚本,我无法更改这些脚本并将输出定向到 php/ajax 可以获取内容并输出到浏览器的文件。

谢谢

【问题讨论】:

  • 等等,什么?你有 PHP 调用 Perl 脚本吗?
  • 非常相似的问题(有很好的答案)在这里:stackoverflow.com/questions/1181135/…
  • 是的,我正在从 PHP 调用 Perl 脚本。

标签: php perl


【解决方案1】:

您可能想要proc_open()flush()

前者允许您随意读/写进程。后者刷新输出缓冲区。

(编辑,添加示例代码)

这是一个示例 PHP 脚本,它调用上面的 Perl 示例(假设它的名称为 test.pl)。请注意,由于 Perl 的输出缓冲机制,您需要告诉您的 Perl 脚本使 STDOUT 隐式刷新(或在 Perl 中“使其变热”)。您可以通过在 Perl 脚本的顶部添加 $|=1 来做到这一点。

<?php

$descriptor = array(
   0 => array("pipe", "r"), // stdin
   1 => array("pipe", "w"), // stdout
   2 => array("pipe", "w"), // stderr
);

$proc = proc_open('./test.pl', $descriptor, $pipes);
if ($proc) {
    fclose($pipes[0]); // no input
    stream_set_blocking($pipes[1], 0); // turn off blocking
    while (!feof($pipes[1])) {
        echo "PHP> (heartbeat)\n";
        $fromPerl = fread($pipes[1], 1024); // read up to 1k
        if ($fromPerl) {
            echo "Perl> {$fromPerl}";
        }
        sleep(2); // do other work instead
    }
    proc_close($proc);
}

这是输出:

$ time php proc.php 
PHP> (heartbeat)
PHP> (heartbeat)
Perl> This is Test Script
PHP> (heartbeat)
PHP> (heartbeat)
Perl> This is Test Script
PHP> (heartbeat)
PHP> (heartbeat)
PHP> (heartbeat)
Perl> This is Test Script
PHP> (heartbeat)
PHP> (heartbeat)
Perl> This is Test Script
PHP> (heartbeat)
PHP> (heartbeat)
PHP> (heartbeat)
Perl> This is Test Script
PHP> (heartbeat)
PHP> (heartbeat)
Perl> Script Testing Done
PHP> (heartbeat)

real    0m30.031s
user    0m0.020s
sys 0m0.018s

【讨论】:

  • 你好 Scoates,你能提供一些代码如何使用这两个函数吗?
  • 我添加了一个示例脚本及其输出。
  • 非常感谢 Scoates...这个例子太棒了.. 我真的很感激。
  • 如果它回答了你的问题,你应该接受它(-:如果不是,那部分还不清楚?
  • +1 @scoates: 但是有什么理由要返回 SUCCESS/FAILURE 标志并像这样停止 perl 进程,提前谢谢
【解决方案2】:

我可能在这里叫错了树,但你不可能是Suffering from Buffering

【讨论】:

    【解决方案3】:

    嗯,在过去,我会使用带有非解析标题的 CGI(NPH...google it)和$|=1“当你想让你的管道变得很热时”。

    您将不得不在 PHP 端做一些类似的事情。

    【讨论】:

      猜你喜欢
      • 2012-08-05
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多