从 php 脚本执行彩色命令

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

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

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

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?

推荐答案

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

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.

相关文章