简体   繁体   English

在 python for 循环中,如何处理可以抛出异常的迭代器?

[英]In a python for loop, how do you handle an iterator that can throw exceptions?

I am using an iterator, namely the standard library CSV reader, that can throw exceptions.我正在使用一个迭代器,即标准库 CSV 阅读器,它可以引发异常。 Here's a minimal working code sample:这是一个最小的工作代码示例:

import csv
import sys

csv.field_size_limit(10_000_000)

reader = csv.reader(sys.stdin)
for row in reader:
    pass

And here's what happens when I run it:这是我运行它时发生的情况:

[joel@vm all_recent]$ python dummy_csv.py < mycsv.csv
Traceback (most recent call last):
  File "/path/dummy_csv.py", line 7, in <module>
    for row in reader:
  File "/usr/lib64/python3.10/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 264: invalid start byte

What I'd like to be able to do is to log the exception, and continue iterating.我想做的是记录异常,并继续迭代。 What's the pythonic way to do this?这样做的pythonic方法是什么?

You can extract elements from the iterator manually instead of the for loop doing it for you.您可以手动从迭代器中提取元素,而不是for循环为您执行此操作。

reader = csv.reader(sys.stdin)
it = iter(reader)

while True:
    try:
        next(it)
    except StopIteration:
        break
    except Exception:
        # do something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM