如何在IOError时继续python脚本循环?

1 投票
5 回答
17848 浏览
提问于 2025-04-17 10:28

我有一个程序,它会向Twitter的API请求信息,但有时候会出现一个错误:

IOError: [Errno socket error] [Errno 54] Connection reset by peer

我想知道怎么才能让我的脚本继续运行(循环)。我知道这和以下内容有关:

try:

except IOError:

但我搞不清楚该怎么做。

5 个回答

1

你缺少的部分是 pass。这个是一个简单的 无操作 表达式,存在的原因是因为 Python 不允许有空的代码块。

更详细的解释:

你需要做的是捕捉到抛出的 IOError 异常,并且忽略它(可能还要记录一下这样的错误)使用 pass

为了做到这一点,你需要把可能出错的代码放在一个 tryexcept 的代码块里,像这样:

try:
    <code that can fail>
except IOError:
    pass

这样做的目的是专门忽略 IOError,而不去忽略其他类型的错误。如果你想忽略所有的异常,只需把 IOError 部分去掉,让这一行变成 except:

你真的应该看看 Python 的教程,特别是关于 错误处理 的那一部分。

2

这里有关于异常处理的文档...

简单来说,如果你的代码块在某些情况下可能会出现已知的错误(比如输入输出错误),你可以定义一个try-except块来处理这些错误。这样可以让你的程序继续运行,并根据不同的错误状态执行不同的代码块……比如:

try:
    <do something>
except IOError:
    <an input-output error occured, do this...>
except ValueError:
    <we got something diffrent then we expected, do something diffrent>
except LookupError:
    pass # we do not need to handle this one, so just kkeep going...
except: 
    <some diffrent error occured, do somethnig more diffrent> 

如果你想在遇到错误时什么都不做并继续执行,可以使用pass,像这样:

try:
    <do something>
except:
    pass
6

更简单的结构是这样的:

my_while_or_for_loop:
    some_code_here_maybe
    try:
        my_code_or_function_that_sometimes_fails()
    except IOError:
        pass   # or some code to clean things that went wrong or to log the failure
    some_more_code_here_maybe

你可以去查看文档

完整的结构可能会更复杂,包括 try/except/else/finally
这是文档中的一个例子

>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print "division by zero!"
...     else:
...         print "result is", result
...     finally:
...         print "executing finally clause"

撰写回答