tdk
tdk

Reputation: 342

Input to process using Python

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 ?

Upvotes: 0

Views: 234

Answers (2)

SethMMorton
SethMMorton

Reputation: 48815

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

Upvotes: 1

Nacib Neme
Nacib Neme

Reputation: 889

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

Upvotes: 0

Related Questions