【问题标题】:Php Command Line Output on the fly动态的 PHP 命令行输出
【发布时间】:2012-05-03 15:31:40
【问题描述】:

我正在编写一个命令行 php 脚本,它会向控制台窗口输出一些内容,它看起来不错,唯一的问题是当我输入时

php myfilename.php -....

在控制台窗口中,只有在其完全执行后才会将结果输出到窗口..

我想要的是像下面这样即时执行此操作

customer id: 1223 skipped.
customer id: 22233 added..

...等

另一个问题是在 printf 函数中添加 \n\r 并没有换行...

关于这些问题的任何想法..

【问题讨论】:

    标签: command-line php


    【解决方案1】:

    关于行尾标记,始终使用 PHP 预定义常量 PHP_EOL; 根据您的平台正确设置,所以您不必担心是对是错。

    对于 [Enter] 问题,可能是输出缓冲已打开。在你的脚本中添加这个简单的测试:

    function test()
    {
        $state = array(' added', ' skipped');
        for ($i = 0; $i < 50; $i++)
        {
            echo 'customer id: ' . rand(1, 1000) . $state[rand(0, 1)] . PHP_EOL;
            usleep(50000); // slow it a bit to see the line by line output
        }
    }
    
    // without ob -------------------------------------------
    
    $start = microtime(true);
    test();
    echo 'Finished in ' . round(microtime(true) - $start, 2) . PHP_EOL . str_repeat('-', 78) . PHP_EOL;
    sleep(1);
    
    // with ob ----------------------------------------------
    
    $start = microtime(true);
    ob_start(); // if called somewhere at the top in your script
    
    // some previous code...
    echo 'Line 1'.PHP_EOL.'Line 2'.PHP_EOL.uniqid().PHP_EOL;
    
    // flush the buffer and stop ob
    // this will echo whatever is in the output buffer!
    //ob_end_flush();
    
    // or, store the current buffer content in a variable and use it later
    $output = ob_get_clean();
    
    test();
    echo $output;
    echo 'Finished in ' . round(microtime(true) - $start, 2) . PHP_EOL . str_repeat('-', 78) . PHP_EOL;
    
    // you could start buffering again, if needed
    ob_start();
    

    有关输出控制功能,请参阅http://www.php.net/manual/en/ref.outcontrol.php。它们是非常强大的工具。

    希望对您有所帮助。干杯!

    【讨论】:

    • 以上帖子解决了一个问题,即使没有直接关系,我也一直在努力解决问题。我以为我有缓冲问题。原来我需要做的就是将 PHP_EOL 添加到我的 echo 语句的末尾,以使标准输出转到我的日志输出。我浪费了好几个小时的最简单的事情。
    【解决方案2】:

    首先,Windows-style end-of-line marker is \r\n, not \n\r。没有多少系统曾经使用过\n\r,但它们非常罕见,你现在可以忘记它们了。

    其次,输出很有可能被块缓冲 - 您可以使用ob_implicit_flush(1) 在每个输出命令之后自动插入flush() 命令。或者,当您需要刷新输出时,您可以手动调用flush()

    【讨论】:

      【解决方案3】:

      这可能是由于output buffering。您可以在需要时使用ob_flush() 手动刷新缓冲区。

      至于您的第二个问题,Microsoft Windows 上换行符的正确顺序是 "\r\n",而不是相反。

      【讨论】:

      • 第一个问题似乎已经解决了,即使我使用了“\r\n”,它也不会在控制台中输入新行,但如果我在代码中输入它就可以正常工作..
      猜你喜欢
      • 2015-09-18
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      • 2016-10-06
      • 2013-01-05
      相关资源
      最近更新 更多