16

このシェルの例を検討してください:

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

当時は、実行中のコンテナーに stdin をアタッチすることはできませんでした。これは変更されました。

現在のバージョンの docker-py では、これが何とか可能になりました (別名 slix の回避策)。これは、Python 2.7 に焦点を当てたGitHubでの議論から取られています。

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 に答える