Getting realtime output using subprocess

前端 未结 18 2793
执笔经年
执笔经年 2020-11-22 10:12

I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation. This requires me to be abl

18条回答
  •  情深已故
    2020-11-22 10:51

    This is the basic skeleton that I always use for this. It makes it easy to implement timeouts and is able to deal with inevitable hanging processes.

    import subprocess
    import threading
    import Queue
    
    def t_read_stdout(process, queue):
        """Read from stdout"""
    
        for output in iter(process.stdout.readline, b''):
            queue.put(output)
    
        return
    
    process = subprocess.Popen(['dir'],
                               stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT,
                               bufsize=1,
                               cwd='C:\\',
                               shell=True)
    
    queue = Queue.Queue()
    t_stdout = threading.Thread(target=t_read_stdout, args=(process, queue))
    t_stdout.daemon = True
    t_stdout.start()
    
    while process.poll() is None or not queue.empty():
        try:
            output = queue.get(timeout=.5)
    
        except Queue.Empty:
            continue
    
        if not output:
            continue
    
        print(output),
    
    t_stdout.join()
    

提交回复
热议问题