How to make exe from python

How to make exe from python

Python on Windows FAQВ¶

How do I run a Python program under Windows?В¶

This is not necessarily a straightforward question. If you are already familiar with running programs from the Windows command line then everything will seem obvious; otherwise, you might need a little more guidance.

The letter may be different, and there might be other things after it, so you might just as easily see something like:

depending on how your computer has been set up and what else you have recently done with it. Once you have started such a window, you are well on the way to running Python programs.

You need to realize that your Python scripts have to be processed by another program called the Python interpreter. The interpreter reads your script, compiles it into bytecodes, and then executes the bytecodes to run your program. So, how do you arrange for the interpreter to handle your Python?

First, you need to make sure that your command window recognises the word “py” as an instruction to start the interpreter. If you have opened a command window, you should try entering the command py and hitting return:

You should then see something like:

You have started the interpreter in “interactive mode”. That means you can enter Python statements or expressions interactively and have them executed or evaluated while you wait. This is one of Python’s strongest features. Check it by entering a few expressions of your choice and seeing the results:

So now you’ll ask the py command to give your script to Python by typing py followed by your script path:

How do I make Python scripts executable?В¶

Why does Python sometimes take so long to start?В¶

Usually Python starts very quickly on Windows, but occasionally there are bug reports that Python suddenly begins to take a long time to start up. This is made even more puzzling because Python will work fine on other Windows systems which appear to be configured identically.

The problem may be caused by a misconfiguration of virus checking software on the problem machine. Some virus scanners have been known to introduce startup overhead of two orders of magnitude when the scanner is configured to monitor all reads from the filesystem. Try checking the configuration of virus scanning software on your systems to ensure that they are indeed configured identically. McAfee, when configured to scan all file system read activity, is a particular offender.

How do I make an executable from a Python script?В¶

See How can I create a stand-alone binary from a Python script? for a list of tools that can be used to make executables.

Is a *.pyd file the same as a DLL?В¶

How can I embed Python into a Windows application?В¶

Embedding the Python interpreter in a Windows app can be summarized as follows:

SWIG will create an init function (a C function) whose name depends on the name of the extension module. For example, if the name of the module is leo, the init function will be called initleo(). If you use SWIG shadow classes, as you should, the init function will be called initleoc(). This initializes a mostly hidden helper class used by the shadow class.

In short, you can use the following code to initialize the Python interpreter with your extension module.

There are two problems with Python’s C API which will become apparent if you use a compiler other than MSVC, the compiler used to build pythonNN.dll.

Problem 1: The so-called “Very High Level” functions that take FILE * arguments will not work in a multi-compiler environment because each compiler’s notion of a struct FILE will be different. From an implementation standpoint these are very _low_ level functions.

Problem 2: SWIG generates the following code when generating wrappers to void functions:

Alas, Py_None is a macro that expands to a reference to a complex data structure called _Py_NoneStruct inside pythonNN.dll. Again, this code will fail in a mult-compiler environment. Replace such code by:

It may be possible to use SWIG’s %typemap command to make the change automatically, though I have not been able to get this to work (I’m a complete SWIG newbie).

Using a Python shell script to put up a Python interpreter window from inside your Windows app is not a good idea; the resulting window will be independent of your app’s windowing system. Rather, you (or the wxPythonWindow class) should create a “native” interpreter window. It is easy to connect that window to the Python interpreter. You can redirect Python’s i/o to _any_ object that supports read and write, so all you need is a Python object (defined in your extension module) that contains read() and write() methods.

How do I keep editors from inserting tabs into my Python source?В¶

The FAQ does not recommend using tabs, and the Python style guide, PEP 8, recommends 4 spaces for distributed Python code; this is also the Emacs python-mode default.

Python raises IndentationError or TabError if mixed tabs and spaces are causing problems in leading whitespace. You may also run the tabnanny module to check a directory tree in batch mode.

How do I check for a keypress without blocking?В¶

Use the msvcrt module. This is a standard Windows-specific extension module. It defines a function kbhit() which checks whether a keyboard hit is present, and getch() which gets one character without echoing it.

How to make an executable file in Python?

I want to make an executable file (.exe) of my Python application.

I want to know how to do it but have this in mind: I use a C++ DLL!

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

7 Answers 7

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

py2exe can generate single file executables. see this link for examples.

The setup.py I use uses the following combination of options:

I usually add external dlls (p.e. msvcr71.dll) in the same folder where the executable is.

To facilitate distribution and to automate installation after generating your exe you can use Inno Setup to create an installer that puts your exe and your dlls, and other documents (readme, etc) into the application directory

Follow These Steps: You can find this documentation in this site.

1) Install PyInstaller:

Assuming you have PIP installed in this directory c:\PythonXX\Scripts if not go to this site and see instructions on how to «Install Python Indexing Project (PIP)». Go to your command prompt and type the following command.

2) Install PyWin32:

Go to this SITE and look for the executable named pywin32-218.win32-py2.7.exe 2.7 which is for 32 bit systems for python27 look for the one that corresponds to you. Run the executable file and it should install PyWin32 successfully which works hand in hand with pyinstaller!

3) Create Single Executable file

Now that you have PyInstaller and PyWin32 you can start to create the single executable file. The single executable file will be created inside another folder called “dist” this folder is also created dynamically when you run the pyinstaller command. To make things clear your pyinstaller files where copied by you to another folder probably called «pyinstaller_files» folder so now type the following command in your command prompt.

pyqtdeploy, или упаковываем Python-программу в exe’шник… the hard way

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Наверняка, каждый, кто хоть раз писал что-то на Python, задумывался о том, как распространять свою программу (или, пусть даже, простой скрипт) без лишней головной боли: без необходимости устанавливать сам интерпретатор, различные зависимости, кроссплатформенно, чтобы одним файлом-exe’шником (на крайний случай, архивом) и минимально возможного размера.

Для этой цели существует немало инструментов: PyInstaller, cx_Freeze, py2exe, py2app, Nuitka и многие другие… Но что, если вы используете в своей программе PyQt? Несмотря на то, что многие (если не все) из выше перечисленных инструментов умеют упаковывать программы, использующие PyQt, существует другой инструмент от разработчиков самого PyQt под названием pyqtdeploy. К моему несчастью, я не смог найти ни одного вменяемого гайда по симу чуду, ни на русском, ни на английском. На хабре и вовсе, если верить поиску, есть всего одно упоминание, и то — в комментариях (из него я и узнал про эту утилиту). К сожалению, официальная документация написана довольно поверхностно: не указан ряд опций, которые можно использовать во время сборки, для выяснения которых мне пришлось лезть в исходники, не описан ряд тонкостей, с которыми мне пришлось столкнуться.

Данная статья не претендует на всеобъемлющее описание pyqtdeploy и работы с ним, но, в конце концов, всегда приятно иметь все в одном месте, не так ли?

Замечание. В статье исполняемый файл собирается под linux. Несмотря на это, в качестве синонима используется слово «exe’шник» для экономии букв и уменьшения числа повторений.

Тут мне подвернулся pyqtdeploy. «Утилита от самих разработчиков PyQt… Ну уж они-то должны знать, как по-максимуму отвязаться от лишних зависимостей внутри PyQt и Qt?» — подумал я и взялся плотненько за сей агрегат.

Так что же такое pyqtdeploy? В первом приближении, то же самое, что и выше перечисленные программы. Все ваши модули (стандартная библиотека, PyQt, все прочие модули) упаковываются средствами Qt (используется утилита rcc) в так называемый файл ресурсов, генерируется обертка вокруг питоновского интерпретатора на C++, позволяющая получать доступ ко все вашим модулям, и потом все это пакуется/компилируется/… в исполняемый файл. Для работы самого pyqtdeploy нужны Python 3.5+ и PyQt5. Перечислим несколько особенностей (за подробностями сюда и сюда):

Установка pyqtdeploy

Как уже было сказано выше, у нас должен быть установлен Python 3.5+ и PyQt5:

Сборка нашего exe’шника состоит из нескольких этапов:

Структура программы

Возьмем в качестве примера проект со следующей структурой: main.py — «точка входа» для нашей программы, она вызывает mainwindow.py — допустим, отрисовывает окошечко с виджетами и берет из resources иконку icon.png и mainwindow.ui, сгенерированный нами с помощью Qt Designer. Имеющиеся зависимости, версии библиотек и прочие необходимые вещи будут всплывать по ходу повествования:

Обзор плагинов sysroot (документация)

Как уже было сказано ранее, на этом этапе мы собираем все необходимые части, которые затем будут использоваться при генерации исполняемого файла. Данный процесс осуществляется с использованием конфигурационного файла sysroot.json (в принципе, вы можете назвать его как хотите и указать затем путь к нему). Он состоит из блоков, каждый из которых описывает сборку отдельного компонента (Python, Qt и т.д.). В pyqtdeploy реализован API, позволяющий вам написать свой плагин, управляющий сборкой необходимой вам библиотеки/модуля/whatever, если он еще не реализован разработчиками pyqtdeploy. Давайте пробежимся по стандартным плагинам и их параметрам (примеры из документации):

openssl (не обязательный) — позволяет собирать из исходников или использовать установленную в системе библиотеку (подробности). Компонент, описывающий данный плагин в sysroot.json, выглядит следующим образом:

zlib (не обязательный) — используется при сборке других компонентов (если не указан, по идее, будет использоваться тот, что установлен в системе) (подробности):

qt5 (обязательный) — тут понятно (подробности):

python (обязательный) — тут тоже понятно (подробности):

sip (обязательный) — компонент, отвечающий за автоматическое генерирование Python-bindings для C/C++ библиотек (подробности тут и тут):

pyqt5 (обязательный) — тут тоже понятно (подробности):

pyqt3D, pyqtchart, pyqtdatavisualization, pyqtpurchasing, qscintilla (не обязательные) — дополнительные модули, не входящие в состав PyQt. Имеют единственный параметр source — имя архива с исходниками.

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

Собираем sysroot

Давайте взглянем на итоговый sysroot.json для нашей программы:

Что интересного мы тут видим? Во-первых, не используется ряд компонентов(например, ssl, pyqt3D и прочие). Во-вторых, собирать наш exe’шник мы будет под linux (а точнее, linux-64; в нашем случае, можно не указывать перед каждым компонентом платформу).

В pyqt5 собираем только модули QtCore, QtGui, QtWidgets.

Прежде чем приступить к сборке sysroot, не забываем скачать все необходимые исходники: zlib, Qt5, Python, sip, PyQt5 и кладем их в папочку с sysroot.json (можно и любую другую, указав потом путь к ней). Запускаем сборку:

Данная команда имеет еще несколько опций, которые можно посмотреть здесь.

Ну и запаситесь попкорном, ибо, в зависимости от мощности вашего калькулятора компьютера, это может занять немалое время.

Создаем «проектный» файл (документация)

Как только у нас все удачно собралось, приступаем к выбору модулей, которые мы хотим запаковать в exe’шник. Для этого в pyqtdeploy есть удобная утилита с GUI. Запускаем (имя .pdy файла может быть любым):

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Application Source. В первой вкладке мы видим следующие настройки:

Еще один момент: любой файл с расширением .py будет «заморожен» (будет сгенерирован байт-код) — в ряде случаев это может быть нежелательным.

qmake. Так как в сборке участвует qmake, здесь можно добавить дополнительные параметры для него (я не использовал);

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

PyQt Modules. На этой вкладке выделяем все PyQt-модули, которые мы явно импортируем в нашей программе. Если они зависят от других модулей, те выделятся автоматически. В нашем случае использовались QtCore, QtGui, QtWidgets, uic; sip подхватился автоматом.
Если планируется использовать уже установленный PyQt, а не привязывать статически его к нашему исполняемому файлу, ничего не выделяем (такой сценарий не тестировался).

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Standard Library. Здесь тот же подход, что и в предыдущем пункте, только для стандартной библиотеки. Если у вас в программе явно импортируется какой-то модуль, ставим галку. Если выделенным нами модулям (или самому интерпретатору) нужны другие модули, они выделятся автоматом (квадратики).

