Python executable file linux

Преобразуем проект на Python в исполняемый файл .EXE

С помощью Auto PY to EXE можно с лёгкостью преобразовывать файлы .py в файлы .exe . Благодаря этому ваш проект на Python будет работать как десктопное приложение и вы сможете запускать приложение на других машинах без необходимости установки Python.

В этой статье я расскажу, как преобразовать проект на Python в исполняемый файл. Решение будет работать вне зависимости от количества файлов .py в приложении. Стоит учесть, что Auto PY to EXE работает только с Python 3.5 или выше.

Установка Auto PY to EXE

Установка через pip

При помощи следующей команды можно установить текущую версию Auto PY to EXE.

Установка с GitHub

Также можно выполнить установку напрямую с GitHub. Для установки Auto PY to EXE с GitHub необходимо сначала клонировать репозиторий GitHub.

Затем нужно перейти в папку auto-py-to-exe .

Теперь необходимо запустить файл setup.py .

Можно также проверить версию при помощи следующей команды:

Текущая версия Auto PY to EXE 2.9.0 и теперь она установлена на ваш компьютер.

Открываем приложение

Чтобы открыть Auto PY to EXE, нужно выполнить в терминале следующую команду:

Откроется удобное приложение с GUI:

Интерфейс пользователя Auto PY to EXE

Теперь с помощью этого интерфейса можно преобразовать файл .py в .exe .

Процесс преобразования

Шаг 1. Добавляем местоположение файла

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

Добавляем местоположение файла

Я добавил местоположение основного файла Python моего проекта. Здесь я использую для примера один из своих проектов на Python. Это приложение с GUI, визуализирующее различные алгоритмы сортировки. О создании этого проекта можно прочитать здесь: Build a Sorting Algorithm Visualizer in Python

Шаг 2. Выбор «One Directory» или «One File»

В интерфейсе есть опция выбора «One Directory» или «One File». Мой проект на Python содержит несколько других файлов, поэтому я выбрал «One Directory». Эта опция создаст папку со всеми необходимыми файлами, а также с файлом .exe .

One directory или One file

Шаг 3. Выбор «Console Based» или «Window Based»

После этого нужно будет выбрать тип приложения: консольное (Console Based) или оконное (Window Based). Если выбрать «Window Based», то это скроет весь консольный вывод приложения. Если ваш проект генерирует консольный вывод, то нужно выбрать «Console Based». Если у вас приложение с GUI или вам не нужно отображать пользователю консольный вывод, то выберите «Window Based». Я выбрал второй вариант, потому что моё приложение имеет GUI.

Console Based или Window Based

Шаг 4. Преобразование

Далее отобразятся другие опции, такие как добавление значков, дополнительных файлов и т.д. Выберите нужные опции самостоятельно. Ну а наш файл .py уже к преобразованию. Достаточно нажать на кнопку CONVERT .PY TO .EXE .

Нажмите кнопку для преобразования

Для завершения процесса придётся немного подождать.

Папка с результатами

После завершения процесса можно будет выбрать опцию открытия папки с результатами.

По умолчанию папка с результатами будет создана там, откуда вы запускали Auto PY to EXE. Я открывал Auto PY to EXE с рабочего стола, поэтому папка создана на нём. В папке находится множество файлов и папок. Но нам важен файл с расширением .exe . В моём случае это main.exe . При двойном нажатии будет запускаться программа.

Читайте также:  Bootcamp не видит образ windows

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

Ресурсы

На правах рекламы

Серверы для всех, в том числе, и для разработчиков! VDS с посуточной оплатой на базе новейших процессоров AMD EPYC и хранилища на основе NVMe дисков от Intel для размещения проектов любой сложности, создавайте собственную конфигурацию сервера в пару кликов!

Источник

Запуск python скрипта в Linux

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

На этом языке написано огромное количество системных программ, среди них пакетный менеджер apt, видеоредактор OpenShot, а также множество скриптов, которые вы можете установить с помощью утилиты pip. В этой небольшой статье мы рассмотрим как запустить Python скрипт в Linux с помощью терминала различными способами.

Запуск python скрипта в Linux

Для примера нам понадобится Python скрипт. Чтобы не брать какой-либо из существующих скриптов, давайте напишем свой:

print(«Hello from losst!»)

