Pyinstaller windows from linux

How to Install PyInstaller В¶

PyInstaller is a normal Python package. You can download the archive from PyPi, but it is easier to install using pip where is is available, for example:

or upgrade to a newer version:

To install the current development version use:

Installing in WindowsВ¶

For Windows, PyWin32 or the more recent pypiwin32, is a prerequisite. The latter is installed automatically when you install PyInstaller using pip or easy_install. If necessary, follow the pypiwin32 link to install it manually.

It is particularly easy to use pip-Win to install PyInstaller along with the correct version of PyWin32. pip-Win also provides virtualenv, which makes it simple to maintain multiple different Python interpreters and install packages such as PyInstaller in each of them. (For more on the uses of virtualenv, see Supporting Multiple Platforms below.)

When pip-Win is working, enter this command in its Command field and click Run:

This creates a new virtual environment rooted at C:\Python\pyi-env-name and makes it the current environment. A new command shell window opens in which you can run commands within this environment. Enter the command

Once it is installed, to use PyInstaller ,

In the Command field enter venv pyi-env-name

Then you have a command shell window in which commands such as pyinstaller execute in that Python environment.

Installing in MacВ OSВ XВ¶

Mac OS X 10.8 comes with Python 2.7 pre-installed by Apple. However, Python 2.7 is end-of-life and no longer supported by PyInstaller , also major packages such as PyQt, Numpy, Matplotlib, Scipy, and the like, have dropped support for Python 2.7, too. Thus we strongly recommend that you install these using either MacPorts or Homebrew.

PyInstaller users report fewer problems when they use a package manager than when they attempt to install major packages individually.

Alternatively you might install Python 3 following the official guide.

Installing from the archiveВ¶

If pip is not available, download the compressed archive from PyPI. If you are asked to test a problem using the latest development code, download the compressed archive from the develop branch of PyInstaller Downloads page.

Expand the archive. Inside is a script named setup.py . Execute python setup.py install with administrator privilege to install or upgrade PyInstaller .

For platforms other than Windows, GNU/Linux and Mac OS, you must first build a bootloader program for your platform: see Building the Bootloader . After the bootloader has been created, use python setup.py install with administrator privileges to complete the installation.

Verifying the installationВ¶

On all platforms, the command pyinstaller should now exist on the execution path. To verify this, enter the command:

The result should resemble 3.n for a released version, and 3.n.dev0-xxxxxx for a development branch.

If the command is not found, make sure the execution path includes the proper directory:

Windows: C:\PythonXY\Scripts where XY stands for the major and minor Python version number, for example C:\Python34\Scripts for Python 3.4)

OS X (using the default Apple-supplied Python) /usr/bin

OS X (using Python installed by homebrew) /usr/local/bin

OS X (using Python installed by macports) /opt/local/bin

To display the current path in Windows the command is echo %path% and in other systems, echo $PATH .

Читайте также:  Aja system test для windows

Installed commandsВ¶

The complete installation places these commands on the execution path:

pyinstaller is the main command to build a bundled application. See Using PyInstaller .

pyi-makespec is used to create a spec file. See Using Spec Files .

pyi-archive_viewer is used to inspect a bundled application. See Inspecting Archives .

pyi-bindepend is used to display dependencies of an executable. See Inspecting Executables .

pyi-grab_version is used to extract a version resource from a Windows executable. See Capturing Windows Version Data .

If you do not perform a complete installation (installing via pip or executing setup.py ), these commands will not be installed as commands. However, you can still execute all the functions documented below by running Python scripts found in the distribution folder. The equivalent of the pyinstaller command is pyinstaller-folder /pyinstaller.py . The other commands are found in pyinstaller-folder /cliutils/ with meaningful names ( makespec.py , etc.)

© Copyright This document has been placed in the public domain.. Revision 5a02f55c .

Источник

How to generate an executable on Linux for Windows? #2613

Comments

Drakota commented May 18, 2017

I’m trying to generate an executable from Linux for Windows.

pyinstaller —onefile —windowed montecarlo.py
I run this command and get a single executable that works on Linux just fine, I can open it and use my program, but if I try on Windows, it’s just a simple file. On Linux it’s a executable (application/x-executable), but on Windows it’s a Type of file: File Why?

The text was updated successfully, but these errors were encountered:

ghost commented May 18, 2017

Come back when you’ve completed CS50.

Drakota commented May 18, 2017

Why this arrogant response? The file created on Linux is executable, but if I copy it to Windows it’s just a File changing the file extension to .exe doesn’t work.

ghost commented May 18, 2017 •

Well, let me just copy and paste what wikipedia says:

Binary compatible operating systems are OSes that aim to implement binary compatibility with another OS, or another variant of the same brand. This means that they are ABI-compatible (for application binary interface). As the job of an OS is to run programs, the instruction set architectures running the OSes have to be the same or compatible. Otherwise, programs can be employed within a CPU emulator or a faster dynamic translation mechanism to make them compatible.

