Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

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

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 switch the text color to red, then switch it back to white?

I'm using ruby but I imagine this would be the same in any other language.

Something like:

red = "123" # character code
white = "223"

print "#{red} ERROR: IT BROKE #{white}"
print "other stuff"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...