使Ruby在OS X的控制台輸出中使用顏色

來源:互聯網
上載者:User

在使用Ruby向控制台輸出文本的時候,很好的Coloring是很有必要的。以下是我找到的如何向OS X的終端中輸出著色文本的方法。其實,在Linux下應該也同樣適用。

本來我只需要把找到的博文連結貼出來就好,可惜那博文是在blogspot上,正在為一堵偉大的牆擋著。所以方便起見,我只能全文貼過來。附上原文連結:

http://craiccomputing.blogspot.com/2010/08/printing-colored-text-in-unix-terminals.html

Printing Colored Text in UNIX Terminals from Ruby Outputting text in color in a UNIX console/Xterminal is kind of old school - some might say obsolete - but once in a while it is very useful. One example is the Red/Green coloring of test results. You don't get a lot of options but enough to highlight relevant text.

The cryptic escape codes are explained in this Wiki page.

This Ruby script outputs fore and background colors and a couple of the other useful modifiers.

#!/usr/bin/ruby

puts "\033[1mForeground Colors...\033[0m\n"
puts " \033[30mBlack (30)\033[0m\n"
puts " \033[31mRed (31)\033[0m\n"
puts " \033[32mGreen (32)\033[0m\n"
puts " \033[33mYellow (33)\033[0m\n"
puts " \033[34mBlue (34)\033[0m\n"
puts " \033[35mMagenta (35)\033[0m\n"
puts " \033[36mCyan (36)\033[0m\n"
puts " \033[37mWhite (37)\033[0m\n"
puts ''

puts "\033[1mBackground Colors...\033[0m\n"
puts " \033[40m\033[37mBlack (40), White Text\033[0m\n"
puts " \033[41mRed (41)\033[0m\n"
puts " \033[42mGreen (42)\033[0m\n"
puts " \033[43mYellow (43)\033[0m\n"
puts " \033[44mBlue (44)\033[0m\n"
puts " \033[45mMagenta (45)\033[0m\n"
puts " \033[46mCyan (46)\033[0m\n"
puts " \033[47mWhite (47)\033[0m\n"
puts ''
puts "\033[1mModifiers...\033[0m\n"
puts " Reset (0)"
puts " \033[1mBold (1)\033[0m\n"
puts " \033[4mUnderlined (4)\033[0m\n"

Note that the exact colors will vary between different terminals. So try it and see.

The script will show you enough to create your own colored terminal output. But what if you sometimes want your output to go to a terminal (TTY) and other times to a file? In the latter, all the escape codes will give you garbage characters when you view the file. The trick here is to test whether our not your script is writing to a TTY with 'STDOUT.tty?'. If so then add the escape codes, if not then leave them out.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.