在用户输入的情况下尝试除

时间:2019-11-19 08:34:37

标签: python exception while-loop try-catch

以下是我的问题的一个示例。我有一个试图访问Excel文件的脚本。它工作正常,但是如果文件当前处于打开状态,我将收到一个权限被拒绝的错误。我通常会关闭文件并再次运行脚本,但是我希望能够关闭程序并仅输入一个击键(例如“ y”),以指示文件已关闭并重试。现在的问题是,当我输入任何值时,它仍然会继续尝试运行,如果再次失败,它将退出脚本。有什么想法吗?

input_yes = 'y'
answer = {}
try:
    finalSheet('my file.xlsx')
except:
    while answer != str(input_yes):
         answer = input('Please confirm that (my file.xlsx) is closed and enter y: ')
         finalSheet('my file.xlsx')
         continue

3 个答案:

答案 0 :(得分:0)

我不能真正地用python编程,但是在大多数语言中,异常处理块不被认为是try块的一部分,否则您将无法从中抛出异常。 / p>

您需要更改代码,以使整个过程都在循环之内。

success = False

while not success:
    try:
        finalSheet('my file.xlsx')
        success = True
    except:
        # We actually don't care what the answer is. You could bail if the 
        # answer is no I guess
        answer = input('Please confirm that (my file.xlsx) is closed and enter y: ')

对于上面的任何错误表示歉意,我的Python不好。

答案 1 :(得分:0)

try:
    while True:
        try:
            finalSheet('my file.xlsx')
            print('Success')
            break
        except:
            if not input('Please confirm that (my file.xlsx) is closed and enter y: ') == str(input_yes):
                raise KeyboardInterrupt #or any other exception
except KeyboardInterrupt:
    print('Cancelled by user')
    return


您要将整个块放在“ try”中。 如果操作成功,循环将中断,并跳过外部的“ except”块。

如果存在异常(即文件被锁定)并且用户回答“ y”,则循环继续。

如果文件被锁定并且用户回答!“ y”,则会引发新的异常,使循环退出到最后一个“ except”块。

答案 2 :(得分:0)

input_yes = 'y'
while True:
    try:
        finalSheet('my file.xlsx')
        break #If reading the file succeeded, it will leave the outer loop
    except:
        while True:
            answer = input('Please confirm that (my file.xlsx) is closed and enter y: ')
            if answer == input_yes:
                break #If the answer is 'y', it will leave the inner loop, and try to read the file. Otherwise, it will continue to ask for readiness