Build python to binary

How to compile python script to binary executable

Or use PyInstaller as an alternative to py2exe. Here is a good starting point. PyInstaller also lets you create executables for linux and mac.

Here is how one could fairly easily use PyInstaller to solve the issue at hand:

From the tool’s documentation:

  • Writes myscript.spec in the same folder as the script.
  • Creates a folder build in the same folder as the script if it does not exist.
  • Writes some log files and working files in the build folder.
  • Creates a folder dist in the same folder as the script if it does not exist.
  • Writes the myscript executable folder in the dist folder.

I recommend PyInstaller, a simple python script can be converted to an exe with the following commands:

utils/Makespec.py [--onefile] oldlogs.py 

which creates a yourprogram.spec file which is a configuration for building the final exe. Next command builds the exe from the configuration file:

Since other SO answers link to this question it’s worth noting that there is another option now in pyoxidizer.

It’s a rust utility which works in some of the same ways as pyinstaller, however has some additional features detailed here, to summarize the key ones:

  • Single binary of all packages by default with the ability to do a zero-copy load of modules into memory, vs pyinstaller extracting them to a temporary directory when using onefile mode
  • Ability to produce a static linked binary

(One other advantage of pyoxidizer is that it does not seem to suffer from the GLIBC_X.XX not found problem that can crop up with pyinstaller if you’ve created your binary on a system that has a glibc version newer than the target system).

Читайте также:  Удалить из массива символы python

Overall pyinstaller is much simpler to use than PyOxidizer, which often requires some complexity in the configuration file, and it’s less Pythony since it’s written in Rust and uses a configuration file format not very familiar in the Python world, but PyOxidizer does some more advanced stuff, especially if you are looking to produce single binaries (which is not pyinstaller’s default).

# -*- mode: python -*- block_cipher = None a = Analysis(['SCRIPT.py'], pathex=[ 'folder path', 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_50c6cb8431e7428f', 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_c4f50889467f081d' ], binaries=[(''C:\\Users\\chromedriver.exe'')], datas=[], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='NAME OF YOUR EXE', debug=False, strip=False, upx=True, runtime_tmpdir=None, console=True ) 

Is it possible to compile a program written in Python?, Python programs are not supposed to be turned into an exe file. Programs in Pythons are usually shipped with the language itself so people first install Python to run it. 4 Years ago I’ve found a way to turn it into an exe file. To “compile” a Python program into an executable, use a bundling tool, such as Gordon …

Create a single executable from a Python project

I want to create a single executable from my Python project. A user should be able to download and run it without needing Python installed. If I were just distributing a package, I could use pip, wheel, and PyPI to build and distribute it, but this requires that the user has Python and knows how to install packages. What can I use to build a self-contained executable from a Python project?

Here are some common ones. I’ve included only projects that are being actively maintained as of my last edit (July 2021).

Unless otherwise noted, all programs listed below will produce an exe specifically for the operating system it’s running in. So for example, running Pyinstaller in Windows will produce a Windows exe, but running Pyinstaller in Linux will produce a Linux exe. If you want to produce an exe for multiple operating systems, you will have to look into using virtual machines or something like Wine.

The following programs all work similarly — they bundle together Python and your program, effectively combining them to produce an executable.

  • PyInstaller: Website || Repo || PyPi Supports Python 3.5 — 3.9 on Windows, Mac, and Linux.
  • cx_Freeze: Website || Repo || PyPi Supports Python 3.6 — 3.9 on Windows, Mac, and Linux.
  • py2exe: Website || Repo || PyPi Supports Python 3.6 — 3.9 on Windows only.
  • py2app: Website || Repo || PyPi Supports Python 2.7 (?) and Python 3 (?) on Macs only. The exact range of supported Python versions is currently undocumented.

Of course, that’s not the only way of doing things:

  • pynsist: Website || Repo || PyPi Pynsist will create a Windows installer for your program which will directly install Python on the user’s computer instead of bundling it with your code and create shortcuts that link to your Python script. The pynsist tool itself requires Python 3.5+ to run, but supports bundling any version of Python with your program. Pynsist will create Windows installers only, but can be run from Windows, Mac, and Linux. See their FAQ for more details.
  • Nuitka: Website || Repo (Github mirror) || PyPi Nuitka will literally compile your Python code and produce an exe (as opposed to the other projects, which simply include Python) to try and speed up your code. As a side effect, you’ll also get a handy exe you can distribute. Note that you need to have a C++ compiler available on your system. Supports Python 2.6 — 2.7 and Python 3.3 — 3.9 on Windows, Mac, and Linux.
  • cython: Website || Repo || PyPi Cython is similar to Nuitka in that it is a Python compiler. However, instead of directly compiling your code, it’ll compile it to C. You can then take that C code and turn your code into an exe. You’ll need to have a C compiler available on your system. Supports Python 2.6 — 2.7 and Python 3.3 — 3.9 on Windows, Mac, and Linux.

My personal preference is to use PyInstaller since it was the easiest for me to get up and running, was designed to work nicely with various popular libraries such as numpy or pygame, and has great compatibility with various OSes and Python versions.

However, I’ve also successfully built various exes using cx_Freeze without too much difficulty, so you should also consider trying that program out.

I haven’t yet had a chance to to try pynist, Nuitka, or Cython extensively, but they seem like pretty interesting and innovative solutions. If you run into trouble using the first group of programs, it might be worthwhile to try one of these three. Since they work fundamentally differently then the Pyinstaller/cx_freeze-style programs, they might succeed in those odd edge cases where the first group fails.

In particular, I think pynist is a good way of sidestepping the entire issue of distributing your code altogether: Macs and Linux already have native support for Python, and just installing Python on Windows might genuinely be the cleanest solution. (The downside is now that you need to worry about targeting multiple versions of Python + installing libraries).

Nuitka and Cython (in my limited experience) seem to work fairly well. Again, I haven’t tested them extensively myself, and so my main observation is that they seem to take much longer to produce an exe then the «freeze» style programs do.

All this being said, converting your Python program into an executable isn’t necessarily the only way of distributing your code. To learn more about what other options are available, see the following links:

  • https://packaging.python.org/overview/#packaging-python-applications
  • https://docs.python-guide.org/shipping/packaging/#for-linux-distributions

pyinstaller is still under active development. You can see the latest changes on GitHub.

It has support for all three major platforms:

and it supports Python versions 2.6 and 2.7. It does not support Python 3, but there is an experimental Python 3 branch.

Update

As of version 3.2.1 it supports Python 2.7, 3.3-3.5

Better use pip install auto-py-to-exe which provides a beautiful UI with all options required to create an executable.

After installing just type auto-py-to-exe in your terminal or command prompt.

Auto-py-to-exe

Python Compilation as executable stand alone, Cx_Freeze is the only one that I mentioned that supports python 3.X; the others only support Python 2.X. The advantage pyinstaller has, is it builds all the dependent files into one executable file that unpacks right before execution, whereas the others create a folder with lots dependent files along with the …

Compiling python code into a single exe

I’ve been trying to compile python code into a single exe, and i didn’t manage to do it correctly.

    I’ve tried pyinstaller, and this is the .spec file:

# -*- mode: python -*- a = Analysis([os.path.join(HOMEPATH,'support\\_mountzlib.py'), os.path.join(HOMEPATH,'support\\useUnicode.py'), 'programs\\toolbox.py'], pathex=['C:\\Users\\Ronaldo\\Desktop\\Python\\pyinstaller']) pyz = PYZ(a.pure) exe = EXE( pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name=os.path.join('dist', 'program.exe'), debug=False, strip=False, upx=True, console=False ) 
Problem signature: Problem Event Name: APPCRASH Application Name: toolbox.exe Application Version: 0.0.0.0 Application Timestamp: 49180193 Fault Module Name: StackHash_0a9e Fault Module Version: 0.0.0.0 Fault Module Timestamp: 00000000 Exception Code: c0000005 Exception Offset: 01b61fcb OS Version: 6.1.7601.2.1.0.256.1 Locale ID: 1033 Additional Information 1: 0a9e Additional Information 2: 0a9e372d3b4ad19135b953a78882e789 Additional Information 3: 0a9e Additional Information 4: 0a9e372d3b4ad19135b953a78882e789 
from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = >, windows = [], zipfile = None, ) single.py file: 
import os, sys, ctypes ctypes.windll.user32.MessageBoxA(0, "curdir: %s\nexedir: %s\nsys.winver: %s" % ( os.path.abspath(os.curdir), os.path.abspath(os.path.dirname(sys.argv[0])), sys.winver, ), "%s - Message" % os.path.basename(sys.executable), 0x30 ) 

The program I wrote uses tkinter, sys, random and win32clipboard(pywin) modules. What am I doing wrong? Are there any other, better compilers?

Update: By Joël’s tip, I compiled with debug, and with console mode. Still didn’t work for users that don’t have python 2.7. This is the error message:

C:\Users\XXXXX\Desktop>program.exe Found embedded PKG: C:\Users\XXXXX\Desktop\program.exe Extracting binaries Setting up to run child Setting magic environment var Creating child process Waiting for child process to finish. Found embedded PKG: C:\Users\XXXXX\Desktop\program.exe workpath: C:/Users/XXXXX/AppData/Local/Temp/_MEI14042/ manifestpath: C:/Users/XXXXX/AppData/Local/Temp/_MEI14042/program.exe.manifest Activation context created Activation context activated C:\Users\XXXXX\AppData\Local\Temp\_MEI14042\python27.dll Manipulating evironment PYTHONPATH=C:/Users/XXXXX/AppData/Local/Temp/_MEI14042;C:/Users/XXXXX/Desktop importing modules from CArchive extracted iu extracted struct extracted archive Installing import hooks outPYZ1.pyz 

I really hope this serves as help for the possible answer.

My two cents: did you make a test using the debug option of PyInstaller ?

Just update your specfile:

(Note: in order to avoid numerous message boxes, you may want to set console output: console=True )

Maybe it would return some useful data. Please provide us with output in this case (if there’s any).

According to the output you get, this is quite a common problem, because if PyInstaller resolves dependencies for your modules, dependencies of dependencies may be forgotten.

In your case, Tcl is missing, and this is needed by some Tkinter library: you should take a look here: Python, Pyinstaller creating shortcuts in windows

According to documentation:

Elaborating on Makespec.py, this is the supported command line: python Makespec.py [opts] [ . ] Where allowed OPTIONS are:

[. ]

-K, —tk include TCL/TK in the deployment.

You may make a try with this argument, and check the impact on your spec file. I bet it’s an addition in the modules taken into account in Analysis or in the EXE function.

Can I somehow «compile» a python script to work on PC, To compile your Python script into a Windows executable, run this script with your program as its argument: $ python compile.py myscript.py It will spit out a binary executable (EXE) with a Python interpreter compiled inside. You can then just distribute this executable file. Share. Follow edited Jun 23, 2016 at 10:11. David …

Источник

Оцените статью