Python 除非调用 yield,否则生成器调用计数器不会增加

Python Generator call counter not increasing unless yield is called

我正在使用 scandir 库查看计算机上的所有文件。一旦我检查了 100 条记录,我想停止循环。如果从未调用 yield 语句,我的变量 c 永远不会增加,循环也不会停止。我输入了一些永远找不到的假文件名 thisfilewontbefound,因此永远不会到达 yield。为什么 c 不递增?

from scandir import scandir, walk
import sys

def subdirs(path):
    for path, folders, files in walk(path):
        for files in scandir(path):
            if 'thisfilewontbefound' in files.path:
                yield files.path

c = 0
for i in subdirs('C:\'):
    if c > 100:
        print "test over"
        sys.exit()
    c += 1
    print i

您的 for 循环正在等待生成器。如果执行 yield,生成器将 产生一个值。但是 yield 永远不会执行,因为没有这样的文件,所以 for 循环会等待很长时间,直到 all files on your C:驱动器已被扫描,生成器结束时没有产生任何东西。

要么将计数器放在生成器中,要么不过滤生成器中的文件并让它更频繁地产生。