[Python] Unable to read output from interactive script in python subprocess.Popen

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

  1. Stack

    Stack Membro Participativo

    The following program is used to simulate cmd.exe using subprocess.

    import subprocess
    import sys
    import threading

    def handle_output(shell):
    while shell:
    output = shell.stdout.readline(1)
    print(output, end="")
    sys.stdout.flush()

    subprocess_shell = subprocess.Popen("cmd.exe", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)

    threading.Thread(target=handle_output, args=(subprocess_shell,), daemon=True).start()

    while True:
    subprocess_shell.stdin.flush()
    cmd = input()
    subprocess_shell.stdin.write(cmd + "\n")


    When I execute commands like dir, echo, etc. it works fine, but once I run an interactive program like python, there is no output.

    Live output from Python subprocess that calls Python script
    This is useful when executing python test.py, by setting os.environ['PYTHONUNBUFFERED'] = '1' and env=os.environ, but still, I got nothing on the output when executing python using that method.

    It seems that this is related unbuffered-output but setting os.environ['PYTHONUNBUFFERED'] = '1' and env=os.environ isn't suitable for all situations.

    When I type python, the program should have the following output

    Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>>


    however, I got nothing on the output.

    Continue reading...

Compartilhe esta Página