### Install PyWinpty using Pip Source: https://github.com/andfoy/pywinpty/blob/main/README.md Installation method using the pip package manager. ```bash pip install pywinpty ``` -------------------------------- ### Build and Install Pywinpty Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/module-overview.md Install dependencies and build the project using Maturin. Use 'maturin develop' for development builds and 'maturin build --release' for release wheels. ```bash # Install dependencies pip install maturin # Build development version maturin develop # Build wheel maturin build --release ``` -------------------------------- ### Minimal Working Example with PtyProcess Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/README.md Spawn a process, interact with it by writing commands, reading output, and then clean up the process. ```python from winpty import PtyProcess # Spawn a process proc = PtyProcess.spawn('cmd.exe') # Interact proc.write('dir\r\n') output = proc.read() print(output) # Cleanup proc.close() ``` -------------------------------- ### PtyProcess Usage Example Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/ptyprocess-class.md A comprehensive example demonstrating how to spawn a Python interpreter using PtyProcess, interact with it by writing commands, reading output, and waiting for the process to exit. ```APIDOC ## Usage Example ```python from winpty import PtyProcess, Backend # Spawn Python interpreter proc = PtyProcess.spawn('python -u -i', backend=Backend.ConPTY) # Interact with the process proc.write('print("Hello from Python")\r\n') # Read output output = proc.read() print("Output:", output) # Check if process is alive if proc.isalive(): proc.write('exit()\r\n') # Wait for process to exit exit_code = proc.wait() print(f"Exit code: {exit_code}") ``` ``` -------------------------------- ### Install PyWinpty using Conda Source: https://github.com/andfoy/pywinpty/blob/main/README.md Recommended installation method using the conda package manager. ```bash conda install pywinpty ``` -------------------------------- ### Usage Patterns Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/README.md Real-world code examples and patterns for common PyWinpty tasks. ```APIDOC ## Usage Patterns ### Description Provides real-world code examples and patterns for various PyWinpty functionalities, from basic spawning to advanced interactive simulations. ### Core Patterns - **Process Spawning:** Basic and advanced techniques. - **Reading Output:** Simple reads, timeout-based reads, line-by-line processing. - **Writing Input:** Single writes, multiple writes, interactive input handling. - **Process Control:** Starting, stopping, and managing processes. - **Terminal Resizing:** Adjusting terminal dimensions. - **Environment and Working Directory:** Customizing execution context. - **Error Handling:** Robust error handling and graceful degradation. - **Low-Level PTY Usage:** Direct and threaded interaction with PTY. - **Output Capture and Filtering:** Capturing and processing terminal output. - **Interactive Simulation:** Simulating interactive terminal sessions. - **Subprocess Integration:** Integrating with Python's `subprocess` module. - **Testing and Automation:** Patterns for testing PyWinpty applications. - **Performance Optimization:** Tips for improving performance. ``` -------------------------------- ### High-Level PyWinpty Usage Source: https://github.com/andfoy/pywinpty/blob/main/README.md Example demonstrating high-level usage of PyWinpty by spawning a Python process and interacting with it. Requires importing PtyProcess. ```python from winpty import PtyProcess proc = PtyProcess.spawn('python') proc.write('print("hello, world!")\r\n') proc.write('exit()\r\n') while proc.isalive(): print(proc.readline()) ``` -------------------------------- ### Install Maturin for Building Source: https://github.com/andfoy/pywinpty/blob/main/README.md Install Maturin, the build backend for Rust-based Python packages, using pip. ```batch pip install maturin ``` -------------------------------- ### Spawn and Interact with PtyProcess Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/ptyprocess-class.md A comprehensive example showing how to spawn a Python interpreter using PtyProcess, write commands to it, read its output, check if it's alive, and wait for its exit. ```python from winpty import PtyProcess, Backend # Spawn Python interpreter proc = PtyProcess.spawn('python -u -i', backend=Backend.ConPTY) # Interact with the process proc.write('print("Hello from Python")\r\n') # Read output output = proc.read() print("Output:", output) # Check if process is alive if proc.isalive(): proc.write('exit()\r\n') # Wait for process to exit exit_code = proc.wait() print(f"Exit code: {exit_code}") ``` -------------------------------- ### Install Testing Dependencies Source: https://github.com/andfoy/pywinpty/blob/main/README.md Install pytest and related libraries required for running the test suite. ```batch pip install pytest pytest-lazy-fixture flaky ``` -------------------------------- ### Install Winpty using Conda Source: https://github.com/andfoy/pywinpty/blob/main/README.md Optional: Install winpty library using conda-forge for building from source. ```batch conda install winpty -c conda-forge ``` -------------------------------- ### High-Level PtyProcess Spawning Example Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/module-overview.md Use the PtyProcess class for standard process spawning and interaction, offering a file-like interface. Suitable for most common use cases. ```python from winpty import PtyProcess proc = PtyProcess.spawn('python -u -i') proc.write('print("Hello")\r\n') output = proc.read() print(output) proc.close() ``` -------------------------------- ### PtyProcess Threading Example Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/module-overview.md Shows how to use PtyProcess with separate threads for writing commands and reading output. This pattern is useful for interactive command-line applications. ```python from winpty import PtyProcess import threading import time proc = PtyProcess.spawn('cmd.exe') def write_commands(): for cmd in ['dir\r\n', 'echo test\r\n', 'exit\r\n']: proc.write(cmd) time.sleep(0.5) def read_output(): while proc.isalive(): try: output = proc.read() if output: print(output, end='', flush=True) except EOFError: break writer = threading.Thread(target=write_commands) reader = threading.Thread(target=read_output) writer.start() reader.start() writer.join() reader.join() ``` -------------------------------- ### PtyProcess Class Reference Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/README.md Comprehensive guide to the high-level `PtyProcess` class, including its factory method, instance methods, properties, and attributes. ```APIDOC ## PtyProcess Class ### Description Comprehensive guide to the high-level `PtyProcess` class, serving as the recommended interface for most applications. ### Factory Method - `PtyProcess.spawn(command, args, cwd, env, …)` - `command` (str): The command to execute. - `args` (list[str]): Arguments for the command. - `cwd` (str): Current working directory. - `env` (dict): Environment variables. - `…`: Other detailed parameters. ### Instance Methods - `read(n)`: Reads up to `n` bytes. - `write(data)`: Writes data to the PTY. - `resize(cols, rows)`: Resizes the terminal. - `close()`: Closes the PTY. - ... (16 methods total) ### Properties - `exitstatus` (int): The exit status of the process. ### Attributes - `pid` (int): Process ID. - `encoding` (str): The encoding used. - `closed` (bool): Whether the PTY is closed. - ... (10+ attributes total) ### Examples [Complete examples for each method and attribute will be provided here.] ### Thread Safety [Notes on thread safety considerations.] ``` -------------------------------- ### Check PyWinpty Version Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/INDEX.md Use this snippet to retrieve and print the currently installed version of the PyWinpty library. Ensure the library is installed. ```python from winpty import __version__; print(__version__) ``` -------------------------------- ### spawn Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/pty-class.md Starts an application process that communicates through the pseudo-terminal. It allows specifying the executable, command-line arguments, working directory, and environment variables. ```APIDOC ## spawn(appname, cmdline=None, cwd=None, env=None) ### Description Starts an application process that communicates through the pseudo-terminal. ### Method Signature ```python def spawn(self, appname: str, cmdline: Optional[str] = None, cwd: Optional[str] = None, env: Optional[str] = None) -> bool ``` ### Parameters #### Path Parameters - **appname** (str) - Required - Full path to the executable to launch (e.g., `C:\Windows\System32\cmd.exe`). - **cmdline** (Optional[str]) - Optional - Command-line arguments for the executable, separated by whitespace. If `None`, only the application name is used. - **cwd** (Optional[str]) - Optional - Working directory for the spawned process. If `None`, inherits the Python interpreter's current working directory. - **env** (Optional[str]) - Optional - Environment variables as a null-separated string in the format `name=value\0name=value\0`. Each variable must be separated by `\0`. If `None`, the process inherits the Python interpreter's environment. ### Returns - **bool** - `True` if the process was spawned successfully; `False` otherwise. ### Raises - **WinptyError** - If an error occurs during process creation. ### Example ```python pty = PTY(80, 24) # Spawn cmd.exe with no arguments pty.spawn(r'C:\Windows\System32\cmd.exe') # Spawn Python with arguments pty.spawn( appname=r'C:\Python310\python.exe', cmdline='-u -i', cwd=r'C:\Users\User\MyProject' ) # Spawn with custom environment env = 'PATH=C:\\bin;C:\\usr\\bin\0USER=admin\0' pty.spawn(r'C:\Windows\System32\cmd.exe', env=env) ``` ``` -------------------------------- ### Low-Level PyWinpty Usage Source: https://github.com/andfoy/pywinpty/blob/main/README.md Example demonstrating low-level usage of PyWinpty using the raw PTY object. This involves manual process spawning, reading, writing, and resizing. ```python from winpty import PTY # Start a new winpty-agent process of size (cols, rows) cols, rows = 80, 25 process = PTY(cols, rows) # Spawn a new console process, e.g., CMD process.spawn(br'C:\\windows\\system32\\cmd.exe') # Read console output (Unicode) process.read() # Write input to console (Unicode) process.write(b'Text') # Resize console size new_cols, new_rows = 90, 30 process.set_size(new_cols, new_rows) # Know if the process is alive alive = process.isalive() # End winpty-agent process del process ``` -------------------------------- ### pywinpty Process Spawning with Error Handling Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/INDEX.md This example shows how to spawn a process using pywinpty and handle potential WinptyErrors during operation. It ensures the process is closed in a finally block. ```python from winpty import PtyProcess, WinptyError try: proc = PtyProcess.spawn('python -u -i') proc.write('print("Hello")\r\n') output = proc.read() print(output) except WinptyError as e: print(f"Error: {e}") finally: if 'proc' in locals(): proc.close() ``` -------------------------------- ### Spawn Process with Custom Environment Variables Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Start a process, inheriting the current environment but adding or overriding specific environment variables. This allows fine-grained control over the process's execution context. ```python from winpty import PtyProcess import os # Inherit current environment and add custom variables env = os.environ.copy() env['CUSTOM_VAR'] = 'my_value' env['PYTHONUNBUFFERED'] = '1' env['DEBUG'] = 'true' proc = PtyProcess.spawn( 'python script.py', env=env ) output = proc.read() print(output) proc.close() ``` -------------------------------- ### Spawn Process for High-Resolution Terminals Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/configuration.md Configure PtyProcess for high-resolution terminals by specifying larger dimensions. This example uses the default backend. ```python proc = PtyProcess.spawn( 'cmd.exe', dimensions=(50, 200) ) ``` -------------------------------- ### Spawn Application with PTY Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/pty-class.md Use spawn to start a new process that communicates via the pseudo-terminal. Provide the executable path and optional command-line arguments, working directory, and environment variables. ```python pty = PTY(80, 24) # Spawn cmd.exe with no arguments pty.spawn(r'C:\Windows\System32\cmd.exe') ``` ```python pty.spawn( appname=r'C:\Python310\python.exe', cmdline='-u -i', cwd=r'C:\Users\User\MyProject' ) ``` ```python # Spawn with custom environment env = 'PATH=C:\\bin;C:\\usr\\bin\0USER=admin\0' pty.spawn(r'C:\Windows\System32\cmd.exe', env=env) ``` -------------------------------- ### Build PyWinpty from Source Source: https://github.com/andfoy/pywinpty/blob/main/README.md Build pywinpty sources locally after installing Rust and Maturin. This command compiles the package and makes it available in the current environment. ```bash maturin develop ``` -------------------------------- ### Add Delay for Process Startup Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/INDEX.md When troubleshooting processes that do not produce output, add a small delay to give the process time to start up. ```python time.sleep(0.5) ``` -------------------------------- ### PtyProcess.spawn() - Factory Method Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/ptyprocess-class.md Creates and spawns a process in a new pseudo-terminal. Use this method to start new processes with configurable working directories, environments, terminal sizes, and backends. ```python @classmethod def spawn(cls, argv: Union[str, list, tuple], cwd: Optional[str] = None, env: Optional[dict] = None, dimensions: tuple = (24, 80), backend: Optional[int] = None) -> PtyProcess ``` ```python from winpty import PtyProcess, Backend # Spawn a command as a string proc = PtyProcess.spawn('python -u -i') ``` ```python # Spawn with explicit arguments proc = PtyProcess.spawn(['cmd.exe', '/k', 'dir']) ``` ```python # Spawn in a specific directory with custom environment env = {'PATH': 'C:\\bin;C:\\usr\\bin', 'USER': 'admin'} proc = PtyProcess.spawn('powershell.exe', cwd='C:\\Users\\User', env=env) ``` ```python # Spawn with a specific terminal size and backend proc = PtyProcess.spawn('cmd.exe', dimensions=(40, 120), backend=Backend.ConPTY) ``` ```python # Spawn using environment variable import os os.environ['PYWINPTY_BACKEND'] = '0' # Force ConPTY proc = PtyProcess.spawn('cmd.exe') ``` -------------------------------- ### Spawn Process with Large Terminal Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Start a process with a predefined large terminal size to accommodate wide output. Ensure the process can handle and display content in this format. ```python from winpty import PtyProcess # Start with large terminal proc = PtyProcess.spawn( 'cmd.exe', dimensions=(50, 200) # 50 rows x 200 cols ) # Process can now display content in wider format proc.write('dir\r\n') output = proc.read() print(output) proc.close() ``` -------------------------------- ### Configure WinPTY Agent Timeout Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/configuration.md Set the maximum time in milliseconds for the WinPTY agent to start up and respond to RPC requests. This parameter is only effective for the WinPTY backend; ConPTY uses OS-level timeouts. Adjust based on system performance to avoid intermittent failures or delayed error reporting. ```python from winpty import PTY # Quick startup pty = PTY(80, 24, backend=1, timeout=5000) # Patient initialization (for slow systems) pty = PTY(80, 24, backend=1, timeout=120000) ``` -------------------------------- ### Configure PTY for Mouse-Enabled TUI Applications Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/configuration.md Configure a raw PTY with mouse support for TUI applications. This example uses the WinPTY backend and enables automatic mouse mode detection. ```python from winpty import PtyProcess, Backend, MouseMode # Using raw PTY with mouse support from winpty import PTY pty = PTY( cols=80, rows=24, backend=Backend.WinPTY, mouse_mode=MouseMode.WINPTY_MOUSE_MODE_AUTO ) pty.spawn(r'C:\path\to\tui_app.exe') ``` -------------------------------- ### Get PyWinpty Version Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/types.md Access the installed PyWinpty package version using the `__version__` attribute. ```python from winpty import __version__ print(f"PyWinpty version: {__version__}") ``` -------------------------------- ### Spawn Command with Arguments Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Shows how to spawn a process with arguments, supporting both string and list formats for the command. ```python from winpty import PtyProcess # Command as string (auto-parsed) proc = PtyProcess.spawn('python -u -i') # Command as list proc = PtyProcess.spawn(['python', '-u', '-i']) # Both work the same way ``` -------------------------------- ### PTY Initialization with Backend Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/types.md Demonstrates how to initialize a PTY instance using explicit backend selection or the default auto-selection. ```python from winpty import PTY, Backend # Use ConPTY explicitly pty = PTY(80, 24, backend=Backend.ConPTY) # Use WinPTY explicitly pty = PTY(80, 24, backend=Backend.WinPTY) # Auto-select (default) pty = PTY(80, 24) # backend=None ``` -------------------------------- ### Spawn Simple Command Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Demonstrates the simplest way to spawn a process and interact with it by writing commands and reading output. ```python from winpty import PtyProcess # Spawn and interact proc = PtyProcess.spawn('cmd.exe') proc.write('dir\r\n') output = proc.read() print(output) proc.close() ``` -------------------------------- ### Configuration Reference Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/README.md Detailed reference for configuring PyWinpty, including constructor parameters, environment variables, and spawn options. ```APIDOC ## Configuration ### Description Detailed reference for configuring PTY and PtyProcess instances, including constructor parameters, environment variables, and spawn options. ### PTY Constructor Parameters - `cols` (int): Terminal width. - `rows` (int): Terminal height. - `backend` (Backend): Backend selection (`CONPTY` or `WINPTY`). - `mouse_mode` (MouseMode): Mouse event handling. - `timeout` (float): I/O operation timeout. - `agent_config` (AgentConfig): Agent configuration flags. ### PtyProcess.spawn() Parameters - `command` (str): Command to execute. - `args` (list[str]): Command arguments. - `cwd` (str): Working directory. - `env` (dict): Environment variables. - `pty_kwargs` (dict): Keyword arguments passed to the `PTY` constructor. ### Environment Variables - `PYWINPTY_BACKEND`: Overrides the default backend. - `PYWINPTY_BLOCK`: Controls blocking behavior. ### Best Practices [Recommendations for optimal configuration.] ``` -------------------------------- ### PtyProcess exitstatus Property Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/method-signatures.md Gets the exit status of the PtyProcess. ```python @property def exitstatus(self) -> Optional[int] ``` -------------------------------- ### Advanced pywinpty Process Configuration Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/INDEX.md This snippet illustrates advanced configuration options when spawning a process with pywinpty, including working directory, environment variables, dimensions, and backend selection. ```python from winpty import PtyProcess, Backend, MouseMode, AgentConfig proc = PtyProcess.spawn( argv='cmd.exe', cwd='C:\\Users\\User\\MyProject', env={'PYTHONUNBUFFERED': '1'}, dimensions=(40, 120), backend=Backend.ConPTY ) ``` -------------------------------- ### Get Terminal Window Size Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/ptyprocess-class.md Retrieves the current dimensions of the pseudo-terminal window. ```python proc = PtyProcess.spawn('cmd.exe') rows, cols = proc.getwinsize() print(f"Terminal size: {rows}x{cols}") ``` -------------------------------- ### Advanced PtyProcess Configuration Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/README.md Shows how to spawn a process with advanced configuration options including current working directory, environment variables, terminal dimensions, and backend selection. ```python from winpty import PtyProcess, Backend proc = PtyProcess.spawn( argv='cmd.exe', cwd='C:\\Users\\User\\MyProject', env={'PYTHONUNBUFFERED': '1'}, dimensions=(40, 120), # 40 rows x 120 columns backend=Backend.ConPTY ) ``` -------------------------------- ### PTY Class fd Property Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/method-signatures.md Gets the file descriptor (fd) of the PTY. ```python @property def fd(self) -> Optional[int] ``` -------------------------------- ### PTY Class pid Property Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/method-signatures.md Gets the process ID (PID) of the PTY. ```python @property def pid(self) -> Optional[int] ``` -------------------------------- ### Get PtyProcess File Descriptor Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/ptyprocess-class.md Returns the file descriptor number associated with the pseudo-terminal. ```python proc = PtyProcess.spawn('cmd.exe') fd = proc.fileno() print(f"File descriptor: {fd}") ``` -------------------------------- ### Configure PTY Agent Behavior Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/types.md Demonstrates how to initialize a PTY with different agent configurations. Flags can be used individually or combined with bitwise OR for custom behavior. Ensure the WinPTY backend is selected for these flags to be effective. ```python from winpty import PTY, AgentConfig # Enable color escapes (default) pty = PTY(80, 24, backend=1, agent_config=AgentConfig.WINPTY_FLAG_COLOR_ESCAPES) ``` ```python # Combine multiple flags config = ( AgentConfig.WINPTY_FLAG_CONERR | AgentConfig.WINPTY_FLAG_COLOR_ESCAPES ) pty = PTY(80, 24, backend=1, agent_config=config) ``` ```python # Disable escape sequences pty = PTY(80, 24, backend=1, agent_config=AgentConfig.WINPTY_FLAG_PLAIN_OUTPUT) ``` -------------------------------- ### Minimal pywinpty Process Spawning Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/INDEX.md This snippet demonstrates the basic usage of pywinpty to spawn a process, send a command, read its output, and close the process. ```python from winpty import PtyProcess # Spawn a process proc = PtyProcess.spawn('cmd.exe') # Interact with it proc.write('dir\r\n') output = proc.read() print(output) # Clean up proc.close() ``` -------------------------------- ### PTY Class Reference Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/README.md Reference for the low-level `PTY` class, detailing its constructor, instance methods, properties, and usage examples. ```APIDOC ## PTY Class ### Description Complete reference for the low-level `PTY` class, including its constructor, instance methods, and read-only properties. ### Constructor - `PTY(cols, rows, backend, mouse_mode, timeout, agent_config)` - `cols` (int): Number of columns. - `rows` (int): Number of rows. - `backend` (Backend): The PTY backend to use (e.g., `Backend.CONPTY` or `Backend.WINPTY`). - `mouse_mode` (MouseMode): Configuration for mouse input handling. - `timeout` (float): Timeout for I/O operations. - `agent_config` (AgentConfig): Bitwise flags for agent configuration. ### Instance Methods - `method1(...)` - `method2(...)` - ... (8 methods total) ### Properties - `pid` (int): The process ID of the PTY. - `fd` (int): The file descriptor of the PTY. ### Examples [Complete examples for each method will be provided here.] ### Thread Safety [Notes on thread safety considerations.] ``` -------------------------------- ### Comprehensive Error Handling for Process Spawning and I/O Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Demonstrates robust error handling for various scenarios, including command not found, invalid arguments, PTY creation failures, unexpected PTY closure, and I/O errors during process interaction. Ensures resources are cleaned up. ```python from winpty import PtyProcess, WinptyError import os try: proc = PtyProcess.spawn('nonexistent_command.exe') except FileNotFoundError as e: print(f"Command not found: {e}") except TypeError as e: print(f"Invalid argument type: {e}") except WinptyError as e: print(f"PTY creation failed: {e}") try: proc = PtyProcess.spawn('cmd.exe') proc.write('dir\r\n') output = proc.read() except EOFError: print("PTY closed unexpectedly") except WinptyError as e: print(f"I/O error: {e}") finally: try: if 'proc' in locals(): proc.close() except Exception as e: print(f"Error closing PTY: {e}") ``` -------------------------------- ### Spawn Process with Auto Backend Selection Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Automatically selects ConPTY on modern Windows, falling back to WinPTY on older systems. Use this for general process spawning. ```python from winpty import PtyProcess # Automatically selects ConPTY on modern Windows, WinPTY as fallback proc = PtyProcess.spawn('cmd.exe') ``` -------------------------------- ### Configure PtyProcess.spawn() with Full Parameters Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/configuration.md Use this snippet to spawn a new process with custom working directory, environment variables, terminal dimensions, and backend selection. Ensure necessary imports are present. ```python from winpty import PtyProcess, Backend # Full configuration proc = PtyProcess.spawn( argv='python -u -i', cwd='C:\\Users\\User\\MyProject', env={ 'PATH': 'C:\\bin;C:\\Windows\\System32', 'PYTHONUNBUFFERED': '1', 'CUSTOM_VAR': 'value' }, dimensions=(40, 120), # 40 rows x 120 cols backend=Backend.ConPTY ) ``` -------------------------------- ### Get PtyProcess Exit Status Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/ptyprocess-class.md Demonstrates how to retrieve the exit status of a PtyProcess after it has completed execution. Ensure the process has been waited upon before accessing this property. ```python proc = PtyProcess.spawn('cmd.exe') proc.write('exit /b 42\r\n') proc.wait() exit_code = proc.exitstatus print(f"Exit code: {exit_code}") ``` -------------------------------- ### Get Process Exit Status Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/pty-class.md Retrieve the exit status code of a terminated process using `get_exitstatus()`. Returns `None` if the process is still running. ```python pty = PTY(80, 24) pty.spawn(r'C:\Windows\System32\cmd.exe') # ... run process ... if not pty.isalive(): status = pty.get_exitstatus() print(f"Process exited with code: {status}") ``` -------------------------------- ### PTY Initialization with Mouse Mode Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/types.md Shows how to create a PTY instance with automatic mouse mode detection using the WinPTY backend. ```python from winpty import PTY, MouseMode # Create PTY with automatic mouse mode detection pty = PTY(80, 24, backend=1, mouse_mode=MouseMode.WINPTY_MOUSE_MODE_AUTO) ``` -------------------------------- ### Spawn Process with Completely Custom Environment Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Launch a process with a minimal, entirely custom environment. This is useful for isolating processes or ensuring they run with a predictable, stripped-down set of variables. ```python from winpty import PtyProcess # Minimal environment env = { 'PATH': 'C:\\Windows\\System32;C:\\Windows', 'TEMP': 'C:\\Temp', 'USERNAME': 'User' } proc = PtyProcess.spawn( 'cmd.exe', env=env ) ``` -------------------------------- ### PtyProcess with Error Handling Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/README.md Demonstrates how to spawn a process and handle potential errors like WinptyError or EOFError during interaction. Ensures cleanup in the finally block. ```python from winpty import PtyProcess, WinptyError try: proc = PtyProcess.spawn('python -u -i') proc.write('print("Hello")\r\n') print(proc.read()) except WinptyError as e: print(f"Error: {e}") except EOFError: print("Process closed") finally: if 'proc' in locals(): proc.close() ``` -------------------------------- ### Spawn Process for Controlled/Testing Environments Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/configuration.md Use this for controlled or testing environments, specifying dimensions and a timeout. It utilizes the WinPTY backend. ```python proc = PtyProcess.spawn( 'python test.py', dimensions=(24, 80), backend=Backend.WinPTY, timeout=5000 ) ``` -------------------------------- ### Low-Level PTY Control Example Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/module-overview.md Use the PTY class for fine-grained control over terminal operations, custom I/O handling, and performance-critical applications. Requires manual I/O looping. ```python from winpty import PTY import time pty = PTY(80, 24) pty.spawn(r'C:\\Windows\\System32\\cmd.exe') # Manual I/O loop while pty.isalive(): output = pty.read() if output: print(output, end='', flush=True) time.sleep(0.01) ``` -------------------------------- ### Terminate a Process Gracefully and Forcefully Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Demonstrates how to terminate a process using `terminate()` for graceful shutdown (like Ctrl+C) and `terminate(force=True)` for immediate termination if the process doesn't respond. ```python from winpty import PtyProcess import time proc = PtyProcess.spawn('python -u -i') # Graceful termination (Ctrl+C) proc.terminate() time.sleep(0.2) if not proc.isalive(): print("Process terminated") else: # Force termination if needed proc.terminate(force=True) time.sleep(0.2) proc.close() ``` -------------------------------- ### Read Process Output in a Loop Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Implements a basic loop to continuously read output from a running process until it terminates. Ensure a small delay after spawning to allow the process to start. ```python from winpty import PtyProcess import time proc = PtyProcess.spawn('cmd.exe') time.sleep(0.5) # Let process start while proc.isalive(): try: output = proc.read() if output: print(output, end='', flush=True) except EOFError: break time.sleep(0.01) proc.close() ``` -------------------------------- ### PtyProcess.spawn() Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/INDEX.md The most common entry point for creating a new pseudo-terminal process. It allows specifying the command to run, the working directory, environment variables, initial dimensions, and the backend to use. ```APIDOC ## PtyProcess.spawn() ### Description Spawns a new pseudo-terminal process. ### Method Signature ```python PtyProcess.spawn( argv: Union[str, list, tuple], cwd: Optional[str] = None, env: Optional[dict] = None, dimensions: tuple[int, int] = (24, 80), backend: Optional[int] = None ) -> PtyProcess ``` ### Parameters - **argv** (Union[str, list, tuple]) - Required - The command and its arguments to execute. - **cwd** (Optional[str]) - Optional - The current working directory for the new process. - **env** (Optional[dict]) - Optional - A dictionary of environment variables for the new process. - **dimensions** (tuple[int, int]) - Optional - The initial dimensions (rows, columns) of the pseudo-terminal. Defaults to (24, 80). - **backend** (Optional[int]) - Optional - The backend to use. If None, it will be auto-selected. ``` -------------------------------- ### Check Process Status and Window Size Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Verify if a process is running, retrieve its terminal window dimensions, and get its process ID. Also checks for EOF and retrieves the exit status. ```python from winpty import PtyProcess proc = PtyProcess.spawn('cmd.exe') if proc.isalive(): print("Process is running") # Get window size rows, cols = proc.getwinsize() print(f"Terminal: {rows}x{cols}") # Get process ID print(f"PID: {proc.pid}") else: print("Process has exited") # Check for EOF if proc.eof(): print("EOF reached") # Get exit code exit_code = proc.exitstatus print(f"Exit code: {exit_code}") ``` -------------------------------- ### Read Process Output Line-by-Line Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Demonstrates reading output from a process one line at a time using `readline()`. This is useful for processing output that is structured into lines. ```python from winpty import PtyProcess proc = PtyProcess.spawn('cmd.exe') try: while proc.isalive(): line = proc.readline() if line: print(f"Line: {line.rstrip()}") except EOFError: pass proc.close() ``` -------------------------------- ### Interactive Python Session with pywinpty Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Spawn an interactive Python interpreter and send commands to it, reading the output. This allows for dynamic interaction with a Python process. ```python from winpty import PtyProcess proc = PtyProcess.spawn('python -u -i') proc.write('x = 42\\r\\n') proc.read() proc.write('print(x * 2)\\r\\n') output = proc.read() print("Result:", output) proc.write('exit()\\r\\n') proc.wait() ``` -------------------------------- ### get_exitstatus() Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/pty-class.md Retrieves the exit status code of the process. Returns the process exit code if the process has terminated; None if the process is still running or has not started. Raises WinptyError if an error occurs. ```APIDOC ## get_exitstatus() ### Description Retrieves the exit status code of the process. ### Method Signature ```python def get_exitstatus(self) -> Optional[int] ``` ### Returns - `Optional[int]` — The process exit code if the process has terminated; `None` if the process is still running or has not started. ### Raises - `WinptyError` if an error occurs while retrieving the exit status. ### Example ```python pty = PTY(80, 24) pty.spawn(r'C:\Windows\System32\cmd.exe') # ... run process ... if not pty.isalive(): status = pty.get_exitstatus() print(f"Process exited with code: {status}") ``` ``` -------------------------------- ### PtyProcess.spawn() Method Signature Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/INDEX.md The most common entry point for creating a new pseudo-terminal process. Allows specifying command arguments, working directory, environment variables, dimensions, and backend. ```python PtyProcess.spawn( argv: Union[str, list, tuple], cwd: Optional[str] = None, env: Optional[dict] = None, dimensions: tuple[int, int] = (24, 80), backend: Optional[int] = None ) -> PtyProcess ``` -------------------------------- ### PtyProcess.spawn Parameter Constraints Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/method-signatures.md Details the constraints for the `argv`, `cwd`, `env`, `dimensions`, and `backend` parameters when spawning a PtyProcess. ```APIDOC ## PtyProcess.spawn Parameter Constraints ### Parameters - **argv** (str, list, or tuple) - Must be str, list, or tuple - **cwd** (str or None) - Must be valid directory path or None - **env** (dict or None) - Must be dict or None - **dimensions** (tuple) - Must be tuple of 2 positive ints - **backend** (int or None) - Must be 0, 1, or None ``` -------------------------------- ### Get File Descriptor (fd) using PTY Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/pty-class.md Shows how to spawn a process and access its file descriptor or handle number using the `fd` property. This property returns `None` if the file descriptor is not available. ```python pty = PTY(80, 24) pty.spawn(r'C:\Windows\System32\cmd.exe') if pty.fd is not None: print(f"File descriptor: {pty.fd}") ``` -------------------------------- ### PtyProcess Class spawn Method Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/method-signatures.md Class method to spawn a new PtyProcess. Accepts command arguments, working directory, environment, dimensions, and backend. ```python @classmethod def spawn( cls, argv: Union[str, list[str], tuple[str, ...]], cwd: Optional[str] = None, env: Optional[dict[str, str]] = None, dimensions: tuple[int, int] = (24, 80), backend: Optional[int] = None ) -> PtyProcess ``` -------------------------------- ### Get Process ID (PID) using PTY Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/pty-class.md Demonstrates how to spawn a process and retrieve its Process ID (PID) using the `pid` property of the PTY class. Ensure the process has been spawned before accessing this property. ```python pty = PTY(80, 24) pty.spawn(r'C:\Windows\System32\cmd.exe') print(f"Process ID: {pty.pid}") ``` -------------------------------- ### PTY Object Lifetime Management Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/module-overview.md Demonstrates the creation, usage, and deletion of a PTY object. The PTY object allocates a Rust PTY and starts the winpty-agent upon creation, and terminates the agent upon deletion. ```python from winpty import PTY # Creation: allocates Rust PTY, starts winpty-agent pty = PTY(80, 24) # Use: spawns process, reads/writes pty.spawn(r'cmd.exe') pty.write('dir\r\n') # Deletion: __del__ is called, winpty-agent terminates del pty ``` -------------------------------- ### Method Signatures Reference Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/README.md Quick reference for all method signatures, parameter types, return types, and exception hierarchies. ```APIDOC ## Method Signatures ### Description A quick reference for all exported class and method signatures, including parameter types, return types, and exception details. ### Exported Classes and Methods - `PTY` class methods and properties. - `PtyProcess` class methods and properties. ### Signature Details - For each method: - Full signature with parameter names and types. - Return type. - Exceptions raised. - GIL release information. ### Availability Matrix - Table indicating method availability for `PTY` vs `PtyProcess`. ### Backward Compatibility - Notes on backward compatibility and versioning. ``` -------------------------------- ### Select PTY Backend Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/configuration.md Specify the backend to use for PTY creation. Options include ConPTY (0), WinPTY (1), or auto-selection (None). ConPTY is preferred for its speed and native Windows implementation if available. ```python from winpty import PTY, Backend # Explicit ConPTY pty = PTY(80, 24, backend=Backend.ConPTY) # Explicit WinPTY pty = PTY(80, 24, backend=Backend.WinPTY) # Auto-select (default) pty = PTY(80, 24) ``` -------------------------------- ### Standard Import - winpty Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/INDEX.md Import the essential PTY and PtyProcess classes for basic usage. ```python from winpty import PTY, PtyProcess ``` -------------------------------- ### Spawn Process with Custom Environment Variables Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/configuration.md Spawn a process with custom environment variables and a specified working directory. This allows for fine-grained control over the process's execution context. ```python import os env = os.environ.copy() env['PYTHONUNBUFFERED'] = '1' env['CUSTOM_OPTION'] = 'value' proc = PtyProcess.spawn( 'python script.py', env=env, cwd='C:\\project' ) ``` -------------------------------- ### Spawn Process with ConPTY and Fallback to WinPTY Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Attempts to spawn a process using ConPTY and gracefully falls back to WinPTY if ConPTY is unavailable. This ensures broader compatibility. ```python from winpty import PtyProcess, Backend, WinptyError def spawn_with_fallback(cmd): try: return PtyProcess.spawn(cmd, backend=Backend.ConPTY) except WinptyError: print("ConPTY not available, falling back to WinPTY") return PtyProcess.spawn(cmd, backend=Backend.WinPTY) proc = spawn_with_fallback('cmd.exe') ``` -------------------------------- ### Instantiate PTY Class Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/pty-class.md Create a PTY instance with specified dimensions. Optional parameters allow for backend selection (ConPTY or WinPTY), mouse mode configuration for WinPTY, and timeout settings. ```python from winpty import PTY, Backend, MouseMode # Create a 80x24 terminal, auto-selecting backend pty = PTY(cols=80, rows=24) # Create a 120x40 terminal explicitly using ConPTY pty = PTY(cols=120, rows=40, backend=Backend.ConPTY) # Create a terminal with WinPTY, enabling mouse mode pty = PTY(cols=80, rows=24, backend=Backend.WinPTY, mouse_mode=MouseMode.WINPTY_MOUSE_MODE_AUTO) ``` -------------------------------- ### Import Version Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/method-signatures.md Imports the library's version string. ```python from winpty import __version__ # type: str ``` -------------------------------- ### Full Import of PyWinPTY Components Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/module-overview.md Import all available components from the winpty module. This is useful when you need access to all functionalities. ```python from winpty import ( PTY, PtyProcess, Backend, Encoding, MouseMode, AgentConfig, WinptyError, __version__ ) ``` -------------------------------- ### Configuration Enums and Constants Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/module-overview.md Provides enums and constants for configuring backend behavior, character encoding, mouse input, and WinPTY agent options. ```APIDOC ## Configuration Enums and Constants ### Description Provides enums and constants for configuring backend behavior, character encoding, mouse input, and WinPTY agent options. ### Components - `Backend` — Select ConPTY or WinPTY - `Encoding` — Specify character encoding - `MouseMode` — Configure mouse input - `AgentConfig` — Set WinPTY agent options ### Example ```python from winpty import PTY, Backend, MouseMode, AgentConfig pty = PTY( 80, 24, backend=Backend.WinPTY, mouse_mode=MouseMode.WINPTY_MOUSE_MODE_AUTO, agent_config=(AgentConfig.WINPTY_FLAG_CONERR | AgentConfig.WINPTY_FLAG_COLOR_ESCAPES) ) ``` ``` -------------------------------- ### Spawn Process in Custom Working Directory Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Launch a process with a specific current working directory. This is essential for applications that expect to find files or executables in a particular location. ```python from winpty import PtyProcess proc = PtyProcess.spawn( 'cmd.exe', cwd='C:\\Users\\User\\MyProject' ) proc.write('dir\r\n') output = proc.read() print(output) proc.close() ``` -------------------------------- ### Write Multiple Commands to Process Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/usage-patterns.md Send a sequence of commands to a spawned process, reading output after each command. This is useful for scripting interactive sessions. ```python from winpty import PtyProcess import time proc = PtyProcess.spawn('cmd.exe') commands = [ 'cd C:\\Temp\\r\\n', 'dir\\r\\n', 'cls\\r\\n', 'echo Done\\r\\n' ] for cmd in commands: proc.write(cmd) time.sleep(0.5) output = proc.read() print(output) proc.close() ``` -------------------------------- ### Tag Release Version Source: https://github.com/andfoy/pywinpty/blob/main/RELEASE.md Create an annotated tag for the release version. ```bash git tag -a vX.X.X -m "Release vX.X.X" ``` -------------------------------- ### Initialize PTY (Low-level) Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/README.md Use this low-level constructor to initialize a pseudo-terminal with specific dimensions and optional configurations for mouse mode, timeout, and agent settings. ```python PTY(cols, rows, backend=None, mouse_mode=0, timeout=30000, agent_config=4) ``` -------------------------------- ### PTY.spawn Parameter Constraints Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/method-signatures.md Details the constraints for the `appname`, `cmdline`, `cwd`, and `env` parameters when spawning a PTY process. ```APIDOC ## PTY.spawn Parameter Constraints ### Parameters - **appname** (str) - Must be valid file path - **cmdline** (str or None) - Must be valid command line string or None - **cwd** (str or None) - Must be valid directory path or None - **env** (str or None) - Must be null-separated string or None ``` -------------------------------- ### Minimal Import of PyWinPTY Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/module-overview.md Import the essential PTY and PtyProcess classes for basic usage. This is suitable for most common scenarios. ```python from winpty import PTY, PtyProcess # Use either low-level or high-level API pty = PTY(80, 24) proc = PtyProcess.spawn('cmd.exe') ``` -------------------------------- ### PTY Constructor Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/pty-class.md Initializes a new pseudo-terminal instance with specified dimensions and optional backend configurations. ```APIDOC ## PTY.__init__ ### Description Creates a new pseudo-terminal instance with the specified dimensions. ### Method `PTY(cols: int, rows: int, backend: Optional[int] = None, mouse_mode: int = 0, timeout: int = 30000, agent_config: int = 4) -> PTY` ### Parameters #### Path Parameters - `cols` (int) - Required - Number of terminal columns (width) in characters. Must be positive and non-zero. - `rows` (int) - Required - Number of terminal rows (height) in characters. Must be positive and non-zero. - `backend` (Optional[int]) - Optional - PTY backend to use. Set to `0` for ConPTY or `1` for WinPTY. If `None`, the backend is selected automatically based on system availability. ConPTY takes precedence if available. See `winpty.Backend`. - `mouse_mode` (int) - Optional - Mouse input mode for WinPTY backend only. One of `WINPTY_MOUSE_MODE_NONE` (0), `WINPTY_MOUSE_MODE_AUTO` (1), or `WINPTY_MOUSE_MODE_FORCE` (2). See `winpty.MouseMode`. - `timeout` (int) - Optional - Maximum time in milliseconds to wait for the agent to start and for RPC requests. Must be greater than 0. - `agent_config` (int) - Optional - Bitwise combination of WinPTY agent configuration flags. Default enables color escapes (`WINPTY_FLAG_COLOR_ESCAPES`). See `winpty.AgentConfig`. Only effective with WinPTY backend. ### Returns A new `PTY` instance ready to spawn a process. ### Raises `WinptyError` if the pseudo-terminal cannot be created. ### Notes - Optional parameters only take effect when the backend is WinPTY. - ConPTY is the native Windows pseudo-terminal (Windows 10+ build 17134+) and is faster than WinPTY. - WinPTY is a fallback implementation provided by the separate winpty library. - Automatic backend selection depends on compilation flags and runtime system capabilities. ### Example ```python from winpty import PTY, Backend, MouseMode # Create a 80x24 terminal, auto-selecting backend pty = PTY(cols=80, rows=24) # Create a 120x40 terminal explicitly using ConPTY pty = PTY(cols=120, rows=40, backend=Backend.ConPTY) # Create a terminal with WinPTY, enabling mouse mode pty = PTY(cols=80, rows=24, backend=Backend.WinPTY, mouse_mode=MouseMode.WINPTY_MOUSE_MODE_AUTO) ``` ``` -------------------------------- ### Python: Set PYWINPTY_BACKEND environment variable Source: https://github.com/andfoy/pywinpty/blob/main/_autodocs/configuration.md Configure the pywinpty backend by setting the PYWINPTY_BACKEND environment variable in Python before spawning a process. The environment variable overrides the backend parameter. ```python import os from winpty import PtyProcess # Set before spawning os.environ['PYWINPTY_BACKEND'] = '1' # WinPTY proc = PtyProcess.spawn('cmd.exe') # Environment variable overrides the backend parameter proc = PtyProcess.spawn('cmd.exe', backend=0) # Still uses WinPTY ```