0

From a bash function, I want to call a python script which prompts for input, and I need to run that script as a module using python -m

Here is select_pod.py

# above this will be a print out of pods
pod = input('Pick pod')
print(pod)

Here is the bash function:

function foo() {
  POD=$(python3 -m select_pod)
  kubectl exec $POD --stdin --tty bash
}

I can't get the input to work, i.e. "Pick pod" is not printed to the terminal.

2 Answers 2

1

When you do POD=$(python3 -m select_pod), the POD=$(...) means that any output printed to stdout within the parentheses will be captured within the POD variable instead of getting printed to the screen. Simply echoing out POD is no good, as this will first be done once the Python script has finished.

What you need to do is to duplicate the output of the Python program. Assuming Linux/Posix, this can be done using e.g.

POD=$(python3 -m select_pod | tee /dev/stderr)

Because your terminal shows both stdout and stderr, duplicating the output from stdout to stderr makes the text show up.

Hijacking the error channel for this might not be ideal, e.g. if you want to later sort the error messages using something like 2> .... A different solution is to just duplicate it directly to the tty:

POD=$(python3 -m select_pod | tee /dev/tty)
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah that worked, thanks. $POD will indeed contain the full stdout but I can split that and grab the last piece.
1

You can change sys.stdout before input :

import sys
save_sys_stdout = sys.stdout
sys.stdout = sys.stderr
pod = input('Pick pod')
sys.stdout = save_sys_stdout
print(pod)

So that POD=$(python3 -m select_pod) will work and you don't need to do split after.

1 Comment

I thought about going down that road, but that's unfortunately not an option for my use case as I won't be in control of the python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.