1

I am working with urllib2, and trying to extract the headers in a printable form from a Response object.

Presently I am printing str(response.info()), however what is printed, is itself a Python string (at least to my understanding).

(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'

I need to turn that string into an "actual" string, such as by evaluation or something similar. The best theoretical solution I've found is to use:

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

But this does not work. Further adding to the confusion is how to handle the quotes within the string, calling eval(s) and str(s) do not work either.

Is there some better way to extract the raw headers in the response without quoting, or a method to decode the string s as above?

Matt Joiner
  • 112,946
  • 110
  • 377
  • 526

3 Answers3

2

str(info()) does give a normal string:

>>> 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

It's only the debugger's p command which prints the string in escaped form.

sth
  • 222,467
  • 53
  • 283
  • 367
  • Good observation; however, this doesn't answer the question *how to unescape a string*. – Humphrey Bogart Jan 16 '11 at 23:34
  • 1
    @Beau: This was meant to help the OP to do what he really wanted to do, as stated in the first line of his post. Answering the question from the title literally wouldn't have helped him at all. If you are searching for an answer to that, [this question](http://stackoverflow.com/questions/1885181/how-do-i-un-escape-a-backslash-escaped-string-in-python) might help. – sth Jan 17 '11 at 15:00
0

response.info() returns a httplib.HTTPMessage, which behaves like a mapping:

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

So in short, you're doing it wrong.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

From pdb, this should work:

print str(response.info())

Not sure if that answers your question, though.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365