Python 对Gmail通知脚本的更改
经过长时间的搜索,我发现它可以满足我的需要,以便在收到新电子邮件时实时通知我的iOS应用程序。我通常使用Objective-c编写,这是我第一次使用Python 对Gmail通知脚本的更改,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,经过长时间的搜索,我发现它可以满足我的需要,以便在收到新电子邮件时实时通知我的iOS应用程序。我通常使用Objective-c编写,这是我第一次使用Python。在我尝试设置和运行脚本之前,我希望能更好地理解它 这是我不确定的部分: # Because this is just an example, exit after 8 hours time.sleep(8*60*60) #finally: # Clean up. idler.stop() idler.join() M.close()
Python
。在我尝试设置和运行脚本之前,我希望能更好地理解它
这是我不确定的部分:
# Because this is just an example, exit after 8 hours
time.sleep(8*60*60)
#finally:
# Clean up.
idler.stop()
idler.join()
M.close()
# This is important!
M.logout()
我的问题是:
M.logout()
很重要感谢脚本已启动另一个线程,实际工作将在此另一个线程中完成。 由于某种原因,主线程没有任何事情可做,这就是为什么作者把time.sleep(8*60*60)占用了一段时间 如果要始终保持连接处于活动状态,则需要取消注释
尝试:
/最后:
,请参阅下文
如果您是python新手,请注意缩进用于定义代码块。如果您不打算停止程序,清理部分实际上可能没有用处,但是使用try:
/finally:
即使您使用Ctrl+C停止程序,清理代码也将被执行
未测试:
# Had to do this stuff in a try-finally, since some testing
# went a little wrong.....
try:
# Set the following two lines to your creds and server
M = imaplib2.IMAP4_SSL("imap.gmail.com")
M.login(USER, PASSWORD)
# We need to get out of the AUTH state, so we just select
# the INBOX.
M.select("INBOX")
numUnseen = getUnseen()
sendPushNotification(numUnseen)
#print M.status("INBOX", '(UNSEEN)')
# Start the Idler thread
idler = Idler(M)
idler.start()
# Sleep forever, one minute at a time
while True:
time.sleep(60)
finally:
# Clean up.
idler.stop()
idler.join()
M.close()
# This is important!
M.logout()
谢谢你的信息。因此,基本上,
time.sleep(60)
会在一分钟后退出一个不再有用的线程,而另一个线程仍在进行中?不,time.sleep()
函数只是让线程等待并防止它消耗cpu时间。我还没有在这里实现最干净的解决方案,这只是一种用最少的更改来修复脚本的方法。