I have a command (Say foo) that I normally run from terminal like so:
user@computer$ foo
enter the string: *(here I enter some string)*
RESULT OF THE COMMAND WITH THE GIVEN INPUT
I know beforehand what input I need to give. So, how do I automate the call using this python code:
from subprocess import call
call(['foo'])
How do I automate the input to foo ?
2 Answers 2
You can check out the third-party pexpect module (Here is the API):
import pexpect
child = pexpect.spawn('foo')
child.expect('enter the string:')
child.sendline('STRING YOU KNOW TO ENTER')
child.close() # End Communication
answered Oct 4, 2013 at 1:35
SethMMorton
49.5k13 gold badges72 silver badges90 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Use Popen and communicate:
from subprocess import Popen, PIPE
process = Popen('foo', stdout=PIPE, stderr=PIPE)
(stdout, stderr) = process.communicate("YOUR INPUT HERE")
print stdout
answered Oct 3, 2013 at 18:44
Nacib Neme
8891 gold badge18 silver badges28 bronze badges
3 Comments
tdk
This does not seem to work. I still get the prompt, and now the rest of the code, i.e. RESULT OF THE COMMAND WITH THE GIVEN INPUT does not seem to work
SethMMorton
@user1928721 "Does not seem to work" Please be more specific. It's like going to the doctor and saying "I hurt" and expecting them to diagnose you. State exactly what isn't working. What output do you see? What behavior do you get? What do you expect?
tdk
My sincerest apologies. I am new to the whole world of python and linux programming. I get a prompt prompt for input (i.e. "enter the string:") which is there for more than a minute, so I assume the automated entry has not taken place and manually enter the input. The rest of the code does not seem to run at all (i.e. the cursor just stands there for 10 minutes, and I kill the process because it generally gives me the result ("RESULT OF THE COMMAND WITH THE GIVEN INPUT") within seconds
lang-py
call([input('Enter the string')])in Python 3.x, orcall([raw_input()])for Python 2.x