Ruby 中 shell 命令的颜色输出 [英] Color output from shell command in Ruby

查看:57
本文介绍了Ruby 中 shell 命令的颜色输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的 Ruby 脚本:

Here's a simple Ruby script:

puts `ls -laG`

在 OS X 的 ls 中,-G 代表颜色.

In OS X's ls, -G is for color.

在 bash 下运行时,我得到颜色输出.当上面从 Ruby 脚本运行时,我在结果输出中看不到颜色或 ANSI 转义序列.

When run under bash, I get color output. When the above is run from a Ruby script, I don't see color or the ANSI escape sequences in the resulting output.

从我读到的内容来看,我的猜测是因为脚本没有作为 tty 运行.有没有办法像在真正的 tty 会话下运行命令一样运行命令——或者类似的东西?

From what I've read, my guess is it's because the script isn't running as a tty. Is there some way to run the command as if it were being run under a true tty session -- or something like that?

推荐答案

查看OS X 中的 ls 手册页,我看到提到了几个环境变量.CLICOLOR 启用颜色(如 -G)和 CLICOLOR_FORCE(强制颜色甚至非终端输出).

Looking at the ls man page in OS X, I see a couple of environment variables mentioned. CLICOLOR enables color (like -G) and CLICOLOR_FORCE (forces color even to non-terminal output).

所以我想你会得到你想要的......

So I think you'll get what you want with...

puts `env CLICOLOR=1 CLICOLOR_FORCE=1 ls -la`

您可以在 .profile 中设置环境变量.在我的示例中,我只是使用了 env 命令来确保它们是在命令行上设置的.我省略了 -G 选项,因为 CLICOLOR 执行等效操作.

You could set the environment variables in your .profile. In my example, I just used the env command to ensure they're set on the command line. I left off the -G option since CLICOLOR does the equivalent.

这篇关于Ruby 中 shell 命令的颜色输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