Python 包裹

Python Packages

我试过 运行 这个使用 Google 云的代码。

import signal
import sys

from google.cloud import language, exceptions

# create a Google Cloud Natural Languague API Python client
client = language.LanguageServiceClient()

但它给出了以下错误信息:

  Traceback (most recent call last):
  File "analyse-comments.py", line 7, in <module>
    client = language.LanguageServiceClient()
  File "C:\Python27\lib\site-packages\google\cloud\language_v1\gapic\language_service_client.py", line 92, in __init__
    scopes=self._DEFAULT_SCOPES)
  File "C:\Python27\lib\site-packages\google\api_core\grpc_helpers.py", line 132, in create_channel
    credentials, _ = google.auth.default(scopes=scopes)
  File "C:\Python27\lib\site-packages\google\auth\_default.py", line 283, in default
    raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or
explicitly create credential and re-run the application. For more
information, please see
https://developers.google.com/accounts/docs/application-default-credentials.

第 7 行是这部分代码

 client = language.LanguageServiceClient()

我已经安装了 pip google 和云。我有 google 的解决方案,但 none 的解决方案适合我的情况需要解决的问题。

您分享的错误清楚地指出凭据存在问题:

google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or
explicitly create credential and re-run the application.

它邀请您访问文档页面以获取 Setting Up Authentication 有关此主题的更多信息:

For more information, please see https://developers.google.com/accounts/docs/application-default-credentials.

这里的具体问题是您正在使用的客户端库 (google.cloud.language) 正在尝试直接在环境变量 GOOGLE_APPLICATION_CREDENTIALS 中查找凭据以使用您的 GCP 帐户进行身份验证,但事实并非如此能够找到他们。为了解决这个问题,您应该首先从 Service Accounts page in the Console (clicking on the three points at the right and creating a new JSON key), store it locally, and then point to it using GOOGLE_APPLICATION_CREDENTIALS, as explained in the documentation 下载您的服务帐户的 JSON 密钥,具体取决于您的 OS 发行版。

一旦此环境变量填充了 JSON 密钥的正确目录路径,您正在使用的客户端库将能够正确进行身份验证并且错误应该消失。

此外,如果该过程对您不起作用(我看不出有任何原因不适用),您可以将凭据文件显式传递给您正在实例化的 LanguageServiceClient(),如下所示,详情见 API reference for the Natural Language API:

from google.cloud import language
from google.oauth2 import service_account

creds = service_account.Credentials.from_service_account_file('path/key.json')
client = language.LanguageServiceClient(
    credentials=creds,
)