pty

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 1, 2026 License: MIT Imports: 6 Imported by: 0

README

go-pty

Go Report Card License MIT Go Doc

A simple Go library for creating and managing pseudo-terminals (PTY). It provides a clean API for spawning processes with terminal emulation.

Installation

go get github.com/danielgatis/go-pty

Usage

Basic Example
package 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
}
Interactive Shell
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)
}
With Custom Environment Variables
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",
	},
})

API

Types
ShellConfig

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
}
PTY

Represents a pseudo-terminal with an associated process. Implements io.ReadWriter.

Functions
New
func New(rows, cols uint16, shellCfg *ShellConfig) (*PTY, error)

Creates a new PTY with the specified dimensions and shell configuration.

Methods
Read
func (p *PTY) Read(b []byte) (int, error)

Reads data from the PTY. Implements io.Reader.

Write
func (p *PTY) Write(b []byte) (int, error)

Writes data to the PTY. Implements io.Writer.

Resize
func (p *PTY) Resize(rows, cols uint16) error

Changes the terminal size. Sends SIGWINCH to notify the process.

SetPixelSize
func (p *PTY) SetPixelSize(width, height uint16) error

Sets the pixel dimensions of the terminal.

Size
func (p *PTY) Size() (rows, cols uint16)

Returns the current terminal size in rows and columns.

File
func (p *PTY) File() *os.File

Returns the underlying os.File for advanced operations.

Wait
func (p *PTY) Wait() error

Waits for the process to exit and returns its exit status.

Close
func (p *PTY) Close() error

Closes the PTY and kills the associated process. Safe to call multiple times.

License

Copyright (c) 2023-present Daniel Gatis

Licensed under MIT License

Documentation

Overview

Package pty provides a simple interface for creating and managing pseudo-terminals (PTY) in Go. It wraps the underlying PTY operations and provides a clean API for spawning processes with terminal emulation.

Example
// 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

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type PTY

type PTY struct {
	// contains filtered or unexported fields
}

PTY represents a pseudo-terminal with an associated process. It implements io.ReadWriter for convenient I/O operations.

func New

func New(rows, cols uint16, shellCfg *ShellConfig) (*PTY, error)

New creates a new PTY with the specified dimensions and shell configuration. It starts the process immediately and returns a PTY ready for I/O.

The rows and cols parameters specify the initial terminal size in characters. The shellCfg parameter provides the program to run and its configuration.

Returns an error if the PTY cannot be created or the process fails to start.

Example
// Create a PTY with custom environment variables
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",
	},
})
if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}
defer p.Close()

buf := make([]byte, 1024)
n, _ := p.Read(buf)
output := strings.TrimSpace(string(buf[:n]))
fmt.Println(output)
Output:
custom_value

func (*PTY) Close

func (p *PTY) Close() error

Close closes the PTY file descriptor and kills the associated process. It is safe to call Close multiple times; subsequent calls are no-ops.

func (*PTY) File

func (p *PTY) File() *os.File

File returns the underlying os.File for the PTY. This can be used for advanced operations not covered by the PTY API.

func (*PTY) Read

func (p *PTY) Read(b []byte) (int, error)

Read reads data from the PTY into b. It implements the io.Reader interface.

func (*PTY) Resize

func (p *PTY) Resize(rows, cols uint16) error

Resize changes the terminal size to the specified dimensions. This sends a SIGWINCH signal to the process to notify it of the size change.

Example
p, err := pty.New(24, 80, &pty.ShellConfig{
	Program: "/bin/sh",
	Args:    []string{"-c", "sleep 1"},
})
if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}
defer p.Close()

// Resize the terminal
err = p.Resize(40, 120)
if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

rows, cols := p.Size()
fmt.Printf("rows=%d, cols=%d\n", rows, cols)
Output:
rows=40, cols=120

func (*PTY) SetPixelSize

func (p *PTY) SetPixelSize(width, height uint16) error

SetPixelSize sets the pixel dimensions of the terminal. This is useful for applications that need to know the exact pixel size for rendering graphics or calculating font metrics.

func (*PTY) Size

func (p *PTY) Size() (rows, cols uint16)

Size returns the current terminal size in rows and columns.

Example
p, err := pty.New(30, 100, &pty.ShellConfig{
	Program: "/bin/sh",
	Args:    []string{"-c", "exit 0"},
})
if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}
defer p.Close()

rows, cols := p.Size()
fmt.Printf("rows=%d, cols=%d\n", rows, cols)
Output:
rows=30, cols=100

func (*PTY) Wait

func (p *PTY) Wait() error

Wait waits for the process to exit and returns its exit status. It is safe to call Wait multiple times; subsequent calls return nil.

func (*PTY) Write

func (p *PTY) Write(b []byte) (int, error)

Write writes data to the PTY from b. It implements the io.Writer interface.

type ShellConfig

type ShellConfig struct {
	// Program is the path to the executable to run.
	Program string
	// Args are the command-line arguments to pass to the program.
	Args []string
	// Env is a map of additional environment variables to set.
	// These are merged with the current environment.
	Env map[string]string
}

ShellConfig holds the configuration for the shell process to be spawned.

Directories

Path Synopsis
Example demonstrates how to use the go-pty package to create an interactive pseudo-terminal session.
Example demonstrates how to use the go-pty package to create an interactive pseudo-terminal session.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL