Golang:如何给 fmt.Fprintf 输出添加颜色?

huangapple go评论80阅读模式
英文:

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")
}

huangapple
  • 本文由 发表于 2022年5月13日 19:51:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/72229143.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定