【问题标题】:Python except block not runningPython除了块没有运行
【发布时间】:2020-08-04 16:15:17
【问题描述】:

我的目标是转发并收藏用户时间线上的第一条推文。如果第一条推文没有被转发或收藏,它会转发推文和收藏,否则转到 except 块并打印“已经转发”并休眠 5 分钟。

这是我的代码:

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)

但是,当推文已经被转发时,脚本永远不会进入 except 块。我不知道为什么。请说明如何解决此问题。

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

我的日志:

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

任何帮助将不胜感激,并提前致谢。

【问题讨论】:

  • 您的意思是使用else 而不是except
  • 你期待的是 tweet.retweet() 还是 tweet。 favourite() 抛出异常?因为您没有明确提出任何问题!我认为您正在寻找的是 if..elif..else 块而不是 try..catch 块..

标签: python block tweepy except


【解决方案1】:

except 块仅在 try 块返回错误时运行。如果except 代码从未运行,那么这意味着没有可以从try 捕获的错误。如果你去掉try/except 错误捕获,你可能会发现它们没有给出错误,这就是except 代码永远不会运行的原因。

试试这个代码

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)

    

【讨论】:

  • 感谢兄弟的工作✌️✌️✌️感谢您的宝贵回复。
  • 如果这解决了您的问题,请将答案标记为正确
猜你喜欢
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 2020-01-24
  • 2018-12-05
相关资源
最近更新 更多