Create python exe in linux

Кросс-упаковка 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 отключает консоль приложения
Читайте также:  Opera на линукс минт

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

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

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

Источник

What do I use on linux to make a python program executable

I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.

No, it isn’t a dupe. That question is related to distributing python software avoiding library availability and compatibility issues.

9 Answers 9

Just put this in the first line of your script :

Make the file executable with

I’m confused. How does the «#!/usr/bin/env python» work when the hash is supposed to make it a commented line? I tried running the script without the hash line, but it didn’t work. So obviously the line is required, but how does it work if it’s a comment?

If you’re sending scripts to a fellow programmer, this is fine. But this is not a suitable way to distribute Python programs to end users. What if the user doesn’t have Python installed? What if they do, but it’s a different version than you wrote the program in? Overall this will only work for a tiny percentage of users, especially on Windows.

@MathManiac If you proceed as you’re implying, about 15% of users will be unable to run your application. This will be a crippling support burden, not to mention a fantastically hostile user experience, which will generate a torrent of hateful «application X sucks» posts. I stand by my assertion that this is not a suitable way to distribute applications to end-users.

Читайте также:  Make linux kernel driver

@Nav That’s called a Shebang. It’s commented out because it shouldn’t be interpreted by python. It gives information to the operating system. More specifically it says what program should be used to execute the script.

If you want to obtain a stand-alone binary application in Python try to use a tool like py2exe or PyInstaller.

You can use PyInstaller. It generates a build dist so you can execute it as a single «binary» file.

Python 3 has the native option of create a build dist also:

Putting these lines at the starting of the code will tell your operating systems to look up the binary program needed for the execution of the python script i.e it is the python interpreter.

So it depends on your operating system where it keeps the python interpreter. As I have Ubuntu as operating system it keeps the python interpreter in /usr/bin/python so I have to write this line at the starting of my python script;

After completing and saving your code

  1. Start your command terminal
  2. Make sure the script lies in your present working directory
  3. Type chmod +x script_name.py
  4. Now you can start the script by clicking the script. An alert box will appear; press «Run» or «Run in Terminal» in the alert box; or, at the terminal prompt, type ./script_name.py

If one want to make executable hello.py

first find the path where python is in your os with : which python

it usually resides under «/usr/bin/python» folder.

at the very first line of hello.py one should add : #!/usr/bin/python

then through linux command chmod

one should just make it executable like : chmod +x hello.py

  1. put #! /usr/bin/env python3 at top of script
  2. chmod u+x file.py
  3. Change .py to .command in file name
Читайте также:  Linux чем занято устройство

This essentially turns the file into a bash executable. When you double-click it, it should run. This works in Unix-based systems.

These steps works irrespective of whether you have single standalone python script or if you have multiple dependent script called by your main file.

On MacOS systems, the source file path requires the full path, not relative to where you are specifying it.

as I find it a bit ambiguous, as to what exactly you refer to with a »Program», I present here an answer, how to make a »package»-program executable from the command line in Linux, as this was not answered in this question before.

Essentially you have to follow the official instructions, but in essence, you have to do the following steps:

1.) Refactor your program into the structure presented here (you essentially have the choice between two structures)

2.) Assuming you chose the »flat layout» and your project name is awesome (i.e. assuming your source files lie in program/awesome ), you create two files, setup.py and setup.cfg file, at your program level (i.e. program ), with the contents below:

from setuptools import setup setup() 
[metadata] name = awesome version = 0.0.1 description = My awesome program is 'awesomer' than yours author =Awesome Name email = awesome@program.earth [options] packages = find: install_requires = [options.entry_points] console_scripts = awesome = awesome:main 

3.) In your program/awesome folder you create a __init__.py file, with a main function, where you can then start your »real» program. I.e. put into your __init__.py file at least the following code to see an effect:

def main(): print("MY AWESOME PROGRAM WORKS!") 

4.) Install it using e.g. python setup.py install

5.) Execute it from the command line using awesome , e.g. $> awesome

Hope this helps anyone — Thinklex

Источник

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