python執行shell實時輸出


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"))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM