intresting buried treasure in the on line reference manual

Jeff Shannon jeff at ccvcorp.com
Tue Dec 11 14:14:54 EST 2001


Kirk Bailey wrote:

> Sending a message in python to the mail MTA
>
> I also found this in the refernece, very helpful, eccept for 2 things- a
> line of gibberish, and there is a bug on line 14.

> 12    msg = ("From: %s\r\nTo: %s\r\n\r\n"
> 13           % (fromaddr, string.join(toaddrs, ", "))) # <-- I suspect
> this is a linewrap error, it does not bomb

This is not an error.  The use of "extra" parentheses forces the parser to
read this entire bit as a single line.  You could also use the
line-continuation character to achieve the same effect:

    msg = "From: %s\r\nTo: %s\r\n\r\n"  \
                   % (fromaddr, string.join(toaddrs, ','))


>
> 14    while 1:
> 15        try:
> 16            line = raw_input()
> 17        except EOFError:
> 18            break
> 19        if not line:
> 20            break
> 21        msg = msg + line

# <-- this line screws everything up!  #  if I place it all on one line.
# the test is APPARENTLY to create an endless loop with 2
# hard coded exit conditions manually built in. But my python hates it.

(Comments moved to increase legibility)

You don't say anything about what *does* happen here, so it's hard to say
what the problem is.  What makes you say that Python hates it?  :)  This
does do exactly what you say it apparently does--it reads successively from
raw_input(), until a blank line or an EOF is entered, appending the input to
an already existing string (msg).  What do you expect it to do, that it's
not doing?

Note that, if I were coding this, I'd do it a bit differently, probably
like...


body = []
while 1:
    try:
        line = raw_input()
    except EOFError:
        break
    if not line:
        break
    body.append(line)

msg = msg + string.join(body, '\n')

As it exists in your code, there's no newline separating the "lines" read in
from raw_input(), those should be added manually (either with string
concatenation, as the original does, or by using string.join() as I do).

Jeff Shannon
Technician/Programmer
Credit International






More information about the Python-list mailing list