0

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 ?

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

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
@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?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.