programing

루비를 사용하여 단말기로 출력되는 텍스트를 컬러화하려면 어떻게 해야 합니까?

telecom 2023. 6. 4. 10:17
반응형

루비를 사용하여 단말기로 출력되는 텍스트를 컬러화하려면 어떻게 해야 합니까?

루비를 사용하여 단말기에서 출력을 위해 배경 및 전경 텍스트 색상화를 수행하려면 어떻게 해야 합니까?

파스칼을 프로그래밍할 때 우리는 모두 자신의 것을 쓰곤 했던 것을 기억합니다.textcolor(…)우리의 작은 교육 프로그램을 더 예쁘고 표현력 있게 보이게 하기 위한 절차들

루비에서 그것과 동등한 것을 코딩하려면 어떻게 해야 합니까?이것에 적합한 핵심 라이브러리에 내장된 지원이 있습니까?만약 그렇지 않다면, 그것을 추가하는 관용적인 방법은 무엇일까요?

컬러라이즈는 제가 가장 좋아하는 보석입니다! :-)

확인해 보십시오.

https://github.com/fazibear/colorize

설치:

gem install colorize

용도:

require 'colorize'

puts "I am now red".red
puts "I am now blue".blue
puts "Testing".yellow

위의 답변을 결합하면 다른 의존성 없이 보석 컬러라이즈처럼 작동하는 것을 구현할 수 있습니다.

class String
  # colorization
  def colorize(color_code)
    "\e[#{color_code}m#{self}\e[0m"
  end

  def red
    colorize(31)
  end

  def green
    colorize(32)
  end

  def yellow
    colorize(33)
  end

  def blue
    colorize(34)
  end

  def pink
    colorize(35)
  end

  def light_blue
    colorize(36)
  end
end

String 클래스 메서드로 지정(Unix만 해당):

class String
def black;          "\e[30m#{self}\e[0m" end
def red;            "\e[31m#{self}\e[0m" end
def green;          "\e[32m#{self}\e[0m" end
def brown;          "\e[33m#{self}\e[0m" end
def blue;           "\e[34m#{self}\e[0m" end
def magenta;        "\e[35m#{self}\e[0m" end
def cyan;           "\e[36m#{self}\e[0m" end
def gray;           "\e[37m#{self}\e[0m" end

def bg_black;       "\e[40m#{self}\e[0m" end
def bg_red;         "\e[41m#{self}\e[0m" end
def bg_green;       "\e[42m#{self}\e[0m" end
def bg_brown;       "\e[43m#{self}\e[0m" end
def bg_blue;        "\e[44m#{self}\e[0m" end
def bg_magenta;     "\e[45m#{self}\e[0m" end
def bg_cyan;        "\e[46m#{self}\e[0m" end
def bg_gray;        "\e[47m#{self}\e[0m" end

def bold;           "\e[1m#{self}\e[22m" end
def italic;         "\e[3m#{self}\e[23m" end
def underline;      "\e[4m#{self}\e[24m" end
def blink;          "\e[5m#{self}\e[25m" end
def reverse_color;  "\e[7m#{self}\e[27m" end
end

사용 방법:

puts "I'm back green".bg_green
puts "I'm red and back cyan".red.bg_cyan
puts "I'm bold and green and backround red".bold.green.bg_red

내 콘솔에서:

여기에 이미지 설명 입력

또한.

