Skip to content

subprocess.Popen.communicate does not send input #141473

@mrowqa

Description

@mrowqa

Bug report

Bug description:

I will start with saying that documentation for subprocess.Popen is not clear. I was using subprocess.run(..., input=..., ...) and needed to monitor other things while the created process is running, so I changed it to subprocess.Popen. The only way to send input was Popen.communicate(input=...), however I wanted to have a timeout. My initial idea was .communicate(input=..., timeout=0), catch the exception, and then continue with .wait(timeout=STEP), however it was hanging. I worked it around by launching .communicate without timeout in a separate thread.

Then, I tested a few platforms and looked at the implementation. On Windows, my initial idea works. On Linux, it hangs. After looking into the implementation, I deduced I shouldn't use .wait(), but rather .communicate() and set the input only for the first invocation. If that's the intention, it would be great to have it documented.

Anyway, the following example hangs on a few Linux versions and few Python versions, including current main branch:

import subprocess
proc = subprocess.Popen(
    ["cat", "-"],
    stdin=subprocess.PIPE
)
try:
    proc.communicate(input="abcd\n".encode(), timeout=0)
except subprocess.TimeoutExpired:
    pass
print("it will hang:")
proc.communicate()  # initially: proc.wait()
print("finished")

It looks like a bug, and this line:

if self.stdin and input:

which should be changed to:

                if self.stdin and not self.stdin.closed and self._input:

After this change, the example above no longer hangs. I'll open PR with the mentioned change.

CPython versions tested on:

3.12, 3.14, CPython main branch

Operating systems tested on:

Linux, Windows

Linked PRs

Metadata

Metadata

Assignees

Labels

stdlibStandard Library Python modules in the Lib/ directorytopic-subprocessSubprocess issues.type-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions