Python:如何将变量保存在内存中,以便可以从其他 Python 脚本中调用它?

标签 python

python中有一个名为tzwhere的模块。当我将它加载到 tz 变量中时,如下所示:-

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

上面的行加载大约需要 45 秒,其范围是直到特定的 python session 停止。所以在这条线之后,我可以获得tz.tzNameAt(latitude, longitude)的尽可能多的输出如我所愿,但问题是这些输出只能在那个 python shell 中快速计算。

我想让 tz 变量像 API 一样可共享,这样如果 tz 变量是从任何 python session 调用的,或者即使从任何使用 exec 命令的 java 程序调用,它也不应该需要 45 秒才能再次加载,也不应该给我NameError: name 'tz' is not defined .

请帮忙。非常感谢你!!

最佳答案

您可能会使用 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

关于Python:如何将变量保存在内存中,以便可以从其他 Python 脚本中调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38188144/

相关文章:

python - 语法无效 : import TextBlob in python 2. 6.6

python - body = 'cmd=' + urllib_parse.quote_plus(unicode(verb).encode ('utf-8' )) 返回 "name ' unicode' 未定义”

python - 如何在 for 循环中注释类型?

python - 为什么 PST(美国/洛杉矶)时间转换为 UTC 时间晚 1 小时?

python - Django SSL Redirect 片段修改,未按预期工作

python - Snakemake 在配置中声明临时文件

python - Keras Conv2D 输入形状

python - 使用python显示docx文件的内容

python - 获取 Django 中模型类的调用堆栈

python - Twisted chainDeferred, deferred.result is None