何时在执行无休止的python脚本时登录到gspread

何时在执行无休止的python脚本时登录到gspread,python,google-api,Python,Google Api,我不知道在无休止地执行python脚本的同时登录gspread的最佳时机 def openSheet(sheetName): scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]

我不知道在无休止地执行python脚本的同时登录gspread的最佳时机

def openSheet(sheetName):
    scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
    creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope)
    client = gspread.authorize(creds)
    sheet = client.open(sheetName).sheet1
    return sheet
现在,每当我从gspread请求一个文件时,我都在执行openSheet方法

但为了优化脚本的性能,我想我可以在脚本的顶部定义作用域、cred和client,这样就可以只定义一次,而不是每次执行无休止的循环


我应该在什么时候执行登录?

这就是我所做的。我的导入语句下面有scope、cred和client,因此当我进入脚本中重复调用的函数时,我只需要在调用文件时包含定义工作表的部分(random_variable_name=gc.open(“我的电子表格”)

例如,我的看起来像这样

import gspread
from google.colab import auth 
auth.authenticate_user()
from google.colab import drive
import gspread 
from oauth2client.client import GoogleCredentials

scope = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive'
]

json_file = 'myfilepath/uberimportantstuff.json'
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file, scope)
gc = gspread.authorize(credentials)
此时,我所要做的就是在下面创建对象

sh = gc.open(spreadsheet_name)