[issue38905] venv python reports wrong sys.executable in a subprocess on Windows

Eryk Sun report at bugs.python.org
Mon Mar 22 18:14:35 EDT 2021


Eryk Sun <eryksun at gmail.com> added the comment:

In some cases, the problem can be worked around by setting the __PYVENV_LAUNCHER__ environment variable and executing the base executable. For example:

    import os
    import sys
    import subprocess

    def get_python_exe_env():
        if sys.executable == getattr(sys, '_base_executable', sys.executable):
            return sys.executable, None
        environ = os.environ.copy()
        environ['__PYVENV_LAUNCHER__'] = sys.executable
        return sys._base_executable, environ

    executable, environ = get_python_exe_env()
    p = subprocess.Popen([executable], env=environ)

---

As is, I don't know how to solve the problem in which an arbitrary application runs a script using the "python" launcher. Half of the problem could be solved. When the launcher creates the base Python process, it could set the parent via PROC_THREAD_ATTRIBUTE_PARENT_PROCESS [1], presuming it can open a handle for the parent application with PROCESS_CREATE_PROCESS access. However, this doesn't solve the problem from the application's perspective. It still gets the handle and process ID of the launcher.

If the purpose of using a launcher was only to allow an in-place upgrade of the base "python3x.dll", then an alternative design would be to set the __PYVENV_LAUNCHER__ environment variable, load the Python DLL from the pyvenv.cfg "home" directory, and call Py_Main(argc, argv). This would eliminate the parent<->child problem and the application directory (__APPDIR__) problem. 

However, naively implementing something like that cannot work for the store app distribution. "python3x.dll" in the app installation directory under "%ProgramFiles%\WindowsApps" only grants execute access to users that have the app's WIN://SYSAPPID identifier in their access token, which gets added by CreateProcessW() when the "python[3[.x]].exe" appexec link is executed. I'd have to experiment to see what works. Maybe "python.exe" in the virtual environment could be created as an appexec link to "venvlauncher.exe" in the app, which loads the DLL, etc.

---

[1] https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-updateprocthreadattribute

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38905>
_______________________________________


More information about the Python-bugs-list mailing list