Python: How to read stdout of subprocess in a nonblocking way

前端 未结 2 713
予麋鹿
予麋鹿 2020-12-16 02:38

I am trying to make a simple python script that starts a subprocess and monitors its standard output. Here is a snippet from the code:

process = subprocess.P         


        
2条回答
  •  無奈伤痛
    2020-12-16 03:16

    You could try this:

    import subprocess
    import os
    
    """ Continuously print command output """
    """ Will only work if there are newline characters in the output. """
    
    def run_cmd(command):    
        popen = subprocess.Popen(command, stdout=subprocess.PIPE)
        return iter(popen.stdout.readline, b"")
    
    for line in run_cmd([path_to_exe, os.path.join(temp_dir,temp_file)]):
        print(line), # the comma keeps python from adding an empty line
    

提交回复
热议问题