【问题标题】:How to output my ruby commandline text in different colours如何以不同颜色输出我的 ruby​​ 命令行文本
【发布时间】:2011-01-05 09:57:39
【问题描述】:

如何使我从基于命令行的 ruby​​ 程序输出的 puts 命令颜色? 我会很感激任何关于我如何称呼每种不同颜色的参考。

假设我们从这个开始..

puts "The following word is blue.. Im Blue!"
puts "The following word is green.. Im Green!"
puts "The following word is red.. Im Red!"

我得到了我想要的不同颜色的不同文本,你明白了。

我使用的是 Ubuntu,我需要改变我的方法,以便程序在 diff os 中正确输出吗?

【问题讨论】:

  • 我在 2010 年问我的问题时想到了 ruby​​ 命令行文本。这个问题有超过 11,000 次查看和一堆外部链接。当我形成我的问题时,我不会想到寻找“彩色红宝石输出”,事实上在搜索时找不到该答案。隐含的答案可能相似,但提出的问题却大不相同。我认为这两个问题不同,但很高兴将它们联系起来。

标签: ruby command-line colors


【解决方案1】:

我想我会添加另一个解决方案,因为它的处理方式略有不同,并且包含更多颜色代码:

先举几个例子……

使用方法链:

String.include(AnsiTextStyles)

puts "How are you?".blue.bold + " " + 'I am good!'.red.bold
puts '%s %s' % ["How are you?".blue.bold, 'I am good!'.red.bold]

使用style 方法并应用多个属性:

puts "How are you?".style(:red)
puts 'I am good!'.style(:blue, :underline)
puts 'Good to hear'.style([:bg_magenta, :blink])

这可用于以某种方式存储样式属性以供以后应用:

text_styles = {
    red_bold:       [:red, :bold],
    blue_underline: [:blue, :underline],
    pretty:         [:bg_magenta, :blink],
  }

text_styles.each do |name, style|
  styled_text = "Text styled multiple ways".style(style)
  puts "%s: %s" % [name, styled_text]
end

我在 this gist I created 上提供了更多示例,并扩展了代码以包括改进,以便对 String 的修改进行限定。

这是基本代码:

module AnsiTextStyles

  TEXT_ATTRIBUTES = {
      # text properties
      none: 0, # turn off all attributes
      bold: 1, bright: 1, # these do the same thing really
      italic: 3, underline: 4, blink: 5,
      reverse: 7, # swap foreground and background colours
      hide: 8, # foreground color same as background

      # foreground colours
      black: 30, grey: 90, lt_grey: 37, :white => 97,
      red: 31, lt_red: 91, 
      green: 32, lt_green: 92,
      dk_yellow: 33, brown: 33, yellow: 93,
      blue: 34, lt_blue: 94,
      magenta: 35, pink: 95, lt_magenta: 95,
      cyan: 36, lt_cyan: 96,
      default: 39,

      # background colours
      bg_black: 40, bg_grey: 100, bg_lt_grey: 47, bg_white: 107,
      bg_red: 41, bg_lt_red: 101,
      bg_green: 42, bg_lt_green: 102,
      bg_dk_yellow: 43, bg_brown: 43, bg_yellow: 103,
      bg_blue: 44, bg_lt_blue: 104,
      bg_magenta: 45, bg_pink: 105, bg_lt_magenta: 105,
      bg_cyan: 46, bg_lt_cyan: 106,
    }

  def self.text_attributes
    TEXT_ATTRIBUTES.keys
  end

  # applies the text attributes to the current string
  def style(*text_attributes)
    codes = TEXT_ATTRIBUTES.values_at(*text_attributes.flatten).compact
    "\e[%sm%s\e[m" % [codes.join(';'), self.to_s]
  end

end

【讨论】:

  • 不错的一个!感谢您的补充,我相信有些人会发现这很有用,喜欢巧妙地使用方法链:)
【解决方案2】:

使用着色宝石!看看吧:

https://github.com/fazibear/colorize

安装:

sudo gem install colorize

用法:

require 'colorize'

puts "I am now red.".red
puts "I am now blue.".green
puts "I am a super coder".yellow

