为Python 3和PyQt构建可执行文件

21

我使用PyQt4构建了一个相当简单的Python 3.1应用程序。完成后,我希望将该应用程序分发到未安装其任何组件的计算机上。

我主要关注Windows平台,因此我的目标是最终只有一个可执行文件以及一些资源文件和.dll文件。

经过搜索,我得出以下结论:

  • py2exe仅支持Python版本2.7及以下
  • pyinstaller仅支持Python版本2.6及以下
  • cx_Freeze对我来说不起作用,因为在尝试执行成功构建的二进制文件时,我不断遇到以下错误:

Y:\Users\lulz\build\exe.win32-3.1>system_shutdown.exe
Traceback (most recent call last):
File "Y:\Program Files (x86)\Python\lib\site-packages\cx_Freeze\initscripts\Console3.py", line 27, in exec(code, m.__dict__)
File "Y:/Users/lulz/Documents/Coding/Python3/projects/System Shutdown/system_shutdown.pyw", line 5, in from PyQt4 import QtCore
File "ExtensionLoader_PyQt4_QtCore.py", line 16, in AttributeError: 'NoneType' object has no attribute 'modules'

我的问题基本上有两个:

  1. 除了cx_Freeze之外,是否还有其他方式来构建具有我的配置的二进制文件?
  2. 如果没有,那么cx_Freeze的问题可能是什么?

如果需要,我可以提供更多关于第二个问题的信息,例如我的cx_Freeze调用、我的distutils设置脚本等。

感谢您的帮助和评论。


好问题。在过去,py2exe对我们来说非常好用。 - Craig McQueen
py2exe现在已经支持Python 3了! - Santosh Kumar
2个回答

13

我一到就会尝试并发布我的结果。到目前为止,谢谢! - WrongAboutMostThings
这终于成功了,必须添加你提到的代码行并包括sip。现在还有一个问题,如何在启动我的漂亮GUI应用程序时抑制控制台窗口。 - WrongAboutMostThings
3
对于未来的读者有所帮助,虽然有点晚,但您可以使用Win32GUI基础冻结来抑制控制台窗口。此处有示例 - Thomas K
我通过pip安装了cx_freeze 4.3.3。我正在使用Python 3.4。我应该在哪里尝试添加这行代码?我找不到任何freeze.py文件。不过Scripts中有一个cxfreeze.py文件。 - To Do

-1
对于Python 3.3及更高版本,这里有一个很好的解决方案: py2exe - 生成单个可执行文件 安装py2exe:
pip install py2exe

然后在 'your_script.py' 文件旁边添加以下的 'Make_exe.py' 文件:

from distutils.core import setup
import py2exe, sys

class Make_exe():
    def __init__(self, python_script):
        sys.argv.append('py2exe')

        setup(
            console=[{'script': python_script}],
            zipfile = None,
            options={
                'py2exe': 
                {
                    'bundle_files': 1, 
                    'compressed': True,
                    # Add includes if necessary, e.g. 
                    'includes': ['lxml.etree', 'lxml._elementpath', 'gzip'],
                }
            }
        )

if __name__ == '__main__':
    Make_exe('your_script.py')

如果你想让 'your_script.py' 每次在Python中运行时都自动重新生成为'your_script.exe',你可以在它的主程序中添加如下代码:

import subprocess
import sys

if __name__ == '__main__':
    currentFile = sys.argv[0]
    if currentFile.lower().endswith(".py"):
        exitCode = subprocess.call("python Make_exe.py")
        if exitCode==0 :
            dirName = os.path.dirname(currentFile)
            exeName = os.path.splitext(os.path.basename(currentFile))[0] + '.exe'
            exePath = dirName + "/dist/" + exeName
            cmd = [exePath] + sys.argv[1:]
            print ("Executing command:\n %s" % cmd)
            exitCode = subprocess.call(cmd)
        sys.exit(exitCode)
    else:
        print ("This will be executed only within the new generated EXE File...")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接