Search code examples
pythoncompilationexesetuptools

How can I use setuptools to create an exe launcher


I can install a python script as an exe file into "scripts" folder on windows.

  1. How can I just create an exe launcher for a script without installing it?

  2. Using 64-bit python, can I create an exe that will work with 32-bit python?


Solution

  • A bit late, but since this is the first result on google, I'll add my findings.

    What creates the scripts is in fact not setuptools, which only registers the config, but pip when it installs a package. And there again, it's distlib shipped inside pip. The little script.exe's can be found in your pip installation folder in

    pip\_vendor\distlib

    For example, the t64.exe will be the terminal (no gui), 64 bit version.

    Long story short, those exe headers can be concatenated with a shebang text file and a zip file into a new exe file, where the shebang file contains a commmand to call this exe file with. When called with python.exe, it will recognize the attached zip file and run the __main__.py inside that.

    The good news is, you can use the API to do all this for you. Assuming you want to create an exe myexe.exe that runs myfunc out of a module mypackage.mymodule on the same python.exe you are currently using, then you can do this:

    import sys
    from pip._vendor.distlib.scripts import ScriptMaker
    
    sm = ScriptMaker(
        None,    # source_dir - not needed when using an entry spec
        target_dir = ".", # folder that your exe should end up inside
        add_launchers = True   # create exe launchers, not just python scripts
    )
    # set the python executable manually
    sm.executable = sys.executable.replace("pythonw", "python")
    
    # create only the main variant (not the one with X.Y suffix)
    sm.variants = [""]   
    
    # provide an entry specification string here, just like in pyproject.toml
    sm.make("myexe = mypackage.mymodule:myfunc")
    

    The exe should now be in the target_dir that you provided above.