【讨论】:

    【解决方案3】:
    【解决方案4】:

    我的建议:paint gem。它不强制字符串扩展并支持 256 色(非 256 色终端具有后备模式)。

    用法:

    puts Paint["I'm blue!", :blue]
    puts Paint["I'm dark blue if your terminal supports it!", "#000044"]
    

    【讨论】:

      【解决方案5】:

      使用转义序列 \033 而不是 \e,因为它 100% 兼容 posix,并且也适用于 bsd-ish(例如 osx)系统。后者是一个 gnu 扩展。

      【讨论】:

        【解决方案6】:

        我发现this article 描述了一种将彩色文本写入控制台的非常简单的方法。这篇文章描述了这个似乎可以解决问题的小例子(我冒昧地对其进行了一些改进):

        def colorize(text, color_code)
          "\e[#{color_code}m#{text}\e[0m"
        end
        
        def red(text); colorize(text, 31); end
        def green(text); colorize(text, 32); end
        
        # Actual example
        puts 'Importing categories [ ' + green('DONE') + ' ]'
        puts 'Importing tags       [' + red('FAILED') + ']'
        

        Best 似乎定义了一些颜色。当您还需要不同的背景颜色时,您可以扩展示例(见文章底部)。

        在使用Window XP 时,作者提到需要一个名为win32console 的gem。

        【讨论】:

        • 为了使其更易于使用,您可以扩展 String 类(“Hello”.red):class String; def red; colorize(self, "\033[31m"); end; end。也检查这个线程:Colorized Ruby output
        【解决方案7】:

        【讨论】:

          【解决方案8】:

          我发现Colored gem 使用起来最简单、最干净。

          puts "this is red".red
          puts "this is red with a blue background (read: ugly)".red_on_blue
          puts "this is red with an underline".red.underline
          puts "this is really bold and really blue".bold.blue
          logger.debug "hey this is broken!".red_on_yellow 
          

          【讨论】:

          • 呵呵,扩展 String 的好方法:/
          【解决方案9】:

          我创造了这样的东西:

          begin
             require 'Win32/Console/ANSI' if PLATFORM =~ /win32/
          rescue LoadError
             raise 'You must gem install win32console to use color on Windows'
          end
          
          class Colors
             COLOR1 = "\e[1;36;40m"
             COLOR2 = "\e[1;35;40m"
             NOCOLOR = "\e[0m"
             RED = "\e[1;31;40m"
             GREEN = "\e[1;32;40m"
             DARKGREEN = "\e[0;32;40m"
             YELLOW = "\e[1;33;40m"
             DARKCYAN = "\e[0;36;40m"
          end
          
          class String
             def color(color)
                return color + self + Colors::NOCOLOR
             end
          end
          

          现在你可以使用 String 的另一种方法了:

          "Hello World".color(Colors::DARKGREEN)
          

          要知道所有颜色,只需执行以下操作:

          begin
            require 'Win32/Console/ANSI' if PLATFORM =~ /win32/
          rescue LoadError
            raise 'You must gem install win32console to use color on Windows'
          end
          
          [0, 1, 4, 5, 7].each do |attr|
            puts '----------------------------------------------------------------'
            puts "ESC[#{attr};Foreground;Background"
            30.upto(37) do |fg|
              40.upto(47) do |bg|
                print "\033[#{attr};#{fg};#{bg}m #{fg};#{bg}  "
              end
            puts "\033[0m"
            end
          end
          

          【讨论】:

            【解决方案10】:

            对于快速而肮脏的解决方案,您可以在字符串中嵌入 ASCII 颜色代码(\e[XXm 设置从现在开始使用的颜色为 XX,\e[0m 将颜色重置为正常):

            puts "The following word is blue.. \e[34mIm Blue!\e[0m"
            puts "The following word is green.. \e[32mIm Green!\e[0m"
            puts "The following word is red.. \e[31mIm Red!\e[0m"
            

            ASCII 代码还支持文本下划线、闪烁和突出显示等功能。

            好像还有helper library 可以为您处理实际的 ASCII 代码。

            编辑:关于不同的平台:在 unix 机器上使用 ASCII 代码应该没有任何问题,但是 Windows,AFAIK,不支持开箱即用。幸运的是,有一个 win32console gem 似乎可以解决这个问题。

            您可以使用以下 sn-p(在 Veger 链接到的页面上找到)仅在 Windows 上加载 win32console 库:

            begin
              require 'Win32/Console/ANSI' if PLATFORM =~ /win32/
            rescue LoadError
              raise 'You must gem install win32console to use color on Windows'
            end
            

            【讨论】:

              猜你喜欢
              • 2015-09-25
              • 1970-01-01
              • 2016-07-04
              • 1970-01-01
              • 2014-07-04
              • 2021-12-04
              • 2022-01-25
              • 2011-01-04
              相关资源
              最近更新 更多