Skip to main content
 首页 » 编程设计

python之python 到 exe 转换后 botocore.exceptions.DataNotFoundError

2024年10月24日15三少

我可以在 Windows 上使用 python 2.7 解释器毫无问题地上传数据。 但是在我将它编译为 exe 之后,它在行中显示错误: s3 = session.client('s3')

import HTMLParser 
import ConfigParser 
# Above packages necessary because boto3 depend on them 
import boto3 
from boto3.session import Session 
# variable initialization 
session = boto3.session.Session() 
s3 = session.client('s3') #Error at this line 
s3.upload_file(fileToUpload, bucketName, keyName) 

错误是:

Traceback (most recent call last): 
  File "myProg.py", line 39, in <module> 
  File "boto3\session.pyc", line 199, in client 
  File "botocore\session.pyc", line 754, in create_client 
  File "botocore\session.pyc", line 660, in get_component 
  File "botocore\session.pyc", line 774, in get_component 
  File "botocore\session.pyc", line 174, in <lambda> 
  File "botocore\session.pyc", line 453, in get_data 
  File "botocore\loaders.pyc", line 119, in _wrapper 
  File "botocore\loaders.pyc", line 364, in load_data 
botocore.exceptions.DataNotFoundError: Unable to load data for: _endpoints 

可能是什么问题?

请您参考如下方法:

这是因为boto3找不到它的数据文件。

在这种情况下,Python27\Lib\site-packages\botocore\data 包含数据文件。我们需要指示 boto3 在主模块所在目录的数据文件夹中搜索它们。然后我们需要让 py2exe 将引用包和数据文件与 EXE 捆绑在一起。

提供数据文件

copy C:\Python27\Lib\site-packages\botocore\data  <project_root>\data 
xcopy /s /i C:\Python27\Lib\site-packages\botocore\data\s3  <project_root>\data\s3 

提供 cacert.pem

copy C:\Python27\Lib\site-packages\botocore\vendored\requests\cacert.pem <project_root>\data 

然后将我的代码重写为:

import boto3 
from boto3.session import Session 
 
CACERT = 'data/cacert.pem' 
session = boto3.session.Session() 
session._loader.search_paths.append('data') # boto3 will search for data files in the 'data' folder within current directory 
s3 = session.client('s3', use_ssl=True, verify=CACERT) # cacert.pem will be used for SSL 
s3.upload_file(fileToUpload, bucketName, keyName) 

现在我的 python 模块使用 <project_root>\data 中的资源而不是 C:\Python27\Lib\site-packages\botocore\data

最后,setup.py它指示 py2exe 将所有数据文件和引用的包包含到分发中。

from distutils.core import setup 
import py2exe 
 
aws_data_files = [ 
                    ('data', ['data/_endpoints.json','data/_retry.json', 'data/cacert.pem']), 
                    ('data/s3/2006-03-01', ['data/s3/2006-03-01/service-2.json']) 
                 ] 
setup( 
        options = { 
            'py2exe': { 
                'bundle_files': 1, 
                'compressed': True, 
                'dll_excludes':['w9xpopen.exe','crypt32.dll'], 
                'packages': ['HTMLParser', 'ConfigParser', 'boto3.s3.inject'], 
                } 
            }, 
        console=['myProg.py'], 
        zipfile = None, 
        data_files = aws_data_files, 
    ) 

答案摘自此 issue感谢jamesls和 rayluo .