I am trying to run a docker command as a child process from a Python script using subprocess module, but I get the below error.
b"unknown flag: --mount\r\nSee 'docker buildx build --help'.\r\n"
The script code I am trying to run is,
command = 'docker build -f /root/magneto/docker_env/Dockerfile.build -t magneto_build /root/magneto && docker run -ti --mount src=$(pwd),dst=/tmp/magneto/build,type=bind -e BUILD_NUMBER=${BUILD_NUMBER:-local} magneto_build'
command_args = shlex.split(command)
p = subprocess.Popen(command_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = p.communicate()
The output variable is blank and the error is received in error variable.
I also tried with the pexpect library, just to check if I am using the correct library and functions but that too threw the same error
Please suggest the reason for this and if possible a solution.
The problem is that you are running
shlex.spliton two commands, which obviously need the shell. Basically, you end up runningdocker buildwith arguments like&&anddockerandrunand--mount, rather than runningdocker buildanddocker runas two separate commands.For a more understandable example, compare:
You see?
&&and the otherechocommand and>/dev/nullare all parsed into arguments for the firstecho.(Perhaps
shlex.splitshould warn you if one of the resulting tokens is;or||or&&or>etc; but it is simply not designed to parse entire shell scripts, just individual commands.)Either simply live with
shell=Trueand pass in a string;or painstakingly refactor this to avoid shell features (including, but not limited to, command substitution and variable interpolation).
Notice also how this avoids bare
Popen; like its documentation clearly tells you, you should usesubprocess.run()and friends when you can.Perhaps see also Actual meaning of
shell=Truein subprocess and Running Bash commands in Python