【发布时间】:2020-06-24 05:46:27
【问题描述】:
我有一个功能,它是我正在处理的另一个程序的 CLI 菜单。每次用户输入输入时,input() 函数都会在 try 块内运行。
如果所有 try 块都成功而没有捕获任何异常,则没有问题并且函数按预期运行;函数运行完,return 1被调用,函数结束。
但是,当引发异常时,会通知用户原因,然后递归调用当前函数。当这种情况发生,然后用户运行该函数时,return 1 会再次被调用,但这一次函数会立即返回到之前引发异常的函数中的第一个 try 块。
有问题的函数:
def menu_userSetup():
selection = 0; selected_key = 0
if userSettings is None:
userSettings = defaultSettings
refresh_UI('\_ Test Setup _/', py3_version, bash_version, True)
COLS = get_terminal_size().columns
print('\n', 'Current Settings:'.center(COLS))
z = 0
for setting in userSettings:
print('{}. {}: {}'.center(COLS - (COLS // 50)).format(z, setting, userSettings[setting]), end='\r')
z += 1
print('\n', 'Which setting would you like to set?'.center(COLS), end='')
try: selection = int(input('{}'.format(' ' * (COLS // 2))))
except KeyboardInterrupt: EXIT('Detected KeyboardInterrupt..')
except:
print('\n', 'Oops. That input is invalid!'.center(COLS))
t.sleep(1.5)
menu_userSetup()
# the tuple function is used to return the key string according to its unordered index
try: selected_key = tuple(userSettings.items())[selection][0]
except KeyboardInterrupt: EXIT('Detected KeyboardInterrupt..')
except:
print('\n', 'That is not an available option!'.center(COLS))
t.sleep(1.5)
menu_userSetup()
COLS = get_terminal_size().columns
refresh_UI('\_ Test Setup _/', py3_version, bash_version, True)
print('\n', 'Ok, {} selected!'.center(COLS - (COLS // 50)).format(selected_key))
print('Type in your new setting:'.center(COLS))
new_set = input('{}'.format(' ' * (COLS // 2)))
if new_set.find('true') and new_set.find('t') != -1:
new_set = True
elif new_set.find('false') and new_set.find('f') != -1:
new_set = False
if new_set is not None or '':
userSettings[selected_key] = new_set
print('\n', '{} has been set to {}!'.center(COLS - (COLS // 50)).format(selected_key, new_set))
t.sleep(1.5)
else:
print('\n', 'Oops. That input is invalid!'.center(COLS))
t.sleep(1.5)
menu_userSetup()
refresh_UI('\_ Test Setup _/', py3_version, bash_version, True)
COLS = get_terminal_size().columns
print('\n', 'Current Settings:'.center(COLS))
z = 0
for setting in userSettings:
print('{}. {}: {}'.center(COLS - (COLS // 50)).format(z, setting, userSettings[setting]), end='\r')
z += 1
r = input("Press enter to return to the main menu or 'r' to make another change!\n")
if r == 'r':
menu_userSetup()
print('returning...'); t.sleep(2)
return 1
可能根本不可能从except 块递归调用函数吗?
如果不是,我怎样才能达到捕获导致递归函数调用的错误的相同效果?
注意:此解决方案不需要与 python 2.x 兼容,但欢迎提供任何额外信息作为奖励!
【问题讨论】:
标签: python-3.x recursion try-catch