Pyinstaller from linux to windows

How to create Windows EXEs for Python on Linux, using PyInstaller and WINE

Packaging a Python project into a standalone executable is often a struggle. Thankfully we have tools like PyInstaller to make this easier. Recently I ran into another struggle of my own, which was that it seemed impossible to “cross-compile” with PyInstaller. That is to say, run PyInstaller on one OS, and have it generate an executable for another. It was hinted at that Linux → Windows was possible using Wine, but I couldn’t find any guides on it.

Eventually, I got it working, so here is that guide. Hope this helps! This guide might also work on macOS, but I have not tested it.

Thanks to Noah Broyles for the script that helped me figure this all out.

First off, I was only able to use Python 3.8. I tried with 3.9, but I was not able to install it under WINE. If you are able to, feel free to use that, and change references to 38 in this post to 39 . I was also using PyInstaller 4.5.1, but other versions should work fine.

The first step is to install WINE for your Linux system. WINE is a compatibility layer that allows the running of Windows software on non-Windows systems. You can install WINE easily enough from your distro’s package manager. I am using wine-6.16 , but most likely your distro’s version will work fine.

Читайте также:  Proxy no arch linux

Next, download the Python 3.8 Windows installer. You can download that directly from the official Python Software Foundation here. With it downloaded, you can run wine python-3.8.9.exe to begin the installation. WINE may prompt you to install something like .NET or Mono, you should click Yes and let it install.

You should not use the default installation, follow these steps:

  1. Check “Add Python 3.8 to PATH”
  2. Click “Customize installation
  3. Click “Next”
  4. Click “Install for all users”
  5. Set the install location as C:\\Python38
  6. Click “Install”
  7. Close the window.

Using the C:\\Python38 path helps keep things standard for this blog post.

Now Python 3.8 should be successfully installed in WINE. You can check this by running wine C:/Python38/python.exe —version , which will run Windows Python through WINE. Amazing!

Next we’ll need to upgrade pip, to make sure things will install fine. Run wine C:/Python38/python.exe -m pip install —upgrade pip . WINE might spit out a lot of warnings about libgnutls or something or other, but as long as Pip doesn’t report any errors it’s fine.

Now if your project has any dependencies, you should export them into the standard Python requirements.txt file. You can then install them into your WINE Python with this command:

wine C:/Python38/python.exe -m pip install -r requirements.txt 

If you’re using a superior dependency manager like Poetry, you should be able to install and use that in WINE, although I haven’t tested that.

In any case, you’ll need PyInstaller to be installed, so run this command if PyInstaller wasn’t in requirements.txt already:

wine C:/Python38/python.exe -m pip install pyinstaller 

Now you can run PyInstaller and an EXE will be built! Just run

wine C:/Python38/Scripts/pyinstaller.exe . 

and replace . with whatever arguments you used to build a Linux executable.

Читайте также:  Intel bluetooth driver linux

All works on this site created by me are licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. They may not be used for commercial purposes.

Источник

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

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

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

Подготовка

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

Я тестировал кросс-сборку на 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 ~/.wine/drive_c/Python27.exe Configure.py

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

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

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

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

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

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

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

Источник

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