简体   繁体   中英

Python except block not running

My goal is to retweet and favorite the very first tweet on a user's timeline. If the very first tweet hasn't been retweeted or fav, it retweets the tweet and fav, otherwise going to the except block and print "already retweeted" and sleep for 5 minutes.

Here is my code:

for i in iter(int, 1):

for tweet in tweepy.Cursor(api.user_timeline, screen_name='realdonaldtrump', include_rts=False, exclude_replies=True).items(1): 
    try:
        print('\nTweet by: @' + tweet.user.screen_name) 

        if not tweet.retweeted:
                    tweet.retweet() 
                    print('Retweeted the tweet')
        if not tweet.favorited:
                    tweet.favorite() 
                    print('Favorited the tweet')
        sleep(60)

    except:
        print('Already retweeted and favorited please be patient till next tweet')
        sleep(300)

But here the script never goes to the except block when the tweet is already retweet. I don't known why. Please explain how to solve this problem.

except:
            print('Already retweeted and favorited please be patient till next tweet')
            sleep(300)

My logs:

2020-08-04T16:06:14.608937+00:00 app[worker.1]: Tweet by: @realDonaldTrump
2020-08-04T16:06:14.785120+00:00 app[worker.1]: Retweeted the tweet
2020-08-04T16:06:15.013208+00:00 app[worker.1]: Favorited the tweet
2020-08-04T16:07:15.566250+00:00 app[worker.1]: Tweet by: @realDonaldTrump
2020-08-04T16:08:15.822568+00:00 app[worker.1]: 
2020-08-04T16:08:15.822615+00:00 app[worker.1]: Tweet by: @realDonaldTrump
2020-08-04T16:09:16.229441+00:00 app[worker.1]: 
2020-08-04T16:09:16.229453+00:00 app[worker.1]: Tweet by: @realDonaldTrump

Any help would be appreciated and thanks in advance.

The except block only runs if the try block returns an error. If the except code never ran, then that means there is no error to catch from the try . If you remove the try/except error catching, you will probably find that their is no error given, this is why the except code never runs.

Try this code

for tweet in tweepy.Cursor(api.user_timeline, screen_name='realdonaldtrump', include_rts=False, exclude_replies=True).items(1): 
    print('\nTweet by: @' + tweet.user.screen_name) 

    if not tweet.retweeted or not tweet.favorited:
        tweet.retweet() 
        print('Retweeted the tweet')

        tweet.favorite() 
        print('Favorited the tweet')
    else:
        print('Already retweeted and favorited please be patient till next tweet')
        sleep(300)

    sleep(60)

    

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