Немного про py2exe
Есть такое приложение. Называется py2exe. Оно позволяет упаковать, сконвертировать программу на python в exe файл (ну, точнее, exe и еще кучку других). Зачем оно все надо? Ну, далеко не у всех пользователей windows установлен интерпретатор python с нужными библиотеками. А вот упакованная программа в идеале должна запуститься на любой windows-машине.
Установка
К сожалению, py2exe не поддерживает третью версию питона.
Скачать py2exe можно на SourceForge.
Если у вас стоит python (а он у вас наверняка стоит), проблем с установкой возникнуть не должно. Ставится в директорию python.
Конвертация
- from distutils.core import setup
- import py2exe
- setup(
- windows=[< "script" : "main.py" >],
- options=< "py2exe" : < "includes" :[ "sip" ]>>
- )
Где main.py имя Вашего скрипта.
Далее запускаем упаковку командой:
Да-да, именно так.
Смотрим, что у нас получилось. Две папки.
build — служебная, можно сразу снести.
dist — собственно, в ней и лежит наша программа.
- main.exe — программа
- pythonXX.dll — интерпретатор python’a
- library.zip — архив со скомпилированными исходниками (всего, кроме собственно программы, как я понимаю)
- .pyd — модули python, которые импортирует программа
- .dll — библиотеки, оказавшиеся необходимыми
- и еще файлы по мелочи, ниже будет сказано еще
Сложности
Скорее всего возникнут какие-то проблемы.
Например, пути к файлам. Не следует использовать относительные пути. Они ведут неведомо куда. Лучше использовать абсолютные.
Как его узнать? в интернете есть решение, функция module_path.
- import os, sys
- def module_path ():
- if hasattr(sys, «frozen» ):
- return os.path.dirname(
- unicode(sys.executable, sys.getfilesystemencoding( ))
- )
- return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))
Или приложение наотрез откажется запускаться (возможно, не у Вас, а у кого-то еще). Из-за отсутствие библиотек Visual Studio.
В качестве решения проблемы можно установить их на компьютер (но это же не наш метод) или кинуть dll и файл манифеста в папку с программой.
msvcr90.dll и Microsoft.VC90.CRT.manifest (не знаю как это лицензируется и выкладывать не буду)
Где их взять? Для меня самым простым было переустановить python (все остальное осталось на месте) в режиме «только для меня». И искомые файлы оказались в папке с python.
Целью топика не являлось раскрыть всех особенностей py2exe. Здесь находится туториал, а тут некоторые советы и трюки.
Размер
В силу некоторых особенностей, приложение может получиться ужасающего размера. Но с этим можно и нужно бороться. Идеи подсказал kAIST (ну, кроме upx’а =р)
-
Самое действенное. Сжать библиотеки upx’ом. Консольное приложение. Работает элементарно. На вход передается файл, оно его сжимает. Для моей игры реверси размер уменьшился в
Как из файла Python3 создать .exe на Windows

