在我的一段代码中,我的脚本生成一个字符串,将其复制到scolled文本小部件中。如果字符串的大小不是很重,则此过程不会出现任何问题,但是当字符串很重时,脚本无法将其粘贴到滚动文本小部件中。发生这种情况时,脚本崩溃,终端中出现错误消息:unable to alloc 27 bytes
(这不是异常事件)
在崩溃之前,我通过sys.getsizeof
函数获得了字符串的字节大小,它是230031360字节(230MB)
在这些情况下,用户可以通过选择在文本文件中写入输出消息来解决问题,但是如果用户尝试在scolled text小部件中写入一个重字符串呢?在这个特定的例子中,我非常希望显示一个消息框,建议用户将输出写入文本文件,但是我如何理解脚本是否可以在滚动文本小部件中写入字符串?Python中字符串的字节限制是多少
更新:
我写了一个例子来告诉你问题发生在哪里。主窗口将在两分钟后崩溃,终端中出现错误消息:unable to alloc 28 bytes
:
from tkinter import *
from tkinter import ttk, scrolledtext
import ipaddress
def GiveMeHosts():
ls = []
for host in ipaddress.ip_network("10.0.0.0/8").hosts():
ls.append(str(host))
return ls
parent = Tk()
parent.geometry("400x350")
parent.title("The window will crash..")
MyWidget=scrolledtext.ScrolledText(parent, wrap=WORD, width=36, height=14, font=("Segoe UI", 9), state="normal")
MyWidget.pack()
parent.update()
# the string "hosts" is too long, and "MyWidget" can't manage it!
hosts = "\n".join(GiveMeHosts())
MyWidget.insert("1.0", hosts) # it makes the script to crash
parent.mainloop()
我运行了您的代码,虽然花了相当长的时间,但最终还是将所有IP地址都放在了滚动文本框中。没有错误,也没有崩溃。顺便问一下:
unable to alloc 28 bytes
,这正是最后两个ip地址的大小?!?(10.255.255.253 10.255.255.254).我更进一步。实际上是两步。尝试运行相同的代码,但将返回值
ls *= 5
相乘。结果仍然有效,没有崩溃。同时ls
的大小为1790312344 bytes (1.67 GB)
在
ls *=10
但是ls
现在的大小为2545286976 bytes (2.37 GB)
,它最终通过以下回溯崩溃:总的来说,似乎确实存在一个限制,但这个限制很可能取决于系统。至少,这是我从中得出的结论
相关问题 更多 >
编程相关推荐