syntaxError:“continue”在循环中不正确

2024-05-13 10:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为这个错误纠结了一段时间,对于口译员为什么抱怨“继续”这个问题,似乎有不同的看法。所以我想提供下面的错误代码。

import tweepy
import time
def writeHandlesToFile():
    file = open("dataFile.txt","w")
    try:
        list = tweepy.Cursor(tweepy.api.followers,screen_name='someHandle',).items(100000)
        print "cursor executed"
        for item in list:
            file.write(item.screen_name+"\n")
    except tweepy.error.TweepError as e:
        print "In the except method"
        print e
        time.sleep(3600)
        continue

我之所以特别希望在末尾包含continue,是因为我希望程序从睡眠后停止的位置重新开始执行,以保持程序状态。我需要睡眠以遵守twitter api的速率限制,其中api只允许您每小时发出一定数量的请求。 因此,任何可能认为我的错误幼稚或其他请指出它,或请提供一个替代实现,而不使用继续语句。

顺便说一句,我没有标签和空间的混合在另一篇文章中的建议。 提前谢谢你的帮助。


Tags: nameimport程序apitime错误itemscreen
2条回答

问题可能在于您使用continue的方式

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition or finally statement within that loop.6.1It continues with the next cycle of the nearest enclosing loop.

^{}只允许在forwhile循环中使用。您可以轻松地重新构造函数以循环,直到有一个有效的请求。

def writeHandlesToFile():
    while True:
        with open("dataFile.txt","w") as f:
            try:
                lst = tweepy.Cursor(tweepy.api.followers,screen_name='someHandle',).items(100000)
                print "cursor executed"
                for item in lst:
                    f.write(item.screen_name+"\n")
                break
            except tweepy.error.TweepError as e:
                print "In the except method"
                print e
                time.sleep(3600)

相关问题 更多 >