Running shell commands from Python and printing the output in real time

后端 未结 3 1965
囚心锁ツ
囚心锁ツ 2021-01-16 06:07

I want to write a function that will execute multiple shell commands one at a time and print what the shell returns in real time.

I currently have the following code

3条回答
  •  旧时难觅i
    2021-01-16 06:43

    Assuming you want control of the output in your python code you might need to do something like this

    import subprocess
    
    def run_process(exe):
        'Define a function for running commands and capturing stdout line by line'
        p = subprocess.Popen(exe.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        return iter(p.stdout.readline, b'')
    
    
    if __name__ == '__main__':
        commands = ["foo", "foofoo"]
        for command in commands:
            for line in run_process(command):
                print(line)
    

提交回复
热议问题