From 44adcd9fae0b8094cf24de54123a48ff0cfa5035 Mon Sep 17 00:00:00 2001 From: CandyRealDandy <101083565+CandyRealDandy@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:29:51 +0800 Subject: [PATCH] gh-445: Set the UCRT's app type in the alias launcher before calling Py_Main The launcher links the C runtime statically, so its startup code sets the app type only in its own copy. Python, loaded in-process through python3.dll, uses the shared UCRT, whose app type stays unknown. The UCRT then doesn't update the process's standard handles when Python swaps fds 0-2 with os.dup2 (as pytest's fd capture does), GetStdHandle keeps returning a closed handle, and a subprocess that inherits stdin fails with WinError 6. Set it to console (or GUI for the windowed launcher) before calling Py_Main, as python.exe's own startup would. --- src/pymanager/launcher.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/pymanager/launcher.cpp b/src/pymanager/launcher.cpp index 79e1063..5fd4cf8 100644 --- a/src/pymanager/launcher.cpp +++ b/src/pymanager/launcher.cpp @@ -3,6 +3,10 @@ #include "_launch.h" +#ifndef PY_WINDOWED +#define PY_WINDOWED 0 +#endif + #define MAXLEN 32768 // HRESULT-compatible error codes @@ -252,6 +256,22 @@ launch_by_dll(void *main_func_ptr, wchar_t *executable, int argc, wchar_t **argv newArgv[i] = argv[i]; } + // This launcher links the C runtime statically, so its startup code tells only + // its own copy what kind of app this is. Python uses the shared UCRT, which + // would otherwise stay "unknown", and then no longer updates the process's + // standard handles when Python swaps fds 0-2 (os.dup2, as pytest's capture + // does): GetStdHandle keeps returning a closed handle, and a subprocess that + // inherits it fails with WinError 6. Tell it what python.exe's startup would. + HMODULE ucrt = GetModuleHandleW(L"ucrtbase.dll"); + if (ucrt) { + typedef void (__cdecl *set_app_type_t)(int); + set_app_type_t set_app_type = (set_app_type_t)GetProcAddress(ucrt, "_set_app_type"); + if (set_app_type) { + // _crt_console_app (1) or _crt_gui_app (2), as for python.exe and pythonw.exe + (*set_app_type)(PY_WINDOWED ? 2 : 1); + } + } + // Our caller assumes that any error result happens before we launch. From // this point on, exit_code is set (possibly to an error), and so we should // only return 0.