关于使用urllib2模块的python中的内存消耗 [英] Regarding memory consumption in python with urllib2 module

查看:148
本文介绍了关于使用urllib2模块的python中的内存消耗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PS:我有一个与请求HTTP库类似的问题这里

PS: I have a similar question with Requests HTTP library here.

我在Windows 7操作系统上使用python v2.7。我正在使用 urllib2 模块。我有两个代码片段。一个文件名为 myServer.py 服务器类有两个名为 getName的方法( self,code) getValue(self)
名为 testServer.py 的另一个脚本只是调用 server 类中的方法来检索值并打印它们。 服务器类基本上从本地网络中的服务器检索值。所以,遗憾的是我无法为您提供测试代码的权限。

I am using python v2.7 on windows 7 OS. I am using urllib2 module. I have two code snippets. One file is named as myServer.py The server class has 2 methods named as getName(self,code) and getValue(self). The other script named as testServer.py simply calls the methods from the server class to retrieve the values and prints them. The server class basically retrieves the values from a Server in my local network. So, unfortunately I can't provide you the access for testing the code.

问题:当我执行<$>时c $ c> testServer.py 文件,我在任务管理器中观察到内存消耗不断增加。它为什么会增加以及如何避免它?如果我注释掉以下行

Problem: When I execute my testServer.py file, I observed in the task manager that the memory consumption keeps increasing. Why is it increasing and how to avoid it? If I comment out the following line

print serverObj.getName(1234)

testServer.py 中,内存消耗量增加

in testServer.py then there is no increase in memory consumption.

我确定问题出在 getName(自我,代码) >服务器类。但不幸的是,我无法弄清问题是什么。

I am sure that the problem is with the getName(self,code) of the server class. But unfortunately, I couldn't figure out what the problem is.

代码:请查看下面的代码段:

Code: Please find the code snippets below:

#This is the myServer.py file

import urllib2
import json
import random

class server():
    def __init__(self):
        url1 = 'https://10.0.0.1/'
        username = 'user'
        password = 'passw0rd'
        passwrdmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
        passwrdmgr.add_password(None, url1, username, password)
        authhandler = urllib2.HTTPBasicAuthHandler(passwrdmgr)
        opener = urllib2.build_opener(authhandler)
        urllib2.install_opener(opener)
    def getName(self, code):
        code = str(code)
        url = 'https://10.0.0.1/' + code
        response = urllib2.urlopen(url)
        data = response.read()
        name = str(data).strip()
        return name
    def getValue(self):
        value = random.randrange(0,11)
        return value

以下是 testServer.py 代码段

from myServer import server
import time

serverObj = server()
while True:
    time.sleep(1)
    print serverObj.getName(1234)
    print serverObj.getValue()

感谢您的时间!

推荐答案

这个问题与我的其他问题非常相似。所以我认为答案也很相似。答案可以在这里找到 https://stackoverflow.com/a/23172330/2382792

This is question is quite similar to my other question. So I think the answer is also quite similar. The answer can be found here https://stackoverflow.com/a/23172330/2382792

这篇关于关于使用urllib2模块的python中的内存消耗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