1.使用readline可以實現
import subprocess
def run_shell(shell):
cmd = subprocess.Popen(shell, stdin=subprocess.PIPE, stderr=subprocess.PIPE,
stdout=subprocess.PIPE, universal_newlines=True, shell=True, bufsize=1)
# 實時輸出
while True:
line = cmd.stdout.readline()
print(line, end='')
if subprocess.Popen.poll(cmd) == 0: # 判斷子進程是否結束
break
return cmd.returncode
if __name__ == '__main__':
print(run_shell("ping www.baidu.com"))
2.readline可能導致卡死,官方推薦使用communicate,但是如果還是使用subprocess.PIPE,執行完命令后才能拿到標准輸出,替換成sys.stdout就能達到實時輸出效果,代碼附上
import subprocess
import sys
def run_shell(shell):
cmd = subprocess.Popen(shell, stdin=subprocess.PIPE, stderr=sys.stderr, close_fds=True,
stdout=sys.stdout, universal_newlines=True, shell=True, bufsize=1)
cmd.communicate()
return cmd.returncode
if __name__ == '__main__':
print(run_shell("ping www.baidu.com"))