[mod_python] os.listdir()

William Chan ycchan at gmail.com
Thu Mar 24 01:29:45 EST 2005


I am sure that the problem is not output conversion. In fact, what I'm
trying to do is:

import os
def index(req, **kwargs):
    ...
    for name in os.listdir('/tmp'):
        if name[0] == '.':
            ...
    ...

However, I get "IndexError: string index out of range". So They are
really empty strings.


On Thu, 24 Mar 2005 01:15:49 -0500, Graham Dumpleton
<grahamd at dscpl.com.au> wrote:
> William Chan wrote ..
> > I'm using mod_python.publisher. My codes are:
> >
> > import os
> > def index():
> >     return str(os.listdir('/tmp'))
> >
> > and the output is:
> >
> > ['', '', '', '', '', '', '', '', '', '']
> 
> The explicit conversion of the result of os.listdir() to a string
> using str() is not actually required as mod_python.publisher
> will automatically convert any result into a string anyway.
> This fact shouldn't make any difference though.
> 
> All I can suggest is changing your handler to:
> 
>   import os
> 
>   def index(req):
>     req.content_type = "text/plain"
>     req.send_http_header()
>     return os.listdir('/tmp')
> 
> By setting the content type to "text/plain" you avoid publisher
> making a guess as to whether the content type may be HTML
> or not. It is possible, although unlikely that some filename in
> /tmp contains the magic characters it looks for. I don't though
> see this happening based on what you say is being displayed.
> 
> Other thing to try would be:
> 
>   import os
> 
>   def index(req):
>     req.content_type = "text/plain"
>     req.send_http_header()
>     return repr(os.listdir('/tmp'))
> 
> This takes the task of converting the result to a string away from
> publisher and displays it in a form which will hopefully encode
> any strange characters so they are visible and will not cause any
> problem.
> 
> Graham
> 
>


More information about the Mod_python mailing list