写入文件不会自动刷新内容并导致 Python 内存不足

发布于 2024-08-23 02:35:09 字数 532 浏览 4 评论 0原文

我制作了简单的 python 程序来生成大文本文件:

import sys
import random

f = open('data.txt', 'w')
for i in range(100000000):
        f.write(str(i) + "\t" + str(random.randint(0,1000)) + "\n")
f.close()

当我使用 CPython 启动它时,它会占用所有可用的操作系统内存,并且不会向文件写入任何内容。

当我在 Jython 上启动它时,我收到 OutOfMemoryException

据我了解,它将所有内容存储在内存缓冲区中,并且在 close() 调用之前从未进行过刷新。

我的问题是:如何限制文件缓冲区并触发自动刷新? 我不想手动调用flush(),我认为从性能角度来看这是错误的。我希望当文件缓冲区过载时自动调用 flush()

谢谢!

I made simple python program to generate big text file:

import sys
import random

f = open('data.txt', 'w')
for i in range(100000000):
        f.write(str(i) + "\t" + str(random.randint(0,1000)) + "\n")
f.close()

When I launch it using CPython it eat all available OS memory and write nothing to the file.

When I launch it on Jython I get OutOfMemoryException.

As far as I understand it stores everything in memory buffer and never did flush before close() call.

My question is: how to limit the file buffer and trigger autoflush?
I don't want to callflush() manually, I think it's wrong from performance point of view. I want flush() to be called automatically when file buffer is overloaded or so.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦纸 2024-08-30 02:35:09

缓冲不是问题。问题是使用一个巨大的参数调用 range() 函数,该函数将尝试分配一个包含大量元素的数组。如果你只是说,你会得到同样的错误

r = range(100000000)

Buffering is not the problem. The problem is calling the range() function with a giant argument, which will attempt to allocate an array with lots of elements. You will get the same error if you just say

r = range(100000000)
半﹌身腐败 2024-08-30 02:35:09

您是否尝试过将缓冲区大小传递给open代码>函数?

f = open('data.txt', 'w', 5000)

Have you tried passing in a buffer size to the open function?

f = open('data.txt', 'w', 5000)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文