Python 3.2:cx_freeze 编译我的程序,但处于调试模式

3 投票
1 回答
1652 浏览
提问于 2025-04-17 18:32

我正在用 Python 3.2 和 Pygame 制作一个游戏。我已经成功地使用 cx_freeze 把所有东西打包成一个可执行文件,并且它可以运行,没问题。唯一的问题是,即使我在我的 setup.py 中加上了 -OO 这个参数,我的游戏还是以调试模式编译的。(我通过 print 语句确认了 __debug__ 确实是 True。)

问题在于,我的游戏有一些调试功能,这些功能在发布模式下是自动禁用的。我不想把这些调试功能分发出去,也不想手动从代码中删除它们。

我的 setup.py 文件,这里简化了一下,内容如下:

from cx_Freeze import setup, Executable

includes     = [<some modules>]
excludes     = [<some unwanted modules>]
include_files = [<game assets>]


build_options = {
                 'append_script_to_exe':True,
                 'bin_excludes':excludes,
                 'compressed':True,
                 'excludes': excludes,
                 'include_files': include_files,
                 'includes': includes,
                 'optimize':2,
                 'packages': ['core', 'game'],
                 }

common_exe_options = {
                      'appendScriptToExe'  : True,
                      'appendScriptToLibrary':True,
                      'compress'           : True,
                      'copyDependentFiles' : True,
                      'excludes'           : excludes,
                      'includes'           : includes, 
                      'script'             : '__init__.py',
                     }

executable = Executable(**common_exe_options)

setup(name='Invasodado',
      version='0.8',
      description='wowza!',
      options = {'build_exe': build_options,
                 'bdist_msi': build_options},
      executables=[executable])

完整的脚本和我其他的代码可以在 https://github.com/CorundumGames/Invasodado/blob/master/setup.py 找到。

在 Ubuntu 12.10 上,我用 python3.2 -OO setup.py build 来构建。在 Windows XP 上,我用 C:\Python32\python -OO setup.py build 来构建。

任何帮助都会很棒!

1 个回答

2

这里有两个稍微不同的概念:一个是把你的代码编译成字节码时的优化,另一个是解释器运行时的优化。在使用cx_Freeze时,如果你设置了optimize选项,它会优化生成的字节码,但解释器仍然是以__debug__ == True的状态运行。

看起来没有简单的方法可以为嵌入式解释器设置调试标志。它会忽略PYTHONOPTIMIZE这个环境变量。作为一种解决方法,你可以使用像这样的调试标志:

debug = __debug__ and not hasattr(sys, 'frozen')

撰写回答