Python использует ряд модулей/пакетов (например, ssl), которым для работы нужны внешние библиотеки. Если мы хотим их статически привязать, то мы настраиваем это дело справа. В INCLUDEPATH указываем путь к заголовочным файлам (headers), в LIBS — путь к этой либе (мной не использовались, так что подробности смотрим в доках).

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Other Packages. На этой вкладке выбираем необходимые нам сторонние пакеты (например, установленные из pypi). Подход тот же, что и в Application source: кликаем дважды на пустой строке, выбираем папку (в нашем случае, site-packages используемого при разработке virtual environment), жмем Scan и выбираем нужные пакеты/модули (у нас это PIL).

Other Extension Modules. Тут мы настраиваем модули расширения на C, которые хотим СТАТИЧЕСКИ привязать к exe’шнику (сторонние; те, что в стандартной библиотеке, привязываются сами).

С компиляцией я не разбирался, но советую почитать, во-первых, про эту вкладку в доках, во-вторых, про qmake (там гораздо подробнее описаны опции, чем в pyqt’шных доках).

Locations. Тут тоже подробно не останавливаемся, за описанием отдельных путей сюда. Если вы действовали в соответствии с этой статьей (собранный sysroot лежит тут же, рядом с main.pdy), тут менять ничего не надо.

Собираем exe’шник (документация)

Наконец-таки собираем наш исполняемый файл:

Гипотетически, все должно собраться, на деле — доки и гугл вам в помощь.

Лирическое отступление #1 — меняем поведение программы в зависимости от того, «заморожено» оно или нет

Если вам нужно определить, запущена ваша программа как есть или из собранного exe’шника, используется тот же подход, что и в PyInstaller:

Лирическое отступление #2 — использование ресурсов (изображения, иконки и пр.)

У Qt имеется специальная «система ресурсов», которая позволяет с помощью утилиты rcc упаковать любые бинарные файлы в exe’шник. Далее с помощью пути специального формата вы можете получить доступ к необходимому ресурсу. В нашем проекте файл с иконкой icon.png расположен в src/resources/images, тогда путь в «системе ресурсов» будет выглядеть так — :/src/resources/images/icon.png. Как видите, ничего хитрого. Однако с таким путем есть одна засада — его понимают только Qt’шные функции. Т.е. если вы напишите у себя в программе что-нибудь в духе:

Все будет в порядке. Но если, например, так:

Ничего не выйдет, ибо open будет пытаться найти такой путь в вашей файловой системе и, естественно, ничего не найдет.

Если вам нужно читать запакованные ресурсы не только средствами Qt (например, вы, как и я, создавали GUI с помощью Qt Designer и получили файл .ui, который потом надо прочитать с помощью loadUi ), нужно будет сделать как-то так:

Итоги

Стоит ли так сильно заморачиваться, если вам нужен exe’шник, и старые добрые дедовские способы распространения программы вам по каким-то причинам не подходят? Если вы не используете PyQt, то, на мой взгляд, точно не стоит. Используйте что-нибудь более дружелюбное (тот же PyInstaller). Если хотите выжать максимум соков из вашего файла — дерзайте. В конечном счете мне таки удалось уменьшить размер файла до

35 МБ), что все-равно больше, чем хотелось бы.

Когда у нас собрана минимально необходимая Qt и PyQt, было бы неплохо попробовать сделать на их основе exe’шник с помощью PyInstaller или cx_Freeze и посмотреть на размер, но это, как говорится, уже другая история.

How to Easily Convert a Python Script to an Executable File (.exe)

Two simple ways to create a Python executable file.

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Although running a Python script using the terminal or your favorite text editor is straightforward, there are some situations in which you will prefer to hide all the code written in the script (.py) inside an executable file (.exe).

Making an Executable file with auto-py-to-exe

The first option offers a nice GUI (graphical user interface) that takes care of all the stuff necessary to convert your Python script into an executable file.

Installing with pip

To install the last version of auto-py-to-exe, just open up a terminal and run the following command.

Note: Make sure that the working environment in which you’re installing auto-py-to-exe contains all the libraries that your script needs to run.

