How to compile a python file?
Adding to Bryan’s answer, if you simply want to compile a file or a bunch of files from a terminal, the py_compile module can be executed as a script in the following manner:
python -m py_compile fileA.py fileB.py fileC.py .
Also be aware that you don’t need to compile a .py file to run it. Python is an interpreted language, and you can run the scripts directly, either using:
Or make your script executable by adding #!/usr/bin/env python to the top of the script, making the file executable with chmod +x hello.py and then running:
The fact that Python internally compiles your .py script to bytecode .pyc files for performance reasons is an implementation detail, and unless you have a strong reason to do so, let python itself decide when and if to compile.
Как скомпилировать python в linux
Python comes preinstalled on most Linux distributions, and is available as a package on all others. However there are certain features you might want to use that are not available on your distro’s package. You can easily compile the latest version of Python from source.
In the event that Python doesn’t come preinstalled and isn’t in the repositories as well, you can easily make packages for your own distro. Have a look at the following links:
for Debian users
for OpenSuse users
for Fedora users
for Slackware users
2.1.2. On FreeBSD and OpenBSD¶
FreeBSD users, to add the package use:
OpenBSD users, to add the package use:
For example i386 users get the 2.5.1 version of Python using:
2.1.3. On OpenSolaris¶
You can get Python from OpenCSW. Various versions of Python are available and can be installed with e.g. pkgutil -i python27 .
2.2. Building Python¶
If you want to compile CPython yourself, first thing you should do is get the source. You can download either the latest release’s source or just grab a fresh clone. (If you want to contribute patches, you will need a clone.)
The build process consists of the usual commands:
Configuration options and caveats for specific Unix platforms are extensively documented in the README.rst file in the root of the Python source tree.
make install can overwrite or masquerade the python3 binary. make altinstall is therefore recommended instead of make install since it only installs exec_prefix /bin/python version .
2.3. Python-related paths and files¶
These are subject to difference depending on local installation conventions; prefix ( $
) and exec_prefix ( $ ) are installation-dependent and should be interpreted as for GNU software; they may be the same.
For example, on most Linux systems, the default for both is /usr .
Recommended location of the interpreter.
prefix /lib/python version , exec_prefix /lib/python version
Recommended locations of the directories containing the standard modules.
prefix /include/python version , exec_prefix /include/python version
Recommended locations of the directories containing the include files needed for developing Python extensions and embedding the interpreter.
2.4. Miscellaneous¶
To easily use Python scripts on Unix, you need to make them executable, e.g. with
and put an appropriate Shebang line at the top of the script. A good choice is usually
which searches for the Python interpreter in the whole PATH . However, some Unices may not have the env command, so you may need to hardcode /usr/bin/python3 as the interpreter path.
To use shell commands in your Python scripts, look at the subprocess module.
2.5. Custom OpenSSL¶
To use your vendor’s OpenSSL configuration and system trust store, locate the directory with openssl.cnf file or symlink in /etc . On most distribution the file is either in /etc/ssl or /etc/pki/tls . The directory should also contain a cert.pem file and/or a certs directory.
Download, build, and install OpenSSL. Make sure you use install_sw and not install . The install_sw target does not override openssl.cnf .
Build Python with custom OpenSSL (see the configure –with-openssl and –with-openssl-rpath options)
Patch releases of OpenSSL have a backwards compatible ABI. You don’t need to recompile Python to update OpenSSL. It’s sufficient to replace the custom OpenSSL installation with a newer version.
Как скомпилировать файл Python?
В дополнение к ответу Брайана, если вы просто хотите скомпилировать файл или группу файлов из терминала, модуль py_compile может быть выполнен в виде сценария следующим образом:
python -m py_compile fileA.py fileB.py fileC.py .
В середине страницы рассказывается о модуле py_compile, который можно импортировать. Синтаксис выглядит следующим образом:
Этот метод компиляции не будет запускать модуль так же, как запуск файла python file.py.
Существует также метод, который компилирует все дерево каталогов, но я позволю вам проверить ссылку, чтобы увидеть, как это выполняется.
Надеюсь, это поможет.
Также знайте, что Вы не должны компилировать a .py файл для выполнения его. Python является интерпретируемым языком, и можно запустить скрипты непосредственно, любое использование:
Или сделайте свой исполняемый файл сценария путем добавления #!/usr/bin/env python к верхней части сценария, делая исполняемый файл файла с chmod +x hello.py и затем выполнение:
То, что Python внутренне компилирует Ваш .py сценарий к байт-коду .pyc файлы по причинам производительности являются деталью реализации, и если у Вас нет веской причины сделать так, позвольте самому Python решить, когда и скомпилировать ли.
Установка Python на Linux
В этой заметке я покажу как собрать из исходников и установить Python на Linux. Я буду все действия производить на Ubuntu 20.04, но инструкция будет одинаково работать и на LinuxMint и Debian.
В моей Ubuntu по умолчанию установлен Python 3.8.10, я хочу установить более свежую версию, как же это сделать?
Подготовка
Обновляем список пакетов
sudo apt update
Устанавливаем все необходимое для сборки Питона из исходников
sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev libsqlite3-dev wget libbz2-dev
Дальше на странице https://www.python.org/downloads/source/ нужно сохранить ссылку на исходники нужной вам версии Python, например я возьму последнюю на данный момент версию Python 3.10.1

С помощью wget скачиваем исходники в домашнюю директорию
sudo wget https://www.python.org/ftp/python/3.10.1/Python-3.10.1.tgz
Далее разархивируем скаченный архив:
sudo tar -xf Python-3.10.1.tgz
Сборка Python в Linux из исходников
Перейдем в директорию с исходным кодом Python
Далее нужно запустить скрипт конфигурации, он выполнит проверки на необходимые для сборки Python
Мы запускаем скрипт с параметром —enable-optimizations, он оптимизирует собираемый двоичный файл Python (правда это замедлит процесс сборки, https://docs.python.org/3/using/configure.html).
После выполнения скрипта нам остается запустить сам процесс сборки:
Параметром -j 4 я указал количество ядер процессора, узнать эту цифру можно командой nproc .
Установка Python в Linux
Процесс сборки довольно длительная операция, после того, как она завершиться можно установить Python одной из двух команд:
sudo make altinstall
Эта команда устанавливает наш Python рядом с предыдущими версиями, в будущем вы сможете выбирать какой версией пользоваться.
sudo make install
Эта команда установит новую версию Python поверх старых.
В данный момент я воспользовался первой командой altinstall .
Дожидаемся окончания процесса установки и проверяем:
В ответ получаем версию Python 3.10.1
Предыдущая версия python, установленная в Убунту 20.04 по умолчанию так же доступна, можно убедится в этом вызвав команду:
В ответ получаем версию Python 3.8.10
Теперь можно удалить архив с исходниками и папку куда мы их разархивировали:
sudo rm -Rf Python-3.10.1 Python-3.10.1.tgz
Еще раз повторюсь, что инструкция выше по сборке Python из исходников в Ubuntu подойдет и для установки Python в LinuxMint и Debian. В репозиториях этих дистрибутивов уже есть собранные Python, но не всегда самой свежей версии.