Created
June 4, 2025 15:29
-
-
Save ronaldpetty/8a36235ccd73cafabed4f7f57e080236 to your computer and use it in GitHub Desktop.
File Description Wrappers and REPL Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess | |
import os | |
import time | |
# Start the Python REPL in interactive mode, with a pipe for stdin and stdout | |
proc = subprocess.Popen( | |
["python3", "-i"], | |
stdin=subprocess.PIPE, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.STDOUT # Merge stderr into stdout for simplicity | |
) | |
# Get file descriptors | |
stdin_fd = proc.stdin.fileno() | |
stdout_fd = proc.stdout.fileno() | |
# Wrap both FDs with high-level I/O objects | |
stdin = open(stdin_fd, "w", encoding="utf-8", closefd=False) | |
stdout = open(stdout_fd, "r", encoding="utf-8", closefd=False) | |
# Send a command to the REPL | |
stdin.write("2 + 2\n") | |
stdin.flush() | |
# Give it time to respond | |
time.sleep(0.2) | |
# Read output | |
output = [] | |
while True: | |
line = stdout.readline() | |
if not line.strip(): | |
break | |
output.append(line) | |
if ">>>" in line: | |
break | |
print("REPL output:\n", "".join(output)) | |
# Clean up | |
stdin.write("exit()\n") | |
stdin.flush() | |
proc.wait() | |
# % python3 repl.py | |
# REPL output: | |
# Python 3.11.1 (v3.11.1:a7a450f84a, Dec 6 2022, 15:24:06) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin | |
# Type "help", "copyright", "credits" or "license" for more information. | |
# >>> 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment