pipe

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 9 Imported by: 1

README

pipeit

pipeit is a Go library designed to simplify cross-platform process IO capture and interaction. It provides a high-level API to spawn processes, capture their standard output and standard error, and write to their standard input.

Key features include:

  • PTY Support: seamless interaction with interactive CLI tools (like shells, REPLs) using pseudo-terminals.
  • Standard Pipes: Support for non-interactive commands using standard OS pipes.
  • Bidirectional Communication: Write to a process's stdin and read from its stdout/stderr in real-time.
  • Simple API: Easy-to-use methods for starting, stopping, and managing processes.

Installation

go get github.com/liliang-cn/pipeit

(Note: If you are developing locally, ensure your go.mod is set up correctly to resolve the package).

Usage

Here is a simple example of how to use pipeit to run a bash command and capture its output.

package main

import (
	"fmt"
	"time"

	"github.com/liliang-cn/pipeit"
)

func main() {
	// 1. Create a new process manager for 'bash'
	pm := pipe.New("bash", "--norc")

	// 2. Set a handler to process output (stdout/stderr)
	pm.SetOutputHandler(func(data []byte) {
		fmt.Printf("[Output]: %s", string(data))
	})

	// 3. Start the process with a PTY (useful for interactive commands)
	if err := pm.StartWithPTY(); err != nil {
		panic(err)
	}
	defer pm.Stop()

	// 4. Send commands to the process
	pm.Writeln("echo 'Hello from pipeit!'")
	time.Sleep(100 * time.Millisecond) // Give it a moment to process

	// 5. Exit the process
	pm.Writeln("exit")
	pm.Wait()
}
Advanced Configuration

You can use NewWithConfig for more control, such as setting environment variables:

config := pipe.Config{
    Command: "python3",
    Args:    []string{"-q"},
    Env:     []string{"PYTHONUNBUFFERED=1"},
    OnOutput: func(data []byte) {
        fmt.Print(string(data))
    },
}

pm := pipe.NewWithConfig(config)
pm.StartWithPTY()
// ... interact with python ...

Examples

Check the examples/ directory for more comprehensive demos:

  • cli/main.go: A CLI tool demonstrating bash, zsh, and python interactions.
  • lib/main.go: A collection of library usage patterns (streaming, error handling, etc.).

To run the CLI demo:

# Run bash example
EXAMPLE=bash go run examples/cli/main.go

# Run python example
EXAMPLE=python go run examples/cli/main.go

License

MIT, see LICENSE.

Documentation

Overview

Package pipe provides a high-level API for capturing and interacting with process input and output across different platforms.

It supports both pseudo-terminal (PTY) for interactive programs (like shells or REPLs) and standard pipes for non-interactive commands.

Index

Constants

View Source
const (
	KeyEnter      = "\r"
	KeyArrowUp    = "\x1b[A"
	KeyArrowDown  = "\x1b[B"
	KeyArrowLeft  = "\x1b[D"
	KeyArrowRight = "\x1b[C"
	KeyTab        = "\t"
	KeyEscape     = "\x1b"
	KeyCtrlC      = "\x03"
)

Special terminal key sequences

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Command is the name or path of the executable.
	Command string
	// Args is the list of arguments for the command.
	Args []string
	// Env specifies the environment variables for the process.
	// If nil, the current process environment is used.
	Env []string
	// OnOutput is the handler for stdout data.
	OnOutput OutputHandler
	// OnError is the handler for stderr data.
	OnError OutputHandler
}

Config specifies the parameters for creating a new ProcessManager.

type OutputHandler

type OutputHandler func([]byte)

OutputHandler is a callback function type used to process output data received from the managed process's stdout or stderr.

type ProcessManager

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

ProcessManager handles the lifecycle and IO of a system process. It manages the execution, provides methods for writing to stdin, and uses handlers to capture stdout and stderr.

func New

func New(command string, args ...string) *ProcessManager

New creates a new ProcessManager for the given command and arguments. It uses default environment variables and provides no initial handlers.

func NewWithConfig

func NewWithConfig(cfg Config) *ProcessManager

NewWithConfig creates a ProcessManager using the provided Config.

func (*ProcessManager) IsRunning

func (p *ProcessManager) IsRunning() bool

IsRunning returns true if the process is currently active.

func (*ProcessManager) Pid

func (p *ProcessManager) Pid() int

Pid returns the process ID of the managed process, or -1 if not started.

func (*ProcessManager) Session

func (p *ProcessManager) Session() *os.File

Session returns the underlying PTY file, if one is in use. This allows for advanced terminal operations like setting window size.

func (*ProcessManager) SetErrorHandler

func (p *ProcessManager) SetErrorHandler(handler OutputHandler)

SetErrorHandler sets or updates the callback for stderr data.

func (*ProcessManager) SetOutputHandler

func (p *ProcessManager) SetOutputHandler(handler OutputHandler)

SetOutputHandler sets or updates the callback for stdout data.

func (*ProcessManager) SetWindowSize added in v0.2.1

func (p *ProcessManager) SetWindowSize(rows, cols uint16) error

SetWindowSize sets the terminal window size for the PTY. This is often required for complex interactive CLI tools to render correctly.

func (*ProcessManager) StartWithPTY

func (p *ProcessManager) StartWithPTY() error

StartWithPTY starts the process attached to a pseudo-terminal (PTY). This is required for interactive programs like shells, Python REPL, etc.

func (*ProcessManager) StartWithPipes

func (p *ProcessManager) StartWithPipes() error

StartWithPipes starts the process using standard OS pipes for stdin/stdout/stderr. This is suitable for non-interactive batch commands.

func (*ProcessManager) Stop

func (p *ProcessManager) Stop() error

Stop terminates the process and closes associated pipes or PTY.

func (*ProcessManager) Wait

func (p *ProcessManager) Wait() error

Wait blocks until the managed process exits.

func (*ProcessManager) Write

func (p *ProcessManager) Write(data []byte) (n int, err error)

Write sends raw bytes to the process's standard input.

func (*ProcessManager) WriteString

func (p *ProcessManager) WriteString(s string) error

WriteString sends a string to the process's standard input.

func (*ProcessManager) Writef

func (p *ProcessManager) Writef(format string, args ...any) error

Writef formats a string and sends it to the process's standard input.

func (*ProcessManager) Writeln

func (p *ProcessManager) Writeln(s string) error

Writeln sends a string followed by a newline to the process's standard input.

Directories

Path Synopsis
cmd
pipeit command
examples
claude_wrapper command
cli command
gemini_wrapper command
lib command

Jump to

Keyboard shortcuts

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