简体   繁体   中英

breaking out of loop in loop and restarting script in python

This is my script for a twitterbot. It does a search based on keywords and retweets the tweets containing the keywords. I need to break out of this loop in loop and restart the script in case of an error code:

    for row in retweeted_id:
        try:
            print(row)
            twitter.api.retweet(row)

            time.sleep(180)
        except tweepy.TweepError, e:
            if e == "[{u'message': u'You have already retweeted this tweet.', u'code': 327}]":
                print(e)
                break                    
            elif e == "[{u'message': u'Rate limit exceeded', u'code': 88}]":
                print(e)
                time.sleep(60*5)
            elif e == "[{u'message': u'User is over daily status update limit.', u'code': 185}]":
                 print(e)
                 break


            else:
                print(e)

I've tried doing:

else:`
    continue
break

And i've also tried to put the entire script in a function but I am not experienced enough to write classes/functions in functions. I would like to restart the script with at the top in the case of an error 327 Your help is highly appreciated!

Here's the entire script:

import time
retweeted_id = []
tweet_text = []
tweet_text_id = []
from TwitterSearch import TwitterSearchOrder, TwitterUserOrder, TwitterSearchException, TwitterSearch

try:
    tso = TwitterSearchOrder() 
    tso.set_keywords([""]) 

    tso.set_language('nl')
    tso.set_include_entities(False) 
    tso.set_result_type('recent')

    ts = TwitterSearch(
        consumer_key = "aaaa",
        consumer_secret = "bbbb",
        access_token = "cccc",
        access_token_secret = "dddd"
                        )
    for retweeted in ts.search_tweets_iterable(tso):
        tweet_text_id.append({retweeted['id'], retweeted['user']['screen_name'] })
        retweeted_id.append(retweeted['id'])
    print('done')

    import tweepy
    class TwitterAPI:
        def __init__(self):
            consumer_key = "aaaa"
            consumer_secret = "bbbb"
            auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
            access_token = "cccc"
            access_token_secret = "dddd"
            auth.set_access_token(access_token, access_token_secret)
            self.api = tweepy.API(auth)

        def tweet(self, message):
            self.api.update_status(status=message)

    if __name__ == "__main__":
        twitter = TwitterAPI()

        for row in retweeted_id:
            try:
                print(row)
                twitter.api.retweet(row)

                time.sleep(180)
            except tweepy.TweepError, e:
                if e == "[{u'message': u'You have already retweeted this tweet.', u'code': 327}]":
                    print(e)
                    break                    
                elif e == "[{u'message': u'Rate limit exceeded', u'code': 88}]":
                    print(e)
                    time.sleep(60*5)
                elif e == "[{u'message': u'User is over daily status update limit.', u'code': 185}]":
                     print(e)
                     break

except TwitterSearchException as e:
    print(e)

If I correctly understand what you want, restructuring this way is probably the easiest answer (better would be to avoid globals).

<imports>

<globals from init>

def init():
    <your init stuff>

class TwitterAPI:
    <...>

def twit():
    twitter = TwitterAPI()
    for row in retweeted_id:
        <rest of loop>

def main():
    init();
    while (True):
        try:
            twit();
        except TwitterSearchException as e:
            print(e)

if __name__ == "__main__":
    main();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM