【问题标题】:Cache file handle to netCDF files in python在python中缓存文件句柄到netCDF文件
【发布时间】:2017-02-08 06:13:46
【问题描述】:

有没有办法缓存 python 文件句柄?我有一个函数,它将 netCDF 文件路径作为输入,打开它,从 netCDF 文件中提取一些数据并关闭它。它被调用很多次,每次打开文件的开销都很高。

如何通过缓存文件句柄来使其更快?也许有一个python库可以做到这一点

【问题讨论】:

  • 你不能保持文件打开,然后发送一个文件对象作为函数参数吗?

标签: python netcdf


【解决方案1】:

是的,您可以使用以下 python 库:

让我们按照示例进行操作。你有两个文件:

# save.py - it puts deserialized file handler object to memcached
import dill
import memcache            


mc = memcache.Client(['127.0.0.1:11211'], debug=0)
file_handler = open('data.txt', 'r')
mc.set("file_handler", dill.dumps(file_handler))
print 'saved!'   

# read_from_file.py - it gets deserialized file handler object from memcached, 
#                     then serializes it and read lines from it
import dill
import memcache


mc = memcache.Client(['127.0.0.1:11211'], debug=0)
file_handler = dill.loads(mc.get("file_handler"))
print file_handler.readlines() 

现在如果你运行:

python save.py
python read_from_file.py

你可以得到你想要的。

为什么有效?

因为你没有关闭文件(file_handler.close()),所以对象仍然存在于内存中(没有被垃圾回收,因为weakref),你可以使用它。即使在不同的过程中。

解决方案

import dill
import memcache


mc = memcache.Client(['127.0.0.1:11211'], debug=0)
serialized = mc.get("file_handler")
if serialized:
    file_handler = dill.loads(serialized)
else:
    file_handler = open('data.txt', 'r')
    mc.set("file_handler", dill.dumps(file_handler))
print file_handler.readlines() 

【讨论】:

    【解决方案2】:

    这个怎么样?

    filehandle = None
    def get_filehandle(filename):
        if filehandle is None or filehandle.closed():
            filehandle = open(filename, "r")
        return filehandle
    

    您可能希望将其封装到一个类中,以防止其他代码与filehandle 变量混淆。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 2013-10-19
      相关资源
      最近更新 更多