For example, the Linux kernel is not compatible with Windows. This does not mean that Linux can’t be binary compatible with Windows applications. Additional software, Wine, is available that does that to some degree. The ReactOS OS development effort, seeks to create an open source, free software OS that is binary compatible with Microsoft’s Windows NT family of OSes using Wine for application compatibility and reimplementing the Windows kernel for additional compatibility such as for drivers whereas Linux would use Linux drivers not Windows drivers. FreeBSD and other members of the BSD family have binary compatibility with the Linux kernel in usermode by translating Linux system calls into BSD ones. This enables the application and libraries code that run on Linux-based OSes to be run on BSD as well.

Note that a binary compatible OS is different from running an alternative OS through virtualization or emulation, which is done to run software within the alternative OS in the case when the host OS isn’t compatible. Sometimes virtualization is provided with the host OS (or such software can be obtained), which effectively makes the host OS compatible with programs. For example, Windows XP Mode for Windows 7 allows users to run a 64-bit version of Windows 7 and enable old software to still work in a 32-bit virtual machine running Windows XP; VMware Workstation/VMware Fusion, Parallels Workstation, and Windows Virtual PC allow other OSes to be run on Windows, Linux, and OS X.

Читайте также:  Создание пакетных файлов для windows

For another example, Mac OS X on the PowerPC had the ability to run Mac OS 9 and earlier application software through Classic—but this did not make OS X a binary compatible OS with Mac OS 9. Instead, the Classic environment was actually running Mac OS 9.1 in a virtual machine, running as a normal process inside of OS X.[1][2]

ghost commented May 18, 2017

Or I could copy from the PyInstaller manual:

PyInstaller is tested against Windows, Mac OS X, and Linux. However, it is not a cross-compiler: to make a Windows app you run PyInstaller in Windows; to make a Linux app you run it in Linux, etc. PyInstaller has been used successfully with AIX, Solaris, and FreeBSD, but is not tested against them.

ghost commented May 18, 2017 •

Also, please do close this issue so as not to waste others’ time.

virtuald commented May 18, 2017

@xoviat that was a bit much. Simply copy/pasting the piece from the pyinstaller manual would have been sufficient. We were all new to this once.

Источник

Кросс-упаковка python кода в exe файл из Linux c помощью PyInstaller

Рано или поздно перед Python программистом встает проблема распространения своего ПО на компьютерах без установленного интерпретатора Python. Наиболее рациональным способом при этом кажется упаковка кода в автономный бинарный файл. Для этого существует целый сомн фреймворков.

По прочтении обсуждений в разных местах, пришел к выводу, что PyInstaller лучше всего подходит для данных целей из-за простоты в использовании, своей кросс-платформенности и потому, что собранный им exe-файл легче переносится с одной версии Windows на другую. А так же позволяет без особых танцев собирать бинарники для Windows из-под других операционных систем.

Подготовка

Нам понадобятся:

  • Python2 — К сожалению PyInstaller работает только для Python-2.x.x
  • Сам Pyinstaller

Pywin32 — дополнения Python для Windows. Опять же последняя стабильная версия (216)
Wine — ну без него тут никуда.

Я тестировал кросс-сборку на Ubuntu 11.04 с Python 2.7.1 и Wine 1.3.20.

Ставим все необходимое:

#Wine
sudo apt-get install wine1.3-dev
#Python
wget http://python.org/ftp/python/2.7.1/python-2.7.1.msi
wine msiexec /i python-2.7.1.msi

#Pyinstaller
wget http://www.pyinstaller.org/static/source/1.5/pyinstaller-1.5.tar.bz2
tar xvf pyinstaller-1.5.tar.bz2

#Pywin32
wget http://downloads.sourceforge.net/project/pywin32/pywin32/Build216/pywin32-216.win32-py2.7.exe?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fpywin32%2Ffiles%2Fpywin32%2FBuild216%2F&ts=1305544745&use_mirror=citylan -o pywin32.exe
wine pywin32.exe

Настройка и запуск

Теперь необходимо настроить Pyinstaller с помощью скрипта Configure.py. Конфигурацию надо производить каждый раз когда меняется конфигурация Python, поэтому имеет смысл держать отдельную версию Pyinstaller для каждой версии Python. Сконфигурируем Pyinstaller под Windows-версию интерпретатора:

cd pyinstaller-1.5
wine

Теперь можно собирать exe-файл. Сначала создаем spec-файл, в котором содержаться настройки упаковки проекта. Для наглядности назовем упаковываемый файл test.py (в случае, когда в проекте не один файл, указываем путь к главному).

/.wine/drive_c/Python27.exe Makespec.py test.py

По умолчанию папка со spec-фалом будет создана в папке Pyinstaller и будет иметь имя упаковываемого файла без расширения (в нашем случае test).

К команде создания spec-файла можно добавить полезные ключи, например:

  • —onefile — по умолчанию PyInstaller создает exe-файл и кладет в папку рядом с ним необходимые dll. Этот ключ форсирует упаковку всего в единый бинарник.
  • —out=DIR — позволяет задать определенную папку для spec-файла
  • —windowed — под Windows отключает консоль приложения

И наконец финальный этап — построение:

