python - 当异常在实际的 'continue' 语句中时,你如何 'for'?

标签 python python-3.x loops exception

这是一个简单的例子。
它是一个递归函数(即它调用自身)尝试列出目录(父级)的内容(children)。

  1. 如果 child 是一个文件,它只打印文件名。

  2. 如果 child 是一个目录,它会打印目录的名称并尝试列出它的内容,等等在。

  3. 如果 child 是一个目录,但是用户没有权限读取它的内容,一个异常(OSError) 被抛出。所以我们用 try:except OSError: continue 包裹它以防止循环终止。它说:“当特权不足时,不要停止;继续前进;摆脱它,继续前进到下一个。”


#!/usr/bin/env python3

import os

def list_children(parent):
    <b>for child in os.listdir(parent):</b>
        try:
            if os.isdir(child):
                print(child)
                list_children(child)
            elif os.isfile(child):
                print(child)
        except OSError:
            continue

list_children('/home')

但是,continue只在循环体内部起作用(如forwhile),当出现异常时你能做什么由实际的 for(或 while)循环表达式(即紧接在循环主体之前的行)抛出,如 os.listdir() 上面例子中的函数?

最佳答案

如果无法生成您正在循环的内容,则无需继续(即,如果没有循环,则无法进入循环的下一次迭代)。只需将整个内容包装在 try 中,或者可能只是将第一个顶级 listdir 包装起来,以便控制缩进:

def list_children(parent: str) -> None:
    try:
        top_level = os.listdir(parent)
    except OSError:
        top_level = []

    for child in top_level:
        try:
            if os.isdir(child):
                print(child)
                list_children(child)
            elif os.isfile(child):
                print(child)
        except OSError:
            continue

关于python - 当异常在实际的 'continue' 语句中时,你如何 'for'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58807172/

相关文章:

Python-将用户输入转换为列表

sql - 循环遍历列 SQL

c# - 在 C# 循环中调用 SQL 存储过程时处理事务

python - 在python中将字符串视为文件

python - 优雅地分配未知长度的变量

python - 如何在 Python 中运行 BigQuery 查询

python-3.x - 等和组合(类似于子集和和换币算法)

pyqt - Python 3 和 PyQt 4 建议

python - 如何在不同乘法表之间插入换行符?

c++ - 确定平方根是否为整数