这里的挑战是评估多个大文件。
什么编码会指示 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
添加到循环中,但内存分配是相同的。
据我所知,惰性求值
“是一种求值策略,它延迟表达式的求值,直到需要它的值”,但在这种情况下,我需要延迟求值,直到可用内存。
我期待着 decorator
、descriptor
和/或使用 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/