我有一个从xml文档中提取文本的脚本,问题是有一个空的xml文件,因此我按以下方式进行管理:

documents_dir = ['../file_1.xml', .....,'../file_N.xml']

try:
    for f in p.imap_unordered(extract_txt, documents_dir):
        print('completed file:', f)
except ShellError:
    pass


事实是,代替继续下一个文件,for循环的流程停止了。我如何才能继续?,请注意,我尝试使用pass。但是,它不起作用。

更新资料

另外,我尝试:

try:
    p.imap_unordered(extract_txt, documents_dir)
except ShellError:
    pass


但是,它没有用。

最佳答案

您需要存储迭代器,以便可以继续迭代:

documents_dir = ['../file_1.xml', .....,'../file_N.xml']

results = p.imap_unordered(extract_txt, documents_dir)
while True:
    try:
        for f in results:
            print('completed file:', f)
        break
    except ShellError:
        continue


每次您按下ShellError时,它将继续无限循环,以尝试使用下一个值在同一迭代器上重新启动for循环。循环自然结束后,它就会无限循环。如果引发了其他一些无法识别的异常,则在异常冒泡时退出循环。

关于python - 管理此python异常时出现问题:无法继续下一个迭代/元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43773516/

10-11 22:49
查看更多