Python脚本调用Google Drive API正常,Pyinstaller编译后报AttributeError错误
Pyinstaller打包Google Drive API脚本exe报错解决方案
错误根源
报错AttributeError: 'NoneType' object has no attribute 'files'说明你的service对象是None——也就是初始化Google Drive服务的逻辑在打包后执行失败,没有生成有效的服务实例。
解决步骤
1. 修复凭证文件的路径问题
打包后exe的工作目录和脚本运行时不同,必须动态获取文件路径:
import sys import os def get_file_path(filename): # 判断是否处于打包后的运行环境 if getattr(sys, 'frozen', False): # 打包后临时目录路径 base_dir = sys._MEIPASS else: # 脚本运行时的目录 base_dir = os.path.dirname(os.path.abspath(__file__)) return os.path.join(base_dir, filename) # 修改凭证加载逻辑,用上面的函数获取路径 creds = None token_file = get_file_path("token.json") if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # 处理credentials.json credential_file = get_file_path("credentials.json") if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file(credential_file, SCOPES) creds = flow.run_local_server(port=0) # 保存token到当前工作目录(方便用户后续运行) with open("token.json", "w") as token: token.write(creds.to_json())
2. 打包时包含凭证文件和必要依赖
执行Pyinstaller打包命令时,要显式添加凭证文件,并指定Google API客户端的隐藏导入:
# Windows系统 pyinstaller --onefile --add-data "credentials.json;." --add-data "token.json;." --hidden-import googleapiclient.discovery --hidden-import googleapiclient.errors --hidden-import google.auth --hidden-import google.auth.transport.requests 你的脚本文件名.py # Mac/Linux系统 pyinstaller --onefile --add-data "credentials.json:." --add-data "token.json:." --hidden-import googleapiclient.discovery --hidden-import googleapiclient.errors --hidden-import google.auth --hidden-import google.auth.transport.requests 你的脚本文件名.py
--add-data:把凭证文件打包进exe,运行时释放到当前目录--hidden-import:强制Pyinstaller包含Google API客户端的隐式依赖
3. 增加服务初始化的错误排查
在初始化service的地方添加错误捕获,方便定位问题:
service = None try: service = build('drive', 'v3', credentials=creds) print("Drive服务初始化成功") except Exception as e: # 打包后窗口版可以把错误写入日志文件 with open("service_error.log", "w") as f: f.write(f"服务初始化失败: {str(e)}") print(f"服务初始化失败: {str(e)}")
如果初始化失败,打开生成的service_error.log就能看到具体原因(比如凭证文件缺失、网络问题等)。
4. 运行注意事项
- 首次运行exe时,会弹出浏览器要求授权Google Drive权限,授权后会生成
token.json,后续运行无需再授权 - 确保exe和生成的
token.json在同一目录 - 运行环境需要能访问Google服务的网络
内容的提问来源于stack exchange,提问作者Put3k
相关产品推荐
相关产品推荐

