【问题标题】:File is not found in MEIPASS Pyinstaller (but was working initially)在 MEIPASS Pyinstaller 中找不到文件(但最初可以使用)
【发布时间】:2022-10-05 02:12:33
【问题描述】:

我有一个程序在while循环中向GCS发送一些数据,它需要一个JSON凭证文件,它大致如下所示:

import os
import sys
from pathlib import Path


GOOGLE_SERVICE_ACCOUNT_FP = "pos-service-account.json"

IS_INSTALLER = getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS")
if IS_INSTALLER:
    GOOGLE_SERVICE_ACCOUNT_FP = os.path.join(sys._MEIPASS, GOOGLE_SERVICE_ACCOUNT_FP)



def send_data(data, credential_fp: Path = Path(GOOGLE_SERVICE_ACCOUNT_FP)):
    if not credential_fp.is_file():
        msg = f"Google service account key json file: {str(credential_fp)!r} is not found!\nPWD files:\n{list(Path.cwd().glob('*'))}"
        raise FileNotFoundError(msg)

    # some function post data to cloud storage
    post_to_gcs(data)


def main():
    while True:
        data = ...
        send_data(data)


if __name__ == '__main__':
    main()

我使用以下命令使用一个文件打包: pyinstaller --onefile -w .\main.py --add-data 'pos-service-account.json;.'

然后当我点击windows上的.exe文件时,它工作正常,我可以看到这个程序发布的数据。但是,几天后我回来了,我得到了找不到文件的错误:

 Google service account key json file: 'C:\\Users\\POS\\AppData\\Local\\Temp\\_MEI30522\\pos-service-account.json' is not found! 

这对我来说没有意义,因为程序一开始就在工作,这意味着它确实找到了 json 文件,我仍在尝试复制错误,但到目前为止我的怀疑是:

  • sys._MEIPASS 目录是否会更改?例如如果计算机进入睡眠状态并重新启动(我将对其进行测试),我可以看到如果程序运行时_MEIPASS 发生更改,我的脚本将如何失败。

【问题讨论】:

    标签: python pyinstaller


    【解决方案1】:

    是的,MEIPASS 文件夹经常更改它的名称,因此硬编码该文件位置是一个坏主意。而是保存相对于__file__ 路径变量的文件,以便它始终引用当前正在运行的程序位置。

    import os
    import sys
    from pathlib import Path
    
    GOOGLE_SERVICE_ACCOUNT_FP = "pos-service-account.json"
    CREDENTIAL = os.path.join(os.path.abspath(__file__), GOOGLE_SERVICES_ACCOUNT_FP)
    
    
    def send_data(data, credential_fp=CREDENTIAL):
        if not credential_fp.is_file():
            msg = f"Google service account key json file: {str(credential_fp)!r} is not found!
    PWD files:
    {list(Path.cwd().glob('*'))}"
            raise FileNotFoundError(msg)
    
        # some function post data to cloud storage
        post_to_gcs(data)
    
    
    def main():
        while True:
            data = ...
            send_data(data)
    
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多