0

我有一个通常从终端运行的命令(说 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 ?

4

2 回答 2

1

您可以查看第三方pexpect模块(这里是 API):

import pexpect
child = pexpect.spawn('foo')
child.expect('enter the string:')
child.sendline('STRING YOU KNOW TO ENTER')
child.close() # End Communication
于 2013-10-04T01:35:30.337 回答
0

使用Popencommunicate

from subprocess import Popen, PIPE

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

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

print stdout
于 2013-10-03T18:44:37.413 回答