如何在Pyinstaller中包含Google API JSON凭据文件



我的第一个问题。我是一个自学成才的蟒蛇爱好者。我知道这可能是一个愚蠢的问题,但经过许多天的搜索,我找不到任何信息。

我正在制作一个应用程序,使用google API读取google电子表格中的数据,然后使用PYFPDF输出带有预先格式化布局的漂亮图片的PDF文件。它在我的Python3.5.2 + Pycharm + Mac OSX环境的计算机上运行没有任何问题。

我的应用程序是通过获取访问google API的凭证开始的。

scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('my_app_creds.json', scope)
client = gspread.authorize(creds)

my_app_creds.json文件如下所示:

{
"type": "service_account",
"project_id": "my_app",
"private_key_id": "1234567890",
"private_key": "-----BEGIN PRIVATE KEY-----nVERY_LONG_PRIVATE_KEYn-----END PRIVATE KEY-----n",
"client_email": "my_email@my_app.iam.gserviceaccount.com",
"client_id": "0987654321",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/my_app.iam.gserviceaccount.com"
}

当我使用pyinstaller以-F(onefolder)模式编译包以生成可执行文件时,出现了问题。应用程序文件夹已成功创建,并正确地位于"dist"文件夹中。但当我试图执行该文件时,它抛出了一个错误:

FileNotFoundError: [Errno 2] No such file or directory: 'my_app_creds.json'
[24713] Failed to execute script my_app

我已经将my_app_creds.json包含在.datas的.spec文件中,并使用pyinstaller文档中的命令:

pyinstaller my_app.spec

my_app.spec是include.json文件,该文件"未找到">

a = Analysis(['my_app.py'],
pathex=['/Users/gungpetrucci/PycharmProjects/myapp'],
binaries=[],
datas=[('my_app_creds.json', '.')],

我验证my_app_creds.json与"dist/my_app"中的可执行文件位于同一文件夹中。我不知道为什么可执行文件找不到它?

当我尝试搜索论坛时,我似乎不清楚:

  • 我不确定这是否与_MEIPASS有关?但我认为_MEIPASS只会在pyinstaller中使用-F onefile模式是一个问题吗?

  • 由于编译后的应用程序从不运行pass-creds过程,因此它从不进入图像处理过程。我想知道该应用程序能否定位子文件夹中的.png图片(编译前)?如何将整个图像文件夹包含到dist包中并使其可访问?

请帮忙。。

我在一个项目中遇到了同样的问题。我使用了以下变通方法-

  1. 从"my_app_creds.json"中装入一个内容字典:

    app_creds_dictionary = <paste contents of json file including {}>
    
  2. 使用"from_json_keyfile_dict()"函数创建cred而不是文件:

    creds = ServiceAccountCredentials.from_json_keyfile_dict(app_creds_dictionary, scope)
    
  3. 现在,由于这是python文件本身的一部分,所以无需担心粘贴/维护json文件的副本。即使是以这种方式创建的.exe也对我有效

希望这能有所帮助!