首页 > 解决方案 > 脚本卡在 try-except 块中

问题描述

我目前正在编写一个 Python 脚本,该脚本基本上为 Spotify 曲目抓取给定的 Twitter 帐户,并创建找到的曲目的播放列表。该脚本在大多数情况下运行正常,但我正在尝试合并一些错误处理并遇到一些问题。我要解决的第一个错误是当用户输入无效的 Spotify/Twitter 用户名时。

到目前为止,我已经创建了 2 个单独的 try-except 循环来不断提示用户输入他们的 Twitter 和 Spotify 用户名,直到输入有效的用户名。Twitter 的 try-except 循环似乎运行正常,但如果输入了错误的用户名,Spotify 循环就会卡住(即除了有效的用户名之外,不会在输入 ^C 时终止)。

Twitter try-except 循环:

# Get request token from Twitter
    reqclient = Twython(consumer_key, consumer_secret)
    reqcreds = reqclient.get_authentication_tokens()

    # Prompt user for Twitter account information until valid account is found
    validated = False
    while validated == False:
        try:
            t_username = input("Please enter your TWITTER username: ")
            user_info = reqclient.show_user(screen_name=t_username)
        # except TwythonError as e:
        except:
            print("Could not find Twitter account " + t_username + ". Please try again.")
            # print(e)
            continue
        else:
            t_user_id = user_info["id"]
            validated = True

Spotify try-except 循环:

    # Create a SpotifyOAuth object to begin authroization code flow
    scope = 'playlist-modify-public playlist-read-collaborative playlist-read-private playlist-modify-private' # Specifies access/user authorization needed to perform request (i.e. create playlist)
    sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id=client_id,client_secret=client_secret,redirect_uri=redirect_uri,scope=scope)

    # Prompt user for Spotify account information until valid account is found
    validated = False
    while validated == False:
        try:
            s_username = input("Please enter your SPOTIFY username: ")
            user_info = sp_oauth.current_user()
        except:
            print("Could not find Spotify account " + s_username + ". Please try again.")
            continue
        else:
            s_user_id = user_info["id"]
            validated = True

我在这里错过了什么吗?我觉得这很明显,但我似乎找不到问题(如果是这种情况,请道歉)?

标签: pythontry-excepttwythonspotipy

解决方案


这里有两件事。

首先,s_username您输入的值永远不会实际应用于任何类型的 Spotify API 对象,因此结果sp_oauth.current_user()永远不会改变。

第二个也是更重要的问题是您正在使用一个笼统的except语句来捕获所有异常。这给您带来了问题,因为它还捕获了KeyboardInterrupt通常允许您通过按退出程序的异常CTRL-C。您应该几乎总是将您捕获的异常缩小到您想要处理的特定错误类型。


推荐阅读