简体   繁体   English

Perl中的彩色端子输出

[英]Color terminal output in Perl

I'd like to print some output to the terminal in color when the terminal supports colors, print it plain otherwise. 当终端支持颜色时,我想以某种颜色将某些输出输出到终端,否则将其打印为纯色。 Also, I'd like no color when the program is not run interactively, eg when piped into grep. 另外,当程序不是交互式运行时(例如,通过管道传输到grep时),我不希望出现任何颜色。

What's the best way to do this in Perl? 在Perl中执行此操作的最佳方法是什么? I'm hoping for some API that's sort of like this: 我希望一些像这样的API:

printColorMaybe( RED, "Hi", PLAIN, " mom!\n" );

where the implementation will ignore the color codes when not appropriate. 在不适当的情况下,实现会忽略颜色代码。

Term::ANSIColor to produced colored output. Term::ANSIColor产生彩色输出。

-t STDOUT to test whether standard output is opened to a terminal. -t STDOUT以测试标准输出是否已打开到端子。

$ENV{ANSI_COLORS_DISABLED} to dynamically disable Term::ANSIColor . $ENV{ANSI_COLORS_DISABLED}动态禁用Term::ANSIColor

use Term::ANSIColor;
$ENV{ANSI_COLORS_DISABLED}++ unless -t STDOUT;
print colored("Hi","red")," mom!\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM