Py2exe как пользоваться python 3
Перейти к содержимому

Py2exe как пользоваться python 3

  • автор:

Rukovodstvo

статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.

Создание исполняемых файлов из скриптов Python с помощью py2exe

Введение Для выполнения сценариев Python требуется множество предварительных условий, таких как наличие установленного Python, наличие множества установленных модулей, использование командной строки и т. Д., В то время как выполнение файла .exe очень просто. Если вы хотите создать простое приложение и распространить его среди множества пользователей, написать его в виде короткого скрипта Python несложно, но предполагается, что пользователи знают, как запускать скрипт, и Python уже установлен на их машине. Примеры, подобные этому, показывают, что там

Время чтения: 4 мин.

Вступление

Выполнение скриптов Python требует множества предварительных условий, таких как наличие установленного Python, наличие множества установленных модулей, использование командной строки и т. Д., В то время как выполнение .exe очень просто.

Если вы хотите создать простое приложение и распространить его среди множества пользователей, написать его в виде короткого скрипта Python несложно, но предполагается, что пользователи знают, как запускать скрипт, и Python уже установлен на их машине.

Примеры, подобные этому, показывают, что есть веская причина для преобразования .py в эквивалентные .exe в Windows. .exe означает «Исполняемый файл» , который также известен как двоичный файл.

Самый популярный способ добиться этого — использовать модуль py2exe В этой статье мы быстро рассмотрим основы py2exe и устраним некоторые распространенные проблемы. Чтобы продолжить, не требуется никаких дополнительных знаний Python, однако вам придется использовать Windows.

Преобразование кода интерпретируемого языка в исполняемый файл — это практика, обычно называемая замораживанием .

Установка py2exe

Чтобы использовать py2exe , нам нужно его установить. Сделаем это с помощью pip :

Преобразование скрипта Python в .exe

Во-первых, давайте напишем программу, которая будет выводить текст на консоль:

Давайте запустим следующие команды в командной строке Windows, чтобы создать каталог ( exampDir ), переместить уже написанный код в указанный каталог и, наконец, выполнить его:

Это должно вывести:

Всегда проверяйте скрипты, прежде чем превращать их в исполняемые файлы, чтобы убедиться, что если есть ошибка, она не вызвана исходным кодом.

Установка и конфигурация

Создайте в той же папке еще один файл с именем setup.py Здесь мы сохраним детали конфигурации того, как мы хотим скомпилировать нашу программу. Сейчас мы просто добавим в него пару строк кода:

Если бы мы имели дело с приложением с графическим интерфейсом пользователя, мы бы заменили console такими windows

Теперь откройте командную строку от имени администратора, перейдите в только что упомянутый каталог и запустите файл setup.py

папка dist

Если все сделано правильно, должен появиться подкаталог с именем dist . Внутри него будет несколько разных файлов, в зависимости от вашей программы, и одним из них должен быть example.exe . Чтобы выполнить его из консоли, запустите:

И вас встретит наша латинская цитата, за которой следует значение 4 !:

Или вы можете дважды щелкнуть по нему, и он запустится в консоли.

Если вы хотите объединить все файлы, добавьте bundle_files и compressed и установите для zipfile значение None следующим образом:

И повторно запустите команды, чтобы сгенерировать файл .exe.

Теперь ваши конечные пользователи могут запускать ваши сценарии без каких-либо знаний или предварительных условий, установленных на их локальных машинах.

Поиск проблемы

Ошибки при преобразовании файлов .py .exe являются обычным явлением, поэтому мы перечислим некоторые распространенные ошибки и решения.

Как исправить отсутствующие библиотеки DLL после использования py2exe

Распространенной проблемой py2exe является отсутствие .dll -s.

DLL означает «библиотека с динамической компоновкой», и они существуют не только для того, чтобы делать ошибки, обещаю. DLL содержат код, данные и ресурсы, которые могут понадобиться нашей программе во время выполнения.

Если после запуска .exe вы получите системную ошибку, которая говорит что-то вроде:

Или в командной строке написано:

Решение состоит в том, чтобы найти недостающую .dll и вставить ее в папку dist. Есть два способа сделать это.

  1. Найдите файл на своем компьютере и скопируйте его. Это будет работать в большинстве случаев.
  2. Найдите в Интернете отсутствующую .dll и загрузите ее. Постарайтесь не скачивать его с какого-нибудь теневого сайта.
Как сгенерировать 32/64-битные исполняемые файлы с помощью py2exe?

Чтобы сделать 64-битный исполняемый файл, установите на ваше устройство 64-битный Python. То же самое и с 32-битной версией.

Как использовать py2exe в Linux или Mac

py2exe не поддерживает Linux или Mac, так как он предназначен для создания файлов .exe, которые являются уникальным для Windows форматом. Вы можете загрузить виртуальную машину Windows как на Mac, так и на Linux, использовать Wine или использовать другой инструмент, например Pyinstaller в Linux или py2app на Mac.

Заключение

Чтобы упростить запуск проектов Python на устройствах Windows, нам нужно создать исполняемый файл. Мы можем использовать множество различных инструментов, таких как Pyinstaller , auto-py-to-exe , cx_Freeze и py2exe .

