Ale*_*iro 2 python pyinstaller
我一直在尝试将 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)
Run Code Online (Sandbox Code Playgroud)
该代码适用于终端版本以及独立应用程序,因此请注意这一点;但是,我想知道是否有一个可行且没有相关错误的解决方案。如果有帮助的话,我正在使用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)
Run Code Online (Sandbox Code Playgroud)
我的脚本中有几个类,因此我将其单独放在最后,以便所有类都可以引用它。然后我替换了我使用过的任何功能
os.getcwd()
Run Code Online (Sandbox Code Playgroud)
- 这可能首先是一个坏主意 - 与
resource_path()
Run Code Online (Sandbox Code Playgroud)
对于resource_path()内部的变量,我使用这个函数:
os.path.dirname(os.path.abspath(__file__))
Run Code Online (Sandbox Code Playgroud)
无论如何,这个函数返回了我想要的东西;正在运行的该文件/程序的位置。
那么,之前的写法是这样的:
filePath = os.getcwd() + "\\my_file.csv"
Run Code Online (Sandbox Code Playgroud)
现在读作:
filePath = resource_path(os.path.dirname(os.path.abspath(__file__))) + "\\my_file.csv"
Run Code Online (Sandbox Code Playgroud)
一旦到位,我的程序就可以正确编译并按预期执行,希望它也可以帮助您。