A simple Go library for creating and managing pseudo-terminals (PTY). It provides a clean API for spawning processes with terminal emulation.
go get github.com/danielgatis/go-ptypackage main
import (
"fmt"
"io"
"strings"
"github.com/danielgatis/go-pty"
)
func main() {
// Create a new PTY running a simple command
p, err := pty.New(24, 80, &pty.ShellConfig{
Program: "/bin/sh",
Args: []string{"-c", "echo hello"},
})
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
defer p.Close()
// Read the output
buf := make([]byte, 1024)
n, err := p.Read(buf)
if err != nil && err != io.EOF {
fmt.Printf("Error: %v\n", err)
return
}
output := strings.TrimSpace(string(buf[:n]))
fmt.Println(output) // Output: hello
}package main
import (
"fmt"
"io"
"os"
"os/signal"
"syscall"
"github.com/danielgatis/go-pty"
"golang.org/x/term"
)
func main() {
shell := os.Getenv("SHELL")
if shell == "" {
shell = "/bin/sh"
}
// Create a new PTY
p, err := pty.New(24, 80, &pty.ShellConfig{
Program: shell,
Env: map[string]string{
"TERM": "xterm-256color",
},
})
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer p.Close()
// Put the terminal in raw mode
oldState, _ := term.MakeRaw(int(os.Stdin.Fd()))
defer term.Restore(int(os.Stdin.Fd()), oldState)
// Handle window resize
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGWINCH)
go func() {
for range sigCh {
width, height, _ := term.GetSize(int(os.Stdout.Fd()))
p.Resize(uint16(height), uint16(width))
}
}()
// Copy stdin to PTY
go io.Copy(p, os.Stdin)
// Copy PTY to stdout
io.Copy(os.Stdout, p)
}p, err := pty.New(24, 80, &pty.ShellConfig{
Program: "/bin/sh",
Args: []string{"-c", "echo $MY_VAR"},
Env: map[string]string{
"MY_VAR": "custom_value",
},
})Configuration for the shell process to be spawned.
type ShellConfig struct {
Program string // Path to the executable to run
Args []string // Command-line arguments
Env map[string]string // Additional environment variables
}Represents a pseudo-terminal with an associated process. Implements io.ReadWriter.
func New(rows, cols uint16, shellCfg *ShellConfig) (*PTY, error)Creates a new PTY with the specified dimensions and shell configuration.
func (p *PTY) Read(b []byte) (int, error)Reads data from the PTY. Implements io.Reader.
func (p *PTY) Write(b []byte) (int, error)Writes data to the PTY. Implements io.Writer.
func (p *PTY) Resize(rows, cols uint16) errorChanges the terminal size. Sends SIGWINCH to notify the process.
func (p *PTY) SetPixelSize(width, height uint16) errorSets the pixel dimensions of the terminal.
func (p *PTY) Size() (rows, cols uint16)Returns the current terminal size in rows and columns.
func (p *PTY) File() *os.FileReturns the underlying os.File for advanced operations.
func (p *PTY) Wait() errorWaits for the process to exit and returns its exit status.
func (p *PTY) Close() errorCloses the PTY and kills the associated process. Safe to call multiple times.
Copyright (c) 2023-present Daniel Gatis
Licensed under MIT License