我有一个 python 脚本,当我从 Spyder 或 Jupyter Notebook 或任何 IDE 或 Visual Studio 编译它时,它可以正常运行;但是,当我尝试从命令提示符运行它时,出现以下错误。
line 50, in func_get_credentials_ret_service if not creds or not creds.valid: UnboundLocalError: local variable 'creds' referenced before assignment
我曾尝试屏蔽获取凭据代码等的某些部分,但我认为出于相当明显的原因,这不是一个解决方案。
如果我在 .bat 文件中作为命令运行,则不起作用(给出相同的错误)
预先感谢您提供的任何帮助。 以下是相关代码部分
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from Message_list import ListMessagesMatchingQuery
from dateutil import parser
import datetime as dt
import pprint
import sys
import base64
from apiclient import errors
import pandas as pd
import holidays
def func_get_credentials_ret_service():
##########################################################################
## From google api page
##
##########################################################################
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
return service
service = func_get_credentials_ret_service()
results = ListMessagesMatchingQuery(service, "me", 'from: "someprovider.com"')
id_list = func_create_id_list(results)
最佳答案
答案:
您在为变量 creds
赋值之前对其进行比较。
修复:
行:
if not creds or not creds.valid:
如果您的 token.pickle
文件存在,则会执行,但是在调用之前没有分配变量 creds
。
在 SCOPES
定义之后添加此行:
creds = None
关于python - Google_api 凭据错误来自 CMD 或 .bat 文件执行,但不是来自 IDE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58334117/