使用 PyInstaller 构建的问题 运行 可执行文件

Problem running executable built with PyInstaller

我正在尝试使用此脚本构建一个 exe:

from pandas import read_csv

def csv_parser(path):
    a = read_csv(path, header=0, sep=";")
    return a

volume_surfarea_table = csv_parser(R"GURPS Vehicles Calc\Tables\Volume Area Table.csv")
component_dr_table = csv_parser(R"GURPS Vehicles Calc\Tables\Components DR Table.csv")

def get_CF():
    vsp = float(input("What's the VSP? "))
    cf = vsp/5
    
    rowN = 0
    for x in range(64):
        if cf <= volume_surfarea_table.iloc[rowN,0]:
            hit_points = volume_surfarea_table.iloc[rowN,1]
            break
        rowN = rowN + 1
    
    return hit_points


def get_DR():
    compo_type = input("What's the component type? ")
    compo_type = compo_type.title()
    
    rowN = 0
    for x in range(6):
        if compo_type in component_dr_table.iloc[rowN,0]:
            compoDR = component_dr_table.iloc[rowN,1]
            break

        rowN = rowN + 1
    
    return compoDR


finished = "false"
while finished == "false":
    hit_points = get_CF()
    compoDR = get_DR()

    compo_stats = f"""Your component has {hit_points}HP and a DR of {compoDR}."""

    print(compo_stats)
    
    done = input("Are you finished? (y/n) ")
    if done == "y":
        finished = "true"

这是我在提示时使用的内容:

pyinstaller -F --add-data "Tables\Volume Area Table.csv;GURPS Vehicles Calc\Tables" --add-data "Tables\Components DR Table.csv;GURPS Vehicles Calc\Tables" "Vehicles Calc.py"

构建过程运行良好,但每当我尝试 运行 exe 时,它​​都会给我这个错误:

Traceback (most recent call last):
  File "Vehicles Calc.py", line 7, in <module>
  File "Vehicles Calc.py", line 4, in csv_parser
  File "pandas\util\_decorators.py", line 311, in wrapper
  File "pandas\io\parsers\readers.py", line 586, in read_csv
  File "pandas\io\parsers\readers.py", line 482, in _read
  File "pandas\io\parsers\readers.py", line 811, in __init__
  File "pandas\io\parsers\readers.py", line 1040, in _make_engine
  File "pandas\io\parsers\c_parser_wrapper.py", line 51, in __init__
  File "pandas\io\parsers\base_parser.py", line 222, in _open_handles
  File "pandas\io\common.py", line 701, in get_handle
FileNotFoundError: [Errno 2] No such file or directory: 'Volume Area Table.csv'
[16192] Failed to execute script 'Vehicles Calc' due to unhandled exception!

我做错了什么?我已经检查了文档和其他一些东西,但我无法构建一个有效的 exe。

我看到您正在使用 --onefile 标志(或 -F)来捆绑您的应用程序。

在这种情况下,您需要特殊的方法来访问您的数据文件。因为您的文件被提取到一个临时目录中(在 Windows 中,即 %temp%\_MEIPASS)。可以参考docs

所以,你可以这样做:

# Answer: 
import sys
import os

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)


volume_surfarea_table = csv_parser(resource_path(r"GURPS Vehicles Calc\Tables\Volume Area Table.csv"))

你可以在这里看到问题:Bundling data files with PyInstaller (--onefile)