Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Using a pseudo-terminal to interact with interactive Python in a subprocess
from subprocess import Popen, PIPE
import pty
import os
from select import select
import sys
import tty
master, slave = pty.openpty()
p = Popen(['python'], stdin=slave, stdout=PIPE, stderr=PIPE)
pin = os.fdopen(master, 'w')
msg = ''
errmsg = ''
while True:
rs, ws, es = select([sys.stdin, p.stdout, p.stderr], [], [])
for r in rs:
if r is sys.stdin:
c =
if c == '':
msg = msg[:-1]
elif c == '\n':
print '\r>>> %s' % msg
msg = ''
msg += c
print '\r '+ ' '*(len(msg)+1),
print '\r>>> %s' % msg,
elif r is p.stdout:
print p.stdout.readline(),
elif r is p.stderr:
errmsg +=
if errmsg.endswith('>>> '):
errmsg = errmsg[:-4]
if errmsg.endswith('\n'):
print 'ERR~%s' % (errmsg,),
errmsg = ''
Copy link

lubyagin commented Jan 14, 2018

Thomas, please see my code:
I am writing pseudo-terminal too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment