golang常用库之-pkg/term包、moby.term包、go-runewidth包 | 返回用户终端的当前宽度和高度、获取字符或字符串的固定宽度 | 基于文本的界面的库ui

golang常用库之-pkg/term包、moby.term包、go-runewidth包 | 返回用户终端的当前宽度和高度、获取字符或字符串的固定宽度 | 基于文本的界面的库ui

文章目录

golang常用库之-pkg/term包、moby.term包、go-runewidth包、gdamore/tcell包pkg/term包moby.term包使用场景demo:返回用户终端的当前宽度和高度

mattn/go-runewidth包使用

gdamore/tcell包- 基于文本的界面的库ui

golang常用库之-pkg/term包、moby.term包、go-runewidth包、gdamore/tcell包

pkg/term包

https://github.com/pkg/term

Package term manages POSIX terminals. As POSIX terminals are connected to, or emulate, a UART, this package also provides control over the various UART and serial line parameters.

term包管理 POSIX 终端。此程序包还提供了对各种UART和串行线参数的控制。

moby.term包

官网:https://github.com/moby/term

term provides structures and helper functions to work with terminal (state, sizes). term 提供结构体和helper函数关于终端(状态,大小)。

官方demo:打印终端大小。

package main

import (

"log"

"os"

"github.com/moby/term"

)

func main() {

fd := os.Stdin.Fd()

if term.IsTerminal(fd) {

ws, err := term.GetWinsize(fd)

if err != nil {

log.Fatalf("term.GetWinsize: %s", err)

}

log.Printf("%d:%d\n", ws.Height, ws.Width)

}

}

使用场景

常用于命令行程序最大给定列数打印给定名称命令行标志集。

根据终端列长度,调试命令行打印的格式。

demo:返回用户终端的当前宽度和高度

package main

import (

"fmt"

"io"

"os"

"github.com/moby/term"

)

// TerminalSize returns the current width and height of the user's terminal. If it isn't a terminal,

// nil is returned. On error, zero values are returned for width and height.

// Usually w must be the stdout of the process. Stderr won't work.

func TerminalSize(w io.Writer) (int, int, error) {

//GetFdInfo返回操作系统的文件描述符。文件并指示该文件是否表示终端。

outFd, isTerminal := term.GetFdInfo(w)

if !isTerminal {

return 0, 0, fmt.Errorf("given writer is no terminal")

}

//GetWinsize根据指定的文件描述符返回窗口大小。

winsize, err := term.GetWinsize(outFd)

if err != nil {

return 0, 0, err

}

return int(winsize.Width), int(winsize.Height), nil

}

func main() {

cols, height, _ := TerminalSize(os.Stdout)

fmt.Printf("Width: %v, Height: %v", cols, height)

}

代码解释: TerminalSize返回用户终端的当前宽度和高度。如果它不是终端,返回nil。出错时,宽度和高度返回零值。通常w必须是进程的标准输出。Stderr不起作用。 程序返回终端的宽度和高度。

mattn/go-runewidth包

githu: https://github.com/mattn/go-runewidth

提供功能以获取字符或字符串的固定宽度。

使用

runewidth.StringWidth("つのだ☆HIRO") == 12

gdamore/tcell包- 基于文本的界面的库ui

github: https://github.com/gdamore/tcell

tcell是一个GO软件包,为文本终端提供基于单元格的视图,例如Xterm。它的灵感来自Termbox,但包括许多其他改进。用于基于文本的界面的库ui。

可以做出类似如下效果:

✧ 相关推荐 ✧

网友查询人民币兑换韩元汇率牌价表
365bet线上注册

网友查询人民币兑换韩元汇率牌价表

📅 07-05 👁️ 391
从贵阳到紫云多少公里、要多长时间、自驾最佳路线、油费、过路费-开车从贵阳到紫云路线(返程)
樊振东包粽子技巧
365bet体育在线网投

樊振东包粽子技巧

📅 10-05 👁️ 1416