I'm trying to create run a containerized application using docker-py, and I need to write input data to its STDIN, and read from its STDOUT. Basically this kind of workflow
echo "hello" | docker run -i --rm busybox sh -c "cat -"
but in Python. In short, I've tried the method described here for the STDIN part, and attached another socket for the STDOUT part. But it does not work as well as I hoped... Here is a minimal example:
docker_test.py
#!/usr/bin/env python
import docker
client = docker.DockerClient()
container = client.containers.run(
auto_remove=True,
command="cat -",
detach=True,
image="busybox",
stdin_open=True,
)
# Writing to stdin
input_socket = container.attach_socket(
params={
"stdin":True,
"stream":True,
},
)
with open("test.txt") as file:
input_socket._sock.send(file.readline().encode("utf-8"))
# Reading from stdout
output_socket = container.attach_socket(
params={
"stdout":True,
"stream":True,
"logs":True,
},
)
for line in output_socket:
print(line.decode())
a dummy test.txt
1
2
3
4
and the result of the execution:
$ ./docker_test.py
1
As you can see, it only outputs the first line of the test file, followed by a bunch of newlines, and hangs. Sometimes, it doesn't output anything at all, but in either case, it never exits.
How do I do this correctly? Any help would be greatly appreciated.
Thanks in advance!