如何解决 Python 3 最大字符串大小?

How to work around Python 3 maximum string size?

在 64 位 Python 构建中 sys.maxsize 为 9223372036854775807 如果我分配更多的字符串,解释器仍然会抛出 MemoryErrorINT_MAX - 512 MiB 个字符:

$ python3
#Python 3.6.6 (default, Jul 19 2018, 14:25:17) 
[GCC 8.1.1 20180712 (Red Hat 8.1.1-5)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "*" * 2684354560
>>> s = "*" * 2684354561
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError

bytes的限制相同,其元素类型肯定是8位。) 有足够的可用内存和交换空间,所以我确定系统不是 达到任何身体极限。

这里发生了什么,我怎样才能增加这个上限?

解决:原来是 数据段大小限制

$ ulimit -d
4194304

出于某种原因,这些 4294967296 B 转换为每个分配 2684354560 B 上限 Python.

将此值设置为 无限制 会移除上限。这可以在外部完成 由父进程(例如 shell 中的 ulimit -d unlimited)或 在 Python 本身使用 wrapper library for resource.h:

resource.setrlimit (resource.RLIMIT_DATA,
                    (resource.RLIM_INFINITY
                    ,resource.RLIM_INFINITY))

Apparently 更多 最近的内核(4.7 及更高版本)RLIMIT_DATA 也影响匿名映射 解释了观察到的大型分配失败和我的存在 惊讶。