Python 优雅的使用 subprocess.Popen 获取实时输出,以及中止 subprocess

# -*- coding: utf-8 -*-

import shlex
import os
import signal
import time
import threading
from subprocess import Popen, PIPE

def run_command(command):
    process = Popen(shlex.split(command), stdout=PIPE)
    st = time.time()
    while True:
        output = process.stdout.readline().rstrip().decode('utf-8')
        if output == '' and process.poll() is not None:
            break
        if output:
            print(output.strip())

        if time.time() - st > 3:
            os.kill(process.pid, signal.CTRL_C_EVENT)
            break

    rc = process.poll()
    return rc

if __name__ == "__main__":
    t = threading.Thread(target=run_command, args=("ping baidu.com",))
    t.start()
posted @ 2023-08-14 18:46  可乐芬达  阅读(3335)  评论(0编辑  收藏  举报