PyInstaller打包含Google Cloud Speech API的Python项目运行报错求助
Let's break down your two errors and walk through the fixes step by step—these are common pitfalls when packaging Google Cloud API apps with PyInstaller, especially on the outdated but still usable Python 2.7.
1. Missing speech_client_config.json Error
PyInstaller doesn't automatically bundle Google Cloud Gapic configuration files by default. To fix this, you need to explicitly tell it to include these files in the package.
Solution: Use --add-data to bundle the config files
Locate where speech_client_config.json lives in your Python 2.7 environment (usually in C:\Python27\Lib\site-packages\google\cloud\gapic\speech\v1\), then add this path to your PyInstaller command:
pyinstaller --add-data "C:\Python27\Lib\site-packages\google\cloud\gapic\speech\v1;google/cloud/gapic/speech/v1" aaa.py
- The
;separates your system's source path from the target path inside the bundled exe (use:instead if you were on Linux/macOS). - Bundling the entire
v1folder is safer than just the single JSON file, as there might be other related configs the API needs.
2. gRPC SSL Root Cert Assertion Error
This error occurs because gRPC can't locate its default SSL root certificate after being packaged. Python 2.7 isn't supported by newer gRPC versions, so we need to handle this explicitly.
Step 1: Use Python 2.7-compatible dependency versions
First, downgrade to the last gRPC version that supports Python 2.7 (newer builds will break compatibility):
pip uninstall grpcio grpcio-tools -y pip install grpcio==1.34.1 grpcio-tools==1.34.1
Also ensure your google-cloud-speech library works with Python 2.7—stick to version 2.0.0:
pip install google-cloud-speech==2.0.0
Step 2: Bundle the gRPC SSL root certificate and point to it in code
- Find the
roots.pemfile in your Python environment (usually inC:\Python27\Lib\site-packages\grpc\_cython\_credentials\). - Add it to your PyInstaller command with
--add-data:
pyinstaller --add-data "C:\Python27\Lib\site-packages\google\cloud\gapic\speech\v1;google/cloud/gapic/speech/v1" --add-data "C:\Python27\Lib\site-packages\grpc\_cython\_credentials\roots.pem;grpc/_cython/_credentials" aaa.py
- Add this code at the very top of your
aaa.pyto tell gRPC where to find the bundled certificate:
import os import sys # Get the base path of the bundled app or local script base_dir = sys._MEIPASS if hasattr(sys, '_MEIPASS') else os.path.dirname(os.path.abspath(__file__)) # Set the path to the bundled SSL root cert grpc_cert_path = os.path.join(base_dir, 'grpc/_cython/_credentials/roots.pem') os.environ['GRPC_DEFAULT_SSL_ROOTS_FILE_PATH'] = grpc_cert_path # Rest of your code below...
Final Test
After making these changes, re-run the PyInstaller command, then launch the generated aaa.exe—it should now handle the speech stream without those errors.
内容的提问来源于stack exchange,提问作者lodestar

