I have a python script that runs a command in terminal using the subprocess module and this command runs another script that asks for a user input. How can I give a user input to terminal from my original python script?
Example:
contents of introduction.sh below
#!/bin/bash
**# Ask the user for their name**
echo Hello, who am I talking to?
read varname
echo It\'s nice to meet you $varname
running introduction.sh would output the following:
user@bash ./introduction.sh
Hello, who am I talking to?
Ryan
It's nice to meet you Ryan
My python script runs introduction.sh in terminal perfectly fine. What I can't figure out how to do is to run introduction.sh with a name such as Ryan as a user input all from my python script.
I tried using the os module to call introduction.sh and then using os again to give the user input as two separate lines. This strategy runs introduction.sh perfectly fine but treats my second input as an undefined variable and does nothing.
My current script testing.py is below.
import subprocess
subprocess.run(["python3", "testing.py"], shell=True, capture_output=True)
subprocess.run(["Ryan"], shell=True, capture_output=True)
print('done')
There are a number of ways of doing this with the subprocess
package. Here's a simple way to do so:
import subprocess
process = subprocess.Popen('/tmp/introduction.sh', stdin=subprocess.PIPE)
process.communicate("George".encode())
Result:
Hello, who am I talking to?
It's nice to meet you George