Constantly print Subprocess output while process is running

后端 未结 13 1011
庸人自扰
庸人自扰 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:38

    Ok i managed to solve it without threads (any suggestions why using threads would be better are appreciated) by using a snippet from this question Intercepting stdout of a subprocess while it is running

    def execute(command):
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    
        # Poll process for new output until finished
        while True:
            nextline = process.stdout.readline()
            if nextline == '' and process.poll() is not None:
                break
            sys.stdout.write(nextline)
            sys.stdout.flush()
    
        output = process.communicate()[0]
        exitCode = process.returncode
    
        if (exitCode == 0):
            return output
        else:
            raise ProcessException(command, exitCode, output)
    

提交回复
热议问题