You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python脚本循环执行直至无错误?(Tweepy改名代码问题)

问题描述

我是Python新手,尝试让一段修改推特用户名的脚本循环执行直至无错误,但一直无法实现。我已尝试所有已知方法仍未解决。当前代码执行后仅尝试一次就停止,预期效果是持续尝试修改相同用户名直至成功。

我的代码如下:

def change_screen_name(self):
    print("Attempting change...")
    try:
        status = self.api.update_profile(screen_name="name")
        print("Name updated!")
    except tweepy.TweepError as error:
        resp = error.response.json()["errors"][0]
        print("Name unavailable.")
        print("{} ({})".format(resp["message"], resp["code"]))
    finally:
        return self
解决方案

嗨,我一眼就看出问题所在啦——你的函数现在只执行了一次修改尝试就直接返回了,完全没有循环逻辑支撑持续重试!要实现一直尝试直到成功的效果,咱们得给函数加上循环结构,同时还要注意别因为频繁请求触发Twitter的API限流机制。

给你改好的可用代码:

import time

def change_screen_name(self):
    while True:
        print("Attempting change...")
        try:
            status = self.api.update_profile(screen_name="name")
            print("Name updated!")
            break  # 修改成功就跳出循环,结束函数
        except tweepy.TweepError as error:
            resp = error.response.json()["errors"][0]
            print("Name unavailable.")
            print("{} ({})".format(resp["message"], resp["code"]))
            # 加个延迟再重试,这里设的60秒,你可以根据实际情况调整时长
            time.sleep(60)
    return self

几个关键修改说明:

  • 无限循环逻辑:用while True创建持续运行的循环,只有在修改成功时执行break退出循环。
  • 限流防护:添加time.sleep()避免短时间内多次请求触发Twitter的API限制,不然可能会被暂时限制账号操作。
  • 明确终止条件:只有当update_profile顺利执行不抛出异常时,才会终止循环,否则会一直重试下去。

另外,如果遇到某些无法恢复的错误(比如用户名格式完全不符合要求),咱们也可以加个判断直接停止重试,避免做无用功:

import time

def change_screen_name(self):
    while True:
        print("Attempting change...")
        try:
            status = self.api.update_profile(screen_name="name")
            print("Name updated!")
            break
        except tweepy.TweepError as error:
            resp = error.response.json()["errors"][0]
            error_code = resp["code"]
            print("Name unavailable.")
            print("{} ({})".format(resp["message"], error_code))
            
            # 比如错误码17是无效用户名,187是重复请求,遇到这些直接停止重试
            if error_code in [17, 187]:
                print("遇到无法修复的错误,停止重试。")
                break
            
            time.sleep(60)
    return self

内容的提问来源于stack exchange,提问作者overwrite777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:18:31