Python中,如何从Try中正确跳出一个While循环?
In Python, how to correctly jump out of a While loop from Try?
我正在编写一个 Python 函数,使用用户提交的凭据向 URL 发送 GET 请求,并获得一个 returned 令牌供以后使用。
# 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
当username/password组合不正确时,代码抛出KeyError异常。我了解到 Try-Else 可以打破最内层的循环,在这种情况下应该是 while 循环。在我的设计中,我希望函数在发生异常时输出以下消息(意味着无效凭据):
Invalid credentials. Please try again.
Enter your username:
如果登录成功,代码应该清除屏幕并return获取令牌。问题是,这些代码在不在 Try 而不是在 While 时运行良好。现在它在登录成功时输出:
Enter your username:
显然即使没有异常发生,程序也不会执行Else 分支。我是Python的新手,请帮我找出这个错误的原因。
编辑:感谢评论中的建议。我设置了几个断点,但断点显示即使我在try块的末尾插入一个break,程序也会先执行它然后直接返回到"while True"语句。好像break没有成功退出循环。
为什么不直接添加一个在成功尝试结束时更改的布尔值?
# Function for logging in and get a valid token
def getToken():
gotToken = False
while not gotToken: # 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
gotToken = True
except: # If credential is invalid and no token returned
os.system('cls')
print 'Invalid credentials. Please try again. \n'
os.system('cls')
return varToken # Return the retrieved token at the end of this function
我正在编写一个 Python 函数,使用用户提交的凭据向 URL 发送 GET 请求,并获得一个 returned 令牌供以后使用。
# 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
当username/password组合不正确时,代码抛出KeyError异常。我了解到 Try-Else 可以打破最内层的循环,在这种情况下应该是 while 循环。在我的设计中,我希望函数在发生异常时输出以下消息(意味着无效凭据):
Invalid credentials. Please try again.
Enter your username:
如果登录成功,代码应该清除屏幕并return获取令牌。问题是,这些代码在不在 Try 而不是在 While 时运行良好。现在它在登录成功时输出:
Enter your username:
显然即使没有异常发生,程序也不会执行Else 分支。我是Python的新手,请帮我找出这个错误的原因。
编辑:感谢评论中的建议。我设置了几个断点,但断点显示即使我在try块的末尾插入一个break,程序也会先执行它然后直接返回到"while True"语句。好像break没有成功退出循环。
为什么不直接添加一个在成功尝试结束时更改的布尔值?
# Function for logging in and get a valid token
def getToken():
gotToken = False
while not gotToken: # 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
gotToken = True
except: # If credential is invalid and no token returned
os.system('cls')
print 'Invalid credentials. Please try again. \n'
os.system('cls')
return varToken # Return the retrieved token at the end of this function