如何在使用cx_freeze时打包其他文件?

61 投票
4 回答
54386 浏览
提问于 2025-04-15 21:05

我在Windows系统上使用Python 2.6和cx_Freeze 4.1.2。我已经创建了setup.py来生成可执行文件,一切都运行得很好。

当cx_Freeze运行时,它会把所有东西移动到build目录里。我还有一些其他文件想要包含在我的build目录中。我该怎么做呢?这是我的文件结构:

src\
    setup.py
    janitor.py
    README.txt
    CHNAGELOG.txt
    helpers\
        uncompress\
            unRAR.exe
            unzip.exe

这是我的代码片段:

setup

( name='Janitor',
  version='1.0',
  description='Janitor',
  author='John Doe',
  author_email='john.doe@gmail.com',
  url='http://www.this-page-intentionally-left-blank.org/',
  data_files = 
      [ ('helpers\uncompress', ['helpers\uncompress\unzip.exe']),
        ('helpers\uncompress', ['helpers\uncompress\unRAR.exe']),
        ('', ['README.txt'])
      ],
  executables =
      [
      Executable\
          (
          'janitor.py', #initScript
          )
      ]
)

我似乎无法让这个工作。难道我需要一个MANIFEST.in文件吗?

4 个回答

3

为了找到你附加的文件(include_files = [-> 你的附加文件 <-]),你需要在你的setup.py代码中插入以下函数:

def find_data_file(filename):
    if getattr(sys, 'frozen', False):
        # The application is frozen
        datadir = os.path.dirname(sys.executable)
    else:
        # The application is not frozen
        # Change this bit to match where you store your data files:
        datadir = os.path.dirname(__file__)

    return os.path.join(datadir, filename)

查看cx-freeze:使用数据文件

6

这里有一个更复杂的例子,可以查看:cx_freeze - wxPyWiki

关于所有选项的文档不太完整,可以在这里找到:cx_Freeze (互联网档案馆)

使用cx_Freeze时,我得到的构建输出是一个文件夹里有11个文件,这和Py2Exe不太一样。

其他选择:打包 | The Mouse Vs. Python

117

我搞定了。

from cx_Freeze import setup,Executable

includefiles = ['README.txt', 'CHANGELOG.txt', 'helpers\uncompress\unRAR.exe', , 'helpers\uncompress\unzip.exe']
includes = []
excludes = ['Tkinter']
packages = ['do','khh']

setup(
    name = 'myapp',
    version = '0.1',
    description = 'A general enhancement utility',
    author = 'lenin',
    author_email = 'le...@null.com',
    options = {'build_exe': {'includes':includes,'excludes':excludes,'packages':packages,'include_files':includefiles}}, 
    executables = [Executable('janitor.py')]
)

注意:

  • include_files 里只能放相对于 setup.py 脚本的路径,如果放了其他路径,构建就会失败。
  • include_files 可以是一个字符串列表,也就是一堆文件的相对路径
    或者
  • include_files 也可以是一个元组列表,元组的前半部分是文件名和绝对路径,后半部分是目标文件名和绝对路径。

(如果文档不够用,可以咨询青蛙凯尔密特)

撰写回答