所以我写了一个Twitter机器人,它从某个subreddit提取最高提交并将其发布到twitter。
它作为一个cron作业运行,如果顶部帖子与上次运行时相同,那么Twitter api会抛出一个错误,帖子是重复的,我想抓住这个错误,然后用密钥重新运行该功能增加,以便尝试下一个帖子继承我的代码(api凭证遗漏)
def pull_reddit_post(key):
r = reddit.Reddit(user_agent='ghettoTwit')
submissions = r.get_subreddit('ghettojerk').get_hot(limit=10)
post = [str(x) for x in submissions]
post = post[key]
post = post.lstrip('0123456789: ')
return post
def tweet_reddit_post(key):
global api
post = pull_reddit_post(key)
api.PostUpdates(pull_reddit_post(key))
try:
key = 0
tweet_reddit_post(key)
except:
key = key + 1
continue
else:
break
答案 0 :(得分:1)
只需编辑try ... except并将其放入循环
key = 0
while True:
try:
tweet_reddit_post(key)
break
except:
key += 1