16

考虑这个shell示例:

echo "hello" | docker run --rm -ti  -a stdin busybox \
    /bin/sh -c "cat - >/out"

这将执行一个 busybox 容器并创建一个包含/out内容的新文件hello

我将如何使用 docker-py 完成此任务?

docker-py等价物:

container = docker_client.create_container( 'busybox',
                                            stdin_open = True,
                                            command    = 'sh -c "cat - >/out"'
                                            )
docker_client.start( container )

stdin_open = True,但我在哪里写'hello'

4

2 回答 2

7

当时不可能将标准输入附加到正在运行的容器。这已经改变了。

使用当前版本的 docker-py,这现在以某种方式成为可能(又名 slix 的解决方法)。这取自GitHub 上的一个讨论,该讨论专注于 python 2.7。

请参阅带有 docker-py 版本 3.1.1 的 python 3 中的此示例

import docker, tarfile
from io import BytesIO

def test_send_data_via_stdin_into_container():
    client = docker.APIClient()

    # create container
    container = client.create_container(
        'busybox',
        stdin_open = True,
        command    = 'sh -c "cat - >/received.txt"')
    client.start(container)

    # attach stdin to container and send data
    original_text_to_send = 'hello this is from the other side'
    s = client.attach_socket(container, params={'stdin': 1, 'stream': 1})
    s._sock.send(original_text_to_send.encode('utf-8'))
    s.close()

    # stop container and collect data from the testfile
    client.stop(container)
    client.wait(container)
    raw_stream,status = client.get_archive(container,'/received.txt')
    tar_archive = BytesIO(b"".join((i for i in raw_stream)))
    t = tarfile.open(mode='r:', fileobj=tar_archive)
    text_from_container_file = t.extractfile('received.txt').read().decode('utf-8')
    client.remove_container(container)

    # check for equality
    assert text_from_container_file == original_text_to_send

if __name__ == '__main__':
    test_send_data_via_stdin_into_container()
于 2015-05-02T20:32:18.677 回答
1

这是一个更新的解决方案:

#!/usr/bin/env python
import docker

# connect to docker
client = docker.APIClient()

# create a container
container = docker_client.create_container(
  'busybox',
  stdin_open = True,
  command    = 'sh -c "cat - >/out"')
client.start(container)

# attach to the container stdin socket
s = client.attach_socket(container, params={'stdin': 1, 'stream': 1})

# send text
s.send('hello')

# close, stop and disconnect
s.close()
client.stop(container)
client.wait(container)
client.remove_container(container)
于 2019-01-15T11:53:57.570 回答