繁体   English   中英

如何使用 Python 启动交互式 Docker 容器?

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

我正在使用以交互模式启动的 Docker 映像,如下所示: docker run -it --rm ubuntu bash

我使用的实际图像有许多复杂的参数,这就是为什么我编写了一个脚本来构建完整的docker run命令并为我启动它。 随着逻辑变得越来越复杂,我想将脚本从 bash 迁移到 Python。

使用docker-py ,我准备了一切来运行图像。 但是,似乎不支持docker.containers.run用于交互式 shell。 使用subprocess似乎合乎逻辑,所以我尝试了以下操作:

import subprocess

subprocess.Popen(['docker', 'run', '-it', '--rm', 'ubuntu', 'bash'])

但这给了我:

$ python3 docker_run_test.py 
$ unable to setup input stream: unable to set IO streams as raw terminal: input/output error
$

请注意,错误消息出现在与 python 命令不同的 shell 提示中。

如何使python3 docker_run_test.py相当于运行docker run -it --rm ubuntu bash

您可以使用伪终端读取和写入容器进程

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)

我们可以用这个吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM