2

我想要这样的东西运行'ls'命令并在STDOUT上输出并希望将相同的输出存储在变量中

对于长时间运行的过程,我需要在屏幕上查看执行输出,最后还要捕获变量

proc = subprocess.Popen(["ls"], stdout=subprocess.PIPE, shell=False)
(out, err) = proc.communicate()
print "program output:-", out

这里是执行后的输出

4

1 回答 1

1

要在子进程刷新其标准输出后立即逐行打印输出并将其存储在变量中:

from subprocess import Popen, PIPE

buf = []
proc = Popen([cmd], stdout=PIPE, bufsize=1)
for line in iter(proc.stdout.readline, b''):
    buf.append(line)
    print line,
proc.communicate() # close `proc.stdout`; wait for the child process to exit
output = b"".join(buf)

可能存在缓冲问题(输出出现延迟);要修复它,您可以使用pexpect, ptymodulesstdbuf, unbuffer, scriptcommands

于 2013-09-08T18:08:03.443 回答