Для того чтобы запустить скрипт необходимо передать его интерпретатору Python. Для этого просто откройте терминал с помощью сочетания клавиш Ctrl + Alt + T, перейдите в папку со скриптом и выполните:

Если вы хотите, чтобы после выполнения скрипта открылась консоль, в которой можно интерактивно выполнять команды языка Python используйте опцию -i:

python -i script.py

Но как вы могли заметить, при запуске apt или openshot не надо писать слово python. Это намного удобнее. Давайте разберемся как это реализовать. Если вы не хотите указывать интерпретатор в командной строке, его надо указать в самом скрипте. Для этого следует в начало скрипта добавить такую строчку:

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

chmod ugo+x script.py

После этого можно запустить скрипт Python просто обращаясь к его файлу:

Если убрать расширение .py и переместить скрипт в каталог, находящийся в переменной PATH, например /usr/bin/, то его можно будет выполнять вот так:

Как видите, запуск команды python Linux выполняется довольно просто и для этого даже есть несколько способов. А каким способом пользуетесь вы? Напишите в комментариях!

Источник

How to create a Linux executable file using python code

For an example I have created welcomeGUI.py file with has a simple GUI as follows using Tkinter.

Then I need to create this file that can be installed on Ubuntu(To create an executable file on Ubuntu). In Windows this is done very easily with .exe file(Using cx-Freeze). Really I have no idea about the file system of Ubuntu and shell files.

Please help me to get an idea about this problem. I don’t have any idea how to enter this matter.

2 Answers 2

Basically, to make a file executable in Unix systems, you just have to do one thing: allow it to be executed (very surprising 😉 ). To do it, you must use the chmod command as follows: chmod +x youfile.py . The +x add the right to be executed.

Now, your system will allow you to execute the script, but for now it’s just a simple text file. Ubuntu doesn’t know that he must use the python command to run it, so you’ll have undermined comportment. To resolve this, we use the sha-bang line (for more information, see the wikipedia page): at the first line of your script, you must write #! program_to_use , in your case it’s python. Generally, we take benefit of the env variables, and use #! /usr/bin/env python , but you can also choose yourself the version of python you want, doing #! /usr/bin/pythonX.X where X.X is the version of python.

Читайте также:  Microsoft windows updateorchestrator backup scan

Источник

How can I make a Python script standalone executable to run without ANY dependency? [duplicate]

I’m building a Python application and don’t want to force my clients to install Python and modules.

So, is there a way to compile a Python script to be a standalone executable?

19 Answers 19

You can use PyInstaller to package Python programs as standalone executables. It works on Windows, Linux, and Mac.

PyInstaller Quickstart

Install PyInstaller from PyPI:

Go to your program’s directory and run:

This will generate the bundle in a subdirectory called dist .

Adding -F (or —onefile) parameter will pack everything into single «exe».

running into «ImportError» you might consider side-packages.

still runing in Import-Erorr — try to downgrade pyinstaller — see Getting error when using pynput with pyinstaller

For a more detailed walkthrough, see the manual.

You can use py2exe as already answered and use Cython to convert your key .py files in .pyc , C compiled files, like .dll in Windows and .so on Linux.

It is much harder to revert than common .pyo and .pyc files (and also gain in performance!).

You might wish to investigate Nuitka. It takes Python source code and converts it in to C++ API calls. Then it compiles into an executable binary (ELF on Linux). It has been around for a few years now and supports a wide range of Python versions.

You will probably also get a performance improvement if you use it. It is recommended.

Yes, it is possible to compile Python scripts into standalone executables.

PyInstaller can be used to convert Python programs into stand-alone executables, under Windows, Linux, Mac OS X, FreeBSD, Solaris, and AIX. It is one of the recommended converters.

py2exe converts Python scripts into only executable on the Windows platform.

Cython is a static compiler for both the Python programming language and the extended Cython programming language.

I would like to compile some useful information about creating standalone files on Windows using Python 2.7.

I have used py2exe and it works, but I had some problems.

It has shown some problems for creating single files in Windows 64 bits: Using bundle_files = 1 with py2exe is not working;

It is necessary to create a setup.py file for it to work. http://www.py2exe.org/index.cgi/Tutorial#Step2;

I have had problems with dependencies that you have to solve by importing packages in the setup file;

