Take the 2-minute tour ×

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)*

I know beforehand what input I need to give. So, how do I automate the call using this python code:

   from subprocess import call

How do I automate the input to foo ?

share|improve this question
call([input('Enter the string')]) in Python 3.x, or call([raw_input()]) for Python 2.x –  karthikr Oct 3 '13 at 18:44
this has no reference to foo. How do I call it? –  tdk Oct 3 '13 at 22:33
@user1928721 Don't use the method in the comment above. It's not what you want. –  SethMMorton Oct 4 '13 at 1:30
add comment

2 Answers

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
share|improve this answer
add comment

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
share|improve this answer
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 –  tdk Oct 3 '13 at 22:32
@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? –  SethMMorton Oct 4 '13 at 1:31
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 –  tdk Oct 4 '13 at 9:18
add comment

Your Answer


