小编Ses*_*shu的帖子

使用BeautifulSoup的Python高内存使用率

我试图在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)

这可能是某种错误吗?

python memory beautifulsoup

9
推荐指数
3
解决办法
6073
查看次数

在C++中关闭析构函数中的连接

我在想一个管理我的TCP连接的C++类(在Linux上).在销毁时,应该关闭连接,类似于:

TCPConnection::~TCPConnection()
{
  close(_socket);
}
Run Code Online (Sandbox Code Playgroud)

问题是,当把这个类的对象放到例如一个向量中时,连接也会像这样关闭,即使我仍然想要使用连接.我怎么解决这个问题?总的来说这是个坏主意吗?

c++ networking

2
推荐指数
1
解决办法
555
查看次数

标签 统计

beautifulsoup ×1

c++ ×1

memory ×1

networking ×1

python ×1