How do I use Python to launch an interactive Docker container? How do I use Python to launch an interactive Docker container? docker docker

How do I use Python to launch an interactive Docker container?


You can use a pseudo-terminal to read from and write to the container process

import ptyimport sysimport selectimport osimport subprocesspty, 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)


Can we use this ?

import osos.system('docker run -it --rm ubuntu bash')