使用 cx_freeze 创建带有附加文本文件的 Python 代码可执行文件

问题描述 投票:0回答:2

我正在使用 Python 3.6 和 cx_freeze 为我创建的 Python 游戏创建可执行文件。该游戏是一个随机句子生成器,其词典使用三个文本文件。

例如“名称.txt”:

 def random_name():
    line_num = 0
    selected_line = ''
    with open('names.txt') as f:
        for line in f:
            line = f.readline()
            if not line: break
            line_num += 1
            if random.uniform(0, line_num) < 1:
                selected_line = line
    return selected_line.strip()

当我尝试创建构建然后运行 exe 时,出现以下错误:

cx_Freeze: Python error in main script
Traceback (most recent call last):
File
"C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 14, in run module.run()
File
"C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\initscripts\Console.py", line 26, in run exec(code, m.__dict__)
File "rcg.py", line 55, in <module>
File "rcg.py", line 22, in random_name
FileNotFoundError: [Errno 2] No such file or directory: 'names.txt'

我之所以提到代码使用单独的txt文件,是因为我认为这可能是错误的原因,尽管我不明白所有的错误消息。

如果这是正确的,我如何确保 cx_freeze 包含这些额外文件?

python cx-freeze
2个回答
0
投票

问题不是冻结,而是文件“names.txt”位置。您确定names.txt与.py文件位于同一位置吗?我确实复制了您的代码示例并运行了它。它给了我同样的错误。所以我创建了一个文件names.txt并且它“有效”

更新答案: 我的 setup.py 如下:

import sys
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]}

# GUI applications require a different base on Windows (the default is for a
# console application).

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "Random Crime Generator",
        version = "1.0",
        description = "A random crime generator for police states",
        options = {"build_exe": build_exe_options},
        executables = [Executable("rcg.py", base=base)])

rcg.py如下:

import random

def random_name():
    line_num = 0
    selected_line = ''
    with open('names.txt') as f:
        for line in f:
            line = f.readline()
            if not line: break
            line_num += 1
            if random.uniform(0, line_num) < 1:
                selected_line = line
    return selected_line.strip()

对于与 rcg.py 位于同一文件夹中的名称.txt,我只添加了以下内容:

Apple
Banana
Carrots

仅此而已,运行良好。我是从 Windows 运行的。


0
投票

我使用了这个命令。它解析为代码中的正确地址,而不是为其提供文件名。

def resolve_path(path):
    # Determine the directory where the executable or script is located
    if getattr(sys, 'frozen', False):
        # If the application is frozen, use the directory containing the executable
        base_path = os.path.dirname(sys.executable)
    else:
        # If the application is not frozen, use the directory containing the script
        base_path = os.path.dirname(os.path.abspath(__file__))
    
    # Path to gui_scraper.py relative to the current script or executable
    resolved_path = os.path.join(base_path, path)
    return resolved_path
© www.soinside.com 2019 - 2024. All rights reserved.