从子进程读取stdout,直到没有任何内容

2024-09-28 19:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在同一个shell中运行几个命令。经过一些研究,我发现我可以使用Popen中的返回过程来保持shell打开。然后我可以对stdin和{}进行读写操作。我试着这样做:

process = Popen(['/bin/sh'], stdin=PIPE, stdout=PIPE)
process.stdin.write('ls -al\n')
out = ' '
while not out == '':
    out = process.stdout.readline().rstrip('\n')
    print out

我的解决方案不仅难看,而且行不通。out从不为空,因为它处理readline()。当没有任何内容可供阅读时,如何才能成功结束while循环?在


Tags: 命令readlinebin过程shstdinstdoutshell
2条回答

在子进程中运行的命令是sh,因此您读取的输出是sh的输出。由于您没有向shell指示它应该退出,它仍然是活动的,因此它的stdout仍然是打开的。在

您可以将exit写入其stdin以使其退出,但请注意,在任何情况下,您都可以从它的stdout中读取不需要的内容,例如提示符。在

总之,这种方法从一开始就有缺陷。。。在

使用iter实时读取数据:

for line in iter(process.stdout.readline,""):
   print line

如果您只想写入stdin并获得输出,您可以使用communicate来结束进程:

^{pr2}$

或者只需使用check_output获得输出:

from subprocess import check_output

out = check_output(["ls", "-al"])

相关问题 更多 >