使用Python进行处理的输入

时间:2013-10-03 18:41:10

标签: python process subprocess

我有一个命令(Say foo),我通常从终端运行,如下所示:

    user@computer$ foo
    enter the string: *(here I enter some string)*
    RESULT OF THE COMMAND WITH THE GIVEN INPUT

我事先知道需要提供什么输入。那么,我如何使用这个python代码自动化调用:

   from subprocess import call
   call(['foo'])

如何自动输入foo?

2 个答案:

答案 0 :(得分:1)

您可以查看第三方pexpect模块(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

答案 1 :(得分:0)

使用Popencommunicate

from subprocess import Popen, PIPE

process = Popen('foo', stdout=PIPE, stderr=PIPE)

(stdout, stderr) = process.communicate("YOUR INPUT HERE")

print stdout