Windows: subprocess won't run different Python interpreter

eryk sun eryksun at gmail.com
Thu Nov 10 18:04:02 EST 2016


On Thu, Nov 10, 2016 at 9:58 PM, Thorsten Kampe
<thorsten at thorstenkampe.de> wrote:
>
> I'm trying to run a script with a different Python version by
> extending the path variable and executing "python.exe". It looks like
> subprocess will always run the current executing Python.

WinAPI CreateProcess checks the application directory, current
directory (an insecure legacy default), %SystemRoot%\System32,
%SystemRoot%\System, %SystemRoot%, and then the directories in %PATH%.
This is listed in the documentation of the lpCommandLine parameter on
MSDN [1].

Let's take a look with a breakpoint set on WinAPI SearchPath [2]:

    >>> subprocess.Popen('python -c 42').wait()
    Breakpoint 0 hit
    KERNELBASE!SearchPathW:
    00007fff`4b344f60 488bc4          mov     rax,rsp

In the x64 ISA, the lpPath parameter is passed in register rcx:

    0:000> du @rcx L4D
    00000241`9a74dbe0  "C:\Program Files\Python35;.;C:\W"
    00000241`9a74dc20  "indows\SYSTEM32;C:\Windows\syste"
    00000241`9a74dc60  "m;C:\Windows;"
    0:000> g
    0

Note that the second entry is ".", which is the current directory.
Setting %NoDefaultCurrentDirectoryInExePath% [3] removes the current
directory from the search path:

    >>> os.environ['NoDefaultCurrentDirectoryInExePath'] = '1'
    >>> subprocess.Popen('python -c 42').wait()
    Breakpoint 0 hit
    KERNELBASE!SearchPathW:
    00007fff`4b344f60 488bc4          mov     rax,rsp

    0:000> du @rcx L4B
    00000241`99e43f90  "C:\Program Files\Python35;C:\Win"
    00000241`99e43fd0  "dows\SYSTEM32;C:\Windows\system;"
    00000241`99e44010  "C:\Windows;"

[1]: https://msdn.microsoft.com/en-us/library/ms682425
[2]: https://msdn.microsoft.com/en-us/library/aa365527
[3]: https://msdn.microsoft.com/en-us/library/ms684269



More information about the Python-list mailing list