[Tutor] while with function

Magnus Lycka magnus@thinkware.se
Tue Nov 19 06:15:03 2002


At 22:05 2002-11-18 -0500, fleet@teachout.org wrote:
>The only person who will use this is me.  From the command line.
>
>What would you recommend to replace raw_input?

Your favourite editor! I tried to describe the process
in my previous mail. This will make it possible for the
user to mess things up by fiddling with the labels, but
if you are the only user, that's probably not a big issue.

You get a much better chance to use your normal editing
facilities, get an overview of the data, and to change
whatever you want in the order that suits you best. You
can also use cut and paste, macros, get data from other
files etc.

Check this out!

# edit.py (c) Magnus Lyck=E5, magnus@thinkware.se, 2002
import os, tempfile

def edit(keyValuePairs, sep=3D':', editor=3D'$EDITOR'):
     fileName =3D tempfile.mktemp('txt')
     data =3D []
     for key, value in keyValuePairs:
         assert key.find(sep) =3D=3D -1
         if key:
             data.append('%s%s %s\n' % (key, sep, value))
         else:
             data.append(value+'\n')
     # Save data to temporary file
     f =3D open(fileName, 'wt')
     f.writelines(data)
     f.close()
     # Edit temporary file
     os.system('%s %s' % (editor, fileName))
     # Read data from temporary file
     data =3D open(fileName, 'rt').readlines()
     # Remove temporary file
     os.unlink(fileName)
     output =3D []
     for row in data:
         if row.find(sep) !=3D -1:
             key, value =3D row.split(sep, 1)
             output.append((key.strip(), value.strip()))
         else:
             output.append(('',row.strip()))
     return output

def test():
     data =3D [('','# Grades for Python training'),
             ('student','Zerblatt'),
             ('grade', 'A'),
             ('','#'),
             ('student','Ernie'),
             ('grade', 'C'),
             ('','#'),
             ('student','Sid'),
             ('grade', 'F'),
             ('','#')]
     data =3D edit(data)
     # Depending on settings and preferences you might
     # want to change this to:
     # data=3Dedit(data, editor=3D'notepad.exe')
     # data=3Dedit(data, editor=3D'vi')
     # data=3Dedit(data, editor=3D'emacs')
     # or whatever...
     for row in data:
         print "%s %s" % row

if __name__ =3D=3D '__main__':
     test()



--=20
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se