当我从Spyder或Jupyter Notebook或任何IDE或Visual Studio进行编译时,我有一个运行良好的python脚本;但是,当我尝试从命令提示符运行它时,出现以下错误。


  第50行,在func_get_credentials_ret_service中
      如果不是creds或不是creds.valid:UnboundLocalError:分配前引用了本地变量'creds'


我尝试屏蔽获取凭证代码等的某些部分,但是我认为出于明显的原因,这不是解决方案。

如果我也无法在.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

10-08 05:15