Google cloud Natural Language API error:google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials

Google cloud Natural Language API error:google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials

我使用 Google 云的自然语言 API link:

我在 powershell 中使用这个命令:

$env:GOOGLE_APPLICATION_CREDENTIALS="D:\analyze_sentiment\MyFirstProject-bbe4f7bccb98.json"

然后我在cmd中使用这个命令:

set GOOGLE_APPLICATION_CREDENTIALS=D:\analyze_sentiment\MyFirstProject-bbe4f7bccb98.json

但是当我使用python代码时:

from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types

# Instantiates a client
client = language.LanguageServiceClient()
# The text to analyze
text = u'Hello, world!'
document = types.Document(
    content=text,
    type=enums.Document.Type.PLAIN_TEXT)
# Detects the sentiment of the text
sentiment = client.analyze_sentiment(document=document).document_sentiment
print('Text: {}'.format(text))
print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))

错误信息说:

raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://developers.google.com/accounts/docs/application-default-credentials.

为什么?

我想你也必须在你的本地机器上设置 GOOGLE_APPLICATION_CREDENTIALS。下载 Google Cloud Shell 并在那里设置凭据

我知道错误原因,我必须使用cmd模式来运行代码,请不要运行带有pycharm或其他IDE.And的代码设置这个link API "enable".

然后错误消失了。