How can I change the text color in the windows command prompt

后端 未结 14 2687
南旧
南旧 2020-12-14 22:32

I have a command line program, which outputs logging to the screen.

I want error lines to show up in red. Is there some special character codes I can output to switc

14条回答
  •  没有蜡笔的小新
    2020-12-14 23:00

    On windows, you can do it easily in three ways:

    require 'win32console'
    puts "\e[31mHello, World!\e[0m"
    

    Now you could extend String with a small method called red

     require 'win32console'
     class String
       def red
         "\e[31m#{self}\e[0m"
       end
     end
    
     puts "Hello, World!".red
    

    Also you can extend String like this to get more colors:

    require 'win32console'
    
    class String
      { :reset          =>  0,
        :bold           =>  1,
        :dark           =>  2,
        :underline      =>  4,
        :blink          =>  5,
        :negative       =>  7,
        :black          => 30,
        :red            => 31,
        :green          => 32,
        :yellow         => 33,
        :blue           => 34,
        :magenta        => 35,
        :cyan           => 36,
        :white          => 37,
      }.each do |key, value|
        define_method key do
          "\e[#{value}m" + self + "\e[0m"
        end
      end
    end
    
    puts "Hello, World!".red
    

    Or, if you can install gems:

    gem install term-ansicolor
    

    And in your program:

    require 'win32console'
    require 'term/ansicolor'
    
    class String
      include Term::ANSIColor
    end
    
    puts "Hello, World!".red
    puts "Hello, World!".blue
    puts "Annoy me!".blink.yellow.bold
    

    Please see the docs for term/ansicolor for more information and possible usage.

提交回复
热议问题