【问题标题】:Try Except While with user input尝试使用用户输入时除外
【发布时间】:2020-03-14 17:10:01
【问题描述】:

以下是我的问题的示例。我有一个试图访问 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

【问题讨论】:

    标签: python exception while-loop try-catch


    【解决方案1】:
    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
    

    【讨论】:

    • 我还没有尝试过,因为第一条评论正是我需要的时候,但是如果将来有人遇到这种情况,我希望他们会尝试一下。
    • @Sigmas 在您使用的答案中,如果用户按下“y”以外的任何内容,它将被中止,而在我的代码中它将等到用户按下“y”,这就是我从问题中明白了。但如果你真的更喜欢他的方法,没问题。
    • 我试过你的,效果也一样。我之前没有尝试过,因为@Yotamz 脚本也可以。我稍微修改了一下,但两者都很棒。从来没有想过怀疑你!
    【解决方案2】:

    我不会真正用 python 编程,但在大多数语言中,异常处理块不被视为 try 块的一部分,否则您将无法从中重新抛出异常。

    您需要更改代码,以便整个事情在一个循环中。

    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 不是很好。

    【讨论】:

    • 没问题,我也在学习,第一条评论正是我需要的,但感谢您的意见。
    【解决方案3】:
    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
    
    
    

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

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

    如果文件被锁定并且用户回答 !"y" 则引发新异常,退出循环进入最后一个 "except" 块。

    【讨论】:

    • 我不想让用户取消,我希望脚本继续运行,并等到文件关闭。
    猜你喜欢
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    相关资源
    最近更新 更多