github.com/dolfly/pty@v1.2.1/README.md (about) 1 # pty 2 3 Pty is a Go package for using unix pseudo-terminals and windows ConPty. 4 5 ## Install 6 7 ```sh 8 go get github.com/creack/pty 9 ``` 10 11 ## Examples 12 13 Note that those examples are for demonstration purpose only, to showcase how to use the library. They are not meant to be used in any kind of production environment. 14 15 __NOTE:__ This package requires `ConPty` support on windows platform, please make sure your windows system meet [these requirements](https://docs.microsoft.com/en-us/windows/console/createpseudoconsole#requirements) 16 17 ### Command 18 19 ```go 20 package main 21 22 import ( 23 "io" 24 "os" 25 "os/exec" 26 27 "github.com/creack/pty" 28 ) 29 30 func main() { 31 c := exec.Command("grep", "--color=auto", "bar") 32 f, err := pty.Start(c) 33 if err != nil { 34 panic(err) 35 } 36 37 go func() { 38 f.Write([]byte("foo\n")) 39 f.Write([]byte("bar\n")) 40 f.Write([]byte("baz\n")) 41 f.Write([]byte{4}) // EOT 42 }() 43 io.Copy(os.Stdout, f) 44 } 45 ``` 46 47 ### Shell 48 49 ```go 50 package main 51 52 import ( 53 "io" 54 "log" 55 "os" 56 "os/exec" 57 "os/signal" 58 "syscall" 59 60 "github.com/creack/pty" 61 "golang.org/x/term" 62 ) 63 64 func test() error { 65 // Create arbitrary command. 66 c := exec.Command("bash") 67 68 // Start the command with a pty. 69 ptmx, err := pty.Start(c) 70 if err != nil { 71 return err 72 } 73 // Make sure to close the pty at the end. 74 defer func() { _ = ptmx.Close() }() // Best effort. 75 76 // Handle pty size. 77 ch := make(chan os.Signal, 1) 78 signal.Notify(ch, syscall.SIGWINCH) 79 go func() { 80 for range ch { 81 if err := pty.InheritSize(os.Stdin, ptmx); err != nil { 82 log.Printf("error resizing pty: %s", err) 83 } 84 } 85 }() 86 ch <- syscall.SIGWINCH // Initial resize. 87 defer func() { signal.Stop(ch); close(ch) }() // Cleanup signals when done. 88 89 // Set stdin in raw mode. 90 oldState, err := term.MakeRaw(int(os.Stdin.Fd())) 91 if err != nil { 92 panic(err) 93 } 94 defer func() { _ = term.Restore(int(os.Stdin.Fd()), oldState) }() // Best effort. 95 96 // Copy stdin to the pty and the pty to stdout. 97 // NOTE: The goroutine will keep reading until the next keystroke before returning. 98 go func() { _, _ = io.Copy(ptmx, os.Stdin) }() 99 _, _ = io.Copy(os.Stdout, ptmx) 100 101 return nil 102 } 103 104 func main() { 105 if err := test(); err != nil { 106 log.Fatal(err) 107 } 108 } 109 ```