英文:
Golang: How to color fmt.Fprintf output?
问题
我知道可以通过以下方式向fmt.Println
的输出添加颜色:
package main
import (
"fmt"
)
func main() {
colorReset := "3[0m"
colorRed := "3[31m"
fmt.Println(string(colorRed), "test", string(colorReset))
fmt.Println("next")
}
有没有办法给fmt.Fprintf
的输出添加颜色呢?
英文:
I know I can add colors to fmt.Println output with something like:
package main
import (
"fmt"
)
func main() {
colorReset := "3[0m"
colorRed := "3[31m"
fmt.Println(string(colorRed), "test", string(colorReset))
fmt.Println("next")
}
Is there any way to colorize the output of fmt.Fprintf
?
答案1
得分: 5
你可以像使用Println一样,使用Fprintf来使用颜色,例如:
const colorRed = "3[0;31m"
const colorNone = "3[0m"
func main() {
fmt.Fprintf(os.Stdout, "Red: 3[0;31m %s None: 3[0m %s", "red string", "colorless string")
fmt.Fprintf(os.Stdout, "Red: %s %s None: %s %s", colorRed, "red string", colorNone, "colorless string")
}
英文:
In the same way you used the Println you can use colors with Fprintf, ex
const colorRed = "\033[0;31m"
const colorNone = "\033[0m"
func main() {
fmt.Fprintf(os.Stdout, "Red: \033[0;31m %s None: \033[0m %s", "red string", "colorless string")
fmt.Fprintf(os.Stdout, "Red: %s %s None: %s %s", colorRed, "red string", colorNone, "colorless string")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论