Issue
I have a simple Python script that asks the user for an ID and returns a serial number:
...
id = input("Enter ID (0-indexed):\n")
...
print(serial_number)
I'm using this .py script inside of a larger bash script via command substitution:
serial_number=$(./get_serial_no.py)
echo "$serial_number"
The problem I'm facing is the following: since command substitution takes the entire output of the command as input, the input prompt inside the Python script is also stored in the serial_number
variable and never gets displayed on screen (until the echo
). Therefore, if I run the shell script, the console waits for input without giving me a prompt. Is there a way to separate the Python prompt from the value that I want returned via command substitution (i.e. the serial number)? The only things I can think of is either write the serial number to another file, or ask for input inside of the shell script and pass the ID as an option to the Python script.
Solution
I recommend against prompts if you are using a python script in a shell script. Use command-line options with a library such as argparse
. It is so much easier, plus you get input validation as a bonus:
import argparse
parser.add_argument(
'-s',
'--serial_number',
type = int,
default = 12345,
required = False,
help = re.sub(
r'\s+', r' ',
'''Serial number (default: %(default)s)'''))
options = parser.parse_args()
print(optiions.serial_number)
Answered By - Timur Shtatland Answer Checked By - Marie Seifert (WPSolving Admin)