[PYTHON]_ELVE_Python源代碼文件編譯成可執行文件(支持macOS High Sierra和window 10)

#0x01 背景

這兩天寫了一個抽獎的Python腳本,要生成可執行文件,總不能一直在sublime上運行吧,或者運行前先安裝Python,因此就查了一下怎麼生成可執行文件,本篇包括mac下和win下,經本人測試,mac下生成.app(mac下的可執行文件爲.app後綴)較win下容易一些。python

我用的Python版本爲:macOS下3.7,win下3.6;系統版本爲:macOS 10.13 ;windows 10;git

#0x02 準備工做

macOS下:mac下比較容易,僅需下載一個pyinstaller就能夠了。在終端下輸入命令行github

pip install pyinstaller

windows下:windows下比較麻煩一些,須要先安裝pywin32,再安裝pyinstaller,故執行順序爲:windows

1.在pywin32的github上下載對應版本安裝:網站連接,最好下載最新的版本,我下的是224版本,下載好後安裝;app

在安裝過程當中若是出現找不到Python模塊,能夠將下面的Python代碼運行一下,親測可用(這是網上一位大神寫得代碼,具體出處找不到了,如遇做者請聯繫我標明,謝謝)。ide

import sys

from winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)


def RegisterPy():
    try:
        reg = OpenKey(HKEY_CURRENT_USER, regpath)
    except EnvironmentError as e:
        try:
            reg = CreateKey(HKEY_CURRENT_USER, regpath)
            SetValue(reg, installkey, REG_SZ, installpath)
            SetValue(reg, pythonkey, REG_SZ, pythonpath)
            CloseKey(reg)
        except:
            print("*** Unable to register!")
            return
        print("--- Python", version, "is now registered!")
        return
    if (QueryValue(reg, installkey) == installpath and
                QueryValue(reg, pythonkey) == pythonpath):
        CloseKey(reg)
        print("=== Python", version, "is already registered!")
        return
    CloseKey(reg)
    print("*** Unable to register!")
    print("*** You probably have another Python installation!")


if __name__ == '__main__':
    RegisterPy()
View Code

2.下載pyinstaller,這裏和mac同樣,直接pip安裝測試

pip install pyinstaller

注:pip版本爲9.多少來着以上最好,如今應該已經到了18以上網站

#0x03 編譯生成

在以上步驟安裝好後,就能夠進行編譯生成文件(注:mac下生成的文件只能在mac下運行,windows下生成的文件也只能在windows下運行)spa

1.首先切換到項目的目錄,也就是Python腳本的位置.net

cd 腳本的位置

2.使用pyinstaller生成

pyinstaller test.py

能夠看到,如今已經生成若干文件和文件夾,在dist文件夾下就能夠找到與Python文件同名的可執行文件,(mac下爲test.app,win下爲test.exe)

3.每次運行都須要打開命令行窗口怎麼辦,並且文件衆多,很差找,因此能夠使用下面的代碼,(這個是我本身比較經常使用的代碼)

pyinstaller -F -w test.py

這裏-F指的是生成僅一個文件,-w指的是不打開命令行窗口。

#0x04 另附pyinstaller經常使用命令

鏈接地址

注:-i命令須要.ico圖標

相關文章
相關標籤/搜索