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

后端 未结 3 1865
囚心锁ツ
囚心锁ツ 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:25

    I believe you need something like this

    commands = ["foo", "foofoo"]
    p = subprocess.Popen("cmd.exe", shell=True, stdin=subprocess.PIPE, \
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    for command in commands:
        p.stdin.write((command + "\n").encode("utf-8"))
    out, err = p.communicate()
    print("{}".format(out))
    print("{}".format(err))
    

提交回复
热议问题