Python 将数据写入google工作表在.ipynb中有效,但在.py中无效
我的脚本将一些数据写入谷歌电子表格。它在iPython笔记本中工作得非常好,但它不是来自Sublime中的.py文件(没有错误,什么都没有)。这两个文件与授权文件“client_secret.json”位于同一文件夹中。有人能提出原因吗?谢谢大家! 我的代码:Python 将数据写入google工作表在.ipynb中有效,但在.py中无效,python,google-sheets,sublimetext,ipython-notebook,Python,Google Sheets,Sublimetext,Ipython Notebook,我的脚本将一些数据写入谷歌电子表格。它在iPython笔记本中工作得非常好,但它不是来自Sublime中的.py文件(没有错误,什么都没有)。这两个文件与授权文件“client_secret.json”位于同一文件夹中。有人能提出原因吗?谢谢大家! 我的代码: import datetime as dt import gspread from oauth2client.service_account import ServiceAccountCredentials def google
import datetime as dt
import gspread
from oauth2client.service_account import ServiceAccountCredentials
def googlesheet():
# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
# Find a workbook by name and open the first sheet
wsheet = client.open("google_cout").worksheet('Count')
return wsheet
def next_available_row(sheet):
str_list = filter(None, sheet.col_values(1)) # fastest
return str(len(str_list)+1)
#insert on the next available row
def write_to_google(next_row, count):
today = dt.datetime.today().strftime("%d %B")
wsheet.update_acell("A{}".format(next_row), today)
for i in count:
if i == u'red':
wsheet.update_acell("B{}".format(next_row), count[i])
if i == u'blue':
wsheet.update_acell("C{}".format(next_row), count[i])
print('Done!')
def main():
total_count = {u'red': 222, u'blue': 91}
wsheet = googlesheet()
next_row = next_available_row(wsheet)
write_to_google(next_row, total_count)
if __name__ == '__main__':
main()
您所说的“它不能从Sublime中的.py文件工作”是什么意思。在Sublime中打开文件将不会执行它。通常,您会从shell执行该文件。你是如何执行.py文件的?抱歉,如果我不够清楚的话。我从shell运行该文件:
python name\u of\u my\u file.py
。代码运行良好,可以打印正确的总计数
,但不会将结果写入谷歌电子表格。不过,如果我在笔记本中运行相同的代码,则会发生这种情况。这就是我困惑的原因。我把所有的东西都放在一个函数中解决了这个问题。我认为这与谷歌如何授权访问电子表格以及笔记本电脑如何处理来自不同单元格的结果有关。现在,当我从shell中运行文件时,它就可以工作了。你说的“它不能从Sublime中的.py文件工作”是什么意思。在Sublime中打开文件将不会执行它。通常,您会从shell执行该文件。你是如何执行.py文件的?抱歉,如果我不够清楚的话。我从shell运行该文件:python name\u of\u my\u file.py
。代码运行良好,可以打印正确的总计数
,但不会将结果写入谷歌电子表格。不过,如果我在笔记本中运行相同的代码,则会发生这种情况。这就是我困惑的原因。我把所有的东西都放在一个函数中解决了这个问题。我认为这与谷歌如何授权访问电子表格以及笔记本电脑如何处理来自不同单元格的结果有关。现在,当我从shell运行文件时,它就可以工作了。