从php脚本执行彩色命令

时间:2012-04-13 20:51:29

标签: php colors command command-line-interface

我有一个命令,例如'git diff',当我从终端运行它时输出一个彩色结果。

现在,我想从CLI php脚本调用该命令,并在控制台中显示彩色结果。我已尝试使用exec(),system(),passthru()但在所有情况下输出都已转换为纯黑白文本。

有没有办法保留标准结果的颜色?如果没有,有人知道为什么这些信息会丢失吗?

2 个答案:

答案 0 :(得分:6)

您正在运行的命令很可能正在检查是否输出到终端而不是将其着色(如果不是)。通常有一种强迫它的方法,但这将特定于命令本身;如果是git diff,您可以指定--color=always

答案 1 :(得分:-1)

检查此课程:https://gist.github.com/2390007

    public static function color($text, $foreground, $background = null)
    {
        if (static::is_windows())
        {
            return $text;
        }

        if ( ! array_key_exists($foreground, static::$foreground_colors))
        {
            throw new \FuelException('Invalid CLI foreground color: '.$foreground);
        }

        if ( $background !== null and ! array_key_exists($background, static::$background_colors))
        {
            throw new \FuelException('Invalid CLI background color: '.$background);
        }

        $string = "\033[".static::$foreground_colors[$foreground]."m";

        if ($background !== null)
        {
            $string .= "\033[".static::$background_colors[$background]."m";
        }

        $string .= $text."\033[0m";

        return $string;
    }
相关问题