Skip to content

Commit da40ef9

Browse files
committed
Convert Interactive terminal Python example to sync
1 parent f259abf commit da40ef9

1 file changed

Lines changed: 38 additions & 42 deletions

File tree

docs/sandbox/pty.mdx

Lines changed: 38 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -386,53 +386,49 @@ try {
386386
```
387387

388388
```python Python
389-
import asyncio
390389
import sys
391390
import tty
392391
import termios
393-
from e2b_code_interpreter import AsyncSandbox
394-
from e2b.sandbox_async.commands.pty import PtySize
395-
396-
397-
async def main():
398-
sandbox = await AsyncSandbox.create()
399-
400-
# Save terminal settings
401-
old_settings = termios.tcgetattr(sys.stdin)
402-
403-
try:
404-
# Set terminal to raw mode
405-
tty.setraw(sys.stdin.fileno())
406-
407-
# Write raw bytes directly to stdout (no extra newlines added)
408-
terminal = await sandbox.pty.create(
409-
size=PtySize(cols=80, rows=24),
410-
on_data=lambda data: sys.stdout.buffer.write(data) or sys.stdout.flush(),
411-
timeout=0,
412-
)
413-
414-
# Forward stdin to PTY (simplified - production code needs async stdin reading)
415-
async def read_stdin():
416-
loop = asyncio.get_event_loop()
417-
while True:
418-
data = await loop.run_in_executor(None, sys.stdin.buffer.read, 1)
419-
if data:
420-
await sandbox.pty.send_stdin(terminal.pid, data)
421-
422-
stdin_task = asyncio.create_task(read_stdin())
423-
424-
try:
425-
await terminal.wait()
426-
finally:
427-
stdin_task.cancel()
428-
429-
finally:
430-
# Restore terminal settings
431-
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
432-
await sandbox.kill()
392+
import threading
393+
from e2b_code_interpreter import Sandbox
433394

395+
sandbox = Sandbox()
434396

435-
asyncio.run(main())
397+
# Save terminal settings
398+
old_settings = termios.tcgetattr(sys.stdin)
399+
400+
try:
401+
# Set terminal to raw mode
402+
tty.setraw(sys.stdin.fileno())
403+
404+
# Write raw bytes directly to stdout (no extra newlines added)
405+
terminal = sandbox.pty.create(
406+
cols=80,
407+
rows=24,
408+
on_data=lambda data: sys.stdout.buffer.write(data) or sys.stdout.flush(),
409+
timeout=0,
410+
)
411+
412+
# Forward stdin to PTY in a background thread
413+
stop_event = threading.Event()
414+
415+
def read_stdin():
416+
while not stop_event.is_set():
417+
data = sys.stdin.buffer.read(1)
418+
if data:
419+
sandbox.pty.send_stdin(terminal.pid, data)
420+
421+
stdin_thread = threading.Thread(target=read_stdin, daemon=True)
422+
stdin_thread.start()
423+
424+
# Wait for the terminal to exit
425+
terminal.wait()
426+
427+
finally:
428+
stop_event.set()
429+
# Restore terminal settings
430+
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
431+
sandbox.kill()
436432
```
437433
</CodeGroup>
438434

0 commit comments

Comments
 (0)