def no_colors
  self.gsub /\e\[\d+m/, ""
end

형식 지정 문자를 제거합니다.

메모

puts "\e[31m" # set format (red foreground)
puts "\e[0m"   # clear format
puts "green-#{"red".red}-green".green # will be green-red-normal, because of \e[0

저는 에릭 스코글런드와 다른 사람들의 대답을 바탕으로 기본적인 색상 모드를 테스트하는 방법을 썼습니다.

#outputs color table to console, regular and bold modes
def colortable
  names = %w(black red green yellow blue pink cyan white default)
  fgcodes = (30..39).to_a - [38]

  s = ''
  reg  = "\e[%d;%dm%s\e[0m"
  bold = "\e[1;%d;%dm%s\e[0m"
  puts '                       color table with these background codes:'
  puts '          40       41       42       43       44       45       46       47       49'
  names.zip(fgcodes).each {|name,fg|
    s = "#{fg}"
    puts "%7s "%name + "#{reg}  #{bold}   "*9 % [fg,40,s,fg,40,s,  fg,41,s,fg,41,s,  fg,42,s,fg,42,s,  fg,43,s,fg,43,s,  
      fg,44,s,fg,44,s,  fg,45,s,fg,45,s,  fg,46,s,fg,46,s,  fg,47,s,fg,47,s,  fg,49,s,fg,49,s ]
  }
end

출력 예:루비색 테스트

콘솔에서 ANSI 이스케이프 시퀀스를 사용하여 이 작업을 수행할 수 있습니다.Linux와 Mac OS X에서 작동하는 것은 알지만 Windows 콘솔(cmd)이 ANSI를 지원하는지는 잘 모르겠습니다.

자바로 했는데 아이디어가 똑같습니다.

// Foreground color
public static final String BLACK_TEXT()   { return "\033[30m";}
public static final String RED_TEXT()     { return "\033[31m";}
public static final String GREEN_TEXT()   { return "\033[32m";}
public static final String BROWN_TEXT()   { return "\033[33m";}
public static final String BLUE_TEXT()    { return "\033[34m";}
public static final String MAGENTA_TEXT() { return "\033[35m";}
public static final String CYAN_TEXT()    { return "\033[36m";}
public static final String GRAY_TEXT()    { return "\033[37m";}

// Background color
public static final String BLACK_BACK()   { return "\033[40m";}
public static final String RED_BACK()     { return "\033[41m";}
public static final String GREEN_BACK()   { return "\033[42m";}
public static final String BROWN_BACK()   { return "\033[43m";}
public static final String BLUE_BACK()    { return "\033[44m";}
public static final String MAGENTA_BACK() { return "\033[45m";}
public static final String CYAN_BACK()    { return "\033[46m";}
public static final String WHITE_BACK()   { return "\033[47m";}

// ANSI control characters
public static final String RESET_COLORS() { return "\033[0m";}
public static final String BOLD_ON()      { return "\033[1m";}
public static final String BLINK_ON()     { return "\033[5m";}
public static final String REVERSE_ON()   { return "\033[7m";}
public static final String BOLD_OFF()     { return "\033[22m";}
public static final String BLINK_OFF()    { return "\033[25m";}
public static final String REVERSE_OFF()  { return "\033[27m";}

대부분의 사람들에게 다른 대답들이 잘 먹히겠지만, 이를 수행하는 "올바른" 유닉스 방식이 언급되어야 합니다.모든 유형의 텍스트 터미널은 이러한 시퀀스를 지원하지 않으므로 다양한 텍스트 터미널의 기능에 대한 추상화인 termfo 데이터베이스를 쿼리할 수 있습니다.이것은 역사적으로 가장 흥미로운 것으로 보일 수 있습니다. 즉, 오늘날 사용되는 소프트웨어 터미널은 일반적으로 ANSI 시퀀스를 지원합니다. 그러나 실제로는 (적어도) 한 가지 효과가 있습니다. 즉, 환경 변수를 설정하는 것이 유용할 때가 있습니다.TERM로.dumb예를 들어 출력을 텍스트 파일에 저장할 때와 같은 모든 스타일을 방지할 수 있습니다.또한, 을 제대로 하는 것은 기분이 좋습니다. :-)

당신은 루비 용어집을 사용할 수 있습니다.설치하려면 C 컴파일이 필요합니다. Ubuntu 14.10 시스템에서 다음을 사용하여 설치할 수 있었습니다.

$ sudo apt-get install libncurses5-dev
$ gem install ruby-terminfo --user-install

