This question already has answers here:
Constantly print Subprocess output while process is running
                                
                                    (13个回答)
                                
                        
                                7个月前关闭。
            
                    
我想在python内运行许多shell命令,并且希望它们是即时输出的(类似于它们在bash中出现的方式)。

为此,我正在使用:

import subprocess
cmd='''
x=1
while [ $x -le 5 ]; do
  echo "$x"
  x=$(( $x + 1 ))
  sleep 2
done
'''
out=subprocess.run(cmd,
    check=True, shell=True,stdin=PIPE, stdout=PIPE, stderr=STDOUT)
out.stdout


问题:


但是,只有在脚本结束时才能获得完整的输出。有没有办法随它去做?
如果相关的话,我实际上不需要从运行中得到任何东西(即,不需要用管道输送任何东西)。我应该改用os.system吗?

最佳答案

您可以使用Popen

from subprocess import Popen, PIPE
cmd = '''
x=1
while [ $x -le 5 ]; do
  echo "$x"
  x=$(( $x + 1 ))
  sleep 2
done
'''
out = Popen(
    cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE
).communicate()[0].decode("utf-8")
print(out)

关于python - 即时从python中的subprocess.run()获取输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57147198/

10-11 22:22
查看更多