脚本卡在 try-except 块中



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

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

推特尝试除外循环:

# 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 loop:

# 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语句。这给您带来了问题,因为它还捕获了通常允许您通过按CTRL-C退出程序的KeyboardInterrupt异常。您几乎总是应该将捕获的异常缩小到要处理的特定错误类型。

最新更新