gpt4 book ai didi

python - Python 3.6.6 上模块 sys 没有 _MEIPASS 成员错误

转载 作者:行者123 更新时间:2023-12-02 20:21:50 35 4
gpt4 key购买 nike

我一直在尝试将 json 文件捆绑到使用 pyinstaller 创建的 python 可执行文件中。经过大量研究,我找到的解决方案涉及使用 _MEIPASS 文件夹;但是,VSCode 声称 sys 包没有 _MEIPASS 成员。

我的代码的相关部分是这样的:

branches_path = 'bank_branches/bank_branches.json'

if hasattr(sys, "_MEIPASS"):
branches_path = os.path.join(sys._MEIPASS, branches_path)

该代码适用于终端版本以及独立应用程序,因此请注意这一点;但是,我想知道是否有一个可行且没有相关错误的解决方案。如果有帮助,我正在使用 Python 3.6.6

最佳答案

我在使用 pyinstaller 创建可执行文件时遇到了类似的问题。为了获得功能性可执行文件,我必须对脚本进行两​​处更改。

首先,我创建了这个函数:

def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)

我的脚本中有几个类,因此我将其单独放在最后,以便所有类都可以引用它。然后我替换了我使用过的所有函数

os.getcwd()

- 这可能首先是一个坏主意 - 与

resource_path() 

对于resource_path()内部的变量,我使用了这个函数:

os.path.dirname(os.path.abspath(__file__))

这个函数无论如何都返回了我想要的;正在运行的该文件/程序的位置。

所以,以前是这样写的:

filePath = os.getcwd() + "\\my_file.csv"

现在读作:

filePath = resource_path(os.path.dirname(os.path.abspath(__file__))) + "\\my_file.csv"

一旦就位,我的程序就会正确编译并按预期执行,希望它也能对您有所帮助。

关于python - Python 3.6.6 上模块 sys 没有 _MEIPASS 成员错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51197722/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com