[PYTHON]_ELVE_Python源代码文件编译成可执行文件(支持macOS High Sierra和window 10)

#0x01 背景

这两天写了一个抽奖的Python脚本,要生成可执行文件,总不能一直在sublime上运行吧,或者运行前先安装Python,所以就查了一下怎么生成可执行文件,本篇包括mac下和win下,经本人测试,mac下生成.app(mac下的可执行文件为.app后缀)较win下容易一些。

我用的Python版本为:macOS下3.7,win下3.6;系统版本为:macOS 10.13 ;windows 10;

#0x02 准备工作

macOS下:mac下比较容易,仅需下载一个pyinstaller就可以了。在终端下输入命令行

pip install pyinstaller

windows下:windows下比较麻烦一些,需要先安装pywin32,再安装pyinstaller,故执行顺序为:

1.在pywin32的github上下载对应版本安装:网站链接,最好下载最新的版本,我下的是224版本,下载好后安装;

在安装过程中如果出现找不到Python模块,可以将下面的Python代码运行一下,亲测可用(这是网上一位大神写得代码,具体出处找不到了,如遇作者请联系我标明,谢谢)。

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下运行)

1.首先切换到项目的目录,也就是Python脚本的位置

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图标

猜你喜欢

转载自www.cnblogs.com/elve960520/p/9989436.html
今日推荐