Telnetlib help. I need a case function.

Dennis Lee Bieber wlfraed at ix.netcom.com
Tue Nov 19 23:05:57 EST 2002


higgeldy Piggeldy fed this fish to the penguins on Tuesday 19 November 
2002 01:10 pm:

        Hopefully I don't raise your ire... Especially since most of my 
comments aren't directly focused on your one question... I'm having a 
hard time reading this densely written sequence.
> 
> #!/usr/bin/python
> import telnetlib
> import sys
> import string
> import re
> import regsub
> import regex
> import smtplib
> succeed = re.compile("( *Successful renewal for title '.*'\.)")
> maynot = re.compile("( *You may not renew '.*\.)")
> noneleft = re.compile(" *No items were renewed .*")
> due = re.compile ("( *Due Date = \d\d \w\w\w \d\d\d\d)")
> tn = telnetlib.Telnet("dyna.multnomah.lib.or.us")
> tn.read_until("login: ")
> print "logging in!\n"
> tn.write("fastcat\n")
> tn.read_until(">>")
> tn.write("\n")
> #tn.read_until("<<VT100>> ")
> tn.write("\n")
> tn.read_until("N")
> tn.write("\n")
> tn.read_until("DYNA -")
> tn.write("\n")
> tn.read_until("<Enter> :")

        I know Python doesn't care, but for /my/ reading, this function def 
would have occurred between the "import" and the "succeed..." lines -- 
I'm not used to reading function definitions in the middle of the 
"main" program code <G>

> def renew(thiscard,thispin,thisemail):
>         fileout = open ('temp.txt','w')
>         tn.write("17\n")
>         tn.read_until("barcode")
>         tn.write(thiscard+"\n")
>         print "\n\nrenewing ",
>         print "for ",thisemail
>         tn.read_until("PHONE")
>         tn.write(thispin+"\n")
>         tn.read_until("below")

        *****   Occurence 1

>         tn.write("1\n")
>         i=1

        Uhm... this assignment is futile, it is immediately overridden by the 
for loop.

>         for i in range(24):
>                 tmp = open('dyna.tmp','w')
>                 i=i+1

        And this seems rather silly too... the range() function has optional 
parameters...

>>> print range.__doc__
range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
These are exactly the valid indices for a list of 4 elements.

        Why not just use "range(1,25)"

>                 tn.read_until("below")

        *****   Occurence 2

        A literal reading of the above indicates that your read until "below", 
and then immediately /repeat/ a read until "below". Removing all the 
extraneous statements you have:

        read_until("below")
        for i in ....:
                read_until("below")

won't this result in missing the first block of data? (Maybe that's why 
your have all those strange things with the i+1 stuff...)


>                 tn.write("r\n")
>                 (tn.read_until('renew'))
>                 tn.write(`i` + "\n")
>                 tmp.write (tn.read_until("Enter"))
>                 tn.write("\n")
>                 tmp.close()

        Okay, you opened a file, wrote what I presume is everything between 
"renew" and "Enter"

>                 file = open('dyna.tmp','r')

        Now you reopen the same file (using a different variable -- and "file" 
could be a dangerous name for this <G>

>                 while 1:
>                         line = file.readline()
>                         if not line: break

        And read the lines back in... The whole tmp file could probably be 
replaced with

                tmpdata = tn.read_until("Enter"))
                for line in string.split(tmpdata, "\n"):
>                         successobj = succeed.search(line)
>                         maynotobj = maynot.search(line)
>                         dueobj = due.search(line)
>                         if successobj:
>                                 fileout.write
> (repr(successobj.groups())+"\n")
>                         if maynotobj:
>                                 fileout.write
> ("ATTENTION"+"\n"+repr(maynotobj.groups())+"\nATTENTION\n")
>                         if dueobj:
>                                 fileout.write
> (repr(dueobj.groups())+"\n")
>                 file.close()
>                 # tn.read_until("below")
>         tn.write("so\n")
>         fileout.close()
>         filein = open ("temp.txt","r")
>         fileout = open ("temp2.txt","w")
>         msg = "Subject:Automatic Library Renewal Notice
> For:"+thisuser+".\r\n\r\nThank You for using my service.\nPlease feel
> free to send any donations or suggestions to me at
> sweetfamily at qwest.net\n\n"

        This could be cleaned up some as well...

        msg = """\
Subject: Automatic Library Renewal Notice For: %s.

Thank you ...
Please feel ...

""" % thisuser


