import pty
import sys
import select
import os
import subprocess
pty, tty = pty.openpty()
p = subprocess.Popen(['docker', 'run', '-it', '--rm', 'ubuntu', 'bash'], stdin=tty, stdout=tty, stderr=tty)
while p.poll() is None:
# Watch two files, STDIN of your Python process and the pseudo terminal
r, _, _ = select.select([sys.stdin, pty], [], [])
if sys.stdin in r:
input_from_your_terminal = os.read(sys.stdin.fileno(), 10240)
os.write(pty, input_from_your_terminal)
elif pty in r:
output_from_docker = os.read(pty, 10240)
os.write(sys.stdout.fileno(), output_from_docker)