Strange loop behavior

Gabriel Rossetti gabriel.rossetti at mydeskfriend.com
Wed Mar 26 04:51:57 EDT 2008


Gabriel Rossetti wrote:
> Hello,
>
> I wrote a program that reads data from a file and puts it in a string, 
> the problem is that it loops infinitely and that's not wanted, here is 
> the code :
>
>     d = repr(f.read(DEFAULT_BUFFER_SIZE))
>     while d != "":
>         file_str.write(d)
>         d = repr(f.read(DEFAULT_BUFFER_SIZE))
>
> I also tried writing the while's condition like so : len(d) > 0, but 
> that doesn't change anything. I tried step-by-step debugging using 
> PyDev(eclipse plugin) and I noticed this, once the while was read once, 
> it is never re-read, basically, the looping does happen, but just in 
> between the two lines in the loop's body/block, it never goes on the 
> while and thus never verifies the condition and thus loops forever. I 
> had been using psyco (a sort of JIT for python) and so I uninstalled it 
> and restarted eclipse and I still get the same thing. This looks like 
> some bug, but I may be wrong, does anybody understand what's going on here?
>
> Thanks,
> Gabriel
>
> PS
> And yes I checked, the "d" variable is en empty string at some point, so 
> the looping should stop.
>
>   
Ok, I get it, the repr() function actually returns a string with quote 
characters around it, thus the length is never 0, but 2. The reason I 
began using the repr() function is that the str() and unicode() 
constructors didn't accept the data read, because it was bigger than 
ord(128) (or something like that. I'm trying to read a binary file and 
put it's contents in an xml message to send via the network, so that I 
can re-create it on the other side. I do need to keep the xml aspect 
though. Is there a better way of doing this?

Thanks,
Gabriel



More information about the Python-list mailing list