Home > Back-end >  Python2.7 use subprocess.Popen to kubectl exec into the bash of a pod not working
Python2.7 use subprocess.Popen to kubectl exec into the bash of a pod not working

Time:06-30

previously I was using a python statement like os.system("kubectl exec --it bash xxx") to exec into a kubernetes pod, it ends up redirect me to the bash of the pod and I could type commands directly. Someone recommended using subprocess.Popen instead because it is safer, so I tried something like

subprocess.Popen(["kubectl", "exec"]   kube_args   ["-it", pod_name, "--", "bash"],
             stdout=subprocess.PIPE)

the python script run through, but it end up like nothing has happened(not redirecting me to the interactive bash of the pod. What should be the correct equivalent of the command in order to achieve this? Thank you.

CodePudding user response:

That's the primitive, and you're calling it correctly. You get back a subprocess sub, which you can further interact with:

proc = Popen( ... )

or better:

with Popen( ... ) as proc:

There are some convenience functions layered on top of the primitive. check_call() makes the most sense, here. It will patiently wait for the child to die, typically when you type "exit" at the remote bash. It calls Popen() for you and manages the details, so you don't have to.

  • Related