我试图在python 2.7.3中使用BeautifulSoup4处理几个网页但是在每次解析之后内存使用量都会上升.
此简化代码产生相同的行为:
from bs4 import BeautifulSoup
def parse():
f = open("index.html", "r")
page = BeautifulSoup(f.read(), "lxml")
f.close()
while True:
parse()
raw_input()
Run Code Online (Sandbox Code Playgroud)
在调用parse()五次后,python进程已经使用了30 MB的内存(使用的HTML文件大约是100 kB),每次调用时它都会增加4 MB.有没有办法释放内存或某种解决方法?
更新: 这种行为让我很头疼.即使应该长时间删除BeautifulSoup变量,此代码也会轻松占用大量内存:
from bs4 import BeautifulSoup
import threading, httplib, gc
class pageThread(threading.Thread):
def run(self):
con = httplib.HTTPConnection("stackoverflow.com")
con.request("GET", "/")
res = con.getresponse()
if res.status == 200:
page = BeautifulSoup(res.read(), "lxml")
con.close()
def load():
t = list()
for i in range(5):
t.append(pageThread())
t[i].start()
for thread in t:
thread.join()
while not raw_input("load? "):
gc.collect()
load()
Run Code Online (Sandbox Code Playgroud)
这可能是某种错误吗?
我在想一个管理我的TCP连接的C++类(在Linux上).在销毁时,应该关闭连接,类似于:
TCPConnection::~TCPConnection()
{
close(_socket);
}
Run Code Online (Sandbox Code Playgroud)
问题是,当把这个类的对象放到例如一个向量中时,连接也会像这样关闭,即使我仍然想要使用连接.我怎么解决这个问题?总的来说这是个坏主意吗?