在Windows上使用Nuitka將Python文件打包成exe文件

Nuitka是用於將Python文件打包成可執行文件的工具,類似於PyInstaller,但是相較而言Nuitka是直接將python編譯成C++代碼, 性能和安全性更好,具體可以參考文章Python 打包工具對比,Nuitka vs Pyinstaller

筆者在安裝使用Nuitka時,遇到了不少的坑,而且沒有找到一篇完整的文章來詳細描述安裝和使用細節,因此特寫此文已做記錄,並給後來者以便利。

安裝Python

我們最好手動安裝Python,方法是直接在Python官網下載Windows的安裝包。

打開鏈接
https://www.python.org/downloads/windows/
,然後選擇正確的安裝包(要選擇64位的安裝包, 比如Windows x86-64 web-based installer

打開安裝包執行安裝程序,這個過程中需要注意的是要勾選選項"將Python安裝路徑添加到Path"

具體可以參考Python 安裝教程(windows)

安裝Nuitka

安裝Nuitka可以直接使用pip進行安裝

pip install nuitka

安裝好之後我們可以測試一下Nuitka是否可以編譯python文件
比如筆者在C:\code\test_code目錄下可以創建一個main.py文件, 文件如下:

#!/usr/bin/env python
# coding: utf-8

def job():
    print("hello")
    

if __name__ == "__main__":
    while True:
        job()
        sleep(60)

我們嘗試編譯這個文件

> cd C:\code\test_code
> nuitka main.py

這時你可能會看到如下報錯:

Error, cannot locate suitable C compiler. You have the following options:

a) If a suitable Visual Studio version is installed, it will not be located automatically, unless you install pywin32 for the Python installation below "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86".

b) To make it find Visual Studio without registry execute from Start Menu the 'Visual Studio Command Prompt' or "vcvarsall.bat". That will add Visual Studio to the "PATH". And it then will be detected.

c) Install MinGW64 to "C:\MinGW64" or "\MinGW", where then it is automatically detected or add it to PATH before executing Nuitka. But be sure to pick the proper variant (32/64 bits, your Python arch is 'x86'), or else cryptic errors will be shown.

Normal MinGW will not work! MinGW64 does not mean 64 bits, just better Windows compatibility. Cygwin based gcc will not work. MSYS2 based gcc will not work. clang-cl will only work if MSVC already worked.

這是由於我們並沒有安裝C編譯器的緣故,因此我們還需要安裝C編譯器

安裝MinGW64

要想使用Nuitka,我們就需要C編譯器,而這通常使用MinGW64(Minimal GNU for Windows)會比較好, MinGW64是一套適用於Windows的開發環境,這個開發環境有一組開源的工具集,其中就有用於C/C++語言編譯的gcc,而Nuitka就需要一個C/C++編譯器,所以我們需要先裝這個。

首先要下載安裝包,下載鏈接

https://sourceforge.net/projects/mingw-w64/files/mingw-w64/mingw-w64-release/

最新的版本是8.1.0,找到這個版本的安裝包x86_64-posix-sjlj, 點擊下載。如圖

下載之後,解壓到你的安裝目錄(解壓後就算安裝了,不需要執行安裝exe),比如C:\MinGW64

然後將安裝目錄下的bin目錄的路徑加入到環境變量PATH中, 比如本例就是C:\MinGW64\mingw64\bin,然後打開CMD驗證是否安裝成功。

>gcc --version
gcc (x86_64-posix-sjlj-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

當看到如上所示的文字說明我們已經安裝成功。

使用Nuitka進行編譯

這時,我們再使用Nuitka進行編譯試下

> nuitka --mingw64 main.py

可以看到這次成功了,在test_code目錄下新生成了一個exe可執行文件。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章