I was not able to make it work together with PyQt.

This last reason made me try PyInstaller http://www.pyinstaller.org/.

In my opinion, it is much better because:

I suggest creating a .bat file with the following lines for example (pyinstaller.exe must be in in the Windows path):

I had only one problem using PyInstaller and multiprocessing package that was solved by using this recipe: https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Multiprocessing.

So, I think that, at least for python 2.7, a better and simpler option is PyInstaller.

And a third option is cx_Freeze , which is cross-platform.

This creates a standalone EXE file on Windows.

Important note 1: The EXE file will be generated in a folder named ‘dist’.

Important note 2: Do not forget —onefile flag

You can install PyInstaller using pip install PyInstaller

NOTE: In rare cases there are hidden dependencies. so if you run the EXE file and get missing library error (win32timezone in the example below) then use something like this:

I like PyInstaller — especially the «windowed» variant:

It will create one single *.exe file in a distination/folder.

You may like py2exe. You’ll also find information in there for doing it on Linux.

Use py2exe. use the below set up files:

I also recommend PyInstaller for better backward compatibility such as Python 2.3 — 2.7.

Читайте также:  Выключение камеры windows 10

For py2exe, you have to have Python 2.6.

/Documents/python101/ and ex50_pycomp.py & ex50.py are in this dir. ex50_pycomp.py importing ex50.py. I run pyinstaller ex50_pycomp.py and i see all complied, produced dist. All good right? I cd into dist/ex50_pycomp/ and run ex50_pycomp it works. Once I put this ex50_pycom into a virtualmachine, then this says import error and in another other linux box it says » -bash: ./ex_50_pycom: cannot execute binary file: Exec format error»

For Python 3.2 scripts, the only choice is cx_Freeze. Build it from sources; otherwise it won’t work.

For Python 2.x I suggest PyInstaller as it can package a Python program in a single executable, unlike cx_Freeze which outputs also libraries.

py2exe will make the EXE file you want, but you need to have the same version of MSVCR90.dll on the machine you’re going to use your new EXE file.

See Tutorial for more information.

You can find the list of distribution utilities listed at Distribution Utilities.

I use bbfreeze and it has been working very well (yet to have Python 3 support though).

Since it seems to be missing from the current list of answers, I think it is worth mentioning that the standard library includes a zipapp module that can be used for this purpose. Its basic usage is just compressing a bunch of Python files into a zip file with extension .pyz than can be directly executed as python myapp.pyz , but you can also make a self-contained package from a requirements.txt file:

Where interpreter can be something like /usr/bin/env python (see Specifying the Interpreter).

Usually, the generated .pyz / .pyzw file should be executable, in Unix because it gets marked as such and in Windows because Python installation usually registers those extensions. However, it is relatively easy to make a Windows executable that should work as long as the user has python3.dll in the path.

If you don’t want to require the end user to install Python, you can distribute the application along with the embeddable Python package.

Not exactly a packaging of the Python code, but there is now also Grumpy from Google, which transpiles the code to Go.

It doesn’t support the Python C API, so it may not work for all projects.

Using PyInstaller, I found a better method using shortcut to the .exe rather than making —onefile . Anyway, there are probably some data files around and if you’re running a site-based app then your program depends on HTML, JavaScript, and CSS files too. There isn’t any point in moving all these files somewhere. Instead what if we move the working path up?

Make a shortcut to the EXE file, move it at top and set the target and start-in paths as specified, to have relative paths going to dist\folder:

We can rename the shortcut to anything, so renaming to «GTFS-Manager». Now when I double-click the shortcut, it’s as if I python -ran the file! I found this approach better than the —onefile one as:

  1. In onefile’s case, there’s a problem with a .dll missing for the Windows 7 OS which needs some prior installation, etc. Yawn. With the usual build with multiple files, no such issues.
  2. All the files that my Python script uses (it’s deploying a tornado web server and needs a whole freakin’ website worth of files to be there!) don’t need to be moved anywhere: I simply create the shortcut at top.
  3. I can actually use this exact same folder on Ubuntu (run python3 myfile.py ) and Windows (double-click the shortcut).
  4. I don’t need to bother with the overly complicated hacking of .spec file to include data files, etc.

Oh, remember to delete off the build folder after building. It will save on size.

Источник

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