Skip to content
Advertisement

How to make python script type when prompted on shell

Something similar to this: How to make python script press ‘enter’ when prompted on Shell

Like that question, if I have test_enter.py:

print("press enter...")
input()
print("yay!")

and this file:

from subprocess import Popen, PIPE
p = Popen(['python test_enter.py'], stdin=PIPE, shell=True)
p.communicate(input=b'n')

But instead of just a new line, I want it to type something then press “enter”. Is that possible?

Advertisement

Answer

Script to call:

print("write something here")
inserted_string = input()
print("You wrote: " + inserted_string)

Caller script:

from subprocess import Popen, PIPE
import sys

print("custom insert here...")
inserted1 = input()

if len(sys.argv) > 1:
  inserted2 = sys.argv[1]
else:
  inserted2 = 'nothing here'

p1 = Popen(['python script_to_call.py'], stdin=PIPE, shell=True)
p1.communicate(input=b'standard stringn')

print(" --- ")

p2 = Popen(['python script_to_call.py'], stdin=PIPE, shell=True)
p2.communicate(input=inserted1.encode('utf-8') + b'n')

print(" --- ")

p3 = Popen(['python script_to_call.py'], stdin=PIPE, shell=True)
p3.communicate(input=inserted2.encode('utf-8') + b'n')

Run command

python caller.py "string got from parameter"

Output:

custom insert here...
string got from input

write something here
You wrote: standard string
 --- 
write something here
You wrote: string got from input
 --- 
write something here
You wrote: string got from parameter

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement