Python subprocess在stdin中写入新行直到进程结束

4 投票
2 回答
5901 浏览
提问于 2025-04-17 17:20

我创建了一个子进程,使用的是

subprocess.Popen(shlex.split(command), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

这个命令会打印出各种信息,然后会等待你按下一个\n(换行键),才会继续打印更多的信息。最终,当\n被按下足够多次后,这个进程就会结束。我需要能够通过编程的方式模拟按下\n,直到进程结束,同时还要捕获所有的输出。我不想让输出显示在终端上,而是希望能把它返回并存储到一个变量里。

我该怎么做呢?

2 个回答

0

试试这个方法

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, err
3

如果你只需要写一次数据到 stdin,你可以使用下面的代码:

proc = subprocess.Popen(..., stdin = subprocess.PIPE)
proc.stdin.write('\n')

但是,如果你需要等待提示或者以更复杂的方式与子进程互动,那就可以使用 pexpect 这个工具。

(pexpect 可以在任何 POSIX 系统上使用,或者在安装了 Cygwin 的 Windows 上使用。)

撰写回答