그런 다음 데이터베이스를 다음과 같이 쿼리할 수 있습니다(사용 가능한 코드 목록은 용어집 페이지 참조).

require 'terminfo' 
TermInfo.control("bold")
puts "Bold text"
TermInfo.control("sgr0")
puts "Back to normal."
puts "And now some " + TermInfo.control_string("setaf", 1) + 
     "red" + TermInfo.control_string("sgr0") + " text."

여기 제가 좀 더 사용하기 쉽게 만들기 위해 만든 작은 포장지 클래스가 있습니다.

require 'terminfo'

class Style
  def self.style() 
    @@singleton ||= Style.new
  end

  colors = %w{black red green yellow blue magenta cyan white}
  colors.each_with_index do |color, index|
    define_method(color) { get("setaf", index) }
    define_method("bg_" + color) { get("setab", index) }
  end

  def bold()  get("bold")  end
  def under() get("smul")  end
  def dim()   get("dim")   end
  def clear() get("sgr0")  end

  def get(*args)
    begin
      TermInfo.control_string(*args)
    rescue TermInfo::TermInfoError
      ""
    end
  end
end

용도:

c = Style.style
C = c.clear
puts "#{c.red}Warning:#{C} this is #{c.bold}way#{C} #{c.bg_red}too much #{c.cyan + c.under}styling#{C}!"
puts "#{c.dim}(Don't you think?)#{C}"

위 루비 스크립트의 출력

(편집) 마지막으로, 보석이 필요하지 않은 것이 좋다면, 당신은 그것에 의존할 수 있습니다.tput프로그램, 여기에 설명된 대로 – Ruby 예:

puts "Hi! " + `tput setaf 1` + "This is red!" + `tput sgr0`

저는 도움이 될 수 있는 방법을 만들었습니다.큰 문제는 아니지만 효과가 있습니다.

def colorize(text, color = "default", bgColor = "default")
    colors = {"default" => "38","black" => "30","red" => "31","green" => "32","brown" => "33", "blue" => "34", "purple" => "35",
     "cyan" => "36", "gray" => "37", "dark gray" => "1;30", "light red" => "1;31", "light green" => "1;32", "yellow" => "1;33",
      "light blue" => "1;34", "light purple" => "1;35", "light cyan" => "1;36", "white" => "1;37"}
    bgColors = {"default" => "0", "black" => "40", "red" => "41", "green" => "42", "brown" => "43", "blue" => "44",
     "purple" => "45", "cyan" => "46", "gray" => "47", "dark gray" => "100", "light red" => "101", "light green" => "102",
     "yellow" => "103", "light blue" => "104", "light purple" => "105", "light cyan" => "106", "white" => "107"}
    color_code = colors[color]
    bgColor_code = bgColors[bgColor]
    return "\033[#{bgColor_code};#{color_code}m#{text}\033[0m"
end

사용 방법은 다음과 같습니다.

puts "#{colorize("Hello World")}"
puts "#{colorize("Hello World", "yellow")}"
puts "#{colorize("Hello World", "white","light red")}"

개선 가능한 사항은 다음과 같습니다.

  • colors그리고.bgColors메서드가 호출될 때마다 정의되며 변경되지 않습니다.
  • 다과같은다른옵추가션음과 같은 다른 합니다.bold,underline,dim 타기.

은 이방은다수없다니습사용할음에법에 사용할 수 .p,~하듯이p.inspect들면 다음과 같습니다.예:

p "#{colorize("Hello World")}"

표시됩니다. \e[0;38m헬로 월드\e[0m"

는 그것을 다니습했트로로 했습니다.puts,print그리고 로거 보석, 그리고 그것은 잘 작동합니다.


. 그래서 는저이개수만들습니다었을업고선하것을▁so▁i다▁class▁a니습만▁improved.colors그리고.bgColors 및 클스상니다입입니다.colorize클래스 메소드입니다.

편집: 코드 스타일 개선, 클래스 변수 대신 상수 정의, 문자열 대신 기호 사용, 굵게, 기울임꼴 등의 옵션 추가.

class Colorizator
    COLOURS = { default: '38', black: '30', red: '31', green: '32', brown: '33', blue: '34', purple: '35',
                cyan: '36', gray: '37', dark_gray: '1;30', light_red: '1;31', light_green: '1;32', yellow: '1;33',
                light_blue: '1;34', light_purple: '1;35', light_cyan: '1;36', white: '1;37' }.freeze
    BG_COLOURS = { default: '0', black: '40', red: '41', green: '42', brown: '43', blue: '44',
                   purple: '45', cyan: '46', gray: '47', dark_gray: '100', light_red: '101', light_green: '102',
                   yellow: '103', light_blue: '104', light_purple: '105', light_cyan: '106', white: '107' }.freeze

    FONT_OPTIONS = { bold: '1', dim: '2', italic: '3', underline: '4', reverse: '7', hidden: '8' }.freeze

    def self.colorize(text, colour = :default, bg_colour = :default, **options)
        colour_code = COLOURS[colour]
        bg_colour_code = BG_COLOURS[bg_colour]
        font_options = options.select { |k, v| v && FONT_OPTIONS.key?(k) }.keys
        font_options = font_options.map { |e| FONT_OPTIONS[e] }.join(';').squeeze
        return "\e[#{bg_colour_code};#{font_options};#{colour_code}m#{text}\e[0m".squeeze(';')
    end
end

다음을 수행하여 사용할 수 있습니다.

Colorizator.colorize "Hello World", :gray, :white
Colorizator.colorize "Hello World", :light_blue, bold: true
Colorizator.colorize "Hello World", :light_blue, :white, bold: true, underline: true

보석이 필요 없이 작동할 수 있도록 하기 위해 제가 한 일은 다음과 같습니다.

def red(mytext) ; "\e[31m#{mytext}\e[0m" ; end
puts red("hello world")

그러면 따옴표의 텍스트만 색상으로 표시되고 정기적으로 예약된 프로그램으로 돌아갑니다.

몇 가지를 찾았습니다.

http://github.com/ssoroka/ansi/tree/master

예:

puts ANSI.color(:red) { "hello there" }
puts ANSI.color(:green) + "Everything is green now" + ANSI.no_color

http://flori.github.com/term-ansicolor/

예:

print red, bold, "red bold", reset, "\n"
print red(bold("red bold")), "\n"
print red { bold { "red bold" } }, "\n"

http://github.com/sickill/rainbow

예:

puts "this is red".foreground(:red) + " and " + "this on yellow bg".background(:yellow) + " and " + "even bright underlined!".underline.bright

Windows(윈도우)에 있는 경우 "gem install win32 콘솔"을 수행하여 색상을 지원해야 할 수도 있습니다.

또한 Colorizing console Ruby-script 출력 기사는 자체 보석을 만들어야 할 경우 유용합니다.문자열에 ANSI 색상을 추가하는 방법을 설명합니다.이 지식을 사용하여 문자열을 확장하는 클래스로 래핑할 수 있습니다.

이것은 당신에게 도움이 될 수 있습니다: 컬러화된 루비 출력.

저는 이전 답변들이 유용하다는 것을 알았습니다.하지만 타사 라이브러리를 사용하지 않고 로그 출력과 같은 색상을 지정하려면 해당 항목이 맞지 않았습니다.다음은 제가 이 문제를 해결한 것입니다.

red = 31
green = 32
blue = 34

def color (color=blue)
  printf "\033[#{color}m";
  yield
  printf "\033[0m"
end

color { puts "this is blue" }
color(red) { logger.info "and this is red" }

언급URL : https://stackoverflow.com/questions/1489183/how-can-i-use-ruby-to-colorize-the-text-output-to-a-terminal

반응형