如何封装读取Google Sheet的函数并返回两个变量供其他函数调用
解决方案
你可以直接将读取逻辑封装为独立函数,在函数末尾返回两个目标变量即可,调用时用两个变量接收返回值就能在其他业务逻辑中正常使用。
封装后的完整代码
def read_google_sheet_ads(spreadsheet): # 读取购买类广告 listads_buy = [] i4a = 0 line1 = 1 # 此处为你原逻辑的初始行号,若实际值不同可自行修改 while i4a <= 2: adlink = spreadsheet.cell(line1, 1).value if adlink != '': listads_buy.append(adlink) line1 += 1 i4a += 1 # 拼接为字符串,优化了空列表兼容逻辑 listads_buy_str = ','.join([str(ad) for ad in listads_buy if ad is not None]) # 读取售卖类广告 listads_sell = [] i4a = 0 line1 = 18 while i4a <= 4: adlink = spreadsheet.cell(line1, 1).value if adlink != '': listads_sell.append(adlink) line1 += 1 i4a += 1 # 拼接为字符串 listads_sell_str = ','.join([str(ad) for ad in listads_sell if ad is not None]) # 同时返回两个结果 return listads_buy_str, listads_sell_str
调用方法
需要读取最新表格内容时直接调用该函数即可,无需重启整个程序:
# 前提是你已经完成spreadsheet对象的初始化授权 buy_str, sell_str = read_google_sheet_ads(spreadsheet) # 后续可直接将两个变量传入其他函数调用 # your_other_function(buy_str, sell_str)
优化说明
- 修复了原逻辑直接取列表第0项的缺陷:如果对应行全为空,原写法会触发索引越界报错,改用
join方法拼接后空列表会返回空字符串,兼容性更好 - 所有变量作用域都在函数内部,不会污染全局变量
- 每次调用都会重新拉取表格最新数据,满足实时重读的需求
内容的提问来源于stack exchange,提问作者Garret Dabner
相关产品推荐
相关产品推荐

