andyhasit
andyhasit

Reputation: 15289

Call python script as module with input from bash script

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.

Upvotes: 0

Views: 90

Answers (2)

Philippe
Philippe

Reputation: 26592

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.

Upvotes: 1

jmd_dk
jmd_dk

Reputation: 13100

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)

Upvotes: 1

Related Questions