Python"而真实"循环不会结束(使用Python Tweepy)

时间:2014-10-07 09:41:31

标签: python python-2.7 twitter tweepy

以下代码似乎主要是“正常工作”。这意味着它会在指定的一天内从Twitter API中删除所有推文。虽然看起来真正的循环从未打破,我看不到预期的“完成!!”字符串甚至通过csv文件完成。

import tweepy
import time
import csv

ckey = "xxx"
csecret = "xxx"
atoken = "xxx-xxx"
asecret = "xxx"

OAUTH_KEYS = {'consumer_key':ckey, 'consumer_secret':csecret,
    'access_token_key':atoken, 'access_token_secret':asecret}
auth = tweepy.OAuthHandler(OAUTH_KEYS['consumer_key'], OAUTH_KEYS['consumer_secret'])
api = tweepy.API(auth)

startSince = '2014-10-03'
endUntil = '2014-10-04'
suffix = '_03OCT2014.csv'

searchTerms = 'xyz'

tweets = tweepy.Cursor(api.search, q=searchTerms,
    since=startSince, until=endUntil).items()

while True:
    try: 
        for tweet in tweets:

            placeHolder = []
            placeHolder.append(tweet.author.name.encode('utf8'))
            placeHolder.append(tweet.author.screen_name.encode('utf8'))
            placeHolder.append(tweet.created_at)

            prefix = 'TweetData_xyz'
            wholeFileName = prefix + suffix     
            with open(wholeFileName, "ab") as f:
                writeFile = csv.writer(f)
                writeFile.writerow(placeHolder)

    except tweepy.TweepError:
        time.sleep(60*15)
        continue

    except IOError:
        time.sleep(60*5)
        continue

    except StopIteration:
        break

print "Finished!!!"

2 个答案:

答案 0 :(得分:2)

StopIteration永远不会在您的代码中引发。 for语句如果由tweepy.Cursor().items()引发,它会 进一步传播。

如果for循环结束,则突然出现:

while True:
    try:
        for tweet in tweets:
            # do stuff

        # completed iterating successfully
        break

并完全删除except StopIteration:处理程序。

答案 1 :(得分:1)

您的代码没有退出条件。 看来你不想;如果你输了一个错误就想退出那个循环。所以我假设当你到达终点时,你想退出,是吗?是的?

def process_tweet(tweet):

    placeHolder = []
    placeHolder.append(tweet.author.name.encode('utf8'))
    placeHolder.append(tweet.author.screen_name.encode('utf8'))
    placeHolder.append(tweet.created_at)

    prefix = 'TweetData_xyz'
    wholeFileName = prefix + suffix     
    with open(wholeFileName, "ab") as f:
       writeFile = csv.writer(f)
       writeFile.writerow(placeHolder)

while True:
    try: 
        for tweet in tweets:
            process_tweet(tweet)
        break
    except tweepy.TweepError:
        time.sleep(60*15)
        continue

    except IOError:
        time.sleep(60*5)
        continue

    except StopIteration:
        break

print "Finished!!!"