/.wine/drive_c/Python27/python.exe Build.py test/test.spec

Упакованное приложение можно найти в папке dist/ внутри папки со spec-файлом.

За сим все. Тестовая программа заработала под Wine, а затем под Windows XP и Windows 7 без малейших писков.

Источник

Собираем проект на python3&PyQT5 под Windows, используя PyInstaller

Причиной написания статьи, явилось огромное количество постоянно возникающих у новичков вопросов такого содержания: «Как собрать проект c pyqt5», «Почему не работает», «Какой инструмент выбрать» и т.д. Сегодня научимся собирать проекты без мучений и танцев с бубном.

Как-то пришлось написать небольшое desktop-приложение. В качестве языка программирования для разработки был выбран python, поскольку для решения моей задачи он подходил идеально. В стандартную библиотеку Python уже входит библиотека tkinter, позволяющая создавать GUI. Но проблема tkinter в том, что данной библиотеке посвящено мало внимания, и найти в интернете курс, книгу или FAQ по ней довольно-таки сложно. Поэтому было решено использовать более мощную, современную и функциональную библиотеку Qt, которая имеет привязки к языку программирования python в виде библиотеки PyQT5. Более подробно про PyQT можете почитать здесь. В качестве примера я буду использовать код:

Читайте также:  Айпи тв плеер для линукс минт

Если вы более-менее опытный разработчик, то понимаете, что без интерпретатора код на python не запустить. А хотелось бы дать возможность каждому пользователю использовать программу. Вот здесь к нам на помощь и приходят специальные библиотеки позволяющие собирать проекты в .exe, которые можно потом без проблем запустить, как обычное приложение.

Существует большое количество библиотек, позволяющих это сделать, среди которых самые популярные: cx_Freeze, py2exe, nuitka, PyInstaller и др. Про каждую написано довольно много. Но надо сказать, что многие из этих решений позволяют запускать код только на компьютере, с предустановленным интерпретатором и pyqt5. Не думаю, что пользователь будет заморачиваться и ставить себе дополнительные пакеты и программы. Надеюсь, вы понимаете, что запуск программы на dev-среде и у пользователя это не одно и тоже. Также нужно отметить, что у каждого решения были свои проблемы: один не запускался, другой собирал то, что не смог потом запустить, третий вообще отказывался что-либо делать.

После долгих танцев с бубном и активным гуглением, мне все же удалось собрать проект с помощью pyinstaller, в полностью работоспособное приложение.

Немного о Pyinstaller

Pyinstaller собирает python-приложение и все зависимости в один пакет. Пользователь может запускать приложение без установки интерпретатора python или каких-либо модулей. Pyinstaller поддерживает python 2.7 и python 3.3+ и такие библиотеки как: numpy, PyQt, Django, wxPython и другие.

Pyinstaller тестировался на Windows, Mac OS X и Linux. Как бы там ни было, это не кросс-платформенный компилятор: чтобы сделать приложение под Windows, делай это на Windows; Чтобы сделать приложение под Linux, делай это на Linux и т.д.

PyInstaller успешно используется с AIX, Solaris и FreeBSD, но тестирование не проводилось.

Подробнее о PyInstaller можно почитать здесь: документация.

К тому же после сборки приложение весило всего около 15 мб. Это к слову и является преимуществом pyinstaller, поскольку он не собирает все подряд, а только необходимое. Аналогичные же библиотеки выдавали результат за 200-300 мб.

Приступаем к сборке

Прежде чем приступить к сборке мы должны установить необходимые библиотеки, а именно pywin32 и собственно pyinstaller:

Чтобы убедится, что все нормально установилось, вводим команду:

должна высветиться версия pyinstaller. Если все правильно установилось, идем дальше.

В папке с проектом запускаем cmd и набираем:

Собственно это и есть простейшая команда, которая соберет наш проект.
Синтаксис команды pyinstaller таков:

pyinstaller [options] script [script . ] | specfile

Наиболее часто используемые опции:

—onefile — сборка в один файл, т.е. файлы .dll не пишутся.
—windowed -при запуске приложения, будет появляться консоль.
—noconsole — при запуске приложения, консоль появляться не будет.
—icon=app.ico — добавляем иконку в окно.
—paths — возможность вручную прописать путь к необходимым файлам, если pyinstaller
не может их найти(например: —paths D:\python35\Lib\site-packages\PyQt5\Qt\bin)

PyInstaller анализирует файл myscript.py и делает следующее:

  1. Пишет файл myscript.spec в той же папке, где находится скрипт.
  2. Создает папку build в той же папке, где находится скрипт.
  3. Записывает некоторые логи и рабочие файлы в папку build.
  4. Создает папку dist в той же папке, где находится скрипт.
  5. Пишет исполняемый файл в папку dist.

В итоге наша команда будет выглядеть так:

После работы программы вы найдете две папки: dist и build. Собственно в папке dist и находится наше приложение. Впоследствии папку build можно спокойно удалить, она не влияет на работоспособность приложения.

Спасибо за внимание. Надеюсь статья была вам полезна.

Источник

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