Двоичные файлы могут использовать библиотеки DLL, поэтому обязательно включите их в свой проект.

Немного про py2exe

Есть такое приложение. Называется py2exe. Оно позволяет упаковать, сконвертировать программу на python в exe файл (ну, точнее, exe и еще кучку других). Зачем оно все надо? Ну, далеко не у всех пользователей windows установлен интерпретатор python с нужными библиотеками. А вот упакованная программа в идеале должна запуститься на любой windows-машине.

Установка

К сожалению, py2exe не поддерживает третью версию питона.
Скачать py2exe можно на SourceForge.
Если у вас стоит python (а он у вас наверняка стоит), проблем с установкой возникнуть не должно. Ставится в директорию python.

Конвертация
  1. from distutils.core import setup
  2. import py2exe
  3. setup(
  4. windows=[< "script" : "main.py" >],
  5. options=< "py2exe" : < "includes" :[ "sip" ]>>
  6. )

Где main.py имя Вашего скрипта.

Далее запускаем упаковку командой:

Да-да, именно так.

Смотрим, что у нас получилось. Две папки.
build — служебная, можно сразу снести.
dist — собственно, в ней и лежит наша программа.

  • main.exe — программа
  • pythonXX.dll — интерпретатор python’a
  • library.zip — архив со скомпилированными исходниками (всего, кроме собственно программы, как я понимаю)
  • .pyd — модули python, которые импортирует программа
  • .dll — библиотеки, оказавшиеся необходимыми
  • и еще файлы по мелочи, ниже будет сказано еще
Сложности

Скорее всего возникнут какие-то проблемы.

Например, пути к файлам. Не следует использовать относительные пути. Они ведут неведомо куда. Лучше использовать абсолютные.
Как его узнать? в интернете есть решение, функция module_path.

  1. import os, sys
  2. def module_path ():
  3. if hasattr(sys, «frozen» ):
  4. return os.path.dirname(
  5. unicode(sys.executable, sys.getfilesystemencoding( ))
  6. )
  7. return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))

Или приложение наотрез откажется запускаться (возможно, не у Вас, а у кого-то еще). Из-за отсутствие библиотек Visual Studio.
В качестве решения проблемы можно установить их на компьютер (но это же не наш метод) или кинуть dll и файл манифеста в папку с программой.
msvcr90.dll и Microsoft.VC90.CRT.manifest (не знаю как это лицензируется и выкладывать не буду)
Где их взять? Для меня самым простым было переустановить python (все остальное осталось на месте) в режиме «только для меня». И искомые файлы оказались в папке с python.

Целью топика не являлось раскрыть всех особенностей py2exe. Здесь находится туториал, а тут некоторые советы и трюки.

Размер

В силу некоторых особенностей, приложение может получиться ужасающего размера. Но с этим можно и нужно бороться. Идеи подсказал kAIST (ну, кроме upx’а =р)

    Самое действенное. Сжать библиотеки upx’ом. Консольное приложение. Работает элементарно. На вход передается файл, оно его сжимает. Для моей игры реверси размер уменьшился в

How To Turn Python Scripts into Windows Executables

Python scripts are useful and easy — but only if you have the Python interpreter installed on your PC. If not, you can’t run them.

The first way around this that I used was called Py2Exe. It was a bit kludgy, but worked well enough at a time when there weren’t many options.

Despite my best efforts, time moved on and now we have more options for turning Python scripts into executables.

One good such option is PyInstaller, which seems to be very straightforward and has a (so far) great one-file packaging option. It produced a

6MB exe for a simple CLI script that does nothing, but who cares about disk usage these days anyway?

PyInstaller

PyInstaller seems to be a much more straightforward means of getting an exe from a Python script. I didn’t have to muck around with any setup.py files or options or anything, just a simple command line. And, I got a single executable very easily.

The webpage for PyInstaller has a pretty straightfoward set of instructions for installing and using PyInstaller. It got me up and running right away.

Installation

Here’s what I did and what happened:

Generating an Executable

After that, it’s a simple command-line to generate an executable:

This produced dist/pyCli.exe — one file only!

I’m kind of sad how easy that was.

Issues

With my version of PyInstaller Windows Defender flags it as a virus: Trojan:Win32/Wacatac.B!ml

This is a false alarm.

There’s a StackOverflow detailing the issue and fixes here.

Py2Exe — Deprecated

You probably shouldn’t even bother reading any of this, but it’s retained here for completeness. Also, maybe it’ll be useful someday. Who knows.

It’s worth noting that Py2Exe only works on Windows with Windows Python — not Cygwin Python.

Installation

You’ll need Python 2.7 for Windows installed before you can do install Py2Exe.

Installation is as simple as opening a command prompt and typing:

Alternately, you can go online and download it form SourceForge and then use the installer to install it.

Usage

First, you need a script to turn into an executable:

Well, that was easy. I’m going to store that script in a subdirectory of my project directory called ‘src’, so it’ll be at the relative path ‘src/helloWorld.py’.

This isn’t the only script you need. You’ll also need a setup.py script which has content that looks like this:

This script acts as a wrapper which allows Py2Exe to turn your script into an executable.

On the command line, you can generate the executable by navigating to the project directory and typing:

This produces a lot of output on the console, but more importantly will produce two directories: build and dist.

build contains temporary and leftover files used in the build. I’ve had no problem deleting it after a build. The dist folder contains everything your EXE needs to operate. The upshot is that if you want to move the EXE to another system, you need to copy everything in the dist folder to the new system and keep the directory structure in that folder intact. The main output of this process is the dist/helloWorld.exe file: the executable name matches the name of the Python script.

Once you run that executable, you’ll get the output you expect:

Generating a Single Executable File

Normally, when using Py2Exe, it will generate a big directory of miscellaneous files that are kinda messy alongside the executable you want. There’s a way you can slim it all down to just one executable file.

This site discusses the options that you can pass to py2exe when you invoke it. The script that generates a single executable is here:

Issues

Missing Modules

I have more complex scripts that I want to turn into executables. These scripts import Python files that are present in the same directory. Py2Exe cannot seem to find these files and include them into the executable which means that the EXE will not work. The way to fix this is to alter the system path from within the setup.py script to add the path to the modules you want to import. For example, if the files are in the src subdirectory of the project directory, then you can modify the setup.py script as follows:

Once done, the script finds all of my custom modules, imports them and the EXE runs fine.

Dropbox, Virus Scanners, and WinError 110

Sometimes, you’ll get an error like this:

This sort of error is caused by another program trying to access the files that py2exe is trying to access. Usually, this is an antivirus program or (in my case) Dropbox. I remedied this error by turning off Dropbox or by moving the folder outside of my Dropbox folder.

py2exe: Python to exe Introduction

py2exe is a simple way to convert Python scripts into Windows .exe applications. It is an utility based in Distutils that allows you to run applications written in Python on a Windows computer without requiring the user to install Python. It is an excellent option when you need to distribute a program to the end user as a standalone application. py2exe currently only works in Python 2.x.

First you need to download and install py2exe from the official sourceforge site

Now, in order to be able to create the executable we need to create a file called setup.py in the same folder where the script you want to be executable is located:

[python]
# setup.py
from distutils.core import setup
import py2exe
setup(console=[‘myscript.py’])
[/python]

In the code above, we are going to create an executable for myscript.py . The setup function receives a parameter console=[‘myscript.py’] telling py2exe that we have a console application called myscript.py .

Then in order to create the executable just run python setup.py py2exe from the Windows command prompt (cmd). You will see a lot of output and then two folders will be created: dist and build . The build folder is used by py2exe as a temporary folder to create the files needed for the executable. The dist folder stores the executable and all of the files needed in order to run that executable. It is safe to delete the build folder. Note: Running python setup.py py2exe assumes that you have Python in your path environment variable. If that is not the case just use C:\Python27\python.exe setup.py py2exe .

Now test if your executable works:

[shell]
cd dist
myscript.exe
[/shell]

GUI Applications

Now it is time to create a GUI application. In this example we will be using Tkinter:
[python]
# tkexample.py
»’A very basic Tkinter example. »’
import Tkinter
from Tkinter import *
root = Tk()
root.title(‘A Tk Application’)
Label(text=’I am a label’).pack(pady=15)
root.mainloop()
[/python]

Then create setup.py , we can use the following code:
[python]
# setup.py
from distutils.core import setup
import py2exe

The setup function now is receiving a parameter windows=[‘tkexample.py’] telling py2exe that this is a GUI application. Again create the executable running python setup.py py2exe in the Windows command prompt. To run the application just navigate to the dist folder in the Windows Explorer and double-click tkexample.exe .

Using External Modules

The previous examples were importing modules from the Python Standard Library. py2exe includes the Standard Library Modules by default. However if we installed a third party library, py2exe is likely not to include it. In most of the cases we need to explicitly include it. An example of this is an application using the ReportLab library to make PDF files:

[python]
# invoice.py
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import mm

if __name__ == ‘__main__’:
name = u’Mr. John Doe’
city = ‘Pereira’
address = ‘ELM Street’
phone = ‘555-7241’
c = canvas.Canvas(filename=’invoice.pdf’, pagesize= (letter[0], letter[1]/2))
c.setFont(‘Helvetica’, 10)
# Print Customer Data
c.drawString(107*mm, 120*mm, name)
c.drawString(107*mm, 111*mm, city)
c.drawString(107*mm, 106*mm, address)
c.drawString(107*mm, 101*mm, phone)
c.showPage()
c.save()
[/python]

In order to include the ReportLab module, we create a setup.py file, passing a options dictionary to the setup function:

[python]
# setup.py
from distutils.core import setup
import py2exe

setup(
console=[‘invoice.py’],
options = <
‘py2exe’: <
‘packages’: [‘reportlab’]
>
>
)
[/python]

The final step to be able to run the executable on other computers, is that the computer running the executable needs to have the Microsoft Visual C++ 2008 Redistributable package installed. A good guide explaining how to do this can be found here. Then just copy the dist folder to the other computer and execute the .exe file.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *