Color ouput with Swift command line tool(使用 Swift 命令行工具进行颜色输出)
问题描述
我正在使用 Swift 编写命令行工具,但在我的 shell 中显示颜色时遇到问题.我正在使用以下代码:
I'm writing a command line tool with Swift and I'm having trouble displaying colors in my shell. I'm using the following code:
println(" 33[31;32mhey 33[39;39m")
甚至
NSFileHandle.fileHandleWithStandardOutput().writeData(" 33[31;32mhey 33[39;39m".dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!)
当我在 php 中使用简单的 echo 时它可以工作(文本显示为绿色),但是它在 Swift 命令行工具中不起作用是有原因的吗?
It works when I use a simple echo in php (the text is displayed in green) but is there a reason it doesn't work in a Swift command line tool?
谢谢!
推荐答案
Swift 内置了 unicode 支持.这使反斜杠的使用无效.所以我使用带有u{}"语法的颜色代码.这是一个在终端上完美运行的 println 代码.
Swift has built in unicode support. This invalidates using of back slash. So that I use color codes with "u{}" syntax. Here is a println code which works perfectly on terminal.
// u{001B}[(attribute code like bold, dim, normal);(color code)m
// Color codes
// black 30
// red 31
// green 32
// yellow 33
// blue 34
// magenta 35
// cyan 36
// white 37
println("u{001B}[0;33myellow")
希望对你有帮助.
这篇关于使用 Swift 命令行工具进行颜色输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!