2

我正在尝试使用cxfreeze将我的 Python 脚本构建到一个.exe文件中。但是,我的脚本使用了一些未打包到libary.zip创建的文件中的外部数据文件。

例如,我的脚本位于src/,外部数据位于src/data/. 我在 中指定了include_files属性build_exe_options,但这只会将目录和文件复制到构建目录中;它不会将它们添加到library.zip,这是脚本最终查找文件的地方。

即使我进入创建library.zip并手动添加data目录,我也会收到相同的错误。知道如何cxfreeze适当地打包这些外部资源吗?

安装程序.py

from cx_Freeze import setup, Executable

build_exe_options = {"includes" : ["re"], "include_files" : ["data/table_1.txt", "data/table_2.txt"]}

setup(name = "My Script",
      version = "0.8",
      description = "My Script",
      options = { "build_exe" : build_exe_options },
      executables = [Executable("my_script.py")])

fileutil.py(它尝试读取资源文件的地方)

def read_file(filename):
    path, fl = os.path.split(os.path.realpath(__file__))
    filename = os.path.join(path, filename)
    with open(filename, "r") as file:
        lines = [line.strip() for line in file]
        return [line for line in lines if len(line) == 0 or line[0] != "#"]

...打电话给...

read_file("data/table_1.txt")

错误回溯

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\cx_Freeze\initscripts\Console3.py", line 2
7, in <module> exec(code, m.__dict__)
  File "my_script.py", line 94, in <module>
  File "my_script.py", line 68, in run
  File "C:\workspaces\py\test_script\src\tables.py", line 12, in load_data
    raw_gems = read_file("data/table_1.txt")
  File "C:\workspaces\py\test_script\src\fileutil.py", line 8, in read_file
    with open(filename, "r") as file:
FileNotFoundError: [Errno 2] No such file or directory:
'C:\\workspaces\\py\\test_script\\src\\build\\exe.win32-3.3\\library.zip\\data/table_1.txt'
4

1 回答 1

3

以下结构对我有用:

|-main.py
|-src
 |-utils.py (containing get_base_dir())
|-data

然后参考您的数据始终相对于您通过 src 目录中的以下函数接收的 main.py 的位置:

import os, sys, inspect
def get_base_dir():
   if getattr(sys,"frozen",False):
       # If this is running in the context of a frozen (executable) file, 
       # we return the path of the main application executable
       return os.path.dirname(os.path.abspath(sys.executable))
   else:
       # If we are running in script or debug mode, we need 
       # to inspect the currently executing frame. This enable us to always
       # derive the directory of main.py no matter from where this function
       # is being called
       thisdir = os.path.dirname(inspect.getfile(inspect.currentframe()))
       return os.path.abspath(os.path.join(thisdir, os.pardir))

如果您根据 cx_Freeze 文档包含数据,它将与.exe文件位于同一目录中(即不在 zipfile 中),这将适用于此解决方案。

于 2013-09-03T16:29:47.587 回答