我使用以下命令创建了一个子流程
subprocess.Popen(shlex.split(command), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)它调用的命令将打印各种信息,然后在打印更多信息之前等待\n。最终,当按下\n的次数足够多时,该过程将结束。我需要能够以编程方式模拟按下\n直到该过程结束,以及捕获所有输出。我不希望将输出打印到终端。我希望返回它并将其设置为变量。
我该怎么做呢?
发布于 2013-02-28 02:23:58
如果你只需要写一次stdin,你可以使用
proc = subprocess.Popen(..., stdin = subprocess.PIPE)
proc.stdin.write('\n')但是,如果需要等待提示或以更复杂的方式与子流程交互,则使用pexpect。(pexpect适用于任何POSIX系统,或带有Cygwin的Windows。)
发布于 2013-02-28 03:45:19
试试这条路
from subprocess import Popen, PIPE
import shlex
with open (filename, 'w') as fileHandle
proc = Popen(shlex.split(command), stdin = PIPE, stdout = PIPE, stderr = PIPE)
out, err = proc.communicate(input = '\n')
print out, errhttps://stackoverflow.com/questions/15119188
复制相似问题