执行 kubectl 命令时出错 popen/subprocess

Error popen/subprocess with exec kubectl command

我有这个 python 代码:

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')

我有这段代码,当它执行时 returns 在步骤“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

有人可以帮助我吗?

Plain split 不会将引用的字符串放在一起。 shlex.split() 确实如此;但为什么不自己拆分呢?

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

另请注意切换到 subprocess.run;你应该尽可能避免Popen