Skip to content

Instantly share code, notes, and snippets.

@metakirby5
Last active September 28, 2022 12:47
Show Gist options
  • Save metakirby5/d33138ca4f79f9f809dc7d1ee73c1dc0 to your computer and use it in GitHub Desktop.
Save metakirby5/d33138ca4f79f9f809dc7d1ee73c1dc0 to your computer and use it in GitHub Desktop.
How to simulate user input on an interpreter using a Python's pty module
import os, sys, subprocess, pty, select, re
BUFSIZ = 1024
MAGIC = '\004\004' # ctrl-D x2
escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]')
data = '\n'.join([
'1 + 1',
'2000',
'(function() {})',
'"yee"',
]) + '\n' + MAGIC
master, slave = pty.openpty()
p = subprocess.Popen('node',
stdin=slave,
stdout=slave,
stderr=subprocess.STDOUT)
while p.poll() is None:
r, w, _ = select.select([master], [master], [], 0)
if r:
sys.stdout.write(escape.sub('', os.read(master, BUFSIZ)))
if w and data:
data = data[os.write(master, data):]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment