Python Pycharm: 加载大 JSON 文件时内存不足

Python Pycharm: Out of memory when loading large JSON files

执行以下代码以加载几个大的 (~200MB) JSON 文件:

def work():
    jsons = get_data()
    # do something with the jsons

def get_data():
    json_files = []
    for json_path in file_paths_list:
        json_files.append(load_json(json_path))
    return json_files

def load_json(json_path):
    import json
    with open(json_path) as f:
        return json.load(f)

这是 Pycharm 的自定义 VM 选项的外观(最多 30GB 堆大小,RAM 为 32GB):

# custom PyCharm VM options

-Xms25000m
-Xmx30000m
...
...
...

已应用“使 Caches/Restart 无效”的热门建议。

加载 2 个文件(总计约 400MB)后,在第 3 个文件中抛出异常“MemoryError”。

我无法理解为什么如果我有高达 30GB 的堆大小,在只有 400MB 后就会抛出内存错误?

PyCharm 是 Python IDE,而不是 Python 解释器。它使用的内存用于编辑阶段。

由于 python 对象的开销,

400MB 的文件可能会扩展到几千兆字节的数据(可能不是 30,而是 3 或 4)。示例:

>>> s = "hello"
>>> import sys
>>> sys.getsizeof(s)
54

基本上ram中对象的大小远大于字符串的大小

因此,如果您的 python 解释器是 32 位解释器,则您有 2GB 或 3GB 的限制,这可以解释这一点。 PyCharm 使用 64 位内核,但无法帮助解释器部分。

升级到 64 位解释器,这样可以充分利用您的 RAM。

您可以用这个(来自 Pycharm)检查版本信息和 32/64 位信息:

>>> import sys
>>> sys.version

例如我得到:

('3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit '
 '(AMD64)]')

如果显示“32位”,我的猜测是正确的。所以卸载 32 位版本 & 只需安装相同版本的 python,但在 64 位中,select 它作为 pycharm.

中的当前解释器

您可能需要在新安装中安装额外的模块,因此最好 dump the requirement textfile 在卸载之前能够在新的 64 位版本上执行全局 pip install