You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Hooks: Runtime hook for subprocess block launching standalone cmd #7118
In windowed build using PySide2, subprocess.Popen(["cmd"]) no longer work (cmd open then close immediately). I figured out that the issue come from the subprocess hook (since v4.8, pr #6364). If I comment out this file, cmd start showing again and stay alive.
Context information (for bug reports)
Output of pyinstaller --version: 5.4.1
Version of Python: 3.7 / 3.8 / 3.9 / 3.10
Platform: Windows
How you installed Python: python.org/downloads
Did you also try this on another platform? Does it work there? → not relevant on other platform.
A minimal example program which shows the error
A cmd shows up at start, if you comment the hook it stays alive, if you don't the cmd disappear instantly.
import subprocess
import sys
from PySide2 import QtWidgets
class CmdExemple(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
p = subprocess.Popen(["cmd"])
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = CmdExemple()
window.show()
exitCode = app.exec_()
sys.exit(exitCode)
I presume you are building with --noconsole/--windowed, and are relying on the fact that cmd.exe sub-process with invalid stream handles opens a new console window for you? In that case, yes, the runtime hook redirecting the unused pipes to DEVNULL in windowed mode will cause your cmd.exe to exit immediately, because it has no stdin to receive commands from.
Forcing the unused pipes to DEVNULL is required to solve a different class of problems within noconsole frozen applications, so it is going to stay. I think the only way to also accommodate this use case is to exempt attempts to spawn cmd from such processing, by checking if self.args[0] (or rather, its basename without extension) is `cmd˙. @bwoodsend, thoughts?
Hmm, surely that would mean that cmd has something special in it to force a terminal window then? Why is cmd different to any other command line application?
Hmm, surely that would mean that cmd has something special in it to force a terminal window then? Why is cmd different to any other command line application?
I had some time to dig around this problem, and I think the error with stream handles that the subprocess runtime hook is solving is actually our fault.
The test program allows spawning a sub-process using the command-line entered in the text field, and allows optionally closing stdin (stdin=subprocess.DEVNULL as opposed to leaving it at default None) and optionally redirecting stdout and/or stderr (stdout=subprocess.PIPE as opposed to leaving it at default None; if redirected, the output is displayed in the bottom text field).
The test application was ran:
unfrozen with pythonw.exe
frozen with windowedonedir (with subprocess runtime hook removed)
frozen with windowedonefile (with subprocess runtime hook removed)
The test command was ffmpeg.exe (and also cbc.exe path\to\problem.lp where cbc.exe comes from PuLP from #6359).
Unfrozen variant always worked, regardless the stream closing/redirection settings.
The onedir variant also always worked, regardless the stream closing/redirection settings.
The onefile variant worked only if no streams were redirected at all, or if all of them were redirected (i.e., stdin was closed and stdout/stderr was redirected). With partial redirection, we get OSError: [WinError 6] The handle is invalid, raised in the subprocess module (and not the subprocess' executable).
That's why the final iteration of the test application also tries running _winapi.GetStdHandle for all three handles are displays the result. When running unfrozen under pythonw or when running frozen in onedir mode, the function returns None for all handles (the underlying C function returns NULL). But in onefile mode, the calls raise exception (the underlying C function returns INVALID_HANDLE_VALUE and the python wrapper then raises exception).
Once we know that the problem is specific to onefile+windowed combination, it is easy to pin-point the source of the problem - we are spawning the child process with invalid handles. And the problematic part is here:
In windowed mode, the handles are invalid, so the fileno() + _get_osfhandle() combination ends up returning INVALID_HANDLE_VALUE, which has value -1, which we set as handles for the child process' streams. Instead, we should put this part under #if defined(WINDOWED), and set them to NULL.
Then, we can remove the runtime hook, and interfering with stream handles will also solve this problem with interactive shells that require stdin.
Activity
rokm commentedon Sep 29, 2022
I presume you are building with
--noconsole/--windowed, and are relying on the fact thatcmd.exesub-process with invalid stream handles opens a new console window for you? In that case, yes, the runtime hook redirecting the unused pipes to DEVNULL in windowed mode will cause yourcmd.exeto exit immediately, because it has no stdin to receive commands from.Forcing the unused pipes to DEVNULL is required to solve a different class of problems within noconsole frozen applications, so it is going to stay. I think the only way to also accommodate this use case is to exempt attempts to spawn
cmdfrom such processing, by checking ifself.args[0](or rather, its basename without extension) is `cmd˙. @bwoodsend, thoughts?bwoodsend commentedon Sep 29, 2022
Does the example actually work if ran via
pythonw? I would have thought not.rokm commentedon Sep 29, 2022
It does, and it opens a new console window. If ran through regular
python, it ends up re-using the existing console.bwoodsend commentedon Sep 29, 2022
Hmm, surely that would mean that
cmdhas something special in it to force a terminal window then? Why iscmddifferent to any other command line application?millerlucas commentedon Sep 30, 2022
It does the same with
powershell, don't know why. I've also tried to provideSTARTUPINFOwithSW_SHOWinwShowWindowbut that doesn't change anything.If you provide this flags
creationflags=subprocess.CREATE_NEW_CONSOLEtoPopenit stops re-using the existing console and always open a new one.rokm commentedon Oct 23, 2022
I had some time to dig around this problem, and I think the error with stream handles that the
subprocessruntime hook is solving is actually our fault.Test application
The test program allows spawning a sub-process using the command-line entered in the text field, and allows optionally closing stdin (
stdin=subprocess.DEVNULLas opposed to leaving it at defaultNone) and optionally redirecting stdout and/or stderr (stdout=subprocess.PIPEas opposed to leaving it at defaultNone; if redirected, the output is displayed in the bottom text field).The test application was ran:
pythonw.exewindowedonedir(withsubprocessruntime hook removed)windowedonefile(withsubprocessruntime hook removed)The test command was
ffmpeg.exe(and alsocbc.exe path\to\problem.lpwherecbc.execomes from PuLP from #6359).Unfrozen variant always worked, regardless the stream closing/redirection settings.
The
onedirvariant also always worked, regardless the stream closing/redirection settings.The
onefilevariant worked only if no streams were redirected at all, or if all of them were redirected (i.e., stdin was closed and stdout/stderr was redirected). With partial redirection, we getOSError: [WinError 6] The handle is invalid, raised in thesubprocessmodule (and not the subprocess' executable).Looking at
subprocesssource, the above behavior can be explained by the following two snippets fromsubprocess._get_handles. First, if all three passed stream handles areNone, the function exits immediately. Otherwise, if not all of them are redirected, the error is raised by the_winapi.GetStdHandlecall here, here, or here.That's why the final iteration of the test application also tries running
_winapi.GetStdHandlefor all three handles are displays the result. When running unfrozen underpythonwor when running frozen inonedirmode, the function returnsNonefor all handles (the underlying C function returnsNULL). But inonefilemode, the calls raise exception (the underlying C function returnsINVALID_HANDLE_VALUEand the python wrapper then raises exception).Once we know that the problem is specific to
onefile+windowedcombination, it is easy to pin-point the source of the problem - we are spawning the child process with invalid handles. And the problematic part is here:pyinstaller/bootloader/src/pyi_utils.c
Lines 842 to 844 in 7b39785
In
windowedmode, the handles are invalid, so thefileno()+_get_osfhandle()combination ends up returningINVALID_HANDLE_VALUE, which has value-1, which we set as handles for the child process' streams. Instead, we should put this part under#if defined(WINDOWED), and set them toNULL.Then, we can remove the runtime hook, and interfering with stream handles will also solve this problem with interactive shells that require stdin.
bwoodsend commentedon Oct 24, 2022
Nice. I can't say that I'll miss that runtime hook.