在调试模式下单步执行时没有错误,但在其他情况下出现 AttributeError

No error when stepping through in debug mode but AttributeError otherwise

示例代码

from pathlib import Path

for f in Path(<dir>).iterdir():
    print(f._str)

我正在使用它来传递给一个函数,但即使 运行 正常或在没有断点的情况下进行调试时,它也不起作用。使用断点并单步执行它可以很好地打印出所有内容(_str 是总路径!

我真的不确定您要做什么或要打印什么,但是,是的,这会引发 AttributeError。可能是因为 ._str 不是 Path class 的属性。

from pathlib import Path

for f in Path('/tmp').iterdir():
    print(f._str)

AttributeError: _str

这会打印完整路径。

for f in Path('/tmp').iterdir():
    print(f)

/tmp/com.apple.launchd.0CERUFd5eE
/tmp/com.apple.launchd.JLaC2VPWPS
/tmp/com.apple.launchd.jyIh6h3f8I

如果您只需要文件和目录的名称,请执行 print(f.name)