我想在同一个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
循环?在
在子进程中运行的命令是
sh
,因此您读取的输出是sh
的输出。由于您没有向shell指示它应该退出,它仍然是活动的,因此它的stdout仍然是打开的。在您可以将
exit
写入其stdin
以使其退出,但请注意,在任何情况下,您都可以从它的stdout
中读取不需要的内容,例如提示符。在总之,这种方法从一开始就有缺陷。。。在
使用iter实时读取数据:
如果您只想写入stdin并获得输出,您可以使用communicate来结束进程:
^{pr2}$或者只需使用
check_output
获得输出:相关问题 更多 >
编程相关推荐