2016-07-04 120 views
3

python中有一个名为tzwhere的模块。当我在TZ变量加载它如下所示: -Python:如何在内存中保存一个变量,使其可以从其他Python脚本中调用?

from tzwhere import tzwhere 
tz = tzwhere.tzwhere(shapely=True) 

线之上大约需要45秒加载,其范围是,直到该特定的Python会话停止。所以在这一行之后,我可以根据需要获得tz.tzNameAt(latitude, longitude)的许多输出,但问题是这些输出只能在该python shell中快速计算。

我想让tz变量可以像API一样共享,例如,如果tz变量是从任何python会话中调用的,或者甚至是从任何使用exec命令的java程序中调用都不需要45秒钟,应该给我NameError: name 'tz' is not defined

请帮忙。非常感谢你!!

+0

@mevius先生,非常感谢你编辑这篇文章。我是一个新手,我不知道如何专业地写... –

+0

你可以编写一个加载tz结构的服务器程序,监听请求,处理它们并发送回复。脚本将是该服务器的客户端。然而这并不重要。 – VPfB

+0

@PrabhatNagpal对不起,但你必须等那么久。腌制对象没有意义,存储在'tzwhere'对象中的数据是巨大的。这就是为什么它需要很长时间才能加载。我会研究@VPFB的答案。 – CodenameLambda

回答

0

您可以使用pickle模块,它可以将类实例存储在文件中。

尝试这样:

from tzwhere import tzwhere 
tz = tzwhere.tzwhere(shapely=True) 

import pickle 

# Dump the variable tz into file save.p 
pickle.dump(tz, open("save.p", "wb")) 

从另一个脚本加载tz只是做:

import pickle 

tz = pickle.load(open("save.p", "rb")) 

NOTE: Python 2 ONLY, will use faster version automatically if on Python3

If you are still unhappy with the speed when loading tz from another script, there is an accelerated version of pickle called cPickle

Just do:

import cPickle as pickle 

欲了解更多信息转到此链接:https://wiki.python.org/moin/UsingPickle

+0

那一刻当你发布你的答案和其他人提出了完全相同的解决方案......我应该学会写得更快一点^^ – CodenameLambda

+0

是啊,我只是在想...... –

+0

这发生在我身上,退出了很多一些原因。 – CodenameLambda

0

您不能共享即使在python关闭后,内存中的任何python对象。但是,您可以使用pickle保存对象的状态(如果库确实支持它,如果不支持,则此解决方案不起作用)。 pickle是一个附带python的库,可以将大多数对象的状态保存到文件中。

下面是泡菜的例子:

要保存状态:

import pickle 
obj = [1, 2, 3, 4] 
f = open("/path/to/the/file/where/the/data/should/be/stored.pickle", 'wb') # you do not have to use the suffix '.pickle' however. 
pickle.dump(obj, f) 
f.close() 

找回它:

import pickle 
f = open("/path/to/the/file/where/the/data/should/be/stored.pickle", 'rb') 
obj = pickle.load(f) 
f.close() 

或者为你的榜样,一旦运行这个事情:

from tzwhere import tzwhere 
import pickle 
f = open("/path/to/the/file", 'wb') 
pickle.dump(tzwhere.tzwhere(shapely=True)) 
f.close() 

并使用硫s到检索:

import pickle 
f = open("/path/to/the/file", 'rb') 
tz = pickle.load(f) 
f.close() 

或者作为一个内胆,所以它不会占用太大的空间:

import pickle;f=open("/path/to/the/file",'rb');tz=pickle.load(f);f.close() 

我希望帮助,

CodenameLambda

PS:如果你想知道咸菜是如何工作的,可以看看the documentation

+0

先生我按照你的步骤,但它会产生此错误: - 文件“D:\ Python \ lib \ site-packages \ shapely \ prepared.py”,第88行,在__reduce__
引发PicklingError(“Prepared geometries can not be腌制。“)
_pickle.PicklingError:准备的几何不能被腌制。 –

+0

@PrabhatNagpal这意味着,图书馆不支持酸洗。 – CodenameLambda