Get terminal width in Windows using golang

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

Get terminal width in Windows using golang

问题

在Go语言中,可以通过使用os.Getpagesize()函数来获取终端的宽度。以下是一个示例代码:

package main

import (
	"fmt"
	"os"
)

func main() {
	width, _, err := terminal.GetSize(int(os.Stdout.Fd()))
	if err != nil {
		fmt.Println("Failed to get terminal width:", err)
		return
	}
	fmt.Println("Terminal width:", width)
}

请注意,这段代码使用了golang.org/x/crypto/ssh/terminal包中的GetSize()函数来获取终端的宽度。你需要确保已经安装了该包,可以使用以下命令进行安装:

go get golang.org/x/crypto/ssh/terminal

希望这可以帮助到你!

英文:

Is it possible to get the terminal width in Go?

I tried using http://github.com/nsf/termbox-go with the code:

package main

import (
	"fmt"

	"github.com/nsf/termbox-go"
)

func main() {
	fmt.Println(termbox.Size())
}

But it prints 0 0.

I also tried http://github.com/buger/goterm but when I try to go get it, I get an error:

$ go get github.com/buger/goterm
# github.com/buger/goterm
..\..\buger\goterm\terminal.go:78: undefined: syscall.SYS_IOCTL
..\..\buger\goterm\terminal.go:82: not enough arguments in call to syscall.Syscall

Any other ideas on how to get the terminal width?

答案1

得分: 8

你需要在调用termbox.Size()之前调用termbox.Init(),然后在完成后调用termbox.Close()

package main

import (
    "fmt"

    "github.com/nsf/termbox-go"
)

func main() {
    if err := termbox.Init(); err != nil {
        panic(err)
    }
    w, h := termbox.Size()
    termbox.Close()
    fmt.Println(w, h)
}

请注意,这是一个示例代码,用于演示如何使用termbox库。

英文:

You need to call termbox.Init() before you call termbox.Size(), and then termbox.Close() when you're done.

package main

import (
    "fmt"

    "github.com/nsf/termbox-go"
)

func main() {
    if err := termbox.Init(); err != nil {
        panic(err)
    }
    w, h := termbox.Size()
    termbox.Close()
    fmt.Println(w, h)
}

答案2

得分: 0

你也可以使用twin包:

package main
import "github.com/walles/moar/twin"

func main() {
   s, e := twin.NewScreen()
   if e != nil {
      panic(e)
   }
   w, h := s.Size()
   println(w, h)
}

https://pkg.go.dev/github.com/walles/moar/twin#Screen

英文:

You can also use the twin package:

package main
import "github.com/walles/moar/twin"

func main() {
   s, e := twin.NewScreen()
   if e != nil {
      panic(e)
   }
   w, h := s.Size()
   println(w, h)
}

https://pkg.go.dev/github.com/walles/moar/twin#Screen

huangapple
  • 本文由 发表于 2015年2月10日 04:42:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/28418950.html
匿名

发表评论

匿名网友

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

确定