Running auto-py-to-exe

Once you install auto-py-to-exe, making an executable file is as easy as writing the following command.

After running the command, the following GUI application will open.

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

I will walk you through each option to properly create an executable file.

Steps to create an executable file

Step 1: Add the script location

Browse the script you wish to convert and add it to the “Script Location” field. In this example, I’m going to choose a script that automates Excel reports (you can find my guide to automate Excel in the link below)

A Simple Guide to Automate Your Excel Reporting with Python

Use openpyxl to automate your Excel reporting with Python.

Feel free to choose any script you want. However, if your script needs to read a path make sure that you use absolute paths since relative paths won’t behave as you might expect with executable files. If necessary, include the following line of code below to know where the executable file is located and make the necessary changes to your script so you read/export files on the right directory.

Step 2: Choosing “One Directory” or “One File”

Now we have to choose whether we want to create “one directory” or “one file.” The first creates a directory with all the dependencies your script needs to run (including the executable file), while the second creates only a single executable file.

For this example, I’ll choose the “one file” option.

Step 3. Choosing “Console Based” or “Window Based”

Now it’s time to choose whether the console will be displayed or not. If you choose “Console Based,” the console will open after running the executable file, which is recommended if your script generates console-based outputs. However, if you don’t want to show the console outputs when running the executable file, choose “Window Based”

My script needs the name of the Excel spreadsheet to be introduced as input in order to create my Excel report, so I’m going to choose “Console Based.”

4 Free and Paid Web Scraping Courses Every Data Scientist Should Take

Acquire this must-have skill every data scientist should have.

Step 4: Advanced options (e.g., output directory, additional imports)

You can add an icon, add files that your script needs to run, and more! However, for this example, I’ll only modify the path where the executable file will be exported. To do so, click on the “Setting” option and browse the output directory you wish.

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Note: If you see an error like this “ModuleFoundNotError: Not module named ‘ name_of_module’” after double-clicking on the executable file created, you’ll have to repeat from step 1 again, but now in the “Advanced” option write the module name is missing inside the “hidden-import” field.

Step 5: Convert the file

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Once the process is finished the executable file should be located in the output directory you set in step 4!

Making an Executable file with PyInstaller

This option fits better for those who prefer to quickly create an executable file running a command on the terminal.

If you’re used to working with the terminal, then the PyInstaller library will be the best option. To install PyInstaller follow these steps.

The command used in step 3 is similar to the code shown in the step 5 picture for the auto-py-to-exe option. You can play a little bit with the GUI offered by auto-py-to-exe to get used to the many options you can add to this command.

After running the command, you should see a message that says “completed successfully.” In the directory where your script is located, a folder named “dist” should have been created. Inside the folder, you’ll find the standalone executable!

Congratulations! Now your Python script has been converted to an executable file. In case you want to schedule when this file will run on your computer check this guide.

Step 1:
Install the library pyinstaller.
Type below command in the command prompt.

Step 2:
Go into the directory where your ‘.py’ file is located.

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Step 3:
Press the shift⇧ button and simultaneously right-click at the same location. You will get the below box.

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Step 4:
Click on ‘Open PowerShell window here’.

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

You will get a window shown below.

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Step 5:
Type the command given below in that PowerShell window.

Here the ‘.py’ file name is ‘1’.
See below:

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

In case you get an error at this point in the PowerShell window like this:

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

The correction while typing the above command:

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Step 6:
After typing the command ‘Hit the Enter’.
It will take some time to finish the process depending on the size of the file and how big is your project.
After the processing has been finished, the window will look as below:

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Step 7:
See the directory it should look like this:

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

‘build’ folder and ‘1.spec’ is of no use. You can delete these if you want, it will not affect your ‘.exe’ file.

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Step 8:
Open ‘dist’ folder above. Here you will get your ‘.exe’ file.

How to make exe from python. Смотреть фото How to make exe from python. Смотреть картинку How to make exe from python. Картинка про How to make exe from python. Фото How to make exe from python

Right-click on the file and check the properties.

Источники информации:

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

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