gotty

Get terminal size in 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\n", out)
  fmt.Printf("err: %#v\n", 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?


Solution

  • 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\n", string(out))
      fmt.Printf("err: %#v\n", err)
      if err != nil {
        log.Fatal(err)
      }
    }
    

    Yields:

    out: "36 118\n"
    err: <nil>