繁体   English   中英

脚本卡在try-except块中

[英]script stuck in try-except block

我目前正在研究一个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

我在这里想念什么吗? 我觉得这确实很明显,但是我似乎找不到问题所在(如果是这种情况,我深表歉意)?

这里有两件事。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM