### PtyProcess.spawn() Example Source: https://context7.com/pexpect/ptyprocess/llms.txt This example demonstrates how to create a temporary file, pass its file descriptor (FD) to a child process spawned by Ptyprocess, and then read the data written by the child. ```APIDOC ## PtyProcess.spawn() with File Descriptor Passing ### Description This example shows how to use `PtyProcess.spawn` to start a child process and pass it a file descriptor (FD) of a temporary file. The child process writes to this FD, and the parent process reads the content after the child finishes. ### Method `PtyProcess.spawn()` ### Endpoint N/A (Local process execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import tempfile import fcntl import os from ptyprocess import PtyProcess # Create a temporary file and pass its FD to the child with tempfile.NamedTemporaryFile(delete=False) as temp: fd = temp.fileno() temp_name = temp.name # Clear close-on-exec flag fcntl.fcntl(fd, fcntl.F_SETFD, fcntl.fcntl(fd, fcntl.F_GETFD) & ~fcntl.FD_CLOEXEC) # Child can write to this FD p = PtyProcess.spawn( ['bash', '-c', f'echo "written by child" >&{fd}'], pass_fds=(fd,) ) while True: try: p.read() except EOFError: break p.wait() # Read what the child wrote with open(temp_name, 'r') as f: print(f"Child wrote: {f.read()}") os.unlink(temp_name) ``` ### Response #### Success Response (Output to stdout) ``` Child wrote: written by child ``` #### Response Example None (This is a script execution example, not an API response) ``` -------------------------------- ### Manage Terminal Window Size (getwinsize, setwinsize) Source: https://context7.com/pexpect/ptyprocess/llms.txt Explains how to get and set the terminal window size using `getwinsize` and `setwinsize`. `getwinsize` returns the dimensions, while `setwinsize` resizes the terminal and notifies the child process with a SIGWINCH signal. ```Python from ptyprocess import PtyProcess # Spawn with custom dimensions p = PtyProcess.spawn(['bash'], dimensions=(40, 120)) # Get current window size rows, cols = p.getwinsize() print(f"Window size: {rows} rows x {cols} cols") # 40 rows x 120 cols # Resize the terminal p.setwinsize(25, 80) rows, cols = p.getwinsize() print(f"New size: {rows} rows x {cols} cols") # 25 rows x 80 cols # Clean up p.write(b'exit\n') p.wait() ``` -------------------------------- ### Send Signals to Child Process Source: https://context7.com/pexpect/ptyprocess/llms.txt Demonstrates the `kill` method for sending signals to a child process. Examples include sending `SIGTERM` for graceful termination and `SIGKILL` for forceful termination, checking the process status afterward. ```python from ptyprocess import PtyProcess import signal import time # Send SIGTERM p = PtyProcess.spawn(['sleep', '3600']) time.sleep(0.1) p.kill(signal.SIGTERM) time.sleep(0.2) if not p.isalive(): print(f"Terminated with signal: {p.signalstatus}") # 15 (SIGTERM) # Send SIGKILL for forceful termination p = PtyProcess.spawn(['sleep', '3600']) time.sleep(0.1) p.kill(signal.SIGKILL) time.sleep(0.2) if not p.isalive(): print(f"Killed with signal: {p.signalstatus}") # 9 (SIGKILL) ``` -------------------------------- ### Wait for Process Exit Source: https://context7.com/pexpect/ptyprocess/llms.txt Illustrates the `wait` method to block until a child process exits. It emphasizes reading all output before calling `wait` to prevent deadlocks. Shows examples for both successful and failing commands. ```python from ptyprocess import PtyProcess # Simple wait p = PtyProcess.spawn(['echo', 'hello']) # Read all output first while True: try: p.read() except EOFError: break # Now wait for exit exit_code = p.wait() print(f"Exit code: {exit_code}") # 0 # Wait on a failing command p = PtyProcess.spawn(['sh', '-c', 'exit 42']) while True: try: p.read() except EOFError: break exit_code = p.wait() print(f"Exit code: {exit_code}") # 42 ``` -------------------------------- ### Spawn PtyProcess: Launching Byte-Based Subprocesses Source: https://context7.com/pexpect/ptyprocess/llms.txt Demonstrates how to spawn a new subprocess using PtyProcess for byte-based I/O. Covers basic spawning, custom environments, working directories, echo settings, and reading output until EOF. Handles cross-platform differences automatically. ```Python from ptyprocess import PtyProcess # Basic spawn - run a shell p = PtyProcess.spawn(['sh']) print(f"PID: {p.pid}, FD: {p.fd}") # Spawn with custom environment and working directory import os custom_env = os.environ.copy() custom_env['MY_VAR'] = 'my_value' p = PtyProcess.spawn( ['bash', '-c', 'echo $MY_VAR && pwd'], cwd='/tmp', env=custom_env, echo=True, dimensions=(40, 120) # rows, columns ) # Read all output until EOF output = b'' while True: try: output += p.read() except EOFError: break print(output.decode()) # Outputs: my_value\n/tmp\n exit_code = p.wait() print(f"Exit code: {exit_code}") ``` -------------------------------- ### spawn - Create a new process Source: https://context7.com/pexpect/ptyprocess/llms.txt Spawns a new process with specific configurations for pre-execution and file descriptor inheritance. ```APIDOC ## spawn ### Description Spawns a new child process with optional pre-execution hooks and file descriptor passing. ### Parameters - **args** (list) - Required - Command and arguments to execute. - **preexec_fn** (callable) - Optional - Function to run in the child process before exec. - **pass_fds** (list) - Optional - List of file descriptors to keep open in the child process. ``` -------------------------------- ### Check Process Status and Exit Source: https://context7.com/pexpect/ptyprocess/llms.txt Demonstrates how to spawn a process using PtyProcess, check if it's alive, wait for its completion, and retrieve its exit status. Handles both successful and quick processes. ```python from ptyprocess import PtyProcess import time # Check a running process p = PtyProcess.spawn(['sleep', '2']) print(f"Process alive: {p.isalive()}") # True # Wait for it to complete time.sleep(2.5) print(f"Process alive: {p.isalive()}") # False print(f"Exit status: {p.exitstatus}") # 0 # Check a quick process p = PtyProcess.spawn(['true']) time.sleep(0.1) print(f"True command alive: {p.isalive()}") # False print(f"Exit status: {p.exitstatus}") # 0 ``` -------------------------------- ### Interactive Session with Unicode Source: https://context7.com/pexpect/ptyprocess/llms.txt Demonstrates an interactive session with a process using Unicode. It spawns a 'bc' process, writes a calculation, waits for processing, reads the output, and then terminates the process. ```Python from ptyprocess import PtyProcessUnicode import time, select p = PtyProcessUnicode.spawn(['bc']) p.write('2+2\n') time.sleep(0.5) # Wait for bc to process output = '' while p.fd in select.select([p.fd], [], [], 0.1)[0]: output += p.read() print(f"Result: {output}") # Contains '4' p.sendeof() p.wait() ``` -------------------------------- ### PtyProcess Class Methods Source: https://github.com/pexpect/ptyprocess/blob/master/docs/api.rst Core methods for interacting with a pseudo-terminal process, including reading, writing, and terminal configuration. ```APIDOC ## PtyProcess Methods ### Description Methods to manage the lifecycle and interaction with a spawned pseudo-terminal process. ### Methods - **spawn(argv, cwd=None, env=None)**: Start a new process. - **read(n=-1)**: Read up to n bytes from the terminal. - **readline()**: Read a single line from the terminal. - **write(s)**: Write a string to the terminal. - **sendcontrol(char)**: Send a control character. - **sendeof()**: Send an EOF signal. - **sendintr()**: Send an interrupt signal. - **getecho() / setecho(state)**: Get or set the terminal echo state. - **getwinsize() / setwinsize(rows, cols)**: Get or set the terminal window size. - **isalive()**: Check if the process is still running. - **wait()**: Wait for the process to terminate. - **close()**: Close the pseudo-terminal. ### Request Example ```python from ptyprocess import PtyProcess p = PtyProcess.spawn(['/bin/bash']) p.write('ls -l\n') print(p.readline()) ``` ``` -------------------------------- ### Run Code Before Exec in Child Source: https://context7.com/pexpect/ptyprocess/llms.txt Explains the `preexec_fn` parameter in `PtyProcess.spawn`, which allows executing a function within the child process before the main command. This is useful for setting up signal handlers or other child-specific configurations. ```python from ptyprocess import PtyProcess import signal def setup_child(): """Reset signal handlers in child process.""" signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGPIPE, signal.SIG_DFL) p = PtyProcess.spawn( ['bash', '-c', 'echo "Child setup complete"'], preexec_fn=setup_child ) while True: try: print(p.read().decode()) except EOFError: break p.wait() ``` -------------------------------- ### Create Temporary File and Pass FD to Child Process (Python) Source: https://context7.com/pexpect/ptyprocess/llms.txt This snippet demonstrates how to create a temporary file, obtain its file descriptor (FD), clear the close-on-exec flag for the FD, and then spawn a child process (bash) that writes to this FD. The parent process later reads the content from the temporary file after the child process has finished. This is useful for inter-process communication where a child process needs to write to a file descriptor that the parent process can access. ```Python import tempfile import fcntl import os from ptyprocess import PtyProcess # Create a temporary file and pass its FD to the child with tempfile.NamedTemporaryFile(delete=False) as temp: fd = temp.fileno() temp_name = temp.name # Clear close-on-exec flag fcntl.fcntl(fd, fcntl.F_SETFD, fcntl.fcntl(fd, fcntl.F_GETFD) & ~fcntl.FD_CLOEXEC) # Child can write to this FD p = PtyProcess.spawn( ['bash', '-c', f'echo "written by child" >&{fd}'], pass_fds=(fd,) ) while True: try: p.read() except EOFError: break p.wait() # Read what the child wrote with open(temp_name, 'r') as f: print(f"Child wrote: {f.read()}") os.unlink(temp_name) ``` -------------------------------- ### Gracefully Terminate Process Source: https://context7.com/pexpect/ptyprocess/llms.txt Shows the `terminate` method for gracefully stopping a child process by sending `SIGHUP`, `SIGCONT`, and `SIGINT`. Includes an option for `force=True` to send `SIGKILL` if the process doesn't respond. ```python from ptyprocess import PtyProcess import time # Graceful termination p = PtyProcess.spawn(['sleep', '3600']) time.sleep(0.1) result = p.terminate(force=False) print(f"Terminated gracefully: {result}") # Forced termination p = PtyProcess.spawn(['sleep', '3600']) time.sleep(0.1) result = p.terminate(force=True) print(f"Terminated with force: {result}") # True print(f"Signal: {p.signalstatus}") ``` -------------------------------- ### Spawn PtyProcessUnicode: Launching Unicode-Aware Subprocesses Source: https://context7.com/pexpect/ptyprocess/llms.txt Illustrates spawning subprocesses with automatic encoding and decoding using PtyProcessUnicode. This class returns unicode strings from read methods and accepts unicode for writing. It supports custom encoding and error handling strategies. ```Python from ptyprocess import PtyProcessUnicode # Spawn with default UTF-8 encoding p = PtyProcessUnicode.spawn(['python3', '-c', 'print("Hello, 世界!")']) output = '' while True: try: output += p.read() except EOFError: break print(output) # Hello, 世界! p.wait() # Handle encoding errors with custom codec_errors p = PtyProcessUnicode.spawn( ['printf', '\344\272!'], codec_errors='backslashreplace' ) result = p.read() print(repr(result)) # '\xe4\xba!' ``` -------------------------------- ### setwinsize / getwinsize Source: https://context7.com/pexpect/ptyprocess/llms.txt Manages terminal window dimensions and notifies the child process via SIGWINCH. ```APIDOC ## setwinsize(rows, cols) ### Description Changes the terminal window size. ### Parameters - **rows** (int) - Required - Number of rows. - **cols** (int) - Required - Number of columns. ## getwinsize() ### Description Returns the current window size. ### Response - **size** (tuple) - Returns (rows, cols). ``` -------------------------------- ### isalive Source: https://context7.com/pexpect/ptyprocess/llms.txt Checks if the child process is currently running. ```APIDOC ## isalive() ### Description Tests if the child process is running. Non-blocking call that updates status attributes. ### Response - **status** (boolean) - True if running, False otherwise. ``` -------------------------------- ### PtyProcess.write: Writing Data to Pseudo-Terminal Source: https://context7.com/pexpect/ptyprocess/llms.txt Describes the `write` method for sending data to a child process via the pseudo-terminal. `PtyProcess` accepts bytes, while `PtyProcessUnicode` accepts unicode strings. The method returns the number of bytes written and flushes by default. ```Python from ptyprocess import PtyProcess, PtyProcessUnicode # Interactive session with bytes p = PtyProcess.spawn(['cat']) p.write(b'Hello\n') output = p.read() print(output) # b'Hello\r\nHello\r\n' (echoed input + cat output) p.sendeof() ``` -------------------------------- ### Spawn and Interact with Python Process in Pty - Python Source: https://github.com/pexpect/ptyprocess/blob/master/README.rst This snippet demonstrates how to spawn a Python subprocess within a pseudo terminal using PtyProcessUnicode. It shows basic interaction by reading output, writing input, and reading subsequent output. This is useful for automating terminal-based applications. ```python from ptyprocess import PtyProcessUnicode p = PtyProcessUnicode.spawn(['python']) p.read(20) p.write('6+6\n') p.read(20) ``` -------------------------------- ### Manage Terminal Echo (getecho, setecho) Source: https://context7.com/pexpect/ptyprocess/llms.txt Explains how to control terminal echo using `getecho` and `setecho`. `getecho` checks if echo is enabled, while `setecho` enables or disables it, which is useful for sensitive inputs like passwords. ```Python from ptyprocess import PtyProcess # Spawn with echo disabled p = PtyProcess.spawn(['cat'], echo=False) print(f"Echo enabled: {p.getecho()}") # False # Enable echo p.setecho(True) print(f"Echo enabled: {p.getecho()}") # True # Disable echo again p.setecho(False) print(f"Echo enabled: {p.getecho()}") # False p.sendeof() while True: try: p.read() except EOFError: break p.wait() ``` -------------------------------- ### PtyProcess.read: Reading Bytes from Pseudo-Terminal Source: https://context7.com/pexpect/ptyprocess/llms.txt Explains the `read` method for `PtyProcess`, which reads bytes from the pseudo-terminal. It blocks if no data is available and raises `EOFError` upon terminal closure, handling platform-specific EOF signals. ```Python from ptyprocess import PtyProcess p = PtyProcess.spawn(['echo', 'Hello, World!']) # Read with default buffer size (1024) try: data = p.read() print(data) # b'Hello, World!\r\n' except EOFError: print("Process ended") # Read with specific size limit p = PtyProcess.spawn(['cat', '/etc/passwd']) chunk = p.read(size=100) # Read at most 100 bytes print(f"Read {len(chunk)} bytes") # Read until EOF pattern p = PtyProcess.spawn(['ls', '-la']) all_output = b'' while True: try: all_output += p.read(2048) except EOFError: break p.wait() ``` -------------------------------- ### Close Process Connection Source: https://context7.com/pexpect/ptyprocess/llms.txt Explains the `close` method to disconnect from a child process and optionally terminate it. It ensures the file descriptor is closed and handles multiple calls safely. Demonstrates closing with and without force. ```python from ptyprocess import PtyProcess # Basic close p = PtyProcess.spawn(['cat']) p.write(b'hello\n') # Read available output import select while p.fd in select.select([p.fd], [], [], 0.5)[0]: try: print(p.read()) except EOFError: break # Close the connection (will terminate cat) p.close(force=True) print(f"Closed: {p.closed}") # True print(f"File descriptor: {p.fd}") # -1 # Safe to call close again p.close() # No error ``` -------------------------------- ### Check if Process is Running (isalive) Source: https://context7.com/pexpect/ptyprocess/llms.txt Describes the `isalive` method, which checks if a child process is currently running. This is a non-blocking call that also updates the process's exit status or signal status if it has terminated. ```Python from ptyprocess import PtyProcess import time # Example usage would follow here, demonstrating isalive checks. ``` -------------------------------- ### Send End-of-File (EOF) Source: https://context7.com/pexpect/ptyprocess/llms.txt Shows how to use the `sendeof` method to send an EOF character (Ctrl-D) to a process's standard input. This is crucial for signaling the end of input to programs like 'cat'. ```Python from ptyprocess import PtyProcess import select # Use sendeof to end input to cat p = PtyProcess.spawn(['cat']) p.write(b'Hello World\n') # Read the echoed input while p.fd in select.select([p.fd], [], [], 0.5)[0]: print(p.read()) # Send EOF to signal end of input p.sendeof() # Read until process ends while True: try: p.read() except EOFError: break exit_code = p.wait() print(f"Exit code: {exit_code}") # 0 ``` -------------------------------- ### PtyProcess.readline: Reading a Single Line from Pseudo-Terminal Source: https://context7.com/pexpect/ptyprocess/llms.txt Details the `readline` method for reading a single, complete line (including the line ending) from the pseudo-terminal. It blocks until a line is available and raises `EOFError` when the terminal closes. ```Python from ptyprocess import PtyProcess, PtyProcessUnicode # Read line by line (bytes) p = PtyProcess.spawn(['cat', '/etc/hostname']) try: line = p.readline() print(f"Hostname: {line.strip().decode()}") except EOFError: pass p.wait() # Read lines with unicode p = PtyProcessUnicode.spawn(['sh', '-c', 'echo "Line 1"; echo "Line 2"']) try: line1 = p.readline() line2 = p.readline() print(f"Got: {line1.strip()}, {line2.strip()}") except EOFError: pass p.wait() ``` -------------------------------- ### setecho / getecho Source: https://context7.com/pexpect/ptyprocess/llms.txt Manages the terminal echo state, useful for password input scenarios. ```APIDOC ## setecho(state) ### Description Enables or disables terminal echo. ### Parameters - **state** (boolean) - Required - True to enable echo, False to disable. ## getecho() ### Description Returns the current terminal echo state. ### Response - **result** (boolean) - Returns True if echo is enabled. ``` -------------------------------- ### terminate - Gracefully terminate the process Source: https://context7.com/pexpect/ptyprocess/llms.txt Attempts to terminate the process gracefully using a sequence of signals, with an optional forced kill. ```APIDOC ## terminate ### Description Attempts to gracefully terminate the child process by sending SIGHUP, then SIGCONT, then SIGINT. If force=True is specified and the process doesn't respond, it sends SIGKILL. ### Parameters - **force** (bool) - Optional - If True, sends SIGKILL if the process does not terminate gracefully. ### Response - **result** (bool) - Returns True if the process was successfully terminated. ``` -------------------------------- ### kill - Send a signal to the child process Source: https://context7.com/pexpect/ptyprocess/llms.txt Sends a specified signal to the child process, allowing for custom process control beyond simple termination. ```APIDOC ## kill ### Description Sends a signal to the child process. It does not necessarily kill the process; the effect depends on the signal sent. ### Parameters - **signal** (int) - Required - The signal constant to send (e.g., signal.SIGTERM, signal.SIGKILL). ``` -------------------------------- ### Send Control Characters Source: https://context7.com/pexpect/ptyprocess/llms.txt Illustrates how to send control characters to a terminal process. The `sendcontrol` method converts a letter into its corresponding ASCII control code, useful for interrupting or signaling processes. ```Python from ptyprocess import PtyProcess # Send Ctrl-C to interrupt a long-running process p = PtyProcess.spawn(['cat']) # cat will wait forever for input p.sendcontrol('c') # Send Ctrl-C (SIGINT) try: p.read() except EOFError: pass p.wait() print(f"Signal status: {p.signalstatus}") # 2 (SIGINT) # Send Ctrl-Z to suspend (SIGTSTP) # p.sendcontrol('z') # Send Ctrl-D for EOF # p.sendcontrol('d') # Send Ctrl-G for bell # p.sendcontrol('g') ``` -------------------------------- ### Wait for Echo to be Disabled (waitnoecho) Source: https://context7.com/pexpect/ptyprocess/llms.txt Details the `waitnoecho` method, which blocks until terminal echo is disabled or a timeout occurs. This is useful for detecting when a program is about to prompt for a password, as echo is typically turned off for such inputs. ```Python from ptyprocess import PtyProcess # Spawn cat with echo disabled p = PtyProcess.spawn(['cat'], echo=False) # Wait for echo to be off (returns immediately since echo=False) result = p.waitnoecho(timeout=2) print(f"Echo is off: {result}") # True p.sendeof() while True: try: p.read() except EOFError: break p.wait() # With echo enabled, waitnoecho will timeout p = PtyProcess.spawn(['cat'], echo=True) result = p.waitnoecho(timeout=1) print(f"Echo turned off within timeout: {result}") # False p.sendeof() while True: try: p.read() except EOFError: break p.wait() ``` -------------------------------- ### Send Interrupt Character (SIGINT) Source: https://context7.com/pexpect/ptyprocess/llms.txt Demonstrates the `sendintr` method, which sends an interrupt character (Ctrl-C) to the terminal. This typically results in a SIGINT signal being sent to the foreground process, usually terminating it. ```Python from ptyprocess import PtyProcess import time # Start a process that runs indefinitely p = PtyProcess.spawn(['sleep', '3600']) # Let it run briefly time.sleep(0.1) # Send interrupt to stop it p.sendintr() # Wait for termination time.sleep(0.2) if not p.isalive(): print("Process terminated by interrupt") print(f"Signal: {p.signalstatus}") # 2 (SIGINT) ``` -------------------------------- ### wait - Wait for process to exit Source: https://context7.com/pexpect/ptyprocess/llms.txt Blocks execution until the child process terminates and returns the exit status. It is critical to read all output before calling wait to avoid deadlocks. ```APIDOC ## wait ### Description Blocks until the child process exits and returns the exit status. Note that this will block forever if the child has unread output, so always read all output before calling wait. ### Method Synchronous Method ### Parameters None ### Response - **exit_code** (int) - The exit status of the child process. ``` -------------------------------- ### Pass File Descriptors to Child Source: https://context7.com/pexpect/ptyprocess/llms.txt Covers the `pass_fds` parameter in `PtyProcess.spawn`, which enables specific file descriptors to remain open in the child process. By default, most file descriptors are closed in the child to isolate it. ```python from ptyprocess import PtyProcess import tempfile import fcntl import os ``` -------------------------------- ### close - Close the connection with the child Source: https://context7.com/pexpect/ptyprocess/llms.txt Closes the file descriptor associated with the child process and optionally terminates it. ```APIDOC ## close ### Description Closes the file descriptor and optionally terminates the child process. Safe to call multiple times. ### Parameters - **force** (bool) - Optional - If True, ensures the child is killed if it does not respond to termination signals. ``` -------------------------------- ### sendcontrol Source: https://context7.com/pexpect/ptyprocess/llms.txt Sends control characters to the terminal by converting a letter to its control code equivalent. ```APIDOC ## sendcontrol(char) ### Description Sends a control character to the terminal. For example, 'c' becomes Ctrl-C (ASCII 3). ### Method Method Call ### Parameters #### Path Parameters - **char** (string) - Required - The character to convert to a control code. ### Request Example ```python p.sendcontrol('c') ``` ``` -------------------------------- ### sendeof Source: https://context7.com/pexpect/ptyprocess/llms.txt Sends an EOF character (typically Ctrl-D) to the terminal to signal end-of-input. ```APIDOC ## sendeof() ### Description Signals end-of-input to programs reading from stdin. Must be sent at the beginning of a line. ### Method Method Call ### Request Example ```python p.sendeof() ``` ``` -------------------------------- ### Check for EOF Encountered Source: https://context7.com/pexpect/ptyprocess/llms.txt Details the `eof` method, which returns `True` if an `EOFError` occurred during a read operation, signaling that the terminal was closed. Shows checking EOF status before and after reading until it occurs. ```python from ptyprocess import PtyProcess p = PtyProcess.spawn(['echo', 'test']) print(f"EOF before read: {p.eof()}") # False # Read until EOF while True: try: p.read() except EOFError: break print(f"EOF after read: {p.eof()}") # True p.wait() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.