Search code examples
pythonpipenvpython-standalone

Create standalone environment for Python


I'm developing a tool based on Python, and I need to distribute this tool for users without technical skills. My way to distribute the tool was to create an installer with all the requirements, including the python executable and the libraries.

For this purpose, I tried to make a virtual environment (used pipenv to create it) and copied the resultant work directory with my code. In some cases the installer worked because some user has Python on it's machine; for user without Python some dependencies are required, but the dependencies are from a full python installation.

I already tried to use Cx_freeze, but it doesn't work for my application. Is there a way to make a standalone python environment to distribute with my application?


Solution

  • My solution was install a version of python and the needed packages. My solution structure was:

    
    -> Python
    -> Program
    -> run.bat
    
    

    The first Python, directory is the python environment with all executables and packages. The directory Program contain the project files and the run.bat that set the environment to work with this local installation. Inside of directory Python\Scripts there is an archive to activate the environment. My scripts code are:

    run.bat

    cls
    @ECHO OFF
    call %~dp0Python\Scripts\activate.bat
    ECHO Starting Program....
    %~dp0Python\python %~dp0ProgramData\starter.py
    

    activate.bat

    @echo off
    
    set "VIRTUAL_ENV=%~dp0\Python"
    
    if defined _OLD_VIRTUAL_PROMPT (
        set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
    ) else (
        if not defined PROMPT (
            set "PROMPT=$P$G"
        )
        if not defined VIRTUAL_ENV_DISABLE_PROMPT (
            set "_OLD_VIRTUAL_PROMPT=%PROMPT%"
        )
    )
    if not defined VIRTUAL_ENV_DISABLE_PROMPT (
        set "PROMPT=(64bits) %PROMPT%"
    )
    
    REM Don't use () to avoid problems with them in %PATH%
    if defined _OLD_VIRTUAL_PYTHONHOME goto ENDIFVHOME
        set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%"
    :ENDIFVHOME
    
    set PYTHONHOME=
    
    REM if defined _OLD_VIRTUAL_PATH (
    if not defined _OLD_VIRTUAL_PATH goto ENDIFVPATH1
        set "PATH=%_OLD_VIRTUAL_PATH%"
    :ENDIFVPATH1
    REM ) else (
    if defined _OLD_VIRTUAL_PATH goto ENDIFVPATH2
        set "_OLD_VIRTUAL_PATH=%PATH%"
    :ENDIFVPATH2
    
    set "PATH=%VIRTUAL_ENV%;%PATH%"
    

    This solution works for in my both application (64 bits and 32 bits) installation.