Skip to content

Instantly share code, notes, and snippets.

@jvns
Last active May 7, 2025 15:01
Show Gist options
  • Select an option

  • Save jvns/fe878425a1663132b0ed1153b55bb73e to your computer and use it in GitHub Desktop.

Select an option

Save jvns/fe878425a1663132b0ed1153b55bb73e to your computer and use it in GitHub Desktop.
import os, pty, subprocess, time
# Ask the OS to create a new "pseudoterminal pair"
# The shell is going to have the "tty" end and the terminal emulator is going to have the
# "pseudoterminal master" ("ptmx") end
ptmx, tty = pty.openpty()
shell_process = subprocess.Popen(
["/bin/bash"], stdin=tty, stdout=tty, stderr=tty, text=False, close_fds=True
)
# send a command to the shell
# (in real life you would wait for the user to type things in and write what they typed in)
os.write(ptmx, b"echo 'Hello from shell'\n")
# wait a bit for the command to execute
time.sleep(0.5)
# read the response and print it out
# (in real life you would implement a GUI and display this to the screen)
response = os.read(ptmx, 1024)
print(response.decode("utf-8"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment