设置环境变量问题

时间:2018-03-13 18:08:36

标签: python authentication google-speech-api

我的google api测试中出现了auth错误,设置环境变量的代码单独工作,但是当与google测试代码一起使用时,auth会失败。我还能够通过在shell中运行EXPORT命令来获得测试代码。为方便起见,我希望能够在我的脚本中设置auth。

 #This program will test the google speech api
 #while setting the environmental variable for the
 #authentication .json file and then authenticating

 import os

 # Imports the Google Cloud client library
 from google.cloud import language
 from google.cloud.language import enums
 from google.cloud.language import types

 # My code sets the authentication env variable
 os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = str('home/kyle/Security/test.json')

 # 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))

错误:

   File "/home/kyle/python projects/googleSpeech/test/venv/lib/python3.5/site-packages/google/auth/_default.py", line 142, in _get_explicit_environ_credentials
os.environ[environment_vars.CREDENTIALS])
   File "/home/kyle/python projects/googleSpeech/test/venv/lib/python3.5/site-packages/google/auth/_default.py", line 67, in _load_credentials_from_file
'File {} was not found.'.format(filename))
 google.auth.exceptions.DefaultCredentialsError: File home/kyle/Security/test.json was not found.

编辑现在导出json文件不起作用我运行此代码来测试读取.json文件

 fd = open(‘/home/kyle/Security/test.json’)
 dat = fd.read()
 fd.close()

结果:

 SyntaxError: Non-ASCII character '\xe2' in file testRead.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

3 个答案:

答案 0 :(得分:0)

仔细观察,我认为可能是这一行:

  

os.environ [' GOOGLE_APPLICATION_CREDENTIALS'] =   STR('家/凯尔/安全性/ test.json&#39)

在home / kyle / ....前面添加/,这样它就是/ home / kyle /...

答案 1 :(得分:0)

使用三个'而不是一个'

将单斜杠更改为两个或转义

答案 2 :(得分:0)

这个问题要求我从api控制台重新生成一个新的json密钥,它具有项目所有者权限,现在无需更改代码