Error popen/subprocess with exec kubectl command

5/5/2021

I have this python codes:

command = "kubectl exec -it " + jmeter_pod + " -n " + namespace + " -- bash -c \"echo "+ ext_ip_lfe +">nelshost\" "
process = subprocess.Popen(command.split(' '), stdout=subprocess.PIPE)
output = process.communicate()[0].decode('utf-8')

I have this code that when executed it returns this error at step "proces = ..." :

10.117.142.201>nelshost": -c: line 0: unexpected EOF while looking for matching `"'
10.117.142.201>nelshost": -c: line 1: syntax error: unexpected end of file
command terminated with exit code 1

can someone help me?

-- giuseppe percuoco
docker
kubectl
kubernetes
popen
python

1 Answer

5/5/2021

Plain split doesn't keep quoted strings together. shlex.split() does; but why not just split it yourself?

output = subprocess.run(
    [ "kubectl", "exec", "-it", jmeter_pod,
      "-n", namespace, "--",
      "bash", "-c", "echo "+ ext_ip_lfe +">nelshost\" "],
    text=True, check=True,
    capture_output=True).stdout

Notice also the switch to subprocess.run; you should avoid Popen always when you can.

-- tripleee
Source: StackOverflow