Execute a colorized command from a php script

被刻印的时光 ゝ 提交于 2019-11-30 23:45:06

问题


I have a command, for example 'git diff' that output a colorized result when I run it from the terminal.

Now, I want to call that command from a CLI php script and display in the console the colorized result. I have try with exec(), system(), passthru() but in all case the output has been converted to plain black and white text.

Is there a way to preserve the color of the standard result? If not, does someone know why this information get lost?


回答1:


In all likelihood the command you are running is checking to see if output is to a terminal and not colorizing it if it isn't. There is usually a way to force it, but that's going to be specific to the command itself; in the case of git diff, you can specify --color=always.




回答2:


Check this class: 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;
    }


来源:https://stackoverflow.com/questions/10148151/execute-a-colorized-command-from-a-php-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!