Мы рассмотрим создание .exe с помощью библиотеки модуля py2exe. Для этого необходим Python 3.4 и ниже.
Если у вас установлена более высокая версия Python, попробуйте использовать Способ 2 (ниже)
В этом примере мы рассмотрим создание .exe на примере Python3.4.
Прежде всего на нужно создать виртуальное окружение для Python3.4. В этом примере мы назовем myenv, Вы можете выбрать любое другое имя, но не забывайте сделать соответствующие изменения.
На терминале наберите следующие команды:
В командной строке появится префикс myenv, а это значит, что виртуальное окружение с именем myenv загружено. Все команды Python теперь будет использовать новое виртуальное окружение.
Теперь давайте установим py2exe (https://pypi.python.org/pypi/py2exe
HEAD=dobj) в нашем виртуальном окружении:
И, наконец, чтобы создать единый EXE-файл, в нашем виртуальном окружении выполняем команду:
(замените hello.py на имя вашего скрипта. Если скрипт находится в другой папке, то нужно использовать полный путь к вашему сценарию, например, C:\Projects\Python\ hello.py). Это создаст папку DIST, которая содержит исполняемый файл. Для быстрого доступа к нему, наберите в терминале:
Вы увидите путь к папке, где находится EXE-файл.
Примечание: При выполнении, откроется окно и исчезают так же быстро, как и появилось.
Это происходит потому, что операционная система автоматически закрывает терминал, в котором консольная программа закончена.
Для того, чтобы изменить эту ситуацию, можно добавить строчку
в конце файла Python. Интерпретатор будет ждать ввода пользователя, а окно будет оставаться открытым, пока пользователь не нажимает клавишу ввода.
Вы можете подробно изучить использование py2exe в документации на странице модуля: https://pypi.python.org/pypi/py2exe
Выход из виртуального окружения производится командой
Способ 2
Через командную строку Windows устанавливаем pyinstaller:
В командной строке переходим в папку, где находится файл
Затем в командной строке набираем команду
Вместо exapmle.py используем имя файла, из которого нужно создать exe файл.
Через пару минут все готово! Скоркее всего, exe файл будет находится во созданной подпапке dist
Creating Executable Files from Python Scripts with py2exe
Executing Python scripts requires a lot of prerequisites like having Python installed, having a plethora of modules installed, using the command line, etc. while executing an .exe file is very straightforward.
If you want to create a simple application and distribute it to lots of users, writing it as a short Python script is not difficult, but assumes that the users know how to run the script and have Python already installed on their machine.
Examples like this show that there is a valid reason to convert .py programs into equivalent .exe programs on Windows. .exe stands for "Executable File", which is also known as a Binary.
The most popular way to achieve this is by using the py2exe module. In this article, we'll quickly go through the basics of py2exe and troubleshoot some common issues. To follow along, no advanced Python knowledge is needed, however you will have to use Windows.
Converting an interpreted language code into an executable file is a practice commonly called freezing.
Installing py2exe
To use the py2exe module, we'll need to install it. Let's do so with pip :
Converting Python Script to .exe
First, let's write up a a program that's going to print some text to the console:
Let's run the following commands in the Windows command line to make a directory ( exampDir ), move the code we already wrote to said directory, and finally, execute it:
This should output:
Always test out the scripts before turning them into executables to make sure that if there is an error, it isn't caused by the source code.
Setup and Configuration
Make another file called setup.py in the same folder. Here we will keep configuration details on how we want to compile our program. We'll just put a couple of lines of code into it for now:
If we were dealing with an app with a graphical UI, we would replace console with windows like so:
Now open Command Prompt as administrator and navigate to the directory we just mentioned and run the setup.py file:
dist folder
If all is done correctly, this should produce a subdirectory called dist . Inside it, there will be a few different files depending on your program, and one of them should be example.exe . To execute it from the console run:
And you'll be greeted by our Latin quote, followed by the value of 4!:
Or, you can double click it and it'll run in the console.
If you'd like to bundle up all the files, add bundle_files and compressed , and set zipfile to None like so:
And re-run the commands to generate the .exe file.
Now, your end-users can run your scripts without any knowledge or prerequisites installed on their local machines.
Troubleshooting
Errors while converting .py files to .exe files are common, so we'll list some common bugs and solutions.
How to Fix Missing DLL-s After Using py2exe
A common issue with py2exe is missing .dll -s.
DLL stands for "dynamic-link library", and they're not there just to make bugs, promise. DLLs contain code, data, and resources which our program might need during execution.
After running the .exe , if you get a system error that says something like:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Or the command line says:
The solution is to find the missing .dll and past it into your dist folder. There are two ways to do this.
- Search your computer for the file and then copy it. This will work most of the time.
- Find the missing .dll online and download it. Try not to download it from some shady website.
How to Generate 32/64-bit Executables Using py2exe?
To make a 64-bit executable, install 64 bit Python on your device. The same goes for the 32-bit version.
How to use py2exe on Linux or Mac
py2exe doesn't support on Linux or Mac, as it's aimed to create .exe files which is a Windows-unique format. You can download a Windows virtual machine on both Mac and Linux, use Wine or use a different tool like Pyinstaller on Linux, or py2app on Mac.
Conclusion
To make Python projects easier to run on Windows devices, we need to generate an executable file. We can use many different tools, like Pyinstaller, auto-py-to-exe, cx_Freeze, and py2exe.
Binary files may use DLL-s, so make sure to include them with your project.