>         while 1:
>                 line = filein.readline()
>                 if not line: break

        Wouldn't this be cleaner as

        for line in filein.readlines():

>                 matchobj = string.replace (line,"(","")
>                 matchobj = string.replace (matchobj,")","")
>                 matchobj = string.replace (matchobj,'"','')
>                 matchobj = string.replace (matchobj,"'","")
>                 matchobj = string.replace (matchobj,",","")
>                 matchobj = string.replace (matchobj,"/","")
>                 print matchobj,
>                 msg = msg+matchobj
>                 fileout.write(matchobj)
>         filein.close()
>         fileout.close()
>         fromaddr = "From:andys at collegenet.com"
>         toaddr = "To: "
>         toaddr = toaddr + thisemail
>         print toaddr
>         sending = smtplib.SMTP('mail.collegenet.com')
>         sending.set_debuglevel(0)
>         sending.sendmail(fromaddr,toaddr,msg)
>         sending.quit()

        That's a pretty long stretch of stuff for one function.

> cardpatt = regex.compile ('^card:\(\w*\)')
> pinpatt = regex.compile ('^pin:\(\w*\)')
> emailpatt = regex.compile ("email:\(.*\)")
> userpatt = regex.compile ("user:\(.*\)")
> config = open("telnetter.cfg")
> status =0
> while 1:
>         line = config.readline()
>         if not line:break

        Another one that might be cleaner as a "for line in 
config.readlines():"

>         card = cardpatt.match(line)
>         pin = pinpatt.match(line)
>         email = emailpatt.match(line)
>         user = userpatt.match(line)
>         if card>=0:
>                 thiscard = str(cardpatt.group(1))
>                 status = status +1
>         if pin>=0:
>                 thispin = str(pinpatt.group(1))
>                 status = status +1
>         if email>=0:
>                 thisemail = str(emailpatt.group(1))
>                 status = status +1
>         if user>=0:
>                 thisuser = str(userpatt.group(1))
>                 status = status+1
>         if status == 4:
>                 status =0
>                 renew(thiscard,thispin,thisemail)

        Might just be me, but I think I'd dump that status counting thing for 
something more like:

thiscard = None
thispin = None
thisemail = None
thisuser = None
for line in config.readlines(): 
        if cardpatt.match(line) >= 0:
                thiscard = str(cardpatt.group(1))
        elif pinpatt.match(line) >= 0:
                thispin = str(pinpat.group(1))
        elif emailpatt.match(line) >= 0:
                thisemail = str(emailpatt.group(1))
        elif userpatt.match(line) >= 0:
                thisuser = str(userpatt.group(1))
        else:
                print "Invalid input line: '%s'" % line

        if thiscard and thispin and thisemail and thisuser:
                renew(thiscard, thispin, thisemail) #what happened to thisuser?
                thiscard = None
                thispin = None
                thisemail = None
                thisuser = None


> #renew("21168013143409","6422")
> #renew("21168018228841","6422")
> tn.read_until("Enter>")
> tn.write("19\n")
> tn.close()
> print "DONE!!"
> 
> 
> It trips up on the tn.read_until("below") because the server is
> sending something else since there are no books to renew.
>

        Okay, there are TWO "tn.read_until("below")", so which one of the two 
is the problem?

        Off-hand, you seem to be rigged for a fairly linear process with no 
allowance for divergence, or modularization.

        Without a captured data file logging all the input for comparison (in 
both situations, normal and empty) it is difficult to determine exactly 
what may be happening.


-- 
 > ============================================================== <
 >   wlfraed at ix.netcom.com  | Wulfraed  Dennis Lee Bieber  KD6MOG <
 >      wulfraed at dm.net     |       Bestiaria Support Staff       <
 > ============================================================== <
 >        Bestiaria Home Page: http://www.beastie.dm.net/         <
 >            Home Page: http://www.dm.net/~wulfraed/             <




More information about the Python-list mailing list