Constantly print Subprocess output while process is running

后端 未结 13 1017
庸人自扰
庸人自扰 2020-11-22 06:51

To launch programs from my Python-scripts, I\'m using the following method:

def execute(command):
    process = subprocess.Popen(command, shell=True, stdout=s         


        
13条回答
  •  爱一瞬间的悲伤
    2020-11-22 07:49

    You can use iter to process lines as soon as the command outputs them: lines = iter(fd.readline, ""). Here's a full example showing a typical use case (thanks to @jfs for helping out):

    from __future__ import print_function # Only Python 2.x
    import subprocess
    
    def execute(cmd):
        popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
        for stdout_line in iter(popen.stdout.readline, ""):
            yield stdout_line 
        popen.stdout.close()
        return_code = popen.wait()
        if return_code:
            raise subprocess.CalledProcessError(return_code, cmd)
    
    # Example
    for path in execute(["locate", "a"]):
        print(path, end="")
    

提交回复
热议问题