【发布时间】:2016-12-20 14:37:04
【问题描述】:
我正在编写一个 Python 函数来使用用户提交的凭据向 URL 发送 GET 请求,并获取返回的令牌以供以后使用。
# Function for logging in and get a valid token
def getToken():
while True: # Loop the cycle of logging in until valid token is received
try:
varUsername = raw_input("Enter your username: ")
varPassword = getpass.getpass("Enter your password: ")
reqAuthLogin = 'https://MY_URL?username=' + varUsername + '&password=' + varPassword # Send the login request
varToken = json.loads(urllib2.urlopen(reqAuthLogin).read())['Token'] # Attempt to parse the JSON response and read the Token, if possible
except: # If credential is invalid and no token returned
os.system('cls')
print 'Invalid credentials. Please try again. \n'
else: # I want this Try to exit the while loop if login is successful
break
os.system('cls')
return varToken # Return the retrieved token at the end of this function
当用户名/密码组合不正确时,代码会抛出 KeyError 异常。我了解到 Try-Else 可以打破最里面的循环,在这种情况下应该是 while 循环。在我的设计中,我希望函数在发生异常(意味着无效凭据)时输出以下消息:
Invalid credentials. Please try again.
Enter your username:
如果登录成功,代码应该清除屏幕并返回获取的令牌。问题是,当这些代码不在 Try 和 While 中时,它们运行良好。现在它在登录成功时输出:
Enter your username:
显然,即使没有发生异常,程序也不会执行 Else 分支。我是 Python 新手,请帮我找出这个错误的原因。
编辑:感谢 cmets 的建议。我设置了几个断点,但断点显示即使我在 try 块的末尾插入一个 break,程序也会先执行它,然后直接返回“while True”语句。好像break没有成功退出循环。
【问题讨论】:
-
你不应该使用 Pokémon 异常(必须全部捕获)。
-
最简单的方法就是将 break 放在 try: block 的末尾。
-
在 try 代码段中添加中断。
-
我会在你的尝试中设置一个断点,以确保你确实有工作代码,因为有一个“catch all”异常,很难准确地说出失败的原因和原因。你必须调查每一行,看看它在做什么。
-
您是否尝试在没有 try...else 块的情况下运行代码以获得有效的凭据?你有任何错误吗?
标签: python try-catch try-except