惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
C
Cybersecurity and Infrastructure Security Agency CISA
P
Palo Alto Networks Blog
N
News | PayPal Newsroom
L
Lohrmann on Cybersecurity
S
Schneier on Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
IT之家
IT之家
云风的 BLOG
云风的 BLOG
博客园_首页
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
Cyber Attacks, Cyber Crime and Cyber Security
量子位
人人都是产品经理
人人都是产品经理
S
Securelist
Last Week in AI
Last Week in AI
V
V2EX
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
I
Intezer
T
The Exploit Database - CXSecurity.com
雷峰网
雷峰网
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
美团技术团队
Project Zero
Project Zero
博客园 - 叶小钗
Cyberwarzone
Cyberwarzone
A
Arctic Wolf
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏
阮一峰的网络日志
阮一峰的网络日志
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
C
Cisco Blogs
G
GRAHAM CLULEY
V
Vulnerabilities – Threatpost
K
Kaspersky official blog
P
Proofpoint News Feed
NISL@THU
NISL@THU
Latest news
Latest news
Scott Helme
Scott Helme
The Hacker News
The Hacker News
Know Your Adversary
Know Your Adversary
F
Full Disclosure
The Cloudflare Blog
Spread Privacy
Spread Privacy
H
Hacker News: Front Page

ZDDHUB

PixelsMeasure 开发第二年总结 PixelsMeasure 开发一年总结 Swift/SwiftUI 踩坑记 为什么说 GPT 利好程序员 ChatGPT 编程实现 Web 数字水印 Web 数字水印探究 Micro Frontends for Mobile URL 加载系统(URL Loading System) Protocol Buffers GraphQL 从 0 到 1 开发一款 IOS 应用 - Swift MV* 软件设计架构 学习一个新技巧需要多久? 不停机数据库迁移 Rspec 如何 mock update 方法更新自己? Rails 使用 mysql2 出现的段错误 使用 Docker-compose 部署 Rails 应用到生产环境 Cocoa troubleshooting 独孤九剑 Dit (0x05) - 终端篇 Gem-based Jekyll theme 开发小记 Miscellaneous 前端手记 TodoMVC 之 Redux 篇 前端手记 TodoMVC 之 Server 篇 前端手记 TodoMVC 之 React 篇 前端手记 TodoMVC 之 CSS 篇 独孤九剑 Dit (0x04) - 测试篇 独孤九剑 Dit (0x03) - 缓存篇 英语小抄 LLDB debug Golang Make mistakes 大牛俱乐部上线啦 独孤九剑 Dit (0x02) - 数据结构篇 独孤九剑 Dit (0x01) - 总决 独孤九剑 Dit (0x00) - 我为什么要做 Dit 零值强制类型转换的使用 Go语法简略 - 正则表达式 Makefile Go语法简略 - Duck框架探索 Go语法简略 - 依赖注入 Go语法简略 - web应用框架 Go语法简略 - 反射 Go语法简略 - 面向对象 Go语法简略 - goroutine Go语法简略 - 方法和接口 Go语法简略 - 基础篇 大牛 轻松科研 未来这几年 为 Android Studio 创建图标 Shell Git Vim 金庸答百问 论拖延症 Flex, A fast scanner generator 有理想的人 从虚拟到现实 常用视频转接口 Recognizer configuration on CentOS 整个世界清静了 《Python源码剖析》读书笔记
终端颜色输出重定向
zddhub · 2015-07-23 · via ZDDHUB

终端颜色输出重定向

在用printf输出时,可加上颜色显示,让输出信息更加友好。

如下:

$ printf "\033[41;32m字体背景是红色,字是绿色\033[0m\n"

这种功能适用于任何形式的printf函数,或者变种。

其中4表示背景色,3表示前景色。颜色编码: | 0 - black | 1 - red | 2 - green | 3 - yellow | 4 - blue | 5 - purple | 6 - cyan | 7 - white |

当将带颜色的命令重定向到文件时,会打印颜色字符:

$ printf "\033[41;32m字体背景是红色,字是绿色\033[0m\n" > a.log
$ vi a.log
^[[41;32m字体背景是红色,字是绿色^[[0m

出现乱码,非常不爽。目前的解决方案是,借助命令行传入全局参数,来打开或者关闭颜色的输出。

以下是Go的一种实现。

package main

import (
  "flag"
  "fmt"
  "github.com/fatih/color"   //color 包对颜色输出进行了封装
)

func main() {
  var flagNoColor = flag.Bool("no-color", false, "Disable color output")
  flag.Parse()
  if *flagNoColor {
    color.NoColor = true // disables colorized output
  }

  // Print with default helper functions
  color.Cyan("Prints text in cyan.")

  // A newline will be appended automatically
  color.Blue("Prints %s in blue.", "text")

  // These are using the default foreground colors
  color.Red("We have red")
  color.Magenta("And many others ..")
  c := color.New(color.FgCyan)
  c.Println("Prints cyan text")
}

调用时:

$ go run color.go # 带颜色
$ go run color.go --no-color # 不带颜色
$ go run color.go --no-color > color.go # 重定向到文件时没有乱码

你有更优雅的解决方案吗?

来自Tony的方案

Tony提供了一个很好的方案,除去了命令行中多余的参数--no-color。非常感谢,么么哒。

package main

import (
  "fmt"
  "github.com/mattn/go-isatty"
  "os"
)

func main() {
  fmt.Println(isatty.IsTerminal(os.Stdin.Fd()), isatty.IsTerminal(os.Stdout.Fd()))

  if !isatty.IsTerminal(os.Stdout.Fd()) {
    color.NoColor = true // disables colorized output
  }
  // Print with default helper functions
  color.Cyan("Prints text in cyan.")

  // A newline will be appended automatically
  color.Blue("Prints %s in blue.", "text")

  // These are using the default foreground colors
  color.Red("We have red")
  color.Magenta("And many others ..")
  c := color.New(color.FgCyan)
  c.Println("Prints cyan text")
}

现在,一切都变的统一了。

$ go run color.go # 带颜色
$ go run color.go > color.go # 重定向到文件时没有乱码

看了一下 isatty 的实现,它使用了系统调用 syscall.Syscall6 来check不同的终端文件描述符:

func check(fd uintptr) bool {
  var garbage [128]byte
  _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd),
    ioctlQuery,                        // Either TCGETS or TIOCGETA, basically request the termios struct
    uintptr(unsafe.Pointer(&garbage)), // A garbage slice to be filled with termios data
    0, 0, 0)
  return err == 0
}

另一个库 go-isatty 同时支持 linux, bsd 和 windows。根据这个内容,给 color 提交了 pull request, 被成功merged。 现在color已经默认支持是否终端判断啦。

如果你喜欢这篇文章,欢迎赞赏作者以示鼓励