如何通过Python在本地运行官方Google Translate API并解决凭证报错
问题根因
你的客户端初始化代码存在语法错误:from_service_account_json是TranslationServiceClient的类方法,不需要先实例化类再调用。你写的TranslationServiceClient()会先触发空实例化逻辑,这个过程会自动尝试读取系统默认凭证,还没执行到后面的from_service_account_json就已经触发了凭证找不到的报错。
解决方案
方案1:直接修正初始化代码(最推荐)
把原代码里的客户端初始化行修改即可,去掉TranslationServiceClient后的括号:
# 修改前 client = translate.TranslationServiceClient().from_service_account_json('key.json') # 修改后 client = translate.TranslationServiceClient.from_service_account_json('key.json')
修正后的完整可运行代码如下:
from google.cloud import translate def translate_text(text="Hello, world!", project_id="weighty-site-333613"): client = translate.TranslationServiceClient.from_service_account_json('key.json') location = "global" parent = f"projects/{project_id}/locations/{location}" response = client.translate_text( request={ "parent": parent, "contents": [text], "mime_type": "text/plain", "source_language_code": "en-US", "target_language_code": "zh-CN", } ) for translation in response.translations: print("Translated text: {}".format(translation.translated_text)) translate_text()
方案2:配置系统环境变量
如果不想修改代码,可以在运行脚本前先配置环境变量,指向你的key.json绝对路径:
- macOS/Linux终端执行:
export GOOGLE_APPLICATION_CREDENTIALS="/Users/jiajunmao/Documents/GitHub/translator_of_excel/key.json" - Windows CMD执行:
set GOOGLE_APPLICATION_CREDENTIALS=C:\Users\jiajunmao\Documents\GitHub\translator_of_excel\key.json - Windows PowerShell执行:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\jiajunmao\Documents\GitHub\translator_of_excel\key.json"
配置完成后再运行脚本即可正常加载凭证。
附加优化建议
建议优先使用动态拼接的绝对路径指向key.json,避免在不同工作目录运行脚本时出现文件找不到的问题,示例:
import os from google.cloud import translate def translate_text(text="Hello, world!", project_id="weighty-site-333613"): # 自动获取当前脚本同级目录下的key.json路径 key_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'key.json') client = translate.TranslationServiceClient.from_service_account_json(key_path) location = "global" parent = f"projects/{project_id}/locations/{location}" response = client.translate_text( request={ "parent": parent, "contents": [text], "mime_type": "text/plain", "source_language_code": "en-US", "target_language_code": "zh-CN", } ) for translation in response.translations: print("Translated text: {}".format(translation.translated_text)) if __name__ == '__main__': translate_text()
内容的提问来源于stack exchange,提问作者Will_jjjjjjj
相关产品推荐
相关产品推荐

