[Python] Why does subprocess require two .readline() calls when shell=False, but only one with...

Discussão em 'Python' iniciado por Stack, Julho 21, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a Python script that sends expressions to the bc command-line calculator using subprocess.Popen. I noticed a difference in behavior based on whether I use shell=True or not.

    When using shell=True:

    from subprocess import Popen, PIPE

    p = Popen("bc -q", shell=True, stdin=PIPE, stdout=PIPE, text=True)
    p.stdin.write("1+2\n")
    p.stdin.flush()
    print(p.stdout.readline().strip()) # outputs: 3


    This behaves as expected. I send 1+2 and the result 3 is printed in one line.

    When using shell=False:

    from subprocess import Popen, PIPE

    p = Popen(["bc", "-q"], shell=False, stdin=PIPE, stdout=PIPE, text=True)
    p.stdin.write("1+2\n")
    p.stdin.flush()
    print(p.stdout.readline().strip()) # outputs: 1+2
    print(p.stdout.readline().strip()) # outputs: 3


    In this case, the first .readline() gives back the echo of the input (1+2), and only the second .readline() gives the actual result (3).

    Why do I need to call .readline() twice when shell=False, but only once when shell=True? Is it related to how the shell processes standard I/O or echoes commands? How can I reliably suppress input echo if I want consistent behavior?

    I tried running both versions — one with shell=True and one with shell=False — using Python's subprocess.Popen. In both cases, I expected the same behavior: send an expression like 1+2 to bc, and get back just the result 3.

    But what I noticed is:

    • With shell=True, I only needed to call .readline() once to get the result.
    • With shell=False, the first .readline() returns the input line (1+2), and the second returns the result (3).

    I wasn’t expecting the input echo to appear when using shell=False, and now I’m trying to understand why this happens and how to make the output consistent between both approaches.

    Continue reading...

Compartilhe esta Página