代码之家  ›  专栏  ›  技术社区  ›  Matt Joiner

在一根绳子内解开一根绳子

  •  1
  • Matt Joiner  · 技术社区  · 15 年前

    我正在和 urllib2 ,并尝试从 Response 对象。

    现在我正在打印 str(response.info()) 不管打印的是什么,它本身就是一个python字符串(至少在我看来是这样)。

    (Pdb) p str(response.info())
    'Date: Tue, 23 Feb 2010 03:12:26 GMT\r\nServer: Apache\r\nVary: Accept-Encoding,User-Agent\r\nContent-Encoding: gzip\r\nContent-Length: 9045\r\nConnection: close\r\nContent-Type: text/html; charset=ISO-8859-1\r\n'
    

    我需要将该字符串转换为“实际”字符串,例如通过计算或类似的方法。我找到的最佳理论解决方案是:

    s = str(response.info())
    print s.decode("string_escape")
    

    但这不起作用。更令人困惑的是如何处理字符串中的引号,调用 eval(s) str(s) 也不要工作。

    有没有更好的方法在不引用的情况下提取响应中的原始头,或者解码字符串的方法 s 如上?

    3 回复  |  直到 15 年前
        1
  •  2
  •   sth    15 年前

    str(info()) 给出一个普通字符串:

    >>> import urllib2
    >>> f = urllib2.urlopen('http://tejp.de')
    >>> print str(f.info())
    Connection: close
    Vary: Accept-Encoding
    Content-Type: text/html
    Accept-Ranges: bytes
    ETag: "-807357257"
    Last-Modified: Wed, 01 Jul 2009 10:05:34 GMT
    Content-Length: 285
    Date: Tue, 23 Feb 2010 03:24:10 GMT
    Server: lighttpd/1.4.19
    

    它只是调试器的 p 以转义形式打印字符串的命令。

        2
  •  1
  •   Marcelo Cantos    15 年前

    在PDB中,这应该有效:

    print str(response.info())
    

    但不确定这是否回答了你的问题。

        3
  •  0
  •   Ignacio Vazquez-Abrams    15 年前

    response.info() 返回A httplib.HTTPMessage ,其行为类似于映射:

    info = response.info()
    for k, v in info.items():
      print '%s: %s' % (k, v)
    

    总之,你做错了。