[Python] How to read multi-line output from subprocess?

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use subprocess to run commands via Python and capture the output. The terminal needs to be persistent, that is if I run one command the second should run in the same terminal. For example if I run "cd Desktop" and then "dir" it should execute "dir" in Desktop, and not the default path. The problem is that I can't figure out how to capture the output of commands like "dir" that have multi-line outputs. Here's my code:

    import subprocess

    cmd_process = subprocess.Popen(
    "cmd.exe",
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True,
    universal_newlines=True,
    creationflags=subprocess.CREATE_NO_WINDOW # Hides the window
    )

    def send_command(command):
    cmd_process.stdin.write(command + "\n")
    cmd_process.stdin.flush()

    def read_output():
    output = cmd_process.stdout.readline()

    return output

    send_command("dir")
    print(read_output())


    When running this code, I want it to output the entirety of the commands output (in this case a list of files and folders within the current directory). However instead it only outputs the first line of the output (in this case "Microsoft Windows [Version 10.0.22631.4974]").

    Continue reading...

Compartilhe esta Página