douhao6271 2013-05-15 15:40
浏览 192
已采纳

在Go中获取终端大小

How to get tty size with Golang? I am trying do this with executing stty size command, but I can't craft code right.

package main

import (
  "os/exec"
  "fmt"
  "log"
)

func main() {
  out, err := exec.Command("stty", "size").Output()
  fmt.Printf("out: %#v
", out)
  fmt.Printf("err: %#v
", err)
  if err != nil {
    log.Fatal(err)
  }
}

Output:

out: []byte{}
err: &exec.ExitError{ProcessState:(*os.ProcessState)(0xc200066520)}
2013/05/16 02:35:57 exit status 1
exit status 1

I think this is because Go spawns a process not related to the current tty, with which it is working. How can I relate the command to current terminal in order to get its size?

  • 写回答

4条回答 默认 最新

  • douxing9641 2013-05-15 15:57
    关注

    It works if you give the child process access to the parent's stdin:

    package main
    
    import (
      "os/exec"
      "fmt"
      "log"
      "os"
    )
    
    func main() {
      cmd := exec.Command("stty", "size")
      cmd.Stdin = os.Stdin
      out, err := cmd.Output()
      fmt.Printf("out: %#v
    ", string(out))
      fmt.Printf("err: %#v
    ", err)
      if err != nil {
        log.Fatal(err)
      }
    }
    

    Yields:

    out: "36 118
    "
    err: <nil>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