Немного про py2exe
Есть такое приложение. Называется py2exe. Оно позволяет упаковать, сконвертировать программу на python в exe файл (ну, точнее, exe и еще кучку других). Зачем оно все надо? Ну, далеко не у всех пользователей windows установлен интерпретатор python с нужными библиотеками. А вот упакованная программа в идеале должна запуститься на любой windows-машине.
Установка
К сожалению, py2exe не поддерживает третью версию питона.
Скачать py2exe можно на SourceForge.
Если у вас стоит python (а он у вас наверняка стоит), проблем с установкой возникнуть не должно. Ставится в директорию python.
Конвертация
Теперь начинается самое интересное. В директории, где лежит Ваша программа на python, надо создать файл setup.py со следующим содержанием
Где 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’ом. Консольное приложение. Работает элементарно. На вход передается файл, оно его сжимает. Для моей игры реверси размер уменьшился в ~3 раза.
- Удалить unicodedata.pyd, bz2.pyd, select.pyd, w9xpopen.exe. Веса немного, но, как минимум, в проекте станет меньше файлов
- Если в setup.py указать опцию optimize:2, то модули будут компилироваться в .pyo (python optimized code), а не в .pyc (python compiler script). Это не дает большого эффекта, но кто знает, может Вам повезет)
- И наконец, можно подчистить library.zip от неиспользованных модулей и кодировок. Только аккуратно.
Вывод
Ну вот, кажется, и все. Мы добились, чего хотели. Да, приложение получилось солидного размера (это вам не C++, например), зато на нашем любимом Python:)
py2exe for Python 3
py2exe is a software to build standalone Windows executable programs from Python scripts. py2exe can build console executables and windows (GUI) executables. py2exe supports the Python versions* included in the official development cycle.
Development of py2exe is hosted here: https://github.com/py2exe/py2exe.
Changes
The detailed changelog is published on GitHub.
- Add support for Python 3.11
- Drop support for Python 3.7
- Drop support for win32 wheels
- win32 wheels are still built and shipped but are provided untested. Issues experienced when using these wheels will not be investigated. See https://github.com/py2exe/py2exe/discussions/157 for further information.
- Introduce the new py2exe.freeze API. Documentation can be found here.
- Use of the setup.py py2exe command and of distutils is deprecated as per PEP 632. Both these interfaces will be removed in the next major release. See here for a migration guide.
- Add two hooks to fix the bundling of winrt and passlib .
- The log file for windows apps is now stored in %APPDATA% by default
- ModuleFinder now raises an explicit error if a required module is in excludes
- Restore hook functionality for pkg_resources
- The Stderr.write method used for windows apps now returns the number of written bytes
- Drop support for Python 3.6
- Include package metadata in the bundle archive (to be used by e.g. importlib.metadata )
- Fixed a bug that prevented to use the optimize option when six was in the bundle
- Fixed a bug that ignored the optimize flag for some packages
- New module finder mf310 written as a wrapper around CPython modulefinder.ModuleFinder
- Add support for Python 3.10
- New hook for scipy
- zipextimporter can now be built as a standalone extension via its own setup script
- ModuleFinder : add support for the pkg_resources.extern.VendorImporter loader
- New hooks for pkg_resources and infi
- zipextimporter supports external modules that use multi-phase initialization (PEP 489)
- New hook for selenium
- dllfinder provides a new method to add data files in the zip archive
- New hook for pycryptodomex
- ModuleFinder : respect excludes list in import_package
- Updated hook for matplotlib >= 3.4.0
- New hook for supporting matplotlib 3.2 and higher.
- Fix for including implicit namespace packages as per PEP420.
- New module finder with support for implicit namespace packages (PEP 420).
- DLLFinder automatically excludes VC++ redist and Windows CRT DLLs from bundles.
- Several fixes for bundling software with bundle_files
- New hooks for pycryptodome and shapely .
- Add support for Python 3.9.
- Drop support for Python 3.5.
- New hooks for urllib3 and pandas .
Version 0.10.0.2 (from versions 0.9.x):
- Introduce compatibility with Python 3.5, 3.6, 3.7, and 3.8.
- Drop compatibility with Python 3.4 and earlier.
- New or updated hooks for certifi , numpy , tkinter , socket , ssl , and six .
- build_exe : the zipfile=None option has been removed.
- runtime : the Python interpreter DLL is no longer altered before being inserted in the executable bundle.
- Several bugfixes, better error messages.
Installation
Usage
Use the py2exe.freeze function as documented here.
Using a setup.py script or the builder
Using a setup.py script with py2exe is deprecated. Please adapt your scripts to use the new freeze API. This interface will be removed in the next major release.
The build_exe (or -m py2exe ) CLI was removed in version 0.13.0.0.
Known issues and notes
- High-level methods or hooks to embed Qt plugins in the bundle (needed by PySide2/PyQt5) are missing.
- (*) win32 wheels are provided without testing. Users are encouraged to use the win_amd64 wheels (see #157).
Credits
Further informations about the original development of py2exe and other usage guidelines can be found in the original README.
Как из файла Python3 создать .exe на Windows
Мы рассмотрим создание .exe с помощью библиотеки модуля py2exe. Для этого необходим Python 3.4 и ниже.
Если у вас установлена более высокая версия Python, попробуйте использовать Способ 2 (ниже)
В этом примере мы рассмотрим создание .exe на примере Python3.4.
Прежде всего на нужно создать виртуальное окружение для Python3.4. В этом примере мы назовем myenv, Вы можете выбрать любое другое имя, но не забывайте сделать соответствующие изменения.
На терминале наберите следующие команды:
>py -3.4 -m venv myenv > myenv\Scripts\activate.bat
В командной строке появится префикс myenv, а это значит, что виртуальное окружение с именем myenv загружено. Все команды Python теперь будет использовать новое виртуальное окружение.
Теперь давайте установим py2exe (https://pypi.python.org/pypi/py2exe~~HEAD=dobj) в нашем виртуальном окружении:
>pip install py2exe
И, наконец, чтобы создать единый EXE-файл, в нашем виртуальном окружении выполняем команду:
>python -m py2exe.build_exe hello.py -c --bundle-files 0
(замените hello.py на имя вашего скрипта. Если скрипт находится в другой папке, то нужно использовать полный путь к вашему сценарию, например, C:\Projects\Python\ hello.py). Это создаст папку DIST, которая содержит исполняемый файл. Для быстрого доступа к нему, наберите в терминале:
Вы увидите путь к папке, где находится EXE-файл.
Примечание: При выполнении, откроется окно и исчезают так же быстро, как и появилось.
Это происходит потому, что операционная система автоматически закрывает терминал, в котором консольная программа закончена.
Для того, чтобы изменить эту ситуацию, можно добавить строчку> input (" Нажмите для выхода . ")
в конце файла Python. Интерпретатор будет ждать ввода пользователя, а окно будет оставаться открытым, пока пользователь не нажимает клавишу ввода.
Вы можете подробно изучить использование py2exe в документации на странице модуля: https://pypi.python.org/pypi/py2exe
Выход из виртуального окружения производится командойСпособ 2
Через командную строку Windows устанавливаем pyinstaller:
В командной строке переходим в папку, где находится файл
Затем в командной строке набираем команду
pyinstaller --onefile example.py
Вместо exapmle.py используем имя файла, из которого нужно создать exe файл.
Через пару минут все готово! Скоркее всего, exe файл будет находится во созданной подпапке dist
py2exe
py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.
Development is hosted on GitHub. You can find the mailing list, svn, and downloads for Python 2 there. Downloads for Python 3 are on PyPI.
py2exe was originally developed by Thomas Heller who still makes contributions. Jimmy Retzlaff, Mark Hammond, and Alberto Sottile have also made contributions. Code contributions are always welcome from the community and many people provide invaluable help on the mailing list and the Wiki.
py2exe is used by BitTorrent, SpamBayes, and thousands more — py2exe averages over 5,000 downloads per month.
In an effort to limit Wiki spam, this front page is not editable. Feel free to edit other pages with content relevant to py2exe. You will need an account to edit (but not to read) and your account information will be used only for the purposes of administering this Wiki.
The old py2exe web site is still available until that information has found its way into this wiki.
Starting Points
- Download py2exe for Python 2 from SourceForge
- Download py2exe for Python 3 from PyPI
- News: information about the most recent releases
- Tutorial: the basics of creating a Windows executable
- FAQ: What does py2exe actually do and what are all those files?
- GeneralTipsAndTricks: general tips for working with special situations
- WorkingWithVariousPackagesAndModules: many just work, others need more handling
- ProblemsToBeFixed
- TroubleshootingImportErrors
- ReleaseProcess
- NonEnglish: read about py2exe in other languages
- Get help on the mailing list
- #py2exe IRC channel at Freenode.net
How to use this site
- Edit any page by pressing Правка at the top or the bottom of the page
- Create a link to another page with joined capitalized words (like WikiSandBox) or with [[words in brackets]]
- Search for page titles or text within pages using the search box at the top of any page
- See HelpForBeginners to get you going, HelpContents for all help pages.
To learn more about what a WikiWikiWeb is, read about WhyWikiWorks and the WikiNature.
FrontPage (последним исправлял пользователь albertosottile 2020-10-27 22:20:58)