This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: On Windows, subprocess.run gets stuck indefinitely
Type: behavior Stage: resolved
Components: Library (Lib), Windows Versions: Python 3.9
process
Status: closed Resolution: duplicate
Dependencies: Superseder: subprocess.run() sometimes ignores timeout in Windows
View: 43346
Assigned To: Nosy List: bugale bugale, eric.smith, paul.moore, steve.dower, tim.golden, zach.ware
Priority: normal Keywords:

Created on 2021-06-28 17:29 by bugale bugale, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (1)
msg396653 - (view) Author: bugale bugale (bugale bugale) Date: 2021-06-28 17:29
The implementation for subprocess.run on Windows has a bug that causes it to hang indefinitely in some scenarios.
The issue can be easily reproduced by this code:

import subprocess
subprocess.run(['cmd.exe', '/c', 'ping 1.2.3.4 -n 9999'], capture_output=True, timeout=1)

Instead of exiting after 1 second, it hangs indefinitely.

After looking at the code a bit, I found the issue:
https://github.com/python/cpython/blob/efe7d08d178a7c09bcca994f2068b019c8633d83/Lib/subprocess.py#L512

            if _mswindows:
                # Windows accumulates the output in a single blocking
                # read() call run on child threads, with the timeout
                # being done in a join() on those threads.  communicate()
                # _after_ kill() is required to collect that and add it
                # to the exception.
                exc.stdout, exc.stderr = process.communicate()

In the case of Windows, after the process is killed, communicate is called without a timeout. This usually works because after the process is killed the pipes are closed and the communicate returns almost immediately.
However, if the created subprocess created other processes that hold the pipes, they are not closed and this line blocks indefinitely.
History
Date User Action Args
2022-04-11 14:59:47adminsetgithub: 88693
2021-06-28 18:32:34eryksunsetstatus: open -> closed
superseder: subprocess.run() sometimes ignores timeout in Windows
resolution: duplicate
stage: resolved
2021-06-28 18:16:44eric.smithsetnosy: + paul.moore, eric.smith, tim.golden, zach.ware, steve.dower

components: + Windows
title: subprocess.run gets stuck indefinitely -> On Windows, subprocess.run gets stuck indefinitely
2021-06-28 17:29:19bugale bugalecreate