Constantly print Subprocess output while process is running

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

    @tokland

    tried your code and corrected it for 3.4 and windows dir.cmd is a simple dir command, saved as cmd-file

    import subprocess
    c = "dir.cmd"
    
    def execute(command):
        popen = subprocess.Popen(command, stdout=subprocess.PIPE,bufsize=1)
        lines_iterator = iter(popen.stdout.readline, b"")
        while popen.poll() is None:
            for line in lines_iterator:
                nline = line.rstrip()
                print(nline.decode("latin"), end = "\r\n",flush =True) # yield line
    
    execute(c)
    

提交回复
热议问题