python - Python 中的内存交换时间

标签 python lazy-loading lazy-evaluation

这里的挑战是评估多个大文件。

什么编码会指示 Python 将有限数量的文件“加载”到内存中、处理它们、垃圾收集然后加载下一组文件?

def main(directory):
    """
    Create AudioAnalysis Objects from directory and call object_analysis().
"""   
    ff = os.listdir(directory)
    for f in ff:
        # can we limit the number we load at one time?
        audiofile = audio.LocalAudioFile(os.path.join(directory,f)) # hungry!

尝试将 audiofile = 0 添加到循环中,但内存分配是相同的。

据我所知,惰性求值“是一种求值策略,它延迟表达式的求值,直到需要它的值”,但在这种情况下,我需要延迟求值,直到可用内存

我期待着 decoratordescriptor 和/或使用 Pythons property() 函数可能会涉及到,或者可能是缓冲或排队输入。

最佳答案

这是一个解决方案:让 Python 生成一个进程,在一个文件上运行该函数,然后退出。父进程将从每个文件中收集结果。

这绝不是优雅的,但如果 LocalAudioFile 拒绝从内存中移除,它允许在获得结果方面有一定的灵 active 。

此代码运行在当前目录中的每个 Python 文件上运行一个函数,向父进程返回一条消息,父进程将其打印出来。

来源

import glob, multiprocessing, os

def proc(path):
    """
    Create AudioAnalysis Objects from directory and call object_analysis().
"""   
    # audiofile = audio.LocalAudioFile(path) # hungry!
    return 'woot: {}'.format(path)

if __name__=='__main__':  # required for Windows
    pool = multiprocessing.Pool()   # one Process per CPU
    for output in pool.map(proc, [
            os.path.abspath(name) for name in glob.glob('q*.py')
            ]):
        print 'output:',output

输出

output: woot: /home/johnm/src/johntellsall/karma/qpopen.py
output: woot: /home/johnm/src/johntellsall/karma/quotes.py

关于python - Python 中的内存交换时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25370960/

相关文章:

Python 和 HyperOpt : How to make multi-process grid searching?

java - 生成器是否不如 "real"协程?

python - 使用列值(字符串数据类型)过滤 pandas group

c# - 实现惰性拖放

javascript - 如何在 JavaScript 中交换二维数组中的两个元素? (对我从 Chrome 中的 console.log 看到的内容感到困惑)

python - 如何使用 Python 从文本文件中绘制数据

asp.net-mvc - DTO 模式 + 延迟加载 + Entity Framework + ASP.Net MVC + 自动映射器

r - 我可以在 R 中添加到现有的惰性数据库而不必重新创建所有内容吗?

spring - 为什么在使用 Spring OpenEntityManagerInViewFilter 时会出现 JPA LazyInitializationException?

haskell $!运算符和无限列表