我有一个命令(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?
答案 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)
使用Popen
和communicate
:
from subprocess import Popen, PIPE
process = Popen('foo', stdout=PIPE, stderr=PIPE)
(stdout, stderr) = process.communicate("YOUR INPUT HERE")
print stdout