fail to grep the "Server:" string line in headers

Steve Holden sholden at holdenweb.com
Mon Nov 26 15:12:31 CET 2001


"printf" <printf at hongkong.com> wrote ...
> Help
>      I would like to grep the string after "Server:" in the headers. Any
> one can help me?
>
You need to understand a little more thoroughly just exactly what the
getreply() method returns.

>      I think I need get the string of headers, then put to search in
> "re", and grep the ...
>
In particular you need to understand that the headers are not returned asa
string. This actually makes your job much easier...

>      And is there any way to "grep" words in python?
>
Yes, but as mentioned above, this isn't what you need to do.

>
> class collectInfo:
>          def __init__(self, _host):
>                  self.host = _host
>          def getServerName(self):
>                  h = httplib.HTTP(self.host)
>                  h.putrequest('GET', '/')
>                  h.putheader('Accept', 'text/html')
>                  h.putheader('Accept', 'text/plain')
>                  h.endheaders()
>                  errcode, errmsg, headers = h.getreply()
> print headers
>
>                  p=re.compile('Server:') #wrong, why?
>                  print p.search(hearders).span()#wrong
>                           why?
>
Try this instead. By the way, your indentation was a little unusual, so I
have adjusted the code to use a four-space indent. Using 9 and/or 8 as the
original code did, you might well find that conplex code runs off the
right-hand side of the page...

import httplib

class collectInfo:

    def __init__(self, _host):
        self.host = _host

    def getServerName(self):
        h = httplib.HTTP(self.host)
        h.putrequest('GET', '/')
        h.putheader('Accept', 'text/html')
        h.putheader('Accept', 'text/plain')
        h.endheaders()
        errcode, errmsg, headers = h.getreply()
        print "Headers object is of type:", type(headers)
        # but it prints because it has an __str__() method

        # p=re.compile('Server:') #wrong, why?
        # because headers is not a string
        # print p.search(hearders).span()#wrong
        # because headers is not a string
        # and there is no "hearders" (typo)

        return headers["server"]

if __name__ == "__main__":
    c = collectInfo("127.0.0.1")
    h = c.getServerName()
    print "Server is:", h

If you read the documentation of the rfc822 module, about the headers
object, it will repay study.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list