0

Below is my sample c program

    #include <stdio.h>
    int main()
    {
      int x, y, z;
      scanf("%d%d", &x, &y);
      printf("%d,%d" ,x,y);
      z = x + y;
      printf("%d", z);
      return 0;
    }

I am able to compile the program and build the image( docker build -t sample_c .). Now while running the container I wanted to pass the input parameters as echo to the container. How I can achieve that using python docker

echo "1 2" | ./c_executable ( passing input values to executable file)

In the python shell I am trying to run the container and pass parameters as shown. Getting the results but x and y values are taken as some random numbers.

>>> import docker
>>> client = docker.from_env()
>>> client.containers.run(image='sample_c',command='echo "1 2" | ',entrypoint='/opt/c_build_dir/c_executable')
b'21911,14414231201441445031'
>>> client.containers.run(image='sample_c',command='echo "1 2" | /opt/c_build_dir/c_executable')
b'1 2 | /opt/c_build_dir/c_executable\n'

How I can achieve that using python docker??

1 Answers1

1

If your main container process uses any shell functionality (pipes, redirection, environment variable expansion) you need to manually include the shell yourself. The Bourne shell sh -c option will run a single inline command.

client.containers.run(
  image='sample_c',
  command=['sh', '-c', 'echo "1 2" | /opt/c_build_dir/c_executable']
)

The command option can be either a string or a list; if you use a list (recommended) then you need to manually break the command into separate words, but having done that, you don't need to further escape things.

David Maze
  • 130,717
  • 29
  • 175
  • 215