Using the Windows "embedded" distribution of Python

Paul Moore p.f.moore at gmail.com
Wed Sep 28 10:35:38 EDT 2016


This is probably more of a Windows question than a Python question, but as it's related to embedding Python, I thought I'd try here anyway.

I'm writing some command line applications in Python, and I want to bundle them into a standalone form using the new "embedding" distribution of Python. The basic process is easy enough - write a small exe that sets up argv, and then call Py_Main. Furthermore, as I'm *only* using Py_Main, I can use the restricted API, and make my code binary compatible with any Python 3 version.

So far so good. I have my exe, and my application code. I create a directory for my app, put the exe/app code in there, and then unzip the embedded distribution in there. And everything works. Yay!

However, I'm expecting my users to put my application directory on their PATH (as these are command line utilities). And I don't really want my private copy of the Python DLLs to be exposed on the user's PATH (I don't *know* that it'll interfere with their actual Python installation, but I'd prefer not to take risks). And this is when my problems start. Ideally, I'd put the embedded Python distribution in a subdirectory (say "embed") of my application directory. But the standard loader won't find python3.dll from there. So I have to do something a bit better.

As I'm only using Py_Main, I thought I'd be OK to dynamically load it - LoadLibrary on the DLL, then GetProcAddress. No big deal. But I need to tell LoadLibrary to get the DLL from the "embed" subdirectory. I suppose I could add that directory to PATH locally to my program, but that seems clumsy. So I thought I'd try SetDllDirectory. That works for python36.dll, but if I load python3.dll, it can't find Py_Main - the export shows as "(forwarded to python36.Py_Main)", maybe the forwarding doesn't handle SetDllDirectory?

So, basically what I'm asking:

* If I want to put my application on PATH, am I stuck with having the embedded distribution in the same directory, and also on PATH?
* If I can put the embedded distribution in a subdirectory, can that be made to work with python3.dll, or will I have to use python36.dll?

None of this is an issue with the most likely use of the embedded distribution (GUI apps, or server apps, both of which are likely to be run by absolute path, and so don't need to be on PATH myself). But I'd really like to be able to promote the embedded distribution as an alternative to tools like py2exe or cx_Freeze, so it would be good to know if a solution is possible (hmm, how come py2exe, and tools like Mercurial, which AFIK use it, don't have this issue too?)

Paul



More information about the Python-list mailing list