Last active
September 28, 2022 12:47
-
-
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
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 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