From pan@uchicago.edu Thu May 1 00:38:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Wed Apr 30 23:38:01 2003 Subject: [Tutor] class.__repr__: 'str' object is not callable??? In-Reply-To: <20030427093402.9323.47533.Mailman@mail.python.org> References: <20030427093402.9323.47533.Mailman@mail.python.org> Message-ID: <1051760257.3eb096812a593@webmail.uchicago.edu> Can someone tell me what the hell is happening in the following code? Why __getattr__ gets called when the __repr__ is the actual one that I called? Why is the ['str' object is not callable] happen ?? thx in advance. pan >>> class aClass: .. def __init__(self):pass .. def __repr__(self): .. return 'this is aClass' .. def __getattr__(self, name): .. print 'getting attr' #<==== [A] .. return 'returned value' .. >>> >>> a=aClass() >>> a this is aClass >>> print a getting attr Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable >>> From idiot1@netzero.net Thu May 1 01:54:01 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Thu May 1 00:54:01 2003 Subject: [Tutor] path issues Message-ID: <3EB0A8B9.4050605@netzero.net> ok, got a code problem. os.remove('./lists/' + mylist) # this deletes the subscriber file. os.remove('./lists/' + mylist + '.*') # remove all files with this blows out the script. Current dir is where the script is, the web cgi-bin, and the /lists dir is immediately under it./ Produces this error: Traceback (innermost last): File "/www/www.tinylist.org/cgi-bin/TLlistkill2.py", line 172, in ? os.remove('./lists/' + mylist + '.*') # remove all files... OSError: [Errno 2] No such file or directory: './lists/foolist.*' ok, is it simply that the language will not permit relative addressing in the os module? It sure does in several others! -- end Respectfully, Kirk D Bailey Owner HowlerMonkey Email Services Company: http://www.howlermonkey.net/ Inventor of TinyList MLM list server: http://www.tinylist.org/ Consulting Grump: http://www.sacredelectron.org/ Remember: it is an ill wind that blows no minds. Fnord. From idiot1@netzero.net Thu May 1 02:08:01 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Thu May 1 01:08:01 2003 Subject: [Tutor] quick fix Message-ID: <3EB0AC18.607@netzero.net> heck with it. mypath = os.getcwd() os.remove(mypath+'/lists/' + mylist) # this deletes the subscriber os.remove(mypath+'/lists/' + mylist + '.*') # remove all files with it's not relative anymore. First line works fine, but the thing does not like the wildcard in the second line, not one little bit. Any suggestions? -- end Respectfully, Kirk D Bailey Owner HowlerMonkey Email Services Company: http://www.howlermonkey.net/ Inventor of TinyList MLM list server: http://www.tinylist.org/ Consulting Grump: http://www.sacredelectron.org/ Remember: it is an ill wind that blows no minds. Fnord. From micforster@yahoo.com Thu May 1 03:38:02 2003 From: micforster@yahoo.com (Mic Forster) Date: Thu May 1 02:38:02 2003 Subject: [Tutor] while statement Message-ID: <20030501063750.64827.qmail@web13407.mail.yahoo.com> Hi, What I want to do is quite simple but I have gotten myself into a bind and any help is much appreciated. In a nutshell I need to iterate through the follow equation: S(n) = [S(S-1)/N](1-n/N)**S-2 where S and N are fixed values but where n increases by 1 after each iteration. So if S=31 and N=834 then after the first iteration: S(1) = [31(31-1)/834](1-1/834)**31-2 = 1.077 Second iteration: S(2) = [31(31-1)/834](1-2/834)**31-2 = 1.04 and this is repeated until n = N. I know that the while statement needs to be used but I am unsure of the exact syntax. I am having problems incrementing n by 1 in each iteration. Thanks again for any help, Mic __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From jjhegde@ncst.ernet.in Thu May 1 04:05:02 2003 From: jjhegde@ncst.ernet.in (Jayprasad J. Hegde) Date: Thu May 1 03:05:02 2003 Subject: [Tutor] Jython problem In-Reply-To: <3EB0AC18.607@netzero.net> References: <3EB0AC18.607@netzero.net> Message-ID: <20030501065941.GB796@konark.ncst.ernet.in> I am facing a problem involving Jython. I have a Debian-Linux system and have downloaded and installed Jython using the "apt-get install .." feature provided by Debian Linux. However, for some reason it refuses to execute ("jython progname.py" returns a pageful of error messages). Could you help me out in locating the source of the problem? I am including the error message and the program(s) for your reference. Comments welcome. - JJH ps - I'm NOT sure whether including error messages like this is a good thing; thought it might help in solving this problem. The error message given by the program is as follows: *sys-package-mgr*: processing new jar, '/usr/share/java/jython-2.1.jar' *sys-package-mgr*: can't write cache file for '/usr/share/java/jython-2.1.jar' *sys-package-mgr*: processing new jar, '/usr/java/j2sdk1.4.0_03/lib/dt.jar' *sys-package-mgr*: skipping bad jar, '/usr/java/j2sdk1.4.0_03/lib/dt.jar' *sys-package-mgr*: processing new jar, '/usr/share/java/libreadline-java-0.8.0.jar' Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at 0x4025d0ec: java.lang.Throwable.Throwable() (/usr/lib/./libgcj.so.3) at 0x4025004b: java.lang.Exception.Exception() (/usr/lib/./libgcj.so.3) at 0x4025394f: java.lang.RuntimeException.RuntimeException() (/usr/lib/./libgcj.so.3) at 0x40250b43: java.lang.IndexOutOfBoundsException.IndexOutOfBoundsException() (/usr/lib/./libgcj.so.3) at 0x4024c2d3: java.lang.ArrayIndexOutOfBoundsException.ArrayIndexOutOfBoundsException() (/usr/lib/./libgcj.so.3) at 0x4024b8f4: java.util.zip.Inflater.inflate(byte[], int, int) (/usr/lib/./libgcj.so.3) at 0x4030753f: java.util.zip.InflaterInputStream.read(byte[], int, int) (/usr/lib/./libgcj.so.3) at 0x40308c1b: java.util.zip.ZipInputStream.read(byte[], int, int) (/usr/lib/./libgcj.so.3) .. .. .. at 0x4037b9e7: ffi_call_SYSV (/usr/lib/./libgcj.so.3) at 0x4037b9af: ffi_raw_call (/usr/lib/./libgcj.so.3) at 0x4022827c: _Jv_InterpMethod.continue1(_Jv_InterpMethodInvocation) (/usr/lib/./libgcj.so.3) at 0x40228a48: _Jv_InterpMethod.run(ffi_cif, void, ffi_raw, _Jv_InterpMethodInvocation) (/usr/lib/./libgcj.so.3) at 0x40226129: _Jv_InterpMethod.run_normal(ffi_cif, void, ffi_raw, void) (/usr/lib/./libgcj.so.3) at 0x4037b8a0: ?? (??:0) at 0x40239642: gnu.gcj.runtime.FirstThread.call_main() (/usr/lib/./libgcj.so.3) at 0x402a2bf5: gnu.gcj.runtime.FirstThread.run() (/usr/lib/./libgcj.so.3) at 0x40244cc2: _Jv_ThreadRun(java.lang.Thread) (/usr/lib/./libgcj.so.3) at 0x40217370: _Jv_RunMain(java.lang.Class, byte const, int, byte const, boolean) (/usr/lib/./libgcj.so.3) at 0x08048928: __gcj_personality_v0 (python.home=/usr/share/jython) at 0x4068ba51: __libc_start_main (/lib/libc.so.6) at 0x080486f1: _Jv_RegisterClasses (python.home=/usr/share/jython) The java program: import java.util.*; import A.*; class SomeClass { public static void main(String[] args) { A a = A.someInitMethod(); Vector v1 = a.getSomeWords("someKeyValue", Config.X, Config.Y); int ele1 = v1.capacity(); for (int i = 0; i < ele1; i++) { System.out.println(v1.get(i).toString()); } } } The python program which is meant to do the same thing: import A from java.util import * a = A.getInstance () v = a.getSomeWords ('someKeyValue', Config.X, Config.Y) print v -- [ Jayprasad J. Hegde, KBCS Division, National Centre for Software Technology, Juhu, Mumbai 400049, India. Tel:+91-22-26201606x373 ] From shalehperry@attbi.com Thu May 1 04:38:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu May 1 03:38:02 2003 Subject: [Tutor] quick fix In-Reply-To: <3EB0AC18.607@netzero.net> References: <3EB0AC18.607@netzero.net> Message-ID: <200305010036.41419.shalehperry@attbi.com> On Wednesday 30 April 2003 22:09, Kirk Bailey wrote: > heck with it. > > mypath = os.getcwd() > os.remove(mypath+'/lists/' + mylist) # this deletes the subscriber > os.remove(mypath+'/lists/' + mylist + '.*') # remove all files with > > it's not relative anymore. > > First line works fine, but the thing does not like the wildcard in > the second line, not one little bit. > > Any suggestions? you need to use glob() to get the functionality. From shalehperry@attbi.com Thu May 1 04:39:06 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu May 1 03:39:06 2003 Subject: [Tutor] while statement In-Reply-To: <20030501063750.64827.qmail@web13407.mail.yahoo.com> References: <20030501063750.64827.qmail@web13407.mail.yahoo.com> Message-ID: <200305010038.22472.shalehperry@attbi.com> > and this is repeated until n = N. > > I know that the while statement needs to be used but I > am unsure of the exact syntax. I am having problems > incrementing n by 1 in each iteration. > while n != N: # or maybe n < N do_stuff n = n + 1 # or with newer (2.2+) n += 1 From micforster@yahoo.com Thu May 1 05:45:02 2003 From: micforster@yahoo.com (Mic Forster) Date: Thu May 1 04:45:02 2003 Subject: [Tutor] while statement In-Reply-To: <200305010038.22472.shalehperry@attbi.com> Message-ID: <20030501084423.76616.qmail@web13407.mail.yahoo.com> Thanks Sean, that's actually what I had written and my mistake was in the equation. Missed a bracket here and there but she's sweet now. Thanks for the assistance. Mic --- Sean 'Shaleh' Perry wrote: > > and this is repeated until n = N. > > > > I know that the while statement needs to be used > but I > > am unsure of the exact syntax. I am having > problems > > incrementing n by 1 in each iteration. > > > > while n != N: # or maybe n < N > do_stuff > n = n + 1 # or with newer (2.2+) n += 1 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From emil@lysator.liu.se Thu May 1 07:27:02 2003 From: emil@lysator.liu.se (Emil Styrke) Date: Thu May 1 06:27:02 2003 Subject: [Tutor] while statement In-Reply-To: <20030501084423.76616.qmail@web13407.mail.yahoo.com> (Mic Forster's message of "Thu, 1 May 2003 01:44:23 -0700 (PDT)") References: <20030501084423.76616.qmail@web13407.mail.yahoo.com> Message-ID: <874r4fdkud.fsf@i110.ryd.student.liu.se> Mic Forster writes: > Thanks Sean, > > that's actually what I had written and my mistake was > in the equation. Missed a bracket here and there but > she's sweet now. Thanks for the assistance. Mic > Another method is the for loop, it will save you the manual incrementing of n: for n in range(1, N+1): do_stuff range(x, y) creates a list with the integer elements i, where x <= i < y, and the for loop will iterate through each element in this list, assigning the current element to n. /Emil > > --- Sean 'Shaleh' Perry wrote: >> > and this is repeated until n = N. >> > >> > I know that the while statement needs to be used >> but I >> > am unsure of the exact syntax. I am having >> problems >> > incrementing n by 1 in each iteration. >> > >> >> while n != N: # or maybe n < N >> do_stuff >> n = n + 1 # or with newer (2.2+) n += 1 >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > __________________________________ > Do you Yahoo!? > The New Yahoo! Search - Faster. Easier. Bingo. > http://search.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From antonmuhin at rambler.ru" References: <20030427093402.9323.47533.Mailman@mail.python.org> <1051760257.3eb096812a593@webmail.uchicago.edu> Message-ID: <1361627450.20030501143919@rambler.ru> Hello pan, Thursday, May 1, 2003, 7:37:37 AM, you wrote: pue> Can someone tell me what the hell is happening in the pue> following code? pue> Why __getattr__ gets called when the __repr__ is the actual pue> one that I called? pue> Why is the ['str' object is not callable] happen ?? pue> thx in advance. pue> pan >>>> class aClass: pue> .. def __init__(self):pass pue> .. def __repr__(self): pue> .. return 'this is aClass' pue> .. def __getattr__(self, name): pue> .. print 'getting attr' #<==== [A] pue> .. return 'returned value' pue> .. >>>> >>>> a=aClass() >>>> a pue> this is aClass >>>> print a pue> getting attr pue> Traceback (most recent call last): pue> File "", line 1, in ? pue> TypeError: 'str' object is not callable >>>> Becuase print calls str method of class. But this method isn't defined and, therefore, __getattr__("__str__") is called. This method returns a string. Python tries to call the string and obviously fails. Scheme: print a --> call a.__str__ ---> __str__ is absent, therefore call --> __getattr__("__str__") --> "returned value" string is returned --> try to call this string --> TypeError exception is raised. hth -- Best regards, anton mailto:antonmuhin@rambler.ru From antonmuhin at rambler.ru" References: <3EB0A8B9.4050605@netzero.net> Message-ID: <1881839394.20030501144251@rambler.ru> Hello Kirk, Thursday, May 1, 2003, 8:55:21 AM, you wrote: KB> ok, got a code problem. KB> os.remove('./lists/' + mylist) # this deletes the subscriber file. KB> os.remove('./lists/' + mylist + '.*') # remove all files with this KB> blows out the script. Current dir is where the script is, the web KB> cgi-bin, and the /lists dir is immediately under it./ Produces this error: KB> Traceback (innermost last): KB> File "/www/www.tinylist.org/cgi-bin/TLlistkill2.py", line 172, in ? KB> os.remove('./lists/' + mylist + '.*') # remove all files... KB> OSError: [Errno 2] No such file or directory: './lists/foolist.*' KB> ok, is it simply that the language will not permit relative addressing KB> in the os module? It sure does in several others! I suppose it doesn't allow deletion with wild cards: you are trying to delete all the files in ./list/ with name footlist and any extension. os.remove('./lists/' + mylist + '.someext') should work. If you want to delete all this files, you may form a list of these files and when delete one by one, or run some shell command to delete them by mask. -- Best regards, anton mailto:antonmuhin@rambler.ru From Don Arnold" <1051760257.3eb096812a593@webmail.uchicago.edu> Message-ID: <08d201c30fce$93441ca0$d510ba3f@defaultcomp> ----- Original Message ----- From: To: Sent: Wednesday, April 30, 2003 10:37 PM Subject: [Tutor] class.__repr__: 'str' object is not callable??? > Can someone tell me what the hell is happening in the > following code? > > Why __getattr__ gets called when the __repr__ is the actual > one that I called? > > Why is the ['str' object is not callable] happen ?? > > thx in advance. > > pan > > > >>> class aClass: > .. def __init__(self):pass > .. def __repr__(self): > .. return 'this is aClass' > .. def __getattr__(self, name): > .. print 'getting attr' #<==== [A] > .. return 'returned value' > .. > >>> > >>> a=aClass() > >>> a > this is aClass > > >>> print a > getting attr > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'str' object is not callable > >>> > Although __repr__ and __str__ often return the same results, __str__ is what get's called when you try to print the object. Since you've overridden __getattr__, the lookup for the object's __str__ method returns the string 'returned value', which isn't callable. HTH, Don From antonmuhin at rambler.ru" References: <20030501063750.64827.qmail@web13407.mail.yahoo.com> Message-ID: <1262044569.20030501144616@rambler.ru> Hello Mic, Thursday, May 1, 2003, 10:37:50 AM, you wrote: MF> Hi, MF> What I want to do is quite simple but I have gotten MF> myself into a bind and any help is much appreciated. MF> In a nutshell I need to iterate through the follow MF> equation: MF> S(n) = [S(S-1)/N](1-n/N)**S-2 MF> where S and N are fixed values but where n increases MF> by 1 after each iteration. So if S=31 and N=834 then MF> after the first iteration: MF> S(1) = [31(31-1)/834](1-1/834)**31-2 MF> = 1.077 MF> Second iteration: MF> S(2) = [31(31-1)/834](1-2/834)**31-2 MF> = 1.04 MF> and this is repeated until n = N. MF> I know that the while statement needs to be used but I MF> am unsure of the exact syntax. I am having problems MF> incrementing n by 1 in each iteration. MF> Thanks again for any help, MF> Mic MF> __________________________________ MF> Do you Yahoo!? MF> The New Yahoo! Search - Faster. Easier. Bingo. MF> http://search.yahoo.com You might use something like this: for n in range(1, N): # or range(1, N + 1), if you need to compute for N too print float(S)*... BTW (S*(S-1)/N) might be precomputed. -- Best regards, anton mailto:antonmuhin@rambler.ru From magnus@thinkware.se Thu May 1 08:49:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 1 07:49:01 2003 Subject: [Tutor] path issues In-Reply-To: <3EB0A8B9.4050605@netzero.net> Message-ID: <5.2.1.1.0.20030501133956.02701f18@www.thinkware.se> At 00:55 2003-05-01 -0400, Kirk Bailey wrote: >ok, got a code problem. > os.remove('./lists/' + mylist) # this deletes the subscriber file. > os.remove('./lists/' + mylist + '.*') # remove all files with this Read the manual. remove(path) Remove the file path. ... In other words, os.remove(x) is (on unix) more or less the same as os.system("rm '%s'" % x) Note the single quotes. In unix, when you do "rm something*", the shell will perform a wildcard expansion before it calls the rm program, so rm will be fed a list of actual file names. Since you've already made your code unix-specific by not using os.path functions to manage paths, your simplest solution will be to use os.system("rm %s" % x), but a more pythonic way would be to do: import glob for fn in glob.glob(x): os.remove(fn) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From hemanexp@yahoo.com Thu May 1 08:59:01 2003 From: hemanexp@yahoo.com (perl lover) Date: Thu May 1 07:59:01 2003 Subject: [Tutor] Making python exe............... Message-ID: <20030501115813.60349.qmail@web41702.mail.yahoo.com> hi, Iam using python and linux. How can i run a python Tkinter program in a machine wich doesnt have python intalled? How can i make an "exe" like application in python? I have a python tkinter program which communicates with C++ using SWIG. In that case how can i make an "exe" or package which will contain all necessary files to run the appliaction? Thanx __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From magnus@thinkware.se Thu May 1 10:41:10 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 1 09:41:10 2003 Subject: [Tutor] Making python exe............... In-Reply-To: <20030501115813.60349.qmail@web41702.mail.yahoo.com> Message-ID: <5.2.1.1.0.20030501153938.00b63348@www.thinkware.se> At 04:58 2003-05-01 -0700, perl lover wrote: >hi, > Iam using python and linux. How can i run a python >Tkinter program in a machine wich doesnt have python >intalled? How can i make an "exe" like application in >python? Use the McMillan installer. http://www.mcmillan-inc.com/install1.html -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From hodge3@llnl.gov Thu May 1 12:41:04 2003 From: hodge3@llnl.gov (Neil Hodge) Date: Thu May 1 11:41:04 2003 Subject: [Tutor] Getting process output in real time Message-ID: <3EB13FDE.8000105@llnl.gov> All: I am building a GUI to wrap around a CLI program. One of the functions of the CLI outputs a progress bar, something like the following: [0....25....50....75....100] I am using one of the os.popen variants for all of my other system calls, and getting the stdout works perfectly. Since all of the other functions are very quick or give no status updates, this would be a moot question. But for this function, I would like to get the stdout back in real time so that I can display it in the GUI. I note that in http://www.python.org/doc/current/lib/popen2-flow-control.html while not necessarily directly my situation, there is the idea that "In particular, note that sys.stderr must be closed after writing all data, or readlines() won't return." I'm not quite sure how this would be useful, but I may be able to do something with it. Any other ideas? Thanks. Neil From magnus@thinkware.se Thu May 1 14:42:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 1 13:42:03 2003 Subject: [Tutor] Getting process output in real time In-Reply-To: <3EB13FDE.8000105@llnl.gov> Message-ID: <5.2.1.1.0.20030501194118.00b4be18@www.thinkware.se> At 08:40 2003-05-01 -0700, Neil Hodge wrote: >All: > >I am building a GUI to wrap around a CLI program. One of the functions of >the CLI outputs a progress bar, something like the following: > >[0....25....50....75....100] > >I am using one of the os.popen variants for all of my other system calls, >and getting the stdout works perfectly. Since all of the other functions >are very quick or give no status updates, this would be a moot >question. But for this function, I would like to get the stdout back in >real time so that I can display it in the GUI. I note that in I don't think you can do this in a platform independent way. What operating system are we talking about? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From jeff@ccvcorp.com Thu May 1 14:51:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu May 1 13:51:01 2003 Subject: [Tutor] Getting process output in real time References: <3EB13FDE.8000105@llnl.gov> Message-ID: <3EB15EEB.40606@ccvcorp.com> Neil Hodge wrote: > All: > > I am building a GUI to wrap around a CLI program. One of the > functions of the CLI outputs a progress bar, something like the > following: > > [0....25....50....75....100] > > I am using one of the os.popen variants for all of my other system > calls, and getting the stdout works perfectly. Since all of the other > functions are very quick or give no status updates, this would be a > moot question. But for this function, I would like to get the stdout > back in real time so that I can display it in the GUI. You may be able to use read() on your pipe object to, in essence, poll for new data. Perhaps easiest would be to fire off your CLI program in a secondary thread, and use read(1) to grab individual bytes of output from it and then post those back to your main (GUI) thread. This lets your GUI remain responsive while your long-running console task is processing, and gives you a fair amount of flexibility in how you present the progress reports (you could simply update a text widget, or run a graphical progressbar dialog, or whatever). Jeff Shannon Technician/Programmer Credit International From hodge3@llnl.gov Thu May 1 14:57:03 2003 From: hodge3@llnl.gov (Neil Hodge) Date: Thu May 1 13:57:03 2003 Subject: [Tutor] Getting process output in real time In-Reply-To: <5.2.1.1.0.20030501194118.00b4be18@www.thinkware.se> References: <5.2.1.1.0.20030501194118.00b4be18@www.thinkware.se> Message-ID: <3EB15FB9.7050602@llnl.gov> Magnus: Magnus Lyck=E5 wrote: > At 08:40 2003-05-01 -0700, Neil Hodge wrote: >=20 >> All: >> >> I am building a GUI to wrap around a CLI program. One of the=20 >> functions of the CLI outputs a progress bar, something like the=20 >> following: >> >> [0....25....50....75....100] >> >> I am using one of the os.popen variants for all of my other system=20 >> calls, and getting the stdout works perfectly. Since all of the other= =20 >> functions are very quick or give no status updates, this would be a=20 >> moot question. But for this function, I would like to get the stdout=20 >> back in real time so that I can display it in the GUI. I note that in >=20 >=20 > I don't think you can do this in a platform independent way. > What operating system are we talking about? >=20 Although I typically try to write platform-independently, that is not=20 necessary in this case. The OS is Linux. I guess what I am looking for is something conceptually like the=20 following: a pipe that can be read from and can return the read data as=20 it arrives. I imagine this would involve threads as well: one thread to=20 read/return data from the pipe while it is still open, and another=20 thread to do something with that data. Neil From Michael Montagne Thu May 1 16:48:02 2003 From: Michael Montagne (Michael Montagne) Date: Thu May 1 15:48:02 2003 Subject: [Tutor] re matching Message-ID: <20030501194730.GA32268@boora.com> I'm trying to quickly parse some errors out of mail.log. Well, ok, the quickly part is already a lost cause. Here is my program: import re fname="/home/montagne/mail.log.0" pattern=".*Abandoning.*" logfile=open(fname,"r") badlist=[] cnt=1 maxcnt=200 loglines=logfile.readlines() logfile.close() for line in loglines: if cnt > maxcnt: break #print line omatch=re.search(pattern,line) if omatch: sDate=line.split("]:")[0] sDate=sDate + "]" print sDate badlist=badlist + [sDate] cnt=cnt + 1 print str(len(badlist)) + " bad things" for line in badlist: line1=line.replace(":","\\\\:") line2=line1.replace("]","\\\\]") line3=line2.replace("[","\\\\[") pattern=line3 print pattern cnt=0 for line in loglines: if cnt > maxcnt: break p=re.compile(pattern) omatch=p.match(line) if omatch: #sOutstring=line[88:] sOutstring=line print sOutstring cnt = cnt + 1 print "Done" It should make a list of strings representing lines with the word "Abandoning" on them. Then for each of those strings, look through the same list of strings for those matching the string. But I can not generate a match as I cycle through badlist. If I plug the strings into the IDLE python shell, they appear to work. I must be missing something. From dyoo@hkn.eecs.berkeley.edu Thu May 1 17:18:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 1 16:18:01 2003 Subject: [Tutor] path issues In-Reply-To: <3EB0A8B9.4050605@netzero.net> Message-ID: On Thu, 1 May 2003, Kirk Bailey wrote: > ok, got a code problem. > os.remove('./lists/' + mylist) # this deletes the subscriber file. > os.remove('./lists/' + mylist + '.*') # remove all files with this > > blows out the script. Current dir is where the script is, the web > cgi-bin, and the /lists dir is immediately under it./ Produces this error: > > Traceback (innermost last): > File "/www/www.tinylist.org/cgi-bin/TLlistkill2.py", line 172, in ? > os.remove('./lists/' + mylist + '.*') # remove all files... > OSError: [Errno 2] No such file or directory: './lists/foolist.*' Hi Kirk, You may want to set things up so that the script does not automatically assume the location of the 'lists' directory. How about making a 'configuration' file called 'TLListConfig.py'; it could have the following: ### TLListConfig.py ## Define the absolute path of the lists directory: ## commented out; it's a bit dangerous to have user data in cgi-bin ## LISTS_DIR = "/www/www.tinylist.org/cgi-bin/lists" LISTS_DIR = "/var/www.tinylist.org/lists" ### In your TLlistkill2 program, or anywhere else in the mailing list system, you can use: ### os.remove(os.path.join(TLListConfig.LISTS_DIR, mylist)) ### The advantage of this is that having a separate configuration file is that it allows your other users to easily relocate 'lists' to somewhere more isolated: Rather than have your users modify every place where './lists' is being used, it might be easier to centralize that variable in a fairly readable configuration file. (I often feel really nervous about CGI programs that modify or write files into the cgi-bin directory. My security spidey sense solicites me to encourage you to make it easy to relocate the 'lists' directory somewhere less dangerous.) > ok, is it simply that the language will not permit relative addressing > in the os module? It sure does in several others! Sean and Magnus mentioned that wildcards aren't natively supported by os.remove() -- you'll want to use the 'glob' module to handle them. Good luck to you! From hodge3@llnl.gov Thu May 1 17:23:01 2003 From: hodge3@llnl.gov (Neil Hodge) Date: Thu May 1 16:23:01 2003 Subject: [Tutor] Getting process output in real time In-Reply-To: <3EB15EEB.40606@ccvcorp.com> References: <3EB13FDE.8000105@llnl.gov> <3EB15EEB.40606@ccvcorp.com> Message-ID: <3EB181E1.80504@llnl.gov> Jeff: Jeff Shannon wrote: > Neil Hodge wrote: > > > You may be able to use read() on your pipe object to, in essence, poll > for new data. Perhaps easiest would be to fire off your CLI program in > a secondary thread, and use read(1) to grab individual bytes of output > from it and then post those back to your main (GUI) thread. This sounds about right. So, within the CLI thread, I am thinking something like the following (more or less): [open pipe, etc.] while 1: string = None while 1: c = read(fd, 1) string = string + c if c = os.linesep: break [assign string representing whole line to trans-thread variable for action by other thread] [check break condition for outer loop here] [close pipe] Seem reasonable? Neil From jeff@ccvcorp.com Thu May 1 17:38:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu May 1 16:38:01 2003 Subject: [Tutor] Getting process output in real time References: <3EB13FDE.8000105@llnl.gov> <3EB15EEB.40606@ccvcorp.com> <3EB181E1.80504@llnl.gov> Message-ID: <3EB18613.2000600@ccvcorp.com> Neil Hodge wrote: > Jeff: > > Jeff Shannon wrote: > >> You may be able to use read() on your pipe object to, in essence, >> poll for new data. Perhaps easiest would be to fire off your CLI >> program in a secondary thread, and use read(1) to grab individual >> bytes of output from it and then post those back to your main (GUI) >> thread. > > > This sounds about right. So, within the CLI thread, I am thinking > something like the following (more or less): > > [open pipe, etc.] > while 1: > string = None > while 1: > c = read(fd, 1) > string = string + c > if c = os.linesep: > break > [assign string representing whole line to > trans-thread variable for action by other thread] > [check break condition for outer loop here] > [close pipe] > > Seem reasonable? Well, for the "progress bar", the program probably puts everything on a single line, so buffering it line-by-line won't do you much good. You'll probably want to send each byte to the GUI thread as it comes in. (Btw, I strongly recommend using Queue.Queue for inter-thread communications.) Something like [open pipe] while 1: c = fd.read(1) if c == [EOF]: break myqueue.put(c) [close pipe] should probably do the trick. In your GUI thread, you can use an idle-handler or a timer to check the queue for contents. I'd do all the assembling of characters in the main thread, since you mostly need to know when each character arrives. Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Thu May 1 17:42:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 1 16:42:01 2003 Subject: [Tutor] class.__repr__: 'str' object is not callable??? In-Reply-To: <1051760257.3eb096812a593@webmail.uchicago.edu> Message-ID: On Wed, 30 Apr 2003 pan@uchicago.edu wrote: > Can someone tell me what the hell is happening in the following code? [some text cut] > >>> class aClass: > .. def __init__(self):pass > .. def __repr__(self): > .. return 'this is aClass' > .. def __getattr__(self, name): > .. print 'getting attr' #<==== [A] > .. return 'returned value' > .. > >>> > >>> a=aClass() > >>> a > this is aClass > > >>> print a > getting attr > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'str' object is not callable Hi Pan, In Python, even the methods of a class are 'attributes': ### >>> class MyClass: ... def __init__(self): ... self.name = 'pan' ... def some_method(self): ... return 42 ** 2 ... >>> inst = MyClass() >>> inst.name 'pan' >>> inst.some_method > ### Notice that we can get at data attributes and methods using the same syntax. The one major thing that distinguishes a method from any other data thing is that we can "apply" it --- to evaluate it as an action. But we know this already with our experience with functions: we know that functions are things that are, in some sense, just like other objects: ### >>> def add(x, y): return x + y ... >>> def mul(x, y): return x * y ... >>> list_of_functions = [add, mul] >>> list_of_functions [, ] >>> list_of_functions[0] >>> f = list_of_functions[0] >>> f(11, 31) 42 >>> list_of_functions[1](11, 31) 341 ### So there's no barrier between the methods in our class and our other instance attributes. By the way, this can cause some accidental problems for people who expect the two to live in different worlds: ### >>> class BuggyClass: ... def __init__(self): ... self.name = 'pan' ... def name(self): ... return "My name is " + self.name ... >>> >>> >>> b = BuggyClass() >>> >>> b.name() ## Review Question: why doesn't this work? Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable >>> >>> >>> >>> BuggyClass.name(b) ## Advanced question: why does this work? 'My name is pan' ### Java programmers, in particular, may need to be careful of old habits, because it's one language that puts variables and methods in different 'namespaces'. In Java, the collision between method names and data attribute names can't occur. This might be a good thing or a bad thing, depending on your perspective. (Personally, I like Python's method better for reasons of unity.) Anyway, back to your question: when we do a 'print' on an object in Python, if that object isn't a string yet, Python will automatically call str() on that object to get a fairly readable representation of that object as a string. Python looks for an __str__() method in our class, but doesn't find one. But since aClass defines an alternative way of getting attributes --- that __getattr__() method! --- that's what Python will try to use. The path to the error message is subtly convoluted. But does it make sense now? Please feel free to ask more questions about this till it starts getting less fuzzy. *grin* Good luck to you! From pan@uchicago.edu Thu May 1 22:26:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Thu May 1 21:26:01 2003 Subject: [Tutor] class.__repr__: 'str' object is not callable??? In-Reply-To: References: Message-ID: <1051838734.3eb1c90e89fbe@webmail.uchicago.edu> Thx to Anton, Don and Danny for soving my puzzle. Now I learned a little bit more about py class. Ok for Danny's 2 review questions: ### >>> class BuggyClass: .. def __init__(self): .. self.name = 'pan' .. def name(self): .. return "My name is " + self.name .. > >>> b = BuggyClass() > >>> > >>> b.name() ## Review Question: why doesn't this work? [A] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'str' object is not callable > >>> > >>> > >>> > >>> BuggyClass.name(b) ## Advanced question: why does this work? [B] > 'My name is pan' > ### My current understanding is: in [B] the class hasn't been 'initialized' yet, so there's no '.name' attribute. The only thing in the namespace with name = 'name' is the function .name() which returns 'My name is pan'. In [A] the class has been instanciated into 'b', meaning that the attribute 'name' exists and having a string value 'pan', which is returned when b.name is called. It's equivalent to 'pan'() so it results in a 'str' object is not callable error. Question: where is the .name() method after the class is instanciated ? Simply overridden by the .name attribute and can no longer be accessed ? pan From pan@uchicago.edu Thu May 1 22:33:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Thu May 1 21:33:01 2003 Subject: [Tutor] copy(): another 'str' object is not callable??? In-Reply-To: References: Message-ID: <1051839139.3eb1caa35d811@webmail.uchicago.edu> Ok folks, here's another "'str' object is not callable" question. This time it happens in the copy module. See below: ''' >>> class aclass: ... def __init__(self): self.aValue='a value' ... def __getattr__(self, name): ... return self.aValue ... def copy(self): ... return copy.deepcopy(self) ... >>> a = aclass() >>> b = a.copy() Traceback (most recent call last): File "", line 1, in ? File "", line 10, in copy File "E:\Program Files\prog\lang\py\ActivePython\lib\copy.py", line 179, in deepcopy y = copierfunction(x, memo) File "E:\Program Files\prog\lang\py\ActivePython\lib\copy.py", line 262, in _deepcopy_inst return x.__deepcopy__(memo) TypeError: 'str' object is not callable ''' What's wrong with the above code? I did a little test and found, again, that this error came from the '__getattr__'. If it is removed then the copy function works. any help is appreciated. pan From pan@uchicago.edu Thu May 1 22:38:02 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Thu May 1 21:38:02 2003 Subject: [Tutor] Get instance name from inside the class ??? In-Reply-To: References: Message-ID: <1051839435.3eb1cbcba8ef3@webmail.uchicago.edu> Here's another ? for u guys: class aclass: def __init__(self): self.val = 'avalue' aaa = aclass() bbb = aclass() Is it possible to put some code inside the aclass to determine is it 'aaa' or 'bbb' that this class is bound to ??? pan From Don Arnold" <1051839435.3eb1cbcba8ef3@webmail.uchicago.edu> Message-ID: <0a8001c31050$ff082da0$d510ba3f@defaultcomp> ----- Original Message ----- From: To: Sent: Thursday, May 01, 2003 8:37 PM Subject: [Tutor] Get instance name from inside the class ??? > Here's another ? for u guys: > > class aclass: > def __init__(self): > self.val = 'avalue' > > aaa = aclass() > bbb = aclass() > > Is it possible to put some code inside the aclass to determine > is it 'aaa' or 'bbb' that this class is bound to ??? > > pan > Not really, because Python variables don't actually have values: they are object references. So there isn't necessarily a one-to-one relationship between a variable and the object it points to. For example: >>> class aclass: def __init__(self): self.val = 'value' >>> aaa = aclass() >>> bbb = aaa >>> ccc = bbb These three variables all point to the exact same object: >>> print aaa <__main__.aclass instance at 0x00A9E678> >>> print bbb <__main__.aclass instance at 0x00A9E678> >>> print ccc <__main__.aclass instance at 0x00A9E678> And modifying one changes all three: >>> aaa.x = 5 >>> print bbb.x 5 >>> print ccc.x 5 The underlying aclass instance doesn't map to a single variable, so it doesn't make much sense to consider it bound to one particular variable. HTH, Don From Don Arnold" <1051839139.3eb1caa35d811@webmail.uchicago.edu> Message-ID: <0a8f01c31051$bcafa950$d510ba3f@defaultcomp> ----- Original Message ----- From: To: Sent: Thursday, May 01, 2003 8:32 PM Subject: Re: [Tutor] copy(): another 'str' object is not callable??? > Ok folks, here's another "'str' object is not callable" question. > This time it happens in the copy module. See below: > > > ''' > >>> class aclass: > ... def __init__(self): self.aValue='a value' > ... def __getattr__(self, name): > ... return self.aValue > ... def copy(self): > ... return copy.deepcopy(self) > ... > >>> a = aclass() > >>> b = a.copy() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 10, in copy > File "E:\Program Files\prog\lang\py\ActivePython\lib\copy.py", line 179, > in deepcopy > y = copierfunction(x, memo) > File "E:\Program Files\prog\lang\py\ActivePython\lib\copy.py", line 262, > in _deepcopy_inst > return x.__deepcopy__(memo) > TypeError: 'str' object is not callable > ''' > > What's wrong with the above code? > > I did a little test and found, again, that this error came > from the '__getattr__'. If it is removed then the copy function > works. > > any help is appreciated. > pan This is the same problem you had before. By overriding __getattr__, the lookup for the object's print method returns a string, which isn't callable. HTH, Don From j.ezequiel@spitech.com Fri May 2 00:11:00 2003 From: j.ezequiel@spitech.com (Ezequiel, Justin) Date: Thu May 1 23:11:00 2003 Subject: [Tutor] Re: Entity to UTF-8 Message-ID: <0F757892D113D611BD2E0002559C1FF40361B1DE@email.spitech.com> Thanks for your comments Paul. I appreciate the time you took. I will have a look at the Archive for something that may help. Do you think I am on the right track? Is there a different approach I could take? Full text of my previous mail is at http://www.sps-spitech.com/wap/utf8.txt Please ignore the question re Hex to Long (I found out that the long() function has an optional 2nd argument) From shalehperry@attbi.com Fri May 2 00:20:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu May 1 23:20:01 2003 Subject: [Tutor] while statement In-Reply-To: <874r4fdkud.fsf@i110.ryd.student.liu.se> References: <20030501084423.76616.qmail@web13407.mail.yahoo.com> <874r4fdkud.fsf@i110.ryd.student.liu.se> Message-ID: <200305012018.36673.shalehperry@attbi.com> > > Another method is the for loop, it will save you the manual > incrementing of n: > > for n in range(1, N+1): > do_stuff > > range(x, y) creates a list with the integer elements i, where x <= i < y, > and the for loop will iterate through each element in this list, > assigning the current element to n. > I personally find this horribly wasteful. xrange() at least generates the next element when it is needed. range(1,100) # builds a 100 item list, ick. Sure this is a scripting language, but no need to waste cycles uselessly. From hemanexp@yahoo.com Fri May 2 00:35:02 2003 From: hemanexp@yahoo.com (perl lover) Date: Thu May 1 23:35:02 2003 Subject: [Tutor] Calling a module function in another class.......... Message-ID: <20030502033416.47862.qmail@web41706.mail.yahoo.com> hi, How to call a member function of one module from another class function? i have created a module and defined a function in that. I called this function from another class. But i got some errror message. My program is given below. ############################################## # classtest.py ############################################## def print_mousepos(self,event): print self.canvas.event.x,self.canvas.event.y ############################################# # mainprg.py ############################################# import classtest from Tkinter import * class App: def __init__(self,parent): self.myparent = parent self.canvas = Canvas(parent,width="1000m",height="1000m") self.canvas.create_rectangle(100,100,200,200,fill='blue') self.canvas.bind('',self.ZoomIn) self.canvas.bind('',self.mousemove) self.canvas.pack() def ZoomIn(self,event): self.canvas.scale(ALL,2,2,1.5,1.5) def mousemove(self,event): classtest.print_mousepos(self,event) root = Tk() myapp = App(root) root.mainloop() Here i called "print_mousepos" of classtest.py module in my "App" class and want to print the mouse position values. But i got the following error: File " mainprg.py", line -- in mousemove NameError:print_mousepos Now how can i rectify this error and call a member function of a module in another calss? Thanx __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From idiot1@netzero.net Fri May 2 01:22:03 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Fri May 2 00:22:03 2003 Subject: [Tutor] searching for a substring in a list of strings. Message-ID: <3EB1F2F4.8070500@netzero.net> target=mylist+':"|/' # all list aliases start as(listname):"|/ for line in aliases: # each 'line' is a string in a list if target not in line: #ie, do NOT write the line with our f1.write(line+'\n') # write the non targeted line f2.close() # now close the file. produces this error: Traceback (innermost last): File "/www/www.tinylist.org/cgi-bin/TLlistkill2.py", line 185, in ? if target not in line: #ie, do NOT write the line with our TypeError: string member test needs char left operand what's a char left operand? I am searching for a substring occuring in a list of strings. IF that subscring exists in a particular string, which is one of N strings in a list, the routine is to NOT write out that string to the file. The list is a file read in using readlines, creating a list. Each line becomes a string in the list. I want to search all the lines ion the list for the occurance of the string. Aliases always start with a name, a ':', then the beginning of the definition of the alias. This is always (listname):"|/ Meaqnwhile, I continue searching the on line documentation and my short stack of 2 manuals. -- end Respectfully, Kirk D Bailey Owner HowlerMonkey Email Services Company: http://www.howlermonkey.net/ Inventor of TinyList MLM list server: http://www.tinylist.org/ Consulting Grump: http://www.sacredelectron.org/ Remember: it is an ill wind that blows no minds. Fnord. From idiot1@netzero.net Fri May 2 03:03:01 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Fri May 2 02:03:01 2003 Subject: [Tutor] problem solved Message-ID: <3EB20A97.9080304@netzero.net> ok, here it goes. string.find(bigstring, substring) returns a -1 if the substring is NOT found. However, for a IF statement, a FALSE is a ZERO (0) and ONLY a 0 will do; a -1 is a TRUE, which I played with interactively in python to test out. Further, if the saught strung is found at THE VERY BEGINNING of the larger string, the returned vaslue is ZERO, as python is zero baised. So I wrote this wrapper: def wrongline(s,ss): # converts the -1 to a ZERO (a NOT) x=string.find(s, ss)# so we can use it in a IF statelemt! x=x+1 return x # return the X value # so if the substring is not found, it returns a ZERO, and any other result, indicating a HIT, returns a value greater than ZERO, allowing this simple function to drive a IF/THEN/ELSE flow structure with no pain or strain at all My program now works, thanks to brute force and persistance. May this effort humbly offered to the community prove educational. . -- end Respectfully, Kirk D Bailey Owner HowlerMonkey Email Services Company: http://www.howlermonkey.net/ Inventor of TinyList MLM list server: http://www.tinylist.org/ Consulting Grump: http://www.sacredelectron.org/ Remember: it is an ill wind that blows no minds. Fnord. From shalehperry@attbi.com Fri May 2 03:17:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri May 2 02:17:02 2003 Subject: [Tutor] searching for a substring in a list of strings. In-Reply-To: <3EB1F2F4.8070500@netzero.net> References: <3EB1F2F4.8070500@netzero.net> Message-ID: <200305012315.35824.shalehperry@attbi.com> On Thursday 01 May 2003 21:24, Kirk Bailey wrote: > target=mylist+':"|/' # all list aliases start as(listname):"|/ > for line in aliases: # each 'line' is a string in a list > if target not in line: #ie, do NOT write the line with our > f1.write(line+'\n') # write the non targeted line > f2.close() # now close the file. > > produces this error: > Traceback (innermost last): > File "/www/www.tinylist.org/cgi-bin/TLlistkill2.py", line 185, in ? > if target not in line: #ie, do NOT write the line with our > TypeError: string member test needs char left operand > > what's a char left operand? > 'if target not in line' treats line like a list of characters. So, the input to the 'in' operator should be a character. > I am searching for a substring occuring in a list of strings. IF that > subscring exists in a particular string, which is one of N strings in a > list, the routine is to NOT write out that string to the file. The list > is a file read in using readlines, creating a list. Each line becomes a > string in the list. I want to search all the lines ion the list for the > occurance of the string. > > Aliases always start with a name, a ':', then the beginning of the > definition of the alias. This is always > (listname):"|/ > > Meaqnwhile, I continue searching the on line documentation and my short > stack of 2 manuals. >>> s = "foo:bar" >>> s.find('bar') 4 >>> s.find('baz') -1 From magnus@thinkware.se Fri May 2 06:35:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 2 05:35:01 2003 Subject: [Tutor] class.__repr__: 'str' object is not callable??? In-Reply-To: <1051838734.3eb1c90e89fbe@webmail.uchicago.edu> References: Message-ID: <5.2.1.1.0.20030502105923.026aeac8@www.thinkware.se> At 20:25 2003-05-01 -0500, pan@uchicago.edu wrote: >Question: where is the .name() method after the class >is instanciated ? Simply overridden by the .name attribute >and can no longer be accessed ? No. The string attribute is in the in instance object, and the method is in the class object, but it's probably a good idea not to use the same name for a method as for an attribute, since you can't use the normal shortcut to call methods, i.e. via the instance.*) >>> class X: ... def __init__(self): ... self.y = 'I am an attribute' ... def y(self): ... return 'I am a method' ... >>> x = X() >>> print x.y I am an attribute >>> print X.y >>> print x.__class__.y >>> print x.y() Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable >>> print X.y(x) I am a method >>> print x.__class__.y() Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method y() must be called with X instance as first argument (got nothing instead) >>> print x.__class__.y(x) I am a method Remember that everything (almost) is a first class object in python. It would not make sense if y referred to different objects when you did x.y or x.y(). For instance, an attribute might be callable: >>> class X: ... def __init__(self): ... self.y = int ... >>> x = X() >>> print x.y(4.34) 4 Here we want to access an attribute, not a method, even if we have () after the attribute name. You can also do something like: a = SomeClass(1,2,3,4) a_meth = a.method for i in aLongRange: a_meth(i) Here we want to access a method, even if we don't use () after the method name. This will save a namespace lookup inside the loop. It's a fairly common way to increase the speed for method calls to small methods that are called in a loop. (For a trivial method that just does "self._cnt += 1" I get a 15-20% speedup for big loops, so this is probably not very useful, but the general abaility to be able to get to any object in a uniform way, whether it's a string, a module or a function, is very useful. *) You can view "x.y()" as shorthand for x.__class__.y(x). After all, methods reside in classes (usually) and you need to feed then an appropriate instance object as the first parameter. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Fri May 2 07:01:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 2 06:01:01 2003 Subject: [Tutor] Calling a module function in another class.......... In-Reply-To: <20030502033416.47862.qmail@web41706.mail.yahoo.com> Message-ID: <5.2.1.1.0.20030502114907.02708318@www.thinkware.se> At 20:34 2003-05-01 -0700, perl lover wrote: >hi, > How to call a member function of one module from >another class function? Just like you did. But functions in a module are typically not called "member functions". For me, a member function sounds like a function in a class, what we usually call a method. A function defined globally in a module is just a function, plain and simple. >def print_mousepos(self,event): > print self.canvas.event.x,self.canvas.event.y But this you should change to "print event.x,event.y" Right? self.canvas has no event attribute. You (or rather Tkinter) passes the event in as parameter, right? > Now how can i rectify this error and call a member >function of a module in another calss? Remove that other "classtest.py" that "import" finds before it finds your file. Or do a reload (see the previous thread about that) if that's what you need. After the fix above, your program works for me. If the code you mailed is the complete program, the imported classtest is not the code you showed. It's either another file, or a different version of that file. I still feel it's better to run programs from the command line than from inside an ide... If you are in fact only showing an excerpt of a file, you might have slipped in a "classtest = ..." somewhere, so that it now refers to something different than the module. So, when will it say "python lover" in that email address? ;) /Magnus P.S. "Python-tutor lover" is fully acceptable. It will probably give you priority in the mail queue... ;^) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Fri May 2 07:20:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 2 06:20:02 2003 Subject: [Tutor] searching for a substring in a list of strings. In-Reply-To: <3EB1F2F4.8070500@netzero.net> Message-ID: <5.2.1.1.0.20030502120321.02721ae0@www.thinkware.se> At 00:24 2003-05-02 -0400, Kirk Bailey wrote: >target=mylist+':"|/' # all list aliases start as(listname):"|/ >for line in aliases: # each 'line' is a string in a list > if target not in line: #ie, do NOT write the line with our This only works in Python 2.3 and above. From 2.3, "a in b" will basically be the same thing as "b.find(a) != -1", but for now, you need to do... if line.find(target) == -1: ...to achieve what you want. Read the library reference chapter 2. (It's a while since I said that, but it's still as relevant.) >what's a char left operand? I suppose "needs a char as its left operand" would have been better English. Or perhaps even "needs a one character long string as its left operand". A "char" is a string with lenght 1. I guess this is not completely obvious for people who haven't programmed in languages such as C, where a string is just a sequence of chars. I doubt the error message will change though, since the behaviour is already changed... A "left operand" is the object or expression on the left hand side of an operator, in this case the "in" operator. For "3 + 5", 3 is the left operator, 5 is the right operator and + is the binary operator. It's called binary operator since it wants two operands. A unary operator only wants one operand. "-" is both a binary operator (subtraction) and a unary operator (negation). Python has no ternary operator (yet) but many other languages have one (but only one). -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From emil@lysator.liu.se Fri May 2 08:50:02 2003 From: emil@lysator.liu.se (Emil Styrke) Date: Fri May 2 07:50:02 2003 Subject: [Tutor] while statement In-Reply-To: <200305012018.36673.shalehperry@attbi.com> (Sean Perry's message of "Thu, 1 May 2003 20:18:36 -0700") References: <20030501084423.76616.qmail@web13407.mail.yahoo.com> <874r4fdkud.fsf@i110.ryd.student.liu.se> <200305012018.36673.shalehperry@attbi.com> Message-ID: <87el3h601t.fsf@i110.ryd.student.liu.se> Sean 'Shaleh' Perry writes: >> >> Another method is the for loop, it will save you the manual >> incrementing of n: >> >> for n in range(1, N+1): >> do_stuff >> >> range(x, y) creates a list with the integer elements i, where x <= i < y, >> and the for loop will iterate through each element in this list, >> assigning the current element to n. >> > > I personally find this horribly wasteful. xrange() at least generates the > next element when it is needed. You're right. I've never worked with ranges so large that it mattered, but when the difference in code is just one letter, I really should get into the habit of putting it there. /Emil > range(1,100) # builds a 100 item list, ick. > > Sure this is a scripting language, but no need to waste cycles uselessly. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From jeff@ccvcorp.com Fri May 2 14:38:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri May 2 13:38:02 2003 Subject: [Tutor] while statement References: <20030501084423.76616.qmail@web13407.mail.yahoo.com> <874r4fdkud.fsf@i110.ryd.student.liu.se> <200305012018.36673.shalehperry@attbi.com> Message-ID: <3EB2AD87.2070106@ccvcorp.com> Sean 'Shaleh' Perry wrote: >>for n in range(1, N+1): >> do_stuff >> >>range(x, y) creates a list with the integer elements i, where x <= i < y, >>and the for loop will iterate through each element in this list, >>assigning the current element to n. >> > >I personally find this horribly wasteful. xrange() at least generates the >next element when it is needed. > >range(1,100) # builds a 100 item list, ick. > >Sure this is a scripting language, but no need to waste cycles uselessly. > As I understand it, range() and xrange() represent a speed/memory tradeoff. xrange() has a higher setup cost than range() does (at least, for small ranges), so that in common cases range() may represent less cycles. (There are also situations where it's advantageous to have a fully-realized list, as well.) And in most cases, a list of a few hundred items *is* relatively insignificant to build, so worrying about range() vs xrange() strikes me as being premature optimization until we've determined that there's a notable bottleneck. Jeff Shannon Technician/Programmer Credit International From phthenry@earthlink.net Fri May 2 16:57:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Fri May 2 15:57:01 2003 Subject: [Tutor] Re: Entity to UTF-8 In-Reply-To: <0F757892D113D611BD2E0002559C1FF40361B1DE@email.spitech.com> References: <0F757892D113D611BD2E0002559C1FF40361B1DE@email.spitech.com> Message-ID: <20030502155620.C13810@localhost.localdomain> I used your code with great success. I don't know if there is a better way. Thanks. Paul On Fri, May 02, 2003 at 11:10:54AM +0800, Ezequiel, Justin wrote: > > Thanks for your comments Paul. > I appreciate the time you took. > I will have a look at the Archive for something that may help. > > Do you think I am on the right track? > Is there a different approach I could take? > > Full text of my previous mail is at http://www.sps-spitech.com/wap/utf8.txt > > Please ignore the question re Hex to Long > (I found out that the long() function has an optional 2nd argument) -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From dyoo@hkn.eecs.berkeley.edu Fri May 2 17:49:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 2 16:49:02 2003 Subject: [Tutor] terminology about operators and operands In-Reply-To: <5.2.1.1.0.20030502120321.02721ae0@www.thinkware.se> Message-ID: > For "3 + 5", 3 is the left operator, 5 is the right operator and + is > the binary operator. Hi everyone, Minor terminology quibble: instead of using the word 'operator' for the things on the left and right sides of the add, we often use the word "operand". An "operand" is the thing being operated on by our operator, so we should say instead that "3 is the left operand, 5 is the right operand, and + is the binary operator". By the way, in mathematics, the term "binary operator" has a special meaning: it says that the left operand and the right operand have to be of the same type. Furthermore the result of the operation needs to be of the type of the two operands. http://mathworld.wolfram.com/BinaryOperator.html Python, for the most part, follows the mathematical definition of a binary operator. Once we understand the terminology, some of the Python error messages won't seem as mysterious. For example: ### >>> 3 + "4" Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand types for +: 'int' and 'str' ### which says that the '+' operator just doesn't know how to add an integer left operand to the string right operand. The one Python operator that immediately comes to mind which doesn't follow the mathy definition closely is 'string multiplication': ### >>> def printHeader(title): ... print '=' * 42 ... print title ... print '=' * 42 ... >>> printHeader("Hello World!") ========================================== Hello World! ========================================== ### But for the most part, Python's binary operators only work on pairs of things of the same types. > It's called binary operator since it wants two operands. Ok, never mind; you corrected yourself. *grin* > Python has no ternary operator (yet) but many other languages have one > (but only one). Magnus is referring to a feature that's being argued on the comp.lang.python list, the "If-then-else expression" Python Enhancement Proposal: http://www.python.org/peps/pep-0308.html Talk to you later! From magnus@thinkware.se Fri May 2 21:57:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 2 20:57:01 2003 Subject: [Tutor] terminology about operators and operands In-Reply-To: References: <5.2.1.1.0.20030502120321.02721ae0@www.thinkware.se> Message-ID: <5.2.1.1.0.20030503025324.02721ae0@www.thinkware.se> At 13:48 2003-05-02 -0700, Danny Yoo wrote: >Minor terminology quibble: instead of using the word 'operator' for the >things on the left and right sides of the add, we often use the word >"operand". Silly me. I should stop writing mails when I'm really all too tired (like right now). Apologies to all, and thanks to Danny for setting me straight in a polite way as usual. It's not a minor terminology quibble, I was inadvertantly confusing people by using obviously wrong words. Oh well, back to slumber mode... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From beyondthezero@earthlink.net Fri May 2 23:48:02 2003 From: beyondthezero@earthlink.net (Peter Jakubowicz) Date: Fri May 2 22:48:02 2003 Subject: [Tutor] nested "for" loops In-Reply-To: Message-ID: <5.2.1.1.1.20030502193811.00b2bb50@earthlink.net> Hi, I've been slogging along learning Python for a while now. Nested "for" loops confuse me (I have trouble trying to run through them in my head). For example, does the following code generate (albeit redundantly) all Pythagorean triples up to 20: i.e., all integers less than or equal to 20 for which i * i + j * j == k * k TIA, Peter for i in range(1, 21): for j in range(1, 21): for k in range(1, 21): if (i * i) + (j * j) == (k * k): print "Pythagorean triple: %d, %d, %d" % (i, j, k) From bgailer@alum.rpi.edu Sat May 3 00:43:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Fri May 2 23:43:02 2003 Subject: [Tutor] nested "for" loops In-Reply-To: <5.2.1.1.1.20030502193811.00b2bb50@earthlink.net> References: Message-ID: <5.2.0.9.0.20030502213210.0301c9c8@66.28.54.253> --=======39571A28======= Content-Type: text/plain; x-avg-checked=avg-ok-25011F82; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 07:43 PM 5/2/2003 -0700, Peter Jakubowicz wrote: >Hi, > >I've been slogging along learning Python for a while now. Nested "for" >loops confuse me (I have trouble trying to run through them in my head). >For example, does the following code generate (albeit redundantly) all >Pythagorean triples up to 20: i.e., all integers less than or equal to 20 >for which i * i + j * j == k * k > >TIA, >Peter > > > >for i in range(1, 21): > for j in range(1, 21): > for k in range(1, 21): > if (i * i) + (j * j) == (k * k): > print "Pythagorean triple: %d, %d, %d" % (i, j, k) Did you run the program? Did it deliver the desired results? There's your answer. Is that what you wanted to know? Or are you needing a way to comprehend nested loops? BTW it's a good idea to anticipate performance and maintenance issues, especially if you wanted to expand this to a higher limit. Suggestion - move the calculation of i*i and j*j out of the inner loop. Right now these calculations are unnecessarily repeated. Also make the limit a variable whose value you set once. Then it's a lot easier to change the limit. Also to eliminate duplications start each inner loop with the current value of the next higher loop. limit = 21 for i in range(1, limit ): iSq = i*i for j in range(i, limit ): jSq = j*j for k in range(j, limit ): if iSq+ jSq == (k * k): print "Pythagorean triple: %d, %d, %d" % (i, j, k) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======39571A28======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-25011F82 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003 --=======39571A28=======-- From beyondthezero@earthlink.net Sat May 3 00:59:07 2003 From: beyondthezero@earthlink.net (Peter Jakubowicz) Date: Fri May 2 23:59:07 2003 Subject: [Tutor] nested "for" loops In-Reply-To: <5.2.0.9.0.20030502213210.0301c9c8@66.28.54.253> References: <5.2.1.1.1.20030502193811.00b2bb50@earthlink.net> Message-ID: <5.2.1.1.1.20030502205317.00b2aac0@earthlink.net> At 09:42 PM 5/2/2003 -0600, you wrote: >At 07:43 PM 5/2/2003 -0700, Peter Jakubowicz wrote: > >>Hi, >> >>I've been slogging along learning Python for a while now. Nested "for" >>loops confuse me (I have trouble trying to run through them in my head). >>For example, does the following code generate (albeit redundantly) all >>Pythagorean triples up to 20: i.e., all integers less than or equal to 20 >>for which i * i + j * j == k * k >> >>TIA, >>Peter >> >> >> >>for i in range(1, 21): >> for j in range(1, 21): >> for k in range(1, 21): >> if (i * i) + (j * j) == (k * k): >> print "Pythagorean triple: %d, %d, %d" % (i, j, k) > >Did you run the program? Did it deliver the desired results? There's your >answer. Is that what you wanted to know? Or are you needing a way to >comprehend nested loops? Thanks. Yes, I did run the program, which is what made me wonder is the results were correct; I am trying to understand how nested loops work. I get a list of triplets, but I was wondering how I could be sure that I'd covered all of the possible combinations. I don't have a mental picture of how or if this code runs through all the combinations of integers through 20 and outputs all possible correct answers. From am@fx.ro Sat May 3 02:57:01 2003 From: am@fx.ro (Adrian Maier) Date: Sat May 3 01:57:01 2003 Subject: [Tutor] nested "for" loops In-Reply-To: <5.2.1.1.1.20030502205317.00b2aac0@earthlink.net>; from beyondthezero@earthlink.net on Fri, May 02, 2003 at 08:58:13PM -0700 References: <5.2.1.1.1.20030502193811.00b2bb50@earthlink.net> <5.2.0.9.0.20030502213210.0301c9c8@66.28.54.253> <5.2.1.1.1.20030502205317.00b2aac0@earthlink.net> Message-ID: <20030503082356.A344@coto> Peter Jakubowicz (beyondthezero@earthlink.net) a scris : > >>for i in range(1, 21): > >> for j in range(1, 21): > >> for k in range(1, 21): > >> if (i * i) + (j * j) == (k * k): > >> print "Pythagorean triple: %d, %d, %d" % (i, j, k) > Thanks. Yes, I did run the program, which is what made me wonder is the > results were correct; I am trying to understand how nested loops work. I > get a list of triplets, but I was wondering how I could be sure that I'd > covered all of the possible combinations. I don't have a mental picture of > how or if this code runs through all the combinations of integers through > 20 and outputs all possible correct answers. You could also try the following program. I've inserted a few "spies" (the print commands) which will show you how does the program run: max_number=3 for i in range(1, max_number): print "i=",i for j in range(1, max_number): print " j=",j for k in range(1, max_number): print " k=",k print " checking if %d*%d + %d*%d = %d*%d"% (i, i, j, j, k, k) if (i * i) + (j * j) == (k * k): print " Pythagorean triple: %d, %d, %d" % (i, j, k) Program output: i=1 j= 1 k= 1 checking if 1*1 + 1*1 = 1*1 k= 2 checking if 1*1 + 1*1 = 2*2 j= 2 k= 1 checking if 1*1 + 2*2 = 1*1 k= 2 checking if 1*1 + 2*2 = 2*2 i=2 j= 1 k= 1 checking if 2*2 + 1*1 = 1*1 k= 2 checking if 2*2 + 1*1 = 2*2 j= 2 k= 1 checking if 2*2 + 2*2 = 1*1 k= 2 checking if 2*2 + 2*2 = 2*2 If you set max_number to 21, you'll see for yourself that the program tries all the (i,j,k) combinations. I hope this helps. -- Adrian Maier (am@fx.ro) From pan@uchicago.edu Sat May 3 05:37:02 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Sat May 3 04:37:02 2003 Subject: [Tutor] nested "for" loops In-Reply-To: <20030502160006.19904.16748.Mailman@mail.python.org> References: <20030502160006.19904.16748.Mailman@mail.python.org> Message-ID: <1051950994.3eb37f92a0d1a@webmail-b.uchicago.edu> Peter, >for i in range(1, 21): > for j in range(1, 21): > for k in range(1, 21): > if (i * i) + (j * j) == (k * k): > print "Pythagorean triple: %d, %d, %d" % (i, j, k) For this sort of operation, you might wanna learn a little bit of the 'list comprehension'... First of all lets do some tests: >>> [x for x in range(1,4)] # build a list using list comprehension [1, 2, 3] >>> [x*x for x in range(1,4)] # another one [1, 4, 9] The following is more interesting. You can get ALL the possible 'cross-pairs' between two lists using just one liner: >>> [(x,y) for x in range(1,4) for y in range(1,4)] [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)] More: >>> [(x*x,y*y) for x in range(1,4) for y in range(1,4)] [(1, 1), (1, 4), (1, 9), (4, 1), (4, 4), (4, 9), (9, 1), (9, 4), (9, 9)] Now add some conditional check: >>> [(x*x,y*y) for x in range(1,4) for y in range(1,4) if y*y == 9] [(1, 9), (4, 9), (9, 9)] Now get the square sums instead: >>> [x*x+y*y for x in range(1,4) for y in range(1,4) if y*y == 9] [10, 13, 18] So, we are getting close to your question, which can actually be solved in one line: >>> [(x,y, x*x+y*y) \ .. for x in range(1,21) \ .. for y in range(1,21) \ .. if (x*x+y*y) in [z*z for z in range(1,21)]] [(3, 4, 25), (4, 3, 25), (5, 12, 169), (6, 8, 100), (8, 6, 100), (8, 15, 289), (9, 12, 225), (12, 5, 169), (12, 9, 225), (12, 16, 400), (15, 8, 289), (16, 12, 400)] >>> It must be harder to comprehend at first, but after you get yourself familiar with this type of functional programming, the coding life will be much easier. Besides, the list comprehension is MUCH faster than the for loops. Comparing the following two functions: ================================== [A] list comprehension >>> def lc(count): .. rang = range(1,count+1) .. sq = [x*x for x in rang] .. return [(x,y, x*x+y*y) for x in rang for y in rang if (x*x+y*y) in sq] .. >>> lc(5) [(3, 4, 25), (4, 3, 25)] >>> lc(10) [(3, 4, 25), (4, 3, 25), (6, 8, 100), (8, 6, 100)] ================================== [B] for loops >>> def fl(count): .. rang=range(1, count+1) .. t = [] .. for i in rang: .. for j in rang: .. for k in rang: .. if i*i+j*j==k*k: .. t.append((i,j,k*k)) .. return t .. >>> fl(5) [(3, 4, 25), (4, 3, 25)] >>> fl(10) [(3, 4, 25), (4, 3, 25), (6, 8, 100), (8, 6, 100)] ================================== Using the built-in module 'profile' to test their speeds (thx to Magnus and Danny for demonstrating its usage so I can show it here): >>> profile.run('lc(20)') 3 function calls in 0.003 CPU seconds >>> profile.run('fl(20)') 3 function calls in 0.018 CPU seconds In your example (count=20) the for-loop function is 6 times slower than the list-comprehension. If the count is larger: >>> profile.run('lc(500)') 3 function calls in 21.986 CPU seconds >>> profile.run('fl(500)') 3 function calls in 268.913 CPU seconds See the for-loop approach is at least 10 times slower, which feels like forever in my computer. pan From rmangaliag@slu.edu.ph Sat May 3 06:43:01 2003 From: rmangaliag@slu.edu.ph (ali mangaliag) Date: Sat May 3 05:43:01 2003 Subject: [Tutor] learning python with a book... References: <000c01c30e8c$43f8e060$3f1ea8c0@slu.edu.ph> <3EAE4167.000011.03688@siahaan> Message-ID: <001c01c31159$57c20340$3f1ea8c0@slu.edu.ph> This is a multi-part message in MIME format. ------=_NextPart_000_0019_01C3119C.653442C0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable will i learn python just by reading web documents??? do i really need a python book?? can i be a proficient python programmer without reading any python = book?? i live in a not so "urban" land.... :) ... can't find any python book = here..... :) ------=_NextPart_000_0019_01C3119C.653442C0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
will i learn = python just by=20 reading web documents???
do i=20 really need a python book??
 
can i=20 be a proficient python programmer without reading any python=20 book??
 
i live=20 in a not so "urban" land.... :) ... can't find any python book here..... = :)
------=_NextPart_000_0019_01C3119C.653442C0-- From magnus@thinkware.se Sat May 3 07:43:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 3 06:43:01 2003 Subject: [Tutor] learning python with a book... In-Reply-To: <001c01c31159$57c20340$3f1ea8c0@slu.edu.ph> References: <000c01c30e8c$43f8e060$3f1ea8c0@slu.edu.ph> <3EAE4167.000011.03688@siahaan> Message-ID: <5.2.1.1.0.20030503122256.02704390@www.thinkware.se> At 17:49 2003-05-03 +0800, ali mangaliag wrote: >will i learn python just by reading web documents??? You make it sound like it would happen automatically. You might learn python if you put your mind into it. You need a computer and python itself. Web access helps, but it's mainly the work you put into actaully trying to write code and to understand code written by others that matters. >do i really need a python book?? No. There are good books that make it easier to grasp some concepts, and others that work as handy references, but there are no "secrets" in any printed books that you can't find in a web document or through asking questions on a mailing list or news group. >can i be a proficient python programmer without reading any python book?? Certainly. >i live in a not so "urban" land.... :) ... can't find any python book >here..... :) I would imagine that most internet book shops can deliver books to the Philippines, I don't know if I ever saw a Python book in a book store around here either. But sure, while it might help with printed books, it's all really a matter of putting some work into it. The documentation included with Python, such as the tutorial and the library reference, and resources such as this mailing list can be very useful. The python distribution itself also includes a lot of source code, although trying to learn from studying that is probably a bit intimidating for a beginner. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From reavey@nep.net Sat May 3 10:32:02 2003 From: reavey@nep.net (reavey) Date: Sat May 3 09:32:02 2003 Subject: [Tutor] [Fwd: distutils and path] Message-ID: <3EB3C3C7.6050701@nep.net> -------- Original Message -------- Subject: distutils and path Date: Sat, 03 May 2003 07:51:48 -0400 From: reavey To: Richard Jones References: <20030502232436.86817.qmail@web10507.mail.yahoo.com> <3EB30D20.3050202@nep.net> <200305031048.01063.richardjones@optushome.com.au> Hi I loaded python 2.2.2 from source and now am having problems setting up my path to the modules. An env command at a shell prompt shows no $PYTHONHOME. I don't understand what the message below, "Consider setting $PYTHONHOME to ..." I can execute the interpreter and import modules like os in user mode only superuser creates errors that the module library is not there. user $python python 2.2.2. ... >>>path.os [root@localhost pub1.0a1]# python setup.py install Could not find platform independent libraries Could not find platform dependent libraries Consider setting $PYTHONHOME to [:] #this is where I need help 'import site' failed; use -v for traceback Traceback (most recent call last): File "setup.py", line 1, in ? from distutils.core import setup ImportError: No module named distutils.core TIA re-v From shalehperry@attbi.com Sat May 3 13:32:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sat May 3 12:32:02 2003 Subject: [Tutor] while statement In-Reply-To: <3EB2AD87.2070106@ccvcorp.com> References: <20030501084423.76616.qmail@web13407.mail.yahoo.com> <200305012018.36673.shalehperry@attbi.com> <3EB2AD87.2070106@ccvcorp.com> Message-ID: <200305030931.19754.shalehperry@attbi.com> > > As I understand it, range() and xrange() represent a speed/memory > tradeoff. xrange() has a higher setup cost than range() does (at least, > for small ranges), so that in common cases range() may represent less > cycles. (There are also situations where it's advantageous to have a > fully-realized list, as well.) And in most cases, a list of a few > hundred items *is* relatively insignificant to build, so worrying about > range() vs xrange() strikes me as being premature optimization until > we've determined that there's a notable bottleneck. > absolutely. I tend to avoid solutions using range() altogether (as my initial post to this thread did) unless I need the list for some reason. At least if I have any concern about the performance, which is not always true. You don't always care. From charlie@begeistert.org Sat May 3 18:04:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sat May 3 17:04:02 2003 Subject: [Tutor] Re: Operators In-Reply-To: <20030503160005.11990.32696.Mailman@mail.python.org> References: <20030503160005.11990.32696.Mailman@mail.python.org> Message-ID: <20030503230250.4072.4@wonderland.1051977784.fake> On 2003-05-03 at 18:00:05 [+0200], tutor-request@python.org wrote: > > Magnus is referring to a feature that's being argued on the > comp.lang.python list, the "If-then-else expression" Python Enhancement > Proposal: > > http://www.python.org/peps/pep-0308.html eek! I've just read the proposal. How do we stop this nonsense? I vote against it! You can write if x: y(); else: z() in one line already and I for one can't see any functional difference between this kind of statement and the proposed "ternary operator" and this looks like a very special case to me. But maybe I'm missing something? Can the gurus enlighten me? Charlie From magnus@thinkware.se Sat May 3 21:37:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 3 20:37:02 2003 Subject: [Tutor] Re: Operators In-Reply-To: <20030503230250.4072.4@wonderland.1051977784.fake> References: <20030503160005.11990.32696.Mailman@mail.python.org> <20030503160005.11990.32696.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030504020917.02721c28@www.thinkware.se> At 23:02 2003-05-03 +0200, Charlie Clark wrote: >eek! I've just read the proposal. How do we stop this nonsense? I vote >against it! Too late. The vote was a long time ago. It wasn't very conclusive though. >You can write >if x: y(); else: z() >in one line already and I for one can't see any functional difference >between this kind of statement and the proposed "ternary operator" and this >looks like a very special case to me. > >But maybe I'm missing something? Can the gurus enlighten me? The current "if x: y(); else: z()" is a statement. In Python, a statement is not an expression (which is why we get a blessed error message if we type "if a=b:" instead of "if a==b:"). The proposed conditional operatator *is* an expression, not a statement, so you could do something like: daysOfFebruary = if isLeapYear(year): 29 else: 28 I.e. you want to be able to write if isLeapYear(year): daysOfFebruary = 29 else: daysOfFebruary = 28 in a single line. In C, this is written "daysOfFebruary = isLeapYear(year)?29:28;" There are certainly situations where you have many conditionals in the middle of large expressions in C programs, and it would grow much bigger if you didn't have ?: there. Today, the typical Python way of doing this is: daysOfFebruary = isLeapYear(year) and 29 or 28 or more generically x = c and a or b The thing is that "A and B" will return "B" if "A" is true and "A" if A is false: >>> print None and 1 None >>> print 0 and 1 0 >>> print 1 and 2 2 >>> print 1 and None None In the case of "c and a or b", b won't even be evaluated if "c and a" is true. Note that b might be a function call with side effects. If "c and a" evaluates to false, "b" will be evaluated, and its result will be returned. Try it out! The problem is that this will fail if "a" evaluates as false, e.g. taxRate = shouldGetReducedTaxes(person) and lowRate or highRate will allways set taxRate to highRate if the lowRate is 0. In his particular case, you could do taxRate = [highRate, lowRate][shouldGetReducedTaxes(person)] or taxRate = {1:lowRate, 0:highRate}[shouldGetReducedTaxes(person)] instead. Using a list or a dict like this is oftem better, but you can't always to that. Instead of x = c and a() or b() you could do x = [b, a][c]() but how do you do x = c and a(p1) or b(p2, p3) in one line so that a(p1) can return 0 or None, and b will still not get called if c was true? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From neh@attbi.com Sat May 3 21:56:02 2003 From: neh@attbi.com (Neil Hodge) Date: Sat May 3 20:56:02 2003 Subject: [Tutor] distutils questions Message-ID: <1052009669.32194.159.camel@zeus.localdomain> All: I have a few questions about distutils: * It is implied in the docs that the directory setup when creating the install needs to be just as it will be after the install (i.e., something like /usr/share/packagename). Is this correct? * Is there some utility in distutils (or command in python in general) to test whether a certain function is available in a certain module? * Is distutils even the "best" (or even a reasonable) way to distribute free-standing applications (as opposed to modules that are specifically meant to be imported into scripts)? Thanks. Neil From hemanexp@yahoo.com Sun May 4 04:22:01 2003 From: hemanexp@yahoo.com (perl lover) Date: Sun May 4 03:22:01 2003 Subject: [Tutor] Setting & validating dialog box entries Message-ID: <20030504072106.87915.qmail@web41703.mail.yahoo.com> hi, i am using tkSimpleDialog box to display employee name and number. I want my entry box should contain some intial values set in "body" routine while loading the dialog box. Which fuction is used to set a value for entry widget? Moreover how can i ensure my entry widget contains proper values? That means name box should not allow numbers and salary box should not contain string. As soon as i type an invalid character ( a number in name box) i expect an message box to be poped out stating the error instead of displaying the messagebox after pressing "Ok". How can i get a messagebox as soon as the condition is violated? My program is given below. from Tkinter import * import tkMessageBox import tkSimpleDialog import string root = Tk() Button(root, width=10, height=10).pack() class MyDialog(tkSimpleDialog.Dialog): def body(self, master): Label(master, text="First:").grid(row=0) Label(master, text="Second:").grid(row=1) self.empname = Entry(master) self.eno = Entry(master) self.empname.grid(row=0, column=1) self.eno.grid(row=1, column=1) # Here i want to set values for entry widgets #self.empname.configure(textvariable = "suresh") def validate(self): try: name= string(self.empname.get()) eno = string.atoi(self.en.get()) self.result = name, eno return 1 except ValueError: tkMessageBox.showwarning("Bad input", "Illegal values, please try again") return 0 def apply(self): name = string.atoi(self.empname.get()) eno = string.atoi(self.eno.get()) print name, eno # or something MyDialog(root) root.mainloop() __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From magnus@thinkware.se Sun May 4 08:39:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun May 4 07:39:02 2003 Subject: [Tutor] distutils questions In-Reply-To: <1052009669.32194.159.camel@zeus.localdomain> Message-ID: <5.2.1.1.0.20030504133537.0270c058@www.thinkware.se> At 17:54 2003-05-03 -0700, Neil Hodge wrote: >* Is distutils even the "best" (or even a reasonable) way to distribute >free-standing applications (as opposed to modules that are specifically >meant to be imported into scripts)? I think you need context to answer this question. What OS? More than one? What kind of users? Do they in general use Python? Do you expect Python to be installed already on the machine? Do you plan to use an already existing Python install, or would you prefer to make a separate (more or less complete) python install for your program if they already have python on the box? Is this to be installed by a system operator or by an end user? Do you want a binary thinge like you can get with py2exe or the McMillan installer? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From neh@attbi.com Sun May 4 10:45:02 2003 From: neh@attbi.com (Neil Hodge) Date: Sun May 4 09:45:02 2003 Subject: [Tutor] distutils questions In-Reply-To: <5.2.1.1.0.20030504133537.0270c058@www.thinkware.se> References: <5.2.1.1.0.20030504133537.0270c058@www.thinkware.se> Message-ID: <1052055850.11942.11.camel@zeus.localdomain> Magnus: On Sun, 2003-05-04 at 04:39, Magnus LyckÃ¥ wrote: > At 17:54 2003-05-03 -0700, Neil Hodge wrote: > >* Is distutils even the "best" (or even a reasonable) way to distribute > >free-standing applications (as opposed to modules that are specifically > >meant to be imported into scripts)? > > I think you need context to answer this question. > > What OS? More than one? > Nope: linux only. > What kind of users? Do they in general use Python? Varies: power to newbies. In general, they do not use python directly, but most of them can do installs, upgrades, know other programming languages, etc. > Do > you expect Python to be installed already on the machine? Typically yes. > Do you plan to use an already existing Python install, or > would you prefer to make a separate (more or less complete) > python install for your program if they already have python > on the box? > Current python install, but they will need to compile and reinstall one extra-python module (pygtk). > Is this to be installed by a system operator or by an end user? > End user. > Do you want a binary thinge like you can get with py2exe > or the McMillan installer? > I would typically prefer to distribute source. If I were to set up a binary install, I would include all of the sources. Neil From reavey@nep.net Sun May 4 14:28:01 2003 From: reavey@nep.net (reavey) Date: Sun May 4 13:28:01 2003 Subject: [Tutor] can't locate module library Message-ID: <3EB54CAE.4060706@nep.net> hi [dad@localhost dad]$ python 'import site' failed; use -v for traceback Python 2.2.2 (#1, May 4 2003, 09:33:03) [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> [dad@localhost dad]$ echo $PYTHONHOME /usr/local/lib/python2.2 [dad@localhost dad]$[dad@localhost dad]$ /usr/local/bin/python 'import site' failed; use -v for traceback Python 2.2.2 (#1, May 4 2003, 09:33:03) [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os Traceback (most recent call last): File "", line 1, in ? ImportError: No module named os What do I need to do to get to the module libraries? TIA re-v From magnus@thinkware.se Sun May 4 17:29:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun May 4 16:29:02 2003 Subject: [Tutor] can't locate module library In-Reply-To: <3EB54CAE.4060706@nep.net> Message-ID: <5.2.1.1.0.20030504221914.02687e68@www.thinkware.se> At 13:23 2003-05-04 -0400, reavey wrote: >[dad@localhost dad]$ echo $PYTHONHOME >/usr/local/lib/python2.2 I don't have $PYTHONHOME set at all in my Mandrake. No need it seems. >[dad@localhost dad]$[dad@localhost dad]$ /usr/local/bin/python >'import site' failed; use -v for traceback >Python 2.2.2 (#1, May 4 2003, 09:33:03) >[GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. > >>> import os There is something wrong with your Python installation. Why don't you use the normal Mandrake Python RPM? You don't have that as well, do you? That would install in another location. Try "rpm -qa | grep -i python" or have a look at /bin/python or look for python directories in /usr/lib/ -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From reavey@nep.net Sun May 4 18:10:02 2003 From: reavey@nep.net (reavey) Date: Sun May 4 17:10:02 2003 Subject: [Tutor] can't locate module library References: <5.2.1.1.0.20030504221914.02687e68@www.thinkware.se> Message-ID: <3EB58085.2000906@nep.net> This is a multi-part message in MIME format. --------------080707010202080306020601 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable X-MIME-Autoconverted: from 8bit to quoted-printable by mail.nep.net id RAA38130 Hi Yes, I had python 2.2 running using RPMs. The python rpm version used on=20 mandrake 8.2 is 2.2 I needed to load 2.2.1 to run a pygame program qct . QCT would not=20 install because it uses "true": not supported in 2.2 After I loaded 2.2.2 from source I ran into problems. I ditched all my=20 2.2 using the mandrake software package manager and the problem remained. I decided to try something I know works --install pub When I tried to install the python universe builder(pub) the error=20 message below threw me a curve. PUB uses distutils and the error message said > [root@localhost pub1.0a1]# python setup.py install > Could not find platform independent libraries Could not find platform=20 > dependent libraries Consider setting $PYTHONHOME to=20 > [:] #this is where I need help > 'import site' failed; use -v for traceback > Traceback (most recent call last): > File "setup.py", line 1, in ? > from distutils.core import setup > ImportError: No module named distutils.core I've been stuck for a couple of days trying to find out what the error=20 message, "Consider setting $PYTHONHOME to [:]", means. Turns out the answer is to set the $PYTHONPATH env variable in .bashrc To make a long story short, it's been a great weekend. thanks re-v Magnus Lyck=E5 wrote: > At 13:23 2003-05-04 -0400, reavey wrote: > >> [dad@localhost dad]$ echo $PYTHONHOME >> /usr/local/lib/python2.2 > > > I don't have $PYTHONHOME set at all in my Mandrake. > No need it seems. > >> [dad@localhost dad]$[dad@localhost dad]$ /usr/local/bin/python >> 'import site' failed; use -v for traceback >> Python 2.2.2 (#1, May 4 2003, 09:33:03) >> [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import os > > > There is something wrong with your Python installation. > > Why don't you use the normal Mandrake Python RPM? > > You don't have that as well, do you? That would install in > another location. Try "rpm -qa | grep -i python" or have > a look at /bin/python or look for python directories in /usr/lib/ > > > --=20 > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The shortest path from thought to working program > --------------080707010202080306020601 Content-Type: application/x-java-vm; name=".bashrc" Content-Disposition: inline; filename=".bashrc" Content-Transfer-Encoding: base64 IyAuYmFzaHJjCgojIFVzZXIgc3BlY2lmaWMgYWxpYXNlcyBhbmQgZnVuY3Rpb25zCgojIFNv dXJjZSBnbG9iYWwgZGVmaW5pdGlvbnMKUFlUSE9OSE9NRT0iL3Vzci9sb2NhbC9saWIvcHl0 aG9uMi4yIgpQWVRIT05QQVRIPS91c3IvbG9jYWwvbGliL3B5dGhvbjIuMgpleHBvcnQgUFlU SE9OSE9NRSBQWVRIT05QQVRICmlmIFsgLWYgL2V0Yy9iYXNocmMgXTsgdGhlbgoJLiAvZXRj L2Jhc2hyYwpmaQo= --------------080707010202080306020601-- From dyoo@hkn.eecs.berkeley.edu Sun May 4 20:03:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun May 4 19:03:02 2003 Subject: [Tutor] An interesting web site for those who want to program adventure games Message-ID: Hi everyone, I just ran into the following link; it's a tutorial on writing adventure games (circa 1983): http://www.atariarchives.org/adventure Would anyone be interested in "porting" the examples over from BASIC to Python? It might make a fun project for us here on Tutor; a few of us appear to have been exposed to Basic in our past lives... *grin* Any takers? For example, in Chapter 4, the following bit of code: ### BASIC code 10 DIM A(5,4) 20 FOR B = 1 TO 5 30 FOR C = 1 TO 4 40 READ A(B,C) 50 NEXT C 60 NEXT B 70 DATA 0,2,3,0 80 DATA 1,0,5,0 90 DATA 0,4,0,1 100 DATA 3,5,0,0 110 DATA 4,0,0,2 ### in BASIC defines an 5x4 array called 'A' to hold information about how to move around in this adventure room. In essence, it's defining the map of our world. We can do a port of this in Python: ### """A defines the exits from each room [N, S, E, W]. """ A = [ [0, 2, 3, 0], ## Room 1 [1, 0, 5, 0], ## Room 2 [0, 4, 0, 1], ## Room 3 [3, 5, 0, 0], ## Room 4 [4, 0, 0, 2] ## Room 5 ] ### Say that we're in room 5. Then we can do a lookup into our 'A' list to see what exits are available to us: n_room, s_room, e_room, w_room = A[4] ... but this may need some adjustment here to make things work conveniently, since in Basic, arrays were indexed starting from 1, but in Python, we start doing counting from 0. Without some adjustments, we will end up having to do error-prone conversions between 0-indexing and 1-indexing in our head. To clarify the problem, if we want to move north from room 5, we end up doing things like: current_location = 5 ## We're in room 5 n_room, s_room, e_room, w_room = A[current_location-1] current_location = n_room ## We move north... and that second statement, doing a subtraction of our current_location, just looks a bit odd: it's there because the room numbers start from 1, but our Python arrays start counting from 0, so we do the decrement to compensate. But it's messy. We can fix this. If we add an extra "sentinel room", the code ends up looking nicer. That is, if we have: ### A = [ [0, 0, 0, 0] ## Sentinel room --- no such room exists [0, 2, 3, 0] ## Room 1 [1, 0, 5, 0], ## Room 2 [0, 4, 0, 1], ## Room 3 [3, 5, 0, 0], ## Room 4 [4, 0, 0, 2] ## Room 5 ] ### Then with the addition of that magical sentinel room, A[5] now really does refer to Room 5, and we don't need to do anything tricky to jump from one room to another: current_location = 5 ## We're in room 5 n_room, s_room, e_room, w_room = A[current_location] current_location = n_room ## We move north... Talk to you later! From R. Alan Monroe" References: Message-ID: <491560996764.20030504203736@columbus.rr.com> > ... but this may need some adjustment here to make things work > conveniently, since in Basic, arrays were indexed starting from 1, but in > Python, we start doing counting from 0. Without some adjustments, we will > end up having to do error-prone conversions between 0-indexing and > 1-indexing in our head. Can you do it using 0-based arrays, and putting "None" for the non-exits? That seems more pythonic. Alan From zak@harlekin-maus.com Mon May 5 00:05:02 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Sun May 4 23:05:02 2003 Subject: [Tutor] An interesting web site for those who want to program adventure games In-Reply-To: References: Message-ID: <3033.4.62.178.63.1052103883.squirrel@mail.harlekin-maus.com> > I just ran into the following link; it's a tutorial on writing adventure > games (circa 1983): > > http://www.atariarchives.org/adventure > > Would anyone be interested in "porting" the examples over from BASIC to > Python? It might make a fun project for us here on Tutor; a few of us > appear to have been exposed to Basic in our past lives... *grin* Any > takers? Man, that's a blast! The great thing is, we're no longer restrained by memory, so we could even convert the rooms to lists: caveRoom = Room () room.exits = {'east':hallwayThree, 'west':guardRoom, 'north':'Your way is blocked by a brick wall.'} That would be a pretty major restructuring of the BASIC code, though. :) -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From wolf_binary@hotmail.com Mon May 5 00:24:01 2003 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Sun May 4 23:24:01 2003 Subject: [Tutor] (no subject) Message-ID: Hi all, How are search engines created for example google or the word searches in a help index? thanks, Cameron _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From jjhegde@ncst.ernet.in Mon May 5 01:20:02 2003 From: jjhegde@ncst.ernet.in (Jayprasad J. Hegde) Date: Mon May 5 00:20:02 2003 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <20030505041531.GA2271@konark.ncst.ernet.in> Hello Cameron, On Sun, May 04, 2003 at 10:23:02PM -0500, Cameron Stoner wrote: > How are search engines created for example google or the word searches in a > help index? This is quite a general question and I am not sure how this is connected with learning more about Python. Anyway, here's something for you... Creating Search Engines belongs to an area called as Information Retrieval. Creating search engines cannot be summarized here. However, in case you are interested you can read up more on it in books like "Modern Information Retrieval" by Baeza-Yates for a more contemporary outlook, or "Information Retrieval: Data Structures and Algorithms" by the same author, for a more practical one. The theory and practice of creating indexes is a subfield under Information Retrieval and I think, this is what you are looking out for. Indices are data structures which allow for faster query handling. You can read about this in the books mentioned above and learn more about popular indexing approaches like Inverted Indices, Suffix Trees, Signature files, etc. -- or you can read up more about this by searching on Google; there's plenty of stuff available online. Hope this helps. Regards, - JJH -- Power corrupts. Absolute power is kind of neat. -- John Lehman, Secretary of the Navy, 1981-1987 [ Jayprasad J. Hegde, Staff Scientist, KBCS Division, National Centre for Software Technology, Juhu, Mumbai 400049, India. Tel:+91-22-26201606x373 ] From hemanexp@yahoo.com Mon May 5 02:12:01 2003 From: hemanexp@yahoo.com (Python-lover) Date: Mon May 5 01:12:01 2003 Subject: [Tutor] Dialogbox issues............................ Message-ID: <20030505051052.6137.qmail@web41706.mail.yahoo.com> hi, I am using python1.5 and Tkinter. I want to display the dialog box when i click the button in my main window. I used tkSimpleDialogBox class. But the following program is not working as it is expected. How can i diaplay a dialog box in Tkinter? Let me know where i gone wrong. from Tkinter import * import tkMessageBox import tkSimpleDialog import string class App: def __init__(self,parent): self.myparent = parent Button(self.myparent,text="Click",width=10, height=10,command=self.showdlg).pack() def showdlg(self): MyDialog(self) #Dialogbox class class MyDialog(tkSimpleDialog.Dialog): def body(self, master): Label(master, text="First:").grid(row=0) Label(master, text="Second:").grid(row=1) self.e1 = Entry(master) self.e2 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) self.e1.insert(0,"suressh") self.e2.insert(0,1234) def validate(self): try: first= (self.e1.get()) second = string.atoi(self.e2.get()) self.result = first, second return 1 except ValueError: tkMessageBox.showwarning("Bad input", "Illegal values, please try again") return 0 def apply(self): first = (self.e1.get()) second = string.atoi(self.e2.get()) print first, second root = Tk() myapp = App(root) root.mainloop() Thanx __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From bkelly@sourcereview.net Mon May 5 02:28:02 2003 From: bkelly@sourcereview.net (Brett Kelly) Date: Mon May 5 01:28:02 2003 Subject: [Tutor] Dialogbox issues............................ In-Reply-To: <20030505051052.6137.qmail@web41706.mail.yahoo.com> References: <20030505051052.6137.qmail@web41706.mail.yahoo.com> Message-ID: <20030505052707.GB30161@inkedmn.homelinux.org> --nVMJ2NtxeReIH9PS Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Any reason you're using python 1.5 instead of 2.2? On Sun, May 04, 2003 at 10:10:52PM -0700, Python-lover wrote: > hi, > I am using python1.5 and Tkinter. I want to > display the dialog box when i click the button in my > main window. I used tkSimpleDialogBox class. But the > following program is not working as it is expected. > How can i diaplay a dialog box in Tkinter? Let me > know where i gone wrong. >=20 > =09 > from Tkinter import * > import tkMessageBox > import tkSimpleDialog > import string >=20 > class App: > def __init__(self,parent): > self.myparent =3D parent > Button(self.myparent,text=3D"Click",width=3D10, > height=3D10,command=3Dself.showdlg).pack() >=20 > def showdlg(self): > MyDialog(self) >=20 > #Dialogbox class > class MyDialog(tkSimpleDialog.Dialog): >=20 > def body(self, master): > Label(master, text=3D"First:").grid(row=3D0) > Label(master, text=3D"Second:").grid(row=3D1) > self.e1 =3D Entry(master) > self.e2 =3D Entry(master) > self.e1.grid(row=3D0, column=3D1) > self.e2.grid(row=3D1, column=3D1) > self.e1.insert(0,"suressh") > self.e2.insert(0,1234) >=20 > def validate(self): > try: > first=3D (self.e1.get()) > second =3D string.atoi(self.e2.get()) > self.result =3D first, second > return 1 > except ValueError: > tkMessageBox.showwarning("Bad input", > "Illegal values, please try again") > return 0 >=20 > def apply(self): > first =3D (self.e1.get()) > second =3D string.atoi(self.e2.get()) > print first, second >=20 > root =3D Tk() > myapp =3D App(root) > root.mainloop() >=20 > Thanx >=20 > __________________________________ > Do you Yahoo!? > The New Yahoo! Search - Faster. Easier. Bingo. > http://search.yahoo.com >=20 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor --=20 Brett Kelly bkelly@sourcereview.net This message was created using the Mutt mail agent and=20 digitally signed using GnuPG. --nVMJ2NtxeReIH9PS Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQE+tfYra7gYa9SI8SoRAgvyAKCYyvkG4Qxg0T20owhHE9bZYDl7ygCfSnDg mmMuwOqVw5YNIsYmYavU2dQ= =V+I5 -----END PGP SIGNATURE----- --nVMJ2NtxeReIH9PS-- From dyoo@hkn.eecs.berkeley.edu Mon May 5 02:29:06 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 5 01:29:06 2003 Subject: [Tutor] (no subject) [search engines and vector space models] In-Reply-To: <20030505041531.GA2271@konark.ncst.ernet.in> Message-ID: > > How are search engines created for example google or the word searches > > in a help index? > > This is quite a general question and I am not sure how this is > connected with learning more about Python. No problem, we can fix that. *grin* Cameron, there's a pretty nice article on IBM's Developerworks by David mertz that talks about the fundamentals on writing a search engine in Python. http://www-106.ibm.com/developerworks/xml/library/l-pyind.html There is also a very cool article from the Perl folks on a different approach to search engines, by using a "vector space" model: http://www.perl.com/pub/a/2003/02/19/engine.html?page=1 The engine the Maciej Ceglowski describes sounds really cool; I think you might like it a lot. (It might make a fun project to implement that Perl code in Python!) I think you'll find that it'll give you a chance to play with some new Python modules. The article mentions the use of a "stemmer" function to transform things like: cats --> cat pets --> pet I've ported over a similar "Lovins stemmer" that does the same sort of thing: http://hkn.eecs.berkeley.edu/~dyoo/python/py_lovins/ Maciej also mentions a Perl module for doing matrix calculations called PDL, and he uses it to do the vector space stuff. Python has an equivalent module called Numeric Python: http://www.pfdubois.com/numpy/ The second page of Maciej's article has lots of awesome references to other introductory material on search engines and document indexing: http://www.perl.com/pub/a/2003/02/19/engine.html?page=2 Anyway, I hope these links give you something to chew on. Good luck to you! From bkelly@sourcereview.net Mon May 5 02:40:03 2003 From: bkelly@sourcereview.net (Brett Kelly) Date: Mon May 5 01:40:03 2003 Subject: [Tutor] Python community website Message-ID: <20030505053912.GC30161@inkedmn.homelinux.org> --f0KYrhQ4vYSV2aJu Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Hey all, I've been using python for a couple years now, and I love it. I'm curious about one thing though... are there any plans for a python community website? (similar to www.perlmonks.com for perl) I think the python community has grown large enough to justify a site such as this. a general inquiry, i know, but i think it to be a logical next step for the python community. --=20 Brett Kelly bkelly@sourcereview.net This message was created using the Mutt mail agent and=20 digitally signed using GnuPG. --f0KYrhQ4vYSV2aJu Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQE+tfkAa7gYa9SI8SoRAqXhAKCKRAYTf06H2rexgtA17n2KLiIkcwCgpp/f Ww7W9tEXhXsdW/JmsYBHgQo= =W7l6 -----END PGP SIGNATURE----- --f0KYrhQ4vYSV2aJu-- From bkelly@sourcereview.net Mon May 5 02:49:01 2003 From: bkelly@sourcereview.net (Brett Kelly) Date: Mon May 5 01:49:01 2003 Subject: [Tutor] Dialogbox issues............................ In-Reply-To: <20030505054410.62246.qmail@web41705.mail.yahoo.com> References: <20030505052707.GB30161@inkedmn.homelinux.org> <20030505054410.62246.qmail@web41705.mail.yahoo.com> Message-ID: <20030505054814.GD30161@inkedmn.homelinux.org> --/3yNEOqWowh/8j+e Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable You might want to go to python.org and download the latest distribution (2.2 is the current stable release). I'm fairly certain there have been several changes/upgrades to the Tkinter module since 1.5 was released. Brett On Sun, May 04, 2003 at 10:44:10PM -0700, Python-lover wrote: > Iam using Linux7.2 which contains python1.5 >=20 > --- Brett Kelly wrote: > > Any reason you're using python 1.5 instead of 2.2? > >=20 > >=20 > > On Sun, May 04, 2003 at 10:10:52PM -0700, > > Python-lover wrote: > > > hi, > > > I am using python1.5 and Tkinter. I want to > > > display the dialog box when i click the button in > > my > > > main window. I used tkSimpleDialogBox class. But > > the > > > following program is not working as it is > > expected. > > > How can i diaplay a dialog box in Tkinter? Let me > > > know where i gone wrong. > > >=20 > > > =20 > > > from Tkinter import * > > > import tkMessageBox > > > import tkSimpleDialog > > > import string > > >=20 > > > class App: > > > def __init__(self,parent): > > > self.myparent =3D parent > > > Button(self.myparent,text=3D"Click",width=3D10, > > > height=3D10,command=3Dself.showdlg).pack() > > >=20 > > > def showdlg(self): > > > MyDialog(self) > > >=20 > > > #Dialogbox class > > > class MyDialog(tkSimpleDialog.Dialog): > > >=20 > > > def body(self, master): > > > Label(master, text=3D"First:").grid(row=3D0) > > > Label(master, text=3D"Second:").grid(row=3D1) > > > self.e1 =3D Entry(master) > > > self.e2 =3D Entry(master) > > > self.e1.grid(row=3D0, column=3D1) > > > self.e2.grid(row=3D1, column=3D1) > > > self.e1.insert(0,"suressh") > > > self.e2.insert(0,1234) > > >=20 > > > def validate(self): > > > try: > > > first=3D (self.e1.get()) > > > second =3D string.atoi(self.e2.get()) > > > self.result =3D first, second > > > return 1 > > > except ValueError: > > > tkMessageBox.showwarning("Bad input", > > > "Illegal values, please try again") > > > return 0 > > >=20 > > > def apply(self): > > > first =3D (self.e1.get()) > > > second =3D string.atoi(self.e2.get()) > > > print first, second > > >=20 > > > root =3D Tk() > > > myapp =3D App(root) > > > root.mainloop() > > >=20 > > > Thanx > > >=20 > > > __________________________________ > > > Do you Yahoo!? > > > The New Yahoo! Search - Faster. Easier. Bingo. > > > http://search.yahoo.com > > >=20 > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > >=20 > > --=20 > > Brett Kelly > > bkelly@sourcereview.net > >=20 > > This message was created using the Mutt mail agent > > and=20 > > digitally signed using GnuPG. > >=20 > >=20 >=20 > > ATTACHMENT part 2 application/pgp-signature=20 >=20 >=20 > __________________________________ > Do you Yahoo!? > The New Yahoo! Search - Faster. Easier. Bingo. > http://search.yahoo.com --=20 Brett Kelly bkelly@sourcereview.net This message was created using the Mutt mail agent and=20 digitally signed using GnuPG. --/3yNEOqWowh/8j+e Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQE+tfsea7gYa9SI8SoRAs5KAJsGjIJitJ1jDhPx8jMAiYQcT57sggCfYdpB pXx2W7AOPJxk/g2w3AKj8AY= =hDTX -----END PGP SIGNATURE----- --/3yNEOqWowh/8j+e-- From magnus@thinkware.se Mon May 5 04:21:16 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 5 03:21:16 2003 Subject: [Tutor] (no subject) In-Reply-To: Message-ID: <5.2.1.1.0.20030505092030.02731100@www.thinkware.se> At 22:23 2003-05-04 -0500, Cameron Stoner wrote: >Hi all, > >How are search engines created for example google or the word searches in >a help index? For some ideas, look at http://www.myelin.co.nz/post/2002/12/17/search_engine_in_python.html and http://ransacker.sourceforge.net/ -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From adamg@mailbox.hu Mon May 5 08:14:01 2003 From: adamg@mailbox.hu (Adam Groszer) Date: Mon May 5 07:14:01 2003 Subject: [Tutor] how-to override method in instance Message-ID: Dear all, I have an object (from omniORB), which has __del__ defined in it's base class (CORBA.Object). If I'm right I cannot override the class, from which the object is instantiated. But somehow I'd like to override the __del__ method of the object to do some housekeeping when the object gets gc'd. Actually I'd like to call a method on the server, then let the base __del__ do it's work. I had something like this in my mind: def janitor(self): print 'janitor' self.done() #call method on the server first self.__super__del() #good-bye ... obj.__super__del = obj.__del__ obj.__del__ = new.instancemethod(janitor, obj, obj.__class__) ... Adam From charlie@begeistert.org Mon May 5 09:57:06 2003 From: charlie@begeistert.org (Charlie Clark) Date: Mon May 5 08:57:06 2003 Subject: [Tutor] Python community website In-Reply-To: <20030505054901.21659.23696.Mailman@mail.python.org> References: <20030505054901.21659.23696.Mailman@mail.python.org> Message-ID: <20030505145600.3704.16@wonderland.1052113546.fake> Hi Brett, > Hey all, > > I've been using python for a couple years now, and I love it. I'm > curious about one thing though... > > are there any plans for a python community website? (similar to > www.perlmonks.com for perl) I think the python community has grown large > enough to justify a site such as this. > > a general inquiry, i know, but i think it to be a logical next step for > the python community. nice idea. There is already Pythoncookbook and the tutor's own uselessPython. I'm always a bit wary of suggestions though as all websites have to be maintained. If you're up to it then I'd say go for it. Charlie From SWidney@ci.las-vegas.nv.us Mon May 5 13:08:02 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Mon May 5 12:08:02 2003 Subject: [Tutor] An interesting web site for those who want to program adventure games Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8579@sovereign.ci.las-vegas.nv.us> > I just ran into the following link; it's a tutorial on > writing adventure > games (circa 1983): > > http://www.atariarchives.org/adventure Holy cow! I actually have that book on one of my shelves! I bought it more than 15 years ago, ran through the whole thing, then put it aside. I hadn't thought about it before but converting the programs to Python would be a great exercise. > Would anyone be interested in "porting" the examples over > from BASIC to Python? It might make a fun project for us > here on Tutor; a few of us appear to have been exposed to > Basic in our past lives... *grin* Any takers? Sure. Also, I think there would be a lot of educational value in converting it straight across as procedural code and then gradually refactoring it into something more pythonic (i.e. utilizing functions, then classes, maybe adding data persistence). What do you think? Scott From lobow@brturbo.com Mon May 5 15:11:18 2003 From: lobow@brturbo.com (Diego Prestes) Date: Mon May 5 14:11:18 2003 Subject: [Tutor] wxShapeCanvas problem Message-ID: <3EB6A925.9030909@brturbo.com> Hi everyone! I start to learn wxPython but I having difficult to create the window when I have a wxShapeCanvas. I dont know very much so this program maybe is all wrong, so if someone could give me some advice to how create a window and insert a object (like a circle), in this window... Tks for the helps. Diego from wxPython.wx import * from wxPython.ogl import * class MyFrame(wxShapeCanvas): def __init__(self, parent, id): wxShapeCanvas.__init__(self, parent, id, wxDefaultPosition, wxDefaultSize) circ=wxCircleShape(40) circ.Show(true) class MyApp(wxApp): def OnInit(self): frame = MyFrame(NULL, -1) frame.Show(true) self.SetTopWindow(frame) return true app=MyApp(0) app.MainLoop() From jeff@ccvcorp.com Mon May 5 15:26:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon May 5 14:26:01 2003 Subject: [Tutor] wxShapeCanvas problem References: <3EB6A925.9030909@brturbo.com> Message-ID: <3EB6AD3D.7050002@ccvcorp.com> Diego Prestes wrote: > Hi everyone! > I start to learn wxPython but I having difficult to create the window > when I have a wxShapeCanvas. I dont know very much so this program > maybe is all wrong, so if someone could give me some advice to how > create a window and insert a object (like a circle), in this window... > > Tks for the helps. > Diego > > from wxPython.wx import * > from wxPython.ogl import * > > class MyFrame(wxShapeCanvas): [...] I'm not particularly familiar with wxShapeCanvas, but I think I know what's going on here. In wxPython, you typically have a variety of "controls" or "widgets", which can be put into a "frame" or a dialog. Frames are the support structure of a window -- they manage the title bar, menu, border, statusbar (if any), etc., and widgets are intended to be simply contents. wxShapeCanvas is (I believe) one of those widgets, but you're trying to treat it like a frame. What you need to do is to create MyFrame as a wxFrame-derived class, and in the __init__() of MyFrame you can create your wxShapeCanvas. Be aware that, in wxPython, the "window parentage" heirarchy is completely different from the Python-class inheritance heirarchy. Thus, when someone says that your Canvas should be a child of a wxFrame, that only means that the "parent" parameter that you pass to wxShapeCanvas.__init__() should be the ID of your wxFrame, it doesn't mean anything about the class heirarchy. If you continue having difficulties, you may want to check out the wxPython-specific mailing list, wxpython-users. You should be able to find subscription information on www.wxpython.org. Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Mon May 5 15:35:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 5 14:35:02 2003 Subject: [Tutor] nested "for" loops In-Reply-To: <5.2.1.1.1.20030502193811.00b2bb50@earthlink.net> Message-ID: On Fri, 2 May 2003, Peter Jakubowicz wrote: > Hi, > > I've been slogging along learning Python for a while now. Nested "for" > loops confuse me (I have trouble trying to run through them in my head). Hi Peter, Don't worry: they confuse me too. *grin* > For example, does the following code generate (albeit redundantly) all > Pythagorean triples up to 20: i.e., all integers less than or equal to > 20 for which i * i + j * j == k * k > > > for i in range(1, 21): > for j in range(1, 21): > for k in range(1, 21): > if (i * i) + (j * j) == (k * k): > print "Pythagorean triple: %d, %d, %d" % (i, j, k) Hmmm... How about this? ### def main(): for i in range(1, 21): check_triples_with_i_fixed(i) def check_triples_with_i_fixed(i): for j in range(1, 21): check_triples_with_i_and_j_fixed(i, j) def check_triples with i_and_j_fixed(i, j): for k in range(1, 21): check_triple(i, j, k) def checkTriple(i, j, k): if (i * i) + (j * j) == (k * k): print "Pythagorean triple: %d, %d, %d" % (i, j, k) ### Does this make more sense? Let's see if looking at the program in a different perspective will help. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Mon May 5 15:40:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 5 14:40:02 2003 Subject: [Tutor] nested "for" loops In-Reply-To: Message-ID: On Mon, 5 May 2003, Danny Yoo wrote: > ### > def main(): > for i in range(1, 21): > check_triples_with_i_fixed(i) > > def check_triples_with_i_fixed(i): > for j in range(1, 21): > check_triples_with_i_and_j_fixed(i, j) > > def check_triples with i_and_j_fixed(i, j): > for k in range(1, 21): > check_triple(i, j, k) > > def checkTriple(i, j, k): > if (i * i) + (j * j) == (k * k): > print "Pythagorean triple: %d, %d, %d" % (i, j, k) > ### Err... that is, if I typed it write --- um, right. *grin* My apologies; I made a mistake in the name 'checkTriple': I meant to write: ### def check_triple(i, j, k): if (i * i) + (j * j) == (k * k): print "Pythagorean triple: %d, %d, %d" % (i, j, k) ### to stay consistant with the naming style I'm using for this example. From jmillr@umich.edu Mon May 5 16:07:01 2003 From: jmillr@umich.edu (John Miller) Date: Mon May 5 15:07:01 2003 Subject: [Tutor] nested "for" loops In-Reply-To: <20030503160005.11990.32696.Mailman@mail.python.org> Message-ID: <9BF0D572-7F2C-11D7-BA52-00039303967A@umich.edu> I found this explanation of how to use list comprehensions instead of for loops very useful; thanks! However, I'd like to ask two questions that arise from this. First, the results from both Peter and Pan (hmmmm...) give, for example, 5,12,13 AND 12,5,13. For my purposes, I would like to exclude one or the other since I consider them symmetric. I can write a solution using nested ifs, but I was wondering if it could be done using list comprehensions? Second, the solution I give below results in a '''RuntimeError: maximum recursion depth exceeded''' after the first three Pythagorean triples. What am I doing that causes this, and how can I avoid it? Thanks! John Miller #!/usr/local/bin/python limit=20 def findtriples(i,j,k): if i <= j: if j <= k: if k <= limit: if (i * i) + (j * j) == (k * k): print "Pythagorean triple: %d, %d, %d" % (i, j, k) k += 1 findtriples(i,j,k) elif j < limit: j += 1 k = j + 1 findtriples(i,j,k) elif i < limit: i += 1 j = i k = j + 1 findtriples(i,j,k) findtriples(1,1,1) On Saturday, May 3, 2003, pan@uchicago.edu wrote: > Peter, > > >> for i in range(1, 21): >> for j in range(1, 21): >> for k in range(1, 21): >> if (i * i) + (j * j) == (k * k): >> print "Pythagorean triple: %d, %d, %d" % (i, j, k) > > > > For this sort of operation, you might wanna learn a little bit of the > 'list comprehension'... > > First of all lets do some tests: > >>>> [x for x in range(1,4)] # build a list using list comprehension > [1, 2, 3] > >>>> [x*x for x in range(1,4)] # another one > [1, 4, 9] > > The following is more interesting. You can get ALL the possible > 'cross-pairs' between two lists using just one liner: > >>>> [(x,y) for x in range(1,4) for y in range(1,4)] > [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, > 3)] > > More: > >>>> [(x*x,y*y) for x in range(1,4) for y in range(1,4)] > [(1, 1), (1, 4), (1, 9), (4, 1), (4, 4), (4, 9), (9, 1), (9, 4), (9, > 9)] > > Now add some conditional check: > >>>> [(x*x,y*y) for x in range(1,4) for y in range(1,4) if y*y == 9] > [(1, 9), (4, 9), (9, 9)] > > Now get the square sums instead: > >>>> [x*x+y*y for x in range(1,4) for y in range(1,4) if y*y == 9] > [10, 13, 18] > > So, we are getting close to your question, which can actually be solved > in one line: > >>>> [(x,y, x*x+y*y) \ > .. for x in range(1,21) \ > .. for y in range(1,21) \ > .. if (x*x+y*y) in [z*z for z in range(1,21)]] > [(3, 4, 25), (4, 3, 25), (5, 12, 169), (6, 8, 100), (8, 6, 100), (8, > 15, 289), > (9, 12, 225), (12, 5, 169), (12, 9, 225), (12, 16, 400), (15, 8, 289), > (16, 12, > 400)] >>>> > > It must be harder to comprehend at first, but after you get yourself > familiar with this type of functional programming, the coding life will > be much easier. > > Besides, the list comprehension is MUCH faster than the for loops. > pan From bgailer@alum.rpi.edu Mon May 5 17:09:03 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Mon May 5 16:09:03 2003 Subject: [Tutor] nested "for" loops In-Reply-To: <9BF0D572-7F2C-11D7-BA52-00039303967A@umich.edu> References: <20030503160005.11990.32696.Mailman@mail.python.org> Message-ID: <5.2.0.9.0.20030505140141.030dc5c8@66.28.54.253> --=======4595345C======= Content-Type: text/plain; x-avg-checked=avg-ok-7E07420; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:06 PM 5/5/2003 -0400, you wrote: >I found this explanation of how to use list comprehensions instead of for >loops very useful; thanks! > >However, I'd like to ask two questions that arise from this. > >First, the results from both Peter and Pan (hmmmm...) give, for example, >5,12,13 AND 12,5,13. For my purposes, I would like to exclude one or the >other since I consider them symmetric. I can write a solution using nested >ifs, but I was wondering if it could be done using list comprehensions? You can take the solution for non-duplicated results that I posted and turn it into a comprehension: limit = 20 [(x,y,z) for x in range(1,limit) for y in range(x,limit) for z in range (y,limit) if x*x + x*y == z*z] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======4595345C======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-7E07420 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003 --=======4595345C=======-- From kikofx@nifty.com Mon May 5 17:09:16 2003 From: kikofx@nifty.com (Tadahiko 'kiko' Uehara) Date: Mon May 5 16:09:16 2003 Subject: [Tutor] ".=" in Python ? Message-ID: <20030506050837.536003e7.kikofx@nifty.com> Hi all, I just start learning Python as my (almost) first programming language. I have a text file which contains something like: ------------------------------ irc.foo1.com irc.foo2.com irc.foo3.com . . . ------------------------------ and I'm trying to generate list as following: ------------------------------ servername = irc.foo1.com servername = irc.foo2.com servername = irc.foo2.com . . . ------------------------------ Here is my script... #! /usr/bin/python text = "servername = " modLine = "" # <-- had to add this line,in order to *1 to work. f = open("/home/kiko/docs/serverList") line = f.readline() while line: modLine = modLine + text + line # *1 line = f.readline() f.close() print modLine ------------------------------------ My question is, What would be an equivalent of Perl's ".=" in Python ? Is my A = A + B right way to do this ? I'm curious this becuase I think don't need to state modLine = "" in either Shell Script or Perl. Also, If this mailing-list is active anymore? I checked list archives http://mail.python.org/pipermail/tutor/ But i only see 1-2 posts per recent month ..!? Thanks in advance, -kiko From bkelly@sourcereview.net Mon May 5 17:17:02 2003 From: bkelly@sourcereview.net (Brett Kelly) Date: Mon May 5 16:17:02 2003 Subject: [Tutor] ".=" in Python ? In-Reply-To: <20030506050837.536003e7.kikofx@nifty.com> References: <20030506050837.536003e7.kikofx@nifty.com> Message-ID: <20030505201636.GD1818@inkedmn.homelinux.org> --GyRA7555PLgSTuth Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable +=3D a +=3D b is the same as a =3D a + b Sometime around Tue, May 06, 2003 at 05:08:37AM +0900, Tadahiko 'kiko' Ueha= ra took the liberty of imparting these morsels of brilliance: >=20 > Hi all, > I just start learning Python as my (almost) first programming language. >=20 > I have a text file which contains something like: > ------------------------------ > irc.foo1.com > irc.foo2.com > irc.foo3.com > . > . > . > ------------------------------ >=20 > and I'm trying to generate list as following: > ------------------------------ > servername =3D irc.foo1.com > servername =3D irc.foo2.com > servername =3D irc.foo2.com > . > . > . > ------------------------------ >=20 > Here is my script... >=20 > #! /usr/bin/python >=20 > text =3D "servername =3D " > modLine =3D "" # <-- had to add this line,in order to *1 to work. > = =20 > f =3D open("/home/kiko/docs/serverList") > line =3D f.readline() > while line: > modLine =3D modLine + text + line # *1 > line =3D f.readline() >=20 > f.close() > = =20 > print modLine > ------------------------------------ >=20 > My question is,=20 > What would be an equivalent of Perl's ".=3D" in Python ? Is my A =3D A + = B right way to do this ? > I'm curious this becuase I think don't need to state modLine =3D "" in ei= ther Shell Script or Perl. >=20 > Also, If this mailing-list is active anymore? I checked list archives ht= tp://mail.python.org/pipermail/tutor/ But i only see 1-2 posts per recent = month ..!? >=20 > Thanks in advance, > -kiko >=20 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor --=20 Brett Kelly bkelly@sourcereview.net This message was created using the Mutt mail agent and=20 digitally signed using GnuPG. --GyRA7555PLgSTuth Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQE+tsaka7gYa9SI8SoRAuOlAKCHjNblmZWZe483GPvO03o2cqV+uACfbvLm F5PMy3ketMPA90/x4tYdYjY= =t7Ab -----END PGP SIGNATURE----- --GyRA7555PLgSTuth-- From zak@harlekin-maus.com Mon May 5 17:36:23 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Mon May 5 16:36:23 2003 Subject: [Tutor] '.=' in Python ? In-Reply-To: <20030506050837.536003e7.kikofx@nifty.com> References: <20030506050837.536003e7.kikofx@nifty.com> Message-ID: <1972.192.207.104.206.1052166948.squirrel@mail.harlekin-maus.com> > Hi all, > I just start learning Python as my (almost) first programming language. > > ------------------------------ > > Here is my script... > > f = open("/home/kiko/docs/serverList") > line = f.readline() > while line: > modLine = modLine + text + line # *1 > line = f.readline() > > f.close() You could also replace the modLine assignment line with modLine = '%s%s' % (text, line) (I think. I'm a beginning Python programmer, too :) -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From bkelly@sourcereview.net Mon May 5 17:46:21 2003 From: bkelly@sourcereview.net (Brett Kelly) Date: Mon May 5 16:46:21 2003 Subject: [Tutor] '.=' in Python ? In-Reply-To: <1972.192.207.104.206.1052166948.squirrel@mail.harlekin-maus.com> References: <20030506050837.536003e7.kikofx@nifty.com> <1972.192.207.104.206.1052166948.squirrel@mail.harlekin-maus.com> Message-ID: <20030505203948.GE1818@inkedmn.homelinux.org> --19uQFt6ulqmgNgg1 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Oh, and as far as file i/o, the open() function is deprecated. use this: myfile =3D file("somefile.txt", 'r') mylist =3D myfile.readlines() myfile.close() etc. Sometime around Mon, May 05, 2003 at 01:35:48PM -0700, Zak Arntson took the= liberty of imparting these morsels of brilliance: > > Hi all, > > I just start learning Python as my (almost) first programming language. > > > > ------------------------------ > > > > Here is my script... > > > > > f =3D open("/home/kiko/docs/serverList") > > line =3D f.readline() > > while line: > > modLine =3D modLine + text + line # *1 > > line =3D f.readline() > > > > f.close() > >=20 > You could also replace the modLine assignment line with >=20 > modLine =3D '%s%s' % (text, line) >=20 > (I think. I'm a beginning Python programmer, too :) >=20 > --=20 > Zak Arntson > www.harlekin-maus.com - Games - Lots of 'em >=20 >=20 >=20 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor --=20 Brett Kelly bkelly@sourcereview.net This message was created using the Mutt mail agent and=20 digitally signed using GnuPG. --19uQFt6ulqmgNgg1 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQE+tswTa7gYa9SI8SoRAr5WAJ93Epc6EaiDmGj1CpscPcsgmXqutwCgipDc qDojgm+yTyc9AROx5faC390= =XQ4j -----END PGP SIGNATURE----- --19uQFt6ulqmgNgg1-- From kikofx@nifty.com Mon May 5 18:04:01 2003 From: kikofx@nifty.com (Tadahiko 'kiko' Uehara) Date: Mon May 5 17:04:01 2003 Subject: [Tutor] ".=" in Python ? In-Reply-To: <20030505201636.GD1818@inkedmn.homelinux.org> References: <20030506050837.536003e7.kikofx@nifty.com> <20030505201636.GD1818@inkedmn.homelinux.org> Message-ID: <20030506060312.4e67f836.kikofx@nifty.com> Thank you for the qucik reply ! On Mon, 5 May 2003 13:16:36 -0700 Brett Kelly wrote: > > += > > a += b > is the same as > a = a + b Sorry I wasn't clear in my previous post(obviouslly, subject too)... perl: my $a .= $a."text"; print $a; Python: a = "" a += a + "test" print a I thought I did something unnatural so I needed to say 1st line 'a = ""'. Or Does it work like this? Thanks, -kiko > > Sometime around Tue, May 06, 2003 at 05:08:37AM +0900, Tadahiko 'kiko' Uehara took the liberty of imparting these morsels of brilliance: > > > > Hi all, > > I just start learning Python as my (almost) first programming language. > > > > I have a text file which contains something like: > > ------------------------------ > > irc.foo1.com > > irc.foo2.com > > irc.foo3.com > > . > > . > > . > > ------------------------------ > > > > and I'm trying to generate list as following: > > ------------------------------ > > servername = irc.foo1.com > > servername = irc.foo2.com > > servername = irc.foo2.com > > . > > . > > . > > ------------------------------ > > > > Here is my script... > > > > #! /usr/bin/python > > > > text = "servername = " > > modLine = "" # <-- had to add this line,in order to *1 to work. > > > > f = open("/home/kiko/docs/serverList") > > line = f.readline() > > while line: > > modLine = modLine + text + line # *1 > > line = f.readline() > > > > f.close() > > > > print modLine > > ------------------------------------ > > > > My question is, > > What would be an equivalent of Perl's ".=" in Python ? Is my A = A + B right way to do this ? > > I'm curious this becuase I think don't need to state modLine = "" in either Shell Script or Perl. > > > > Also, If this mailing-list is active anymore? I checked list archives http://mail.python.org/pipermail/tutor/ But i only see 1-2 posts per recent month ..!? > > > > Thanks in advance, > > -kiko > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Brett Kelly > bkelly@sourcereview.net > > This message was created using the Mutt mail agent and > digitally signed using GnuPG. > > From kikofx@nifty.com Mon May 5 18:09:02 2003 From: kikofx@nifty.com (Tadahiko 'kiko' Uehara) Date: Mon May 5 17:09:02 2003 Subject: [Tutor] '.=' in Python ? In-Reply-To: <1972.192.207.104.206.1052166948.squirrel@mail.harlekin-maus.com> References: <20030506050837.536003e7.kikofx@nifty.com> <1972.192.207.104.206.1052166948.squirrel@mail.harlekin-maus.com> Message-ID: <20030506060806.62908773.kikofx@nifty.com> On Mon, 5 May 2003 13:35:48 -0700 (PDT) "Zak Arntson" wrote: > > You could also replace the modLine assignment line with > > modLine = '%s%s' % (text, line) > I'm yet not familiar with these cool way. Howeer,It didn't work on the fly... result was just "servername = "(only 1 line). But I'll try to figure out what these %s stuff do, so I might be able to fit it to my script. :) Thank you! -kiko From jeff@ccvcorp.com Mon May 5 18:10:12 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon May 5 17:10:12 2003 Subject: [Tutor] ".=" in Python ? References: <20030506050837.536003e7.kikofx@nifty.com> Message-ID: <3EB6D3C8.1010206@ccvcorp.com> Tadahiko 'kiko' Uehara wrote: >I have a text file which contains something like: >------------------------------ >irc.foo1.com >irc.foo2.com >irc.foo3.com >------------------------------ > >and I'm trying to generate list as following: >------------------------------ >servername = irc.foo1.com >servername = irc.foo2.com >servername = irc.foo2.com >------------------------------ > What are you planning on doing with this list?? There's a few ways that you can approach this, that look a fair bit different from what you're doing, but the best approach depends on what exactly the desired end result is. Your script, as it stands, will create a single multiline string -- is that what you actually want, or would a list of lines be better? In any case, I'd write it something like this: f = file('/home/kiko/docs/serverList') lines = f.readlines() # this reads the entire file, creating a list of lines f.close() modlines = [] # an empty list for line in lines: modline = "servername = %s" % line modlines.append(modline) modtext = ''.join(modlines) # optional First, I read the entire file into a list of lines, because lists are convenient to work with in Python. Once I have that, I create a new, empty list. I then iterate over my list of lines, for each one creating a modified line using string formatting, and adding that modified line to my new list. Once I've done that for all lines, I then join the list of modified lines into a single string. (Note that readlines(), as well as readline(), will leave the '\n' at the end of every line of the file. I leave that alone so that my final result still contains the newlines in the appropriate places. If I wanted to use these lines as a list, instead of a single string, I'd probably want to strip off the newlines, which could be done by calling line.strip() during the string-formatting -- i.e., 'modline = "servername = %s" % line.strip()'. I'd be left with a set of lines that I could then easily iterate over again.) This could be condensed quite a bit, especially by using a list comprehension: f = file('/home/kiko/docs/serverList') modlines = ["servername = %s" % line.strip() for line in f.readlines()] f.close() Hopefully this makes sense, and the cold medicine I'm taking hasn't addled my brains too much. :) Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Mon May 5 18:26:09 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon May 5 17:26:09 2003 Subject: [Tutor] ".=" in Python ? References: <20030506050837.536003e7.kikofx@nifty.com> <20030505201636.GD1818@inkedmn.homelinux.org> <20030506060312.4e67f836.kikofx@nifty.com> Message-ID: <3EB6D765.1020508@ccvcorp.com> Tadahiko 'kiko' Uehara wrote: >Sorry I wasn't clear in my previous post(obviouslly, subject too)... > >perl: > my $a .= $a."text"; > print $a; > >Python: > a = "" > a += a + "test" > print a > >I thought I did something unnatural so I needed to say 1st line 'a = ""'. >Or Does it work like this? > > No, you didn't do anything unnatural -- that's the way that Python works. It's a little bit more picky about creating variables than Perl is. The += requires that the variable already exist, as does "a = a + b" (which is more or less equivalent). Python only creates variables when you assign to them, i.e. when they're on the left side of an =. In both cases, the first time through you're asking your program to add "text" to something that doesn't exist yet. The difference is that Python tells you "Hey, this doesn't exist -- are you sure you meant to do that?", whereas Perl says quietly to itself "Well, this doesn't exist, so I guess they might mean for this to be an empty string. I'm gonna try that and hope that it's right." This is a design difference between the languages -- Perl tries to guess your intent, while Python refuses to guess. This means that Perl is less likely to complain... but it also means that Perl might guess *wrong*, and you'll never know unless you look *very* carefully. In the Python example, by creating the empty string beforehand, you're telling Python exactly what you want to start off with. That means that Python doesn't need to guess at what you meant by trying to use a nonexistent variable, so it has no need to complain. Jeff Shannon Technician/Programmer Credit International From jmillr@umich.edu Mon May 5 18:28:02 2003 From: jmillr@umich.edu (John Miller) Date: Mon May 5 17:28:02 2003 Subject: [Tutor] nested "for" loops In-Reply-To: <5.2.0.9.0.20030505140141.030dc5c8@66.28.54.253> Message-ID: <613E46B6-7F40-11D7-9375-00039303967A@umich.edu> When I run this, I get: >>> limit = 20 >>> [(x,y,z) for x in range(1,limit) for y in range(x,limit) for z in range (y,limit) if x*x + x*y == z*z] [(4, 5, 6), (8, 10, 12), (12, 15, 18)] These are not Pythagorean triples. Nevertheless, the code seems reasonable and I'm not sure why it isn't working. If I take Pan's solution and make a single change: >>> [(x,y, x*x+y*y) for x in range(1,21) for y in range(x,21) if (x*x+y*y) in [z*z for z in range(1,21)]] [(3, 4, 25), (5, 12, 169), (6, 8, 100), (8, 15, 289), (9, 12, 225), (12, 16, 400)] I get the non-duplicating results I want. BUT, I don't want z*z in the result set, I only want z. So if I do: >>> [(x,y,z) for x in range(1,21) for y in range(x,21) if (x*x+y*y) in [z*z for z in range(1,21)]] [(3, 4, 20), (5, 12, 20), (6, 8, 20), (8, 15, 20), (9, 12, 20), (12, 16, 20)] Here, 'z' is always at the end of the range operation. It seems as though some blend of Bob and Pan's one-liners ought to generate non-duplicating triples (without using the sqrt() function), but the syntax is eluding me... (Also, I'm still wondering why the earlier code I posted generates the '''RuntimeError: maximum recursion depth exceeded''' error.) John Miller On Monday, May 5, 2003, at 04:07 PM, Bob Gailer wrote: > You can take the solution for non-duplicated results that I posted and > turn it into a comprehension: > > limit = 20 > [(x,y,z) for x in range(1,limit) for y in range(x,limit) for z in > range (y,limit) if x*x + x*y == z*z] From dyoo@hkn.eecs.berkeley.edu Mon May 5 18:33:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 5 17:33:02 2003 Subject: [Tutor] ".=" in Python ? In-Reply-To: <20030506050837.536003e7.kikofx@nifty.com> Message-ID: > Also, If this mailing-list is active anymore? I checked list archives > http://mail.python.org/pipermail/tutor/ But i only see 1-2 posts per > recent month ..!? Hi Kiko, Welcome aboard! The others have responded to your other questions, so I'll focus on this one. Yes, Tutor is very active these days. I suspect you might be looking at the articles from the future, http://mail.python.org/pipermail/tutor/2027-January/date.html *cough* Those few were misfiled due to the incorrect date on the poster's system. We've recently set things up on the mailing list so that we set the date of each message to the arrival on the list, so things should be more accurate now. But there are still some lingering misfiled posts in the archive. I don't know how to fix those yet, so I'd recommend ignoring them for the moment. For a more representative view, we can look at: http://mail.python.org/pipermail/tutor/2003-May/thread.html http://mail.python.org/pipermail/tutor/2003-April/thread.html http://mail.python.org/pipermail/tutor/2003-March/thread.html for a sample of the activity on Python-tutor for the past three months. Best of wishes to you! From jeff@ccvcorp.com Mon May 5 18:34:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon May 5 17:34:01 2003 Subject: [Tutor] nested "for" loops References: <613E46B6-7F40-11D7-9375-00039303967A@umich.edu> Message-ID: <3EB6D934.4080200@ccvcorp.com> John Miller wrote: > When I run this, I get: > > >>> limit = 20 > >>> [(x,y,z) for x in range(1,limit) for y in range(x,limit) for z in > range (y,limit) if x*x + x*y == z*z] > [(4, 5, 6), (8, 10, 12), (12, 15, 18)] > > These are not Pythagorean triples. You've got a typo in your code -- "x*x + x*y == z*z" should be " x*x + y*y == z*z". Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Mon May 5 18:46:18 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 5 17:46:18 2003 Subject: [Tutor] ".=" in Python ? In-Reply-To: <3EB6D765.1020508@ccvcorp.com> Message-ID: > Sorry I wasn't clear in my previous post(obviouslly, subject too)... > > perl: > my $a .= $a."text"; > print $a; By the way, the code above should start raising havoc if Perl is in 'full warnings' mode: ### [dyoo@tesuque dyoo]$ perl -w use strict; my $a .= $a . "text"; print $a; [I pressed Ctrl-D at this point to tell Perl to start processing] Name "main::a" used only once: possible typo at - line 2. text ### So in that sense, Perl is trying to accept something that it knows is incorrect. Dunno if that's a good thing or not, but that's how Perl works. >I thought I did something unnatural so I needed to say 1st line 'a = ""'. >Or Does it work like this? You did it right. a = "" a += "test" print a is fine; it initializes 'a' to the empty string first, and then starts doing things with it. Good luck! From magnus@thinkware.se Mon May 5 19:28:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 5 18:28:02 2003 Subject: [Tutor] An interesting web site for those who want to program adventure games Message-ID: <5.2.1.1.0.20030506002744.02744a50@www.thinkware.se> At 09:03 2003-05-05 -0700, Scott Widney wrote: >Sure. Also, I think there would be a lot of educational value in converting >it straight across as procedural code and then gradually refactoring it into >something more pythonic (i.e. utilizing functions, then classes, maybe >adding data persistence). What do you think? I think that sounds like a very useful tutorial if the process is documented in the right way. It might not only be helpful for learning how to actually port code, but also to learn how to "port" one's thinking from Basic to Python... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From Janssen@rz.uni-frankfurt.de Mon May 5 19:38:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Mon May 5 18:38:02 2003 Subject: [Tutor] ".=" in Python ? In-Reply-To: <20030506050837.536003e7.kikofx@nifty.com> Message-ID: On Tue, 6 May 2003, Tadahiko 'kiko' Uehara wrote: > > Hi all, > I just start learning Python as my (almost) first programming language. Hello Tadahiko! > text = "servername = " > modLine = "" # <-- had to add this line,in order to *1 to work. > > f = open("/home/kiko/docs/serverList") > line = f.readline() > while line: > modLine = modLine + text + line # *1 > line = f.readline() even if you use python's "+=" you need to write 'modLine = ""' first. 'modLine += text' would assume that modLine is already defined. This might be strictly necessary with python's type of typing (combined with the "refusal to guess in the face of ambiguity") or just a mater of "Explicit is better than implicit". Do an "import this" to get more of python's tellings :-) > > f.close() > > print modLine > ------------------------------------ > > Also, If this mailing-list is active anymore? I checked list archives > http://mail.python.org/pipermail/tutor/ But i only see 1-2 posts per > recent month ..!? tutor absolutly meets my opionion of a active list (as you should have already expirienced ;-). You possibly have seen those rediculess "far in future posts" (mostly due to a very badly adjustet system clock - but how knows, maybe those guys have a time machine indeed? ;-). Make shure you request the archives for recent months. Michael > > Thanks in advance, > -kiko > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kikofx@nifty.com Mon May 5 20:20:02 2003 From: kikofx@nifty.com (Tadahiko 'kiko' Uehara) Date: Mon May 5 19:20:02 2003 Subject: Thank you (was Re: [Tutor] ".=" in Python ?) In-Reply-To: <20030506050837.536003e7.kikofx@nifty.com> References: <20030506050837.536003e7.kikofx@nifty.com> Message-ID: <20030506081939.584d82d7.kikofx@nifty.com> Thank you for all who replied to my question ! It really amazed me how helpful(ahem,active indeed) this list is. Jeff Shannon's answer worked as I wanted. Right now, I'm figuring out lines that I haven't taught myslef yet. I started scripting few month ago , with MEL(Maya Embed Language) and then recently I start looking for other scripting language for more generic stuff. First Perl... then after reading some amount of debating on the web, Python rang my bell. :) (Please don't get me wrong here, I don't say I'm this side so others bad. Just I'm not capable of learning lot, so narrowed my todo list) With respect to the community that took me in warmly. -kiko From reavey@nep.net Mon May 5 22:08:02 2003 From: reavey@nep.net (reavey) Date: Mon May 5 21:08:02 2003 Subject: [Tutor] adventure games Message-ID: <3EB709D7.9040805@nep.net> hi thanks, great site. > http://www.atariarchives.org/adventure > > > > > rewrite the code in Python. I'm in. Sounds like like great fun with a capital F, Please, suggest as an opener. Thanks re-v From tony@tcapp.com Mon May 5 23:42:02 2003 From: tony@tcapp.com (Tony Cappellini) Date: Mon May 5 22:42:02 2003 Subject: [Tutor] Gui recommendations requested: Which GUI wxPython or PyQT ? In-Reply-To: <20030506023501.13177.40244.Mailman@mail.python.org> Message-ID: <20030505193724.L1144-100000@yamato.yamato.com> I want to do some GUI apps in Python, mostly for Win32 programs. Since I don't know either one, I have to start from scratch with both. Which is faster to learn ? (I have done some event-driven programming before) Which of the 2 gui's above is better to use, in the long run ? Are there any comparisons of Python Guis available ? thanks tony From dyoo@hkn.eecs.berkeley.edu Tue May 6 02:49:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 6 01:49:02 2003 Subject: [Tutor] adventure games [transforming Basic BASIC to Basic Python In-Reply-To: <3EB709D7.9040805@nep.net> Message-ID: On Mon, 5 May 2003, reavey wrote: > thanks, great site. > > > http://www.atariarchives.org/adventure > > > rewrite the code in Python. > > I'm in. Sounds like like great fun with a capital F, Please, suggest as > an opener. Hi Reavey, This one should be fun: how about the "monster name" generator in the appendix? http://www.atariarchives.org/adventure/appendices.php It's short, it's sweet, and it's sort of an instant gratification thing: as soon as we have it ported, we can start playing with it, independent of the rest of the system. ### 10 REM CHARACTER NAME GENERATOR 20 RANDOMIZE VAL(RIGHT$(TIME$,2)) 30 DIM 2(5) 40 FOR T= 1 TO 5:READ Z(T):NEXT 50 FOR H = 1 TO 4 60 FOR T = 1 TO 4 + INT(RND(1)*4) 70 B = 0 80 A = 66 + INT(RND(1)*25) 90 IF RND(1)>.7 AND (A=69 OR A = 73 OR A = 79 OR A = 85) THEN 80 100 IF (T = 2 OR T = 5 OR T=7) THEN B= Z(INT(RND(1)*5)) 110 IF B<>0 THEN LPRINT CHR$(B);:GOTO 130 120 LPRINT CHR$(A); 130 NEXT T 140 LPRINT " "; 150 NEXT H 160 LPRINT 170 GOTO 50 180 DATA 65,69,73,79,85 ### This deathly code produces the names of hideous monsters like "MEZPO" or "GEDIE" or "MEDSA"! These names strike mortal error in any true adventurer's heart. But it, too, pales in comparison to the code itself. Just kidding. Actually, this doesn't look so bad. Part of this code appears to assume that the user knows that the mysterious numbers are ASCII character codes. In Python, we have the functions 'ord()' and 'chr()' to let us go back and forth between the numeric codes and the actual characters: ### >>> ord('A') 65 >>> ord('B') 66 >>> ord('Z') 90 >>> chr(66) 'B' ### so if you're wondering what in the world the BASIC lines: ### 40 FOR T= 1 TO 5:READ Z(T):NEXT ... 100 IF (T = 2 OR T = 5 OR T=7) THEN B= Z(INT(RND(1)*5)) ... 180 DATA 65,69,73,79,85 ### are doing, try doing a chr() across the list [65, 69, 73, 79, 85], and you should immediately see what it's doing. *grin* Do you want to give it a shot first? Good luck! From magnus@thinkware.se Tue May 6 05:30:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 6 04:30:01 2003 Subject: [Tutor] Gui recommendations requested: Which GUI wxPython or PyQT ? In-Reply-To: <20030505193724.L1144-100000@yamato.yamato.com> References: <20030506023501.13177.40244.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030506095016.00b55690@www.thinkware.se> At 19:41 2003-05-05 -0700, Tony Cappellini wrote: >I want to do some GUI apps in Python, mostly for Win32 programs. If you want *only* Win32, there are a few ways to write MFC programs in Python, but I don't think it's very common. >Since I don't know either one, I have to start from scratch with both. > >Which is faster to learn ? (I have done some event-driven programming >before) > >Which of the 2 gui's above is better to use, in the long run ? Why just these two? There seems to be four main condenders for Python (not Jython) today: Tkinter, wxPython, PyQt and PyGtk. PyQt is only freely available in a GPL version on Linux. On Windows, the cheapest way to get access to PyQt seems to be to buy Blackadder for a few hundred dollars. A full Qt licence from Trolltech costs at least $1500, and a PyQt licence is another =A3150. I haven't used it. Tkinter comes with Python, which is convenient. It's lacking bells and whistles, so you'd probably have to use Pmw or Tix with it, but it still doesn't seem as feature rich as wxPython, and the Tix included in Python seems to lack things like grids. I haven't used PyGtk either, but it's used by for instance WingIDE. It's been rather ugly-looking on Windows, but there are now themes that will make it look like a Windows 2000 or XP app, but I have just seen screenshots of that. I don't know if there is anything odd with the behaviour. Finally, wxPython is the toolkit I use, but I can't really say I'm such an expert in the others that I know that it's the best choice. I has a big user community with a very active mailing list. One might worry about the somewhat Robin Dunn-centris community though. He answers a very large part of the questions. If the original designer of the (python port of) the toolkit has to step in and answer questions all the time, one might 1) wonder how easy to use it really is and 2) wonder what happens if he gets run over by a bus. Anyway, a wxPython book by Patrick O'Brien and Robin is in production. I think wxPython has the most features, at least among the free toolkits on Windows. There are also minor players like PyFox, AnyGUI and PyFLTK. And if you run Jython, swing will be the obvious choise. >Are there any comparisons of Python Guis available ? I haven't seen any really thorough comparisions. For some more info, see: http://www.thinkware.se/cgi-bin/thinki.cgi/PythonGuis -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program=20 From hemanexp@yahoo.com Tue May 6 07:33:15 2003 From: hemanexp@yahoo.com (Python-lover) Date: Tue May 6 06:33:15 2003 Subject: [Tutor] Finding the widget name which generated an event Message-ID: <20030506103142.22957.qmail@web41702.mail.yahoo.com> Hi, how can i find the widget name that generated an event? I have placed 2 entry widgets in my window and bind "FocusIn","FocusOut" events to those entry boxes. In the event handler i want to print the name of the entry widget that generated the event. I tried with event.widget. But i got an instance number of the widget rather than widget name. How can i get the widget name that generated an event? My coding is given below. import Tkinter def gotFocus(event): print 'Focus in',' Widget: ',event.widget def lostFocus(event): print 'Focus out',' Widget: ',event.widget root = Tkinter.Tk() e = Tkinter.Entry() e1=Tkinter.Entry() e.bind('', gotFocus) e.bind('', lostFocus) e1.bind('', gotFocus) e1.bind('', lostFocus) e.pack() e1.pack() root.mainloop() Thanx __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From tbstep@tampabay.rr.com Tue May 6 07:52:02 2003 From: tbstep@tampabay.rr.com (Todd Stephens) Date: Tue May 6 06:52:02 2003 Subject: [Tutor] adventure games [transforming Basic BASIC to Basic Python In-Reply-To: References: Message-ID: <200305060649.43809.tbstep@tampabay.rr.com> On Tuesday 06 May 2003 01:48 am, Danny Yoo wrote: > These names strike mortal error in any true That old BASIC code brings back memories of some of my own mortal errors :) Todd Stephens From a_abdi406@yahoo.com Tue May 6 10:31:01 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Tue May 6 09:31:01 2003 Subject: [Tutor] program that processes tokenized words in xml Message-ID: <20030506133045.78326.qmail@web14503.mail.yahoo.com> --0-260525435-1052227845=:78244 Content-Type: multipart/alternative; boundary="0-100186042-1052227845=:78244" --0-100186042-1052227845=:78244 Content-Type: text/plain; charset=us-ascii Hi everyone, I was working on a program that indexes a file that has a tokenizedwords such as the following: Similarity-Based Estimation of Word what my program needs to do is to index the words in between ... I already set up class that reads the file line by line,Can anyone suggest how I can incorporate a regular expression for eliminating these tags? I have attached the program with this e-mail ....Please help and have a look thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-100186042-1052227845=:78244 Content-Type: text/html; charset=us-ascii
Hi everyone,
 
I was working on a program that indexes a file that has a tokenized
words such as the following:
 
<S ID='S-0'> <W>Similarity-Based</W> <W>Estimation</W> <W>of</W> <W>Word</W>
 
 what my program needs to do is to index the words in between <W>...</W>  I already set up class that reads the file line by line,
Can anyone suggest how I can incorporate a  regular expression for  
eliminating these tags?
 
I have attached the program with this e-mail  ....Please help and have a look
 
thanks in advance
 
 


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-100186042-1052227845=:78244-- --0-260525435-1052227845=:78244 Content-Type: text/plain; name="index.py" Content-Description: index.py Content-Disposition: inline; filename="index.py" #!/usr/bin/python import sys, socket, time, os, errno, re, random, profile,string,math import win32con,win32file # backwards-compatibility hack try: StopIteration except: StopIteration = "StopIteration" def search_file(filename,searchpath): """It takes a filename and a searchpath and returns the filename if it exists otherwise it returns none """ for path in string.split(searchpath): candidate = os.path.join(path,filename) if os.path.exists(candidate): return os.path.abspath(candidate) return None def ContainsAny(filename, word): """it takes a word and and a filename and checks whether the word contains in the filename given. this is then used for calculating the # of Documents that a word contains """ line = open(filename) #print line input = line.read() test = input.lower() #print test for txt in test.split(): #print txt #print word if cmp(txt,word)== 0: return 1 else: return 0 jumper = random.Random() jumper.seed() serial = 0 def link_file_into(dir, file): """ the routine links a file to a directory""" while 1: global serial serial = serial + 1 filename = str(serial) try: # XXX assumes symlink() is atomic #os.path.walk(file,os.path.join(dir, filename)) file_name = search_file(file,os.path.join(dir, filename)) return file_name except OSError, err: err_errno, msg = err if err_errno == errno.EEXIST: serial = serial + 10**jumper.randrange(3) else: raise class word_iterator: def __init__(self, filename): self.file = open(filename) self.readline() def readline(self): #aword = re.compile (r'<[^<>]*>|\b[\w-]+\b')#|([^<]+)') #added now self.line = self.file.readline() #already there print self.line #test = aword.findall(self.line) #print test #self.line = ' '.join(self.line) if self.line == '': self.words = None else: self.words = filter(None, self.line.split())#mod form \W ->\s+ #print self.words #testing #re.split(r'\W+' changed littletbit def next(self): """ this routine gets the next line of the text to be line form the file input """ while 1: if self.words is None: raise StopIteration elif self.words: return self.words.pop() else: self.readline() class text_type: def getwords(self, filename): "Return a word iterator." return word_iterator(filename) def makedirs(dirname): """"check if directory exists if not create """ if not os.path.exists(dirname): os.makedirs(dirname) class indexer: def docsdir(self): return os.path.join(self.indexdir, "docs") def wordsdir(self): return os.path.join(self.indexdir, "words") def __init__(self, indexdir): self.indexdir = indexdir self.count = 0 #extra self.TestCount = 0 #extra self.words = {} texttypeinstance = text_type() def Filetype(self, origname, linkedname): """ this routine avoids all unwanted file extension and returns a texttype instance """ for file_extension in ['.zip', '.gz', '.pdf', '.PDF']: if origname[-len(file_extension):] == file_extension: return None return self.texttypeinstance #this function checks the case of the characters def check_case(self, word): return word.lower() def Good_words(self, word): """ this function eliminates all stopwords with in the stop_list and returns the required good words """ #stoplist words to be excluded the indexing process stop_list = [ 'about', 'all', 'also', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'because', 'been', 'being', 'but', 'by', 'can', 'cannot', 'did', 'do', 'doing', 'each', 'either', 'else', 'even', 'for', 'from', 'get', 'got', 'had', 'has', 'have', 'he', 'her', 'hers', 'herself', 'him', 'himself', 'his', 'how', 'if', 'in', 'into', 'is', 'it', 'its', 'me', 'my', 'myself', 'no', 'not', 'of', 'on', 'one', 'only', 'onto', 'or', 'our', 'ourselves', 'she', 'since', 'so', 'some', 'take', 'than', 'that', 'the', 'their', 'them', 'themselves', 'then', 'there', 'these', 'they', 'this', 'those', 'through', 'to', 'too', 'unless', 'until', 'upon', 'us', 'very', 'was', 'we', 'were', 'what', 'when', 'where', 'which', 'while', 'who', 'whoever', 'whom', 'whomever', 'whose', 'why', 'will', 'with', 'without', 'would', 'yes', 'you', 'your', 'yours', 'yourself', 'yourselves','a','such'] return (word not in stop_list) def indexfile(self, origname, linkedname): """Add a file to the full-text index. indexdir ---> the top-level directory the index lives in origname ---> the file's original name (used for guessing type) linkedname ---> the name the file is known as in this system This routine figures out what kind of file the file is, extracts words from it, changes the case them, and adds them to the index. """ filetype = self.Filetype(origname, linkedname) if filetype is None: return #report as failure! filewords = filetype.getwords(os.path.join(self.docsdir(), linkedname)) words = {} try: while 1: word = self.check_case(filewords.next()) print word[0], break if self.Good_words(word): if not words.has_key(word): words[word] = 0 words[word] = words[word] + 1 #compute the doc weighting #print"words[word] = %d" %(words[word]) #testing #print"count_doc = %d" %(self.count)#testing #print"Test_count = %d" %(self.TestCount)#testing #compute the doc weighting #Inverse_doc_freq = math.log(self.count / self.TestCount) #Doc_weighting = words[word] * Inverse_doc_freq #print Doc_weighting except StopIteration: pass for word in words.keys(): if not self.words.has_key(word): self.words[word] = [] self.words[word].append((linkedname, words[word])) #self.words[word].append(Doc_weighting) def index(self, filename): """ this function calls the index function,it retrieves the appropriate file to be indexed and it also counts the number of docs processed. """ self.count = self.count + 1 #works filename = os.path.abspath(filename) #---------------------------- file = open(filename) # Ia am here start form tommorow test = file.read() x = test.lower() for i in x.split(): check = ContainsAny(filename, i) if check == 1: self.TestCount = self.TestCount + 1 #print self.TestCount #------------------------------ print "\nTest count = %d" %(self.TestCount) print filename #extra print "\ncount_doc = %d" %(self.count)#extra docsdir = self.docsdir() makedirs(docsdir) linkedname = link_file_into(docsdir, filename) self.indexfile(filename, linkedname) def commit(self): wordsdir = self.wordsdir() makedirs(wordsdir) for word in self.words.keys(): wordfile = open(os.path.join(wordsdir, word), "a") for file, data in self.words[word]: # FIXME: really big concurrent indexing jobs could # exceed PIPE_MAX bytes and result in interleaved appends # due to buffering wordfile.write("\n%s: %s" % (file, data)) #posix.fdatasync(wordfile.fileno()) #!!!!!!!!!!!!!!!!!!!!!!!!!!!! win32file._get_osfhandle(wordfile.fileno()) wordfile.close() self.words.clear() #print " test = %d" %(self.count) # this is the # of DOcuments in the sys. def main(argv): if len(argv) < 2: sys.stderr.write(usage + "\n") return 1 indexdir = argv[1] files = argv[2:] myindexer = indexer(indexdir) try: for file in files: print "indexing....", file, sys.stdout.flush() myindexer.index(file) print "...done." finally: print "committing....", sys.stdout.flush() myindexer.commit() print "....done." return 0 #-------------------------------------------END----------------------------------- if __name__ == "__main__": sys.exit(main(sys.argv)) --0-260525435-1052227845=:78244-- From magnus@thinkware.se Tue May 6 11:39:00 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 6 10:39:00 2003 Subject: [Tutor] program that processes tokenized words in xml In-Reply-To: <20030506133045.78326.qmail@web14503.mail.yahoo.com> Message-ID: <5.2.1.1.0.20030506155751.02760a98@www.thinkware.se> At 06:30 2003-05-06 -0700, Abdirizak abdi wrote: >Can anyone suggest how I can incorporate a regular expression for >eliminating these tags? Don't! Regular expressions are not the right tool for the task if we are talking about XML parsing. There are finely crafted tools particularly for XML in Python. Use them instead. Imagine you have XML data in a string like this and want to extract the names of the persons (but not the animals): data=''' John CleeseFunny Basil Fawlty WandaFish Eric Idle Funny ''' Then we can do something like this... import xml.parsers.expat isPerson = False isName = False def start_element(name, attrs): global isPerson, isName if name == 'person': isPerson = True elif name == 'name': isName = True def end_element(name): global isPerson, isName if name == 'person': isPerson = False elif name == 'name': isName = False def char_data(data): if isPerson and isName: print data parser = xml.parsers.expat.ParserCreate() parser.StartElementHandler = start_element parser.EndElementHandler = end_element parser.CharacterDataHandler = char_data parser.Parse(data) ...and get: John Cleese Basil Fawlty Eric Idle This won't break if someone starts adding attributes to the name tags, or if anyone decides to format the file differently, so that the items you imagined were located on the same row, is suddenly divided over three rows. If two files represent the same content from an XML perspective, this program should also extract the same data. I don't think you can ever fix that with regular expressions. (At least it will be very hard work.) A simple regular expression might well seem to solve the problem for you, with less code than expat etc, but it will probably be much more brittle than using a real XML parser. I have made the assumption here that persons aren't nested inside persons, and that names aren't nested inside names, but as long as that's true, I think this should work as intended. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From hemanexp@yahoo.com Tue May 6 11:41:05 2003 From: hemanexp@yahoo.com (Python-lover) Date: Tue May 6 10:41:05 2003 Subject: [Tutor] Assigning entry widget value in a dialog box from other module Message-ID: <20030506143107.91255.qmail@web41711.mail.yahoo.com> Hi, Iam using python and tkinter. My program run number of lines. To increase the maintainablity i divided my program in to two modules (ie, 2 python programs) and imported them at needed place. My first program called "a.py" is the main program in which i placed a button. When u click the button a dialogbox which is defined in "b.py" will be poped up. The dialog box contains two entry widgets. Now the problem is i want to set some default values for the entry widgets when they displayed. I defined 2 variables called "name" ,"eno" in "a.py" and want to assign their values to corresponding entry widgets. When i run the program i got the following error: File "a.py" line 12, in ? import b File "b.py" line 4 from import a My program is given below. ########################################## ############# a.py ########################################## from Tkinter import * import b class App: def __init__(self,parent): self.myparent = parent Button(self.myparent,text="Click",width=10, height=10,command=self.showdlg).pack() self.name = "AAAAA" self.no = 100 def showdlg(self): b.MyDialog(self.myparent) root = Tk() myapp = App(root) root.mainloop() ########################################## ############# b.py ########################################## import tkMessageBox import tkSimpleDialog from Tkinter import * import a import string class MyDialog(tkSimpleDialog.Dialog): def body(self, master): Label(master, text="First:").grid(row=0) Label(master, text="Second:").grid(row=1) self.e1 = Entry(master) self.e2 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) self.e1.insert(0,a.myapp.name) self.e2.insert(0,a.myapp.no) def apply(self): first = (self.e1.get()) #string.atoi second = string.atoi(self.e2.get()) print first, second # or something Let me know where i gone wrong and correct my mistake. Thanx __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From zak@harlekin-maus.com Tue May 6 13:42:03 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Tue May 6 12:42:03 2003 Subject: [Tutor] Textparsing, a better way? Message-ID: <1394.192.207.104.206.1052239264.squirrel@mail.harlekin-maus.com> I'm working on my text adventure text parser (think Zork), and have created the following code to turn a sentence into a list of words and punctuation. E.g.: "Sailor, throw me the bottle. Get bottle" -> ['sailor',',','throw','me','the','bottle','.','get','bottle'] Here's my current code, but I can't help thinking there are areas for improvement. Any suggestions/comments? I couldn't find a way for a regular expression to create a list of all of its matches. I'd love to do something like re.compile ('(\w+)|([\.,:;])') and have that drive something to make a list of all occuring blocks of that reg exp. ### def textparse (rawSentence): sentence = [] reWord = re.compile (r'([\.,:;])') for chunk in re.compile (r'\s').split (rawSentence.strip ().lower ()): # first get rid of whitespace for word in reWord.split (chunk): # now separate puncuation from words if word: sentence.append (word) return sentence ### -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From magnus@thinkware.se Tue May 6 15:03:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 6 14:03:01 2003 Subject: [Tutor] Textparsing, a better way? In-Reply-To: <1394.192.207.104.206.1052239264.squirrel@mail.harlekin-mau s.com> Message-ID: <5.2.1.1.0.20030506200058.0274b190@www.thinkware.se> At 09:41 2003-05-06 -0700, Zak Arntson wrote: >I'm working on my text adventure text parser (think Zork), and have >created the following code to turn a sentence into a list of words and >punctuation. E.g.: "Sailor, throw me the bottle. Get bottle" -> >['sailor',',','throw','me','the','bottle','.','get','bottle'] Is this what you want? (I threw in support for ?, ! and - as well.) >>> t = "Sailor, throw me the bottle. Get bottle" >>> b = re.compile(r'\S+?\b|[\.,:;\-\?!]') >>> b.findall(t.lower()) ['sailor', ',', 'throw', 'me', 'the', 'bottle', '.', 'get', 'bottle'] -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From hemanexp@yahoo.com Tue May 6 15:15:25 2003 From: hemanexp@yahoo.com (Python-lover) Date: Tue May 6 14:15:25 2003 Subject: [Tutor] Assigning values to dialog box entry widgets..................... Message-ID: <20030506181331.4080.qmail@web41713.mail.yahoo.com> --0-1496109714-1052244811=:3037 Content-Type: text/plain; charset=us-ascii Hi, Iam using python and tkinter. My program run number of lines. To increase the maintainablity i divided my program in to two modules (ie, 2 python programs) and imported them at needed place. My first program called "a.py" is the main program in which i placed a button. When u click the button a dialogbox which is defined in "b.py" will be poped up. The dialog box contains two entry widgets. Now the problem is i want to set some default values for the entry widgets when they displayed. I defined 2 variables called "name" ,"eno" in "a.py" and want to assign their values to corresponding entry widgets. When i run the program i got the following error: File "a.py" line 12, in ? import b File "b.py" line 4 from import a My program is given below.########################################## ############# a.py ##########################################from Tkinter import * import bclass App: def __init__(self,parent): self.myparent = parent Button(self.myparent,text="Click",width=10, height=10,command=self.showdlg).pack() self.name = "AAAAA" self.no = 100 def showdlg(self): b.MyDialog(self.myparent)root = Tk() myapp = App(root) root.mainloop()########################################## ############# b.py ##########################################import tkMessageBox import tkSimpleDialog from Tkinter import * import a import stringclass MyDialog(tkSimpleDialog.Dialog): def body(self, master): Label(master, text="First:").grid(row=0) Label(master, text="Second:").grid(row=1) self.e1 = Entry(master) self.e2 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) self.e1.insert(0,a.myapp.name) self.e2.insert(0,a.myapp.no) def apply(self): first = (self.e1.get()) #string.atoi second = string.atoi(self.e2.get()) print first, second # or something Let me know where i gone wrong and correct my mistake.Thanx --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-1496109714-1052244811=:3037 Content-Type: text/html; charset=us-ascii
Hi,
   Iam using python and tkinter. My program run number
of lines. To increase the maintainablity i divided my
program in to two modules (ie, 2 python programs) and
imported them at needed place.
  
   My first program called  "a.py" is the main program
in which i placed a button. When u click the button a
dialogbox which is defined in "b.py" will be poped up.
The dialog box contains two entry widgets.  Now the
problem is i want to set some default values for the
entry widgets when they displayed. I defined 2
variables called "name" ,"eno" in "a.py" and want to
assign their values to corresponding entry widgets.
When i run the program i got the following error:
    File "a.py" line 12, in ?
         import b
    File "b.py" line 4
 from import  a 
 
My program is given below.
##########################################
#############  a.py
##########################################
from Tkinter import *
import b
class App:
 def __init__(self,parent):
  self.myparent = parent
  Button(self.myparent,text="Click",width=10,
height=10,command=self.showdlg).pack()
  self.name = "AAAAA"
  self.no = 100
 def showdlg(self):
  b.MyDialog(self.myparent)
root = Tk()
myapp =  App(root)
root.mainloop()
##########################################
#############  b.py
##########################################
import tkMessageBox
import tkSimpleDialog
from Tkinter import *
import a
import string
class MyDialog(tkSimpleDialog.Dialog):
    def body(self, master):
        Label(master, text="First:").grid(row=0)
        Label(master, text="Second:").grid(row=1)
        self.e1 = Entry(master)
        self.e2 = Entry(master)
        self.e1.grid(row=0, column=1)
        self.e2.grid(row=1, column=1)
 self.e1.insert(0,a.myapp.name)
 self.e2.insert(0,a.myapp.no)
    def apply(self):
        first = (self.e1.get()) #string.atoi
        second = string.atoi(self.e2.get())
        print first, second # or something
 Let me know where i gone wrong and correct my
mistake.
Thanx
 


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-1496109714-1052244811=:3037-- From tony@tcapp.com Tue May 6 15:37:08 2003 From: tony@tcapp.com (Tony Cappellini) Date: Tue May 6 14:37:08 2003 Subject: [Tutor] Gui recommendations requested: Which GUI wxPython or PyQT ? In-Reply-To: <5.2.1.1.0.20030506095016.00b55690@www.thinkware.se> Message-ID: <20030506110904.H11574-100000@yamato.yamato.com> Thanks Magnus. > If you want *only* Win32, there are a few ways to write > MFC programs in Python, but I don't think it's very > common. My main concern is for Win32 at the moment, but it would be nice if I could get implicit cross- platform compatibility, without jumping through hoops. (I promise not to directly call the win API or MFC from my code) :-) > Why just these two? There seems to be four main condenders for > Python (not Jython) today: Tkinter, wxPython, PyQt and PyGtk. Because TKinter seems so limited, and it's look and feel is plain. > PyQt is only freely available in a GPL version on Linux. I can't understand that- but ok. > I haven't used PyGtk either, but it's used by for instance > WingIDE. It's been rather ugly-looking on Windows, but there > are now themes that will make it look like a Windows 2000 > or XP app, but I have just seen screenshots of that. I don't > know if there is anything odd with the behaviour. > > Finally, wxPython is the toolkit I use, but I can't really > say I'm such an expert in the others that I know that it's > There are also minor players like PyFox, AnyGUI and PyFLTK. > And if you run Jython, swing will be the obvious choise. I've narrowed it down to the two main GUI's I felt (with my miniscule experience and time behind the Python helm) were the more-prominent. I've installed Boa & wx Python and am going through the tutorial. Pretty good functionality for the alpha version. thanks for your input. Tony From bkelly@sourcereview.net Tue May 6 15:45:03 2003 From: bkelly@sourcereview.net (Brett Kelly) Date: Tue May 6 14:45:03 2003 Subject: [Tutor] gnome2 API? Message-ID: <20030506184451.GB2447@inkedmn.homelinux.org> --7ZAtKRhVyVSsbBD2 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable I'm looking to write a small app to watch my mailboxes and have it run in the gnome panel. i've got python2.2-gnome installed, but i can't find any sort of api for it. i've checked gnome.org and python.org, can't find anything. any ideas? --=20 Brett Kelly bkelly@sourcereview.net This message was created using the Mutt mail agent and=20 digitally signed using GnuPG. --7ZAtKRhVyVSsbBD2 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQE+uAKja7gYa9SI8SoRAsoVAJ43AWqAuM5EFJ3Qb8d/X6zQKXCmsgCgp7Fn vHAVQE6OV7ly6Be3Ow0dla0= =JCx8 -----END PGP SIGNATURE----- --7ZAtKRhVyVSsbBD2-- From norvell@houseofspearman.org Tue May 6 15:51:07 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Tue May 6 14:51:07 2003 Subject: [Tutor] Textparsing, a better way? In-Reply-To: <1394.192.207.104.206.1052239264.squirrel@mail.harlekin-maus.com> References: <1394.192.207.104.206.1052239264.squirrel@mail.harlekin-maus.com> Message-ID: <20030506185045.GA28927@houseofspearman.org> On Tuesday, 2003.05.06, 09:41:04 -0700, Zak Arntson wrote: > I'm working on my text adventure text parser (think Zork), and have > created the following code to turn a sentence into a list of words and > punctuation. E.g.: "Sailor, throw me the bottle. Get bottle" -> > ['sailor',',','throw','me','the','bottle','.','get','bottle'] Two text adventrue/interactive fiction systems written in Python (there may be more): Python Universe Builder http://py-universe.sourceforge.net/ It claims that its parser is better than Infocom's in some ways*. PAWS (Python Adventure Writing System) http://w3.one.net/~wolf/PAWS.shtml You may want to look at their parsers --- not to distract you from anyone's responses on this list. I've been thinking about writing a gaming system in Python myself (more like a cross between NetHack and Zork), but haven't looked at either of those two parsers because I'm still learning Python and wanted to see how far I could get with what I've learned so far. *I don't know if that means very much these days; the latest Zork text adventure was written in Inform, the source code of which may be helpful: http://mirror.ifarchive.org/if-archive/infocom/compilers/inform6/source/inform621_source.zip -- Norvell Spearman From zak@harlekin-maus.com Tue May 6 16:03:01 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Tue May 6 15:03:01 2003 Subject: [Tutor] Textparsing, a better way? In-Reply-To: <5.2.1.1.0.20030506200058.0274b190@www.thinkware.se> References: <1394.192.207.104.206.1052239264.squirrel@mail.harlekin-mau <5.2.1.1.0.20030506200058.0274b190@www.thinkware.se> Message-ID: <2757.192.207.104.206.1052247728.squirrel@mail.harlekin-maus.com> > At 09:41 2003-05-06 -0700, Zak Arntson wrote: >>I'm working on my text adventure text parser (think Zork), and have >> created the following code to turn a sentence into a list of words and >> punctuation. E.g.: "Sailor, throw me the bottle. Get bottle" -> >>['sailor',',','throw','me','the','bottle','.','get','bottle'] > > Is this what you want? (I threw in support for ?, ! and - as well.) > > >>> t = "Sailor, throw me the bottle. Get bottle" > >>> b = re.compile(r'\S+?\b|[\.,:;\-\?!]') > >>> b.findall(t.lower()) > ['sailor', ',', 'throw', 'me', 'the', 'bottle', '.', 'get', 'bottle'] Oh man. I completely missed the findall method, even _after_ going to help documentation and the dir(). Thank you tons! And thanks for throwing in the extra functionality, to boot! And here was lamenting the absence of a 'get a list of matches' functionality. :) Note, for anyone who'll be following my text adventure code in the future: I need '-' to be part of a word (like 'fixed-width' or 'blue-green'), so I'm going to change the above expression to: r'[\S\-]+?\b|[\.,:;\-\?!]' Thanks again! -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From carroll@tjc.com Tue May 6 16:04:03 2003 From: carroll@tjc.com (Terry Carroll) Date: Tue May 6 15:04:03 2003 Subject: [Tutor] scoping issues Message-ID: I have a module I'm writing. One method in it maintains a list, call it mylist. I want to set it up so that, if the method is never called, mylist is an empty list. If it's called, it gets set to the results from that call. This is easy: mylist = [] def meth(): mylist.append('a') mylist.append('b') mylist.append('c') The problem is, I want to re-set mylist on each call to meth() so that it only has the things from the last call. If I call this twice, I get: before first call: [] after first call: ['a', 'b', 'c'] after second call: ['a', 'b', 'c', 'a', 'b', 'c'] The first two are what I want, the last isn't. I tried resetting mylist back to [] in meth(): before first call: [] after first call: [] after second call: [] Well, that's no good. I'm sure everything in meth() is working, but now (and I'm not sure I fully understand this) there seem to be two "mylist" variables, modulename.mylist and another that I'm not sure how to even access. So, how can I achieve my goal here? How can I "reset" mylist to a null list in each invocation of the method? -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From Janssen@rz.uni-frankfurt.de Tue May 6 16:10:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue May 6 15:10:01 2003 Subject: [Tutor] Textparsing, a better way? In-Reply-To: <1394.192.207.104.206.1052239264.squirrel@mail.harlekin-maus.com> Message-ID: On Tue, 6 May 2003, Zak Arntson wrote: > I'm working on my text adventure text parser (think Zork), and have > created the following code to turn a sentence into a list of words and > punctuation. E.g.: "Sailor, throw me the bottle. Get bottle" -> > ['sailor',',','throw','me','the','bottle','.','get','bottle'] > > Here's my current code, but I can't help thinking there are areas for > improvement. Any suggestions/comments? I couldn't find a way for a regular > expression to create a list of all of its matches. I'd love to do the expression is OK, but you need to use re.findall instead of re.search. The disadvantage (but enough for many uses) of findall is, that it only returns a list of results (matched strings) and not matchobject with them nice features. > something like re.compile ('(\w+)|([\.,:;])') and have that drive > something to make a list of all occuring blocks of that reg exp. > > ### > def textparse (rawSentence): > sentence = [] > > reWord = re.compile (r'([\.,:;])') "compile" is only an optimisation, when doing it once for many operations. You can do this easily in global namespace for many calls of "textparse" (OTOH global namespace is not the best place to put all kind of stuff). Or you should simply use re.search([non-precompiled-expression], [string]) syntax. > for chunk in re.compile (r'\s').split (rawSentence.strip ().lower ()): > # first get rid of whitespace > for word in reWord.split (chunk): # now separate puncuation from > words > if word: > sentence.append (word) I don't understand everything what you do here (seems, you try to archive behaviour of unknown-for-you findall via split - interesting) but: sentence = reWord.findall(rawSentence) is possibly aequivalent. Or maybe: sentence = reWord.findall(rawSentence.lower()) Whitespace isn't within results, cause reWord matches no whitespace. Michael > > return sentence > ### > > -- > Zak Arntson > www.harlekin-maus.com - Games - Lots of 'em > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo@hkn.eecs.berkeley.edu Tue May 6 16:11:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 6 15:11:01 2003 Subject: [Tutor] gnome2 API? In-Reply-To: <20030506184451.GB2447@inkedmn.homelinux.org> Message-ID: On Tue, 6 May 2003, Brett Kelly wrote: > I'm looking to write a small app to watch my mailboxes and have it run > in the gnome panel. i've got python2.2-gnome installed, but i can't find > any sort of api for it. > > i've checked gnome.org and python.org, can't find anything. Hi Brett, Hmmm... your question's a bit specialized; I'm not sure if many of us are equipped to handle it. You might want to check on the PyGTK mailing list instead. What I've found on Google sounds slightly dismaying, http://www.daa.com.au/pipermail/pygtk/2003-February/004442.html But that was back in February, so perhaps someone has worked on the documentation problem since then. Information on the PyGTK mailing list can be found here: http://www.daa.com.au/mailman/listinfo/pygtk They seem pretty active, so I'd definitely recommend chatting with the PyGTK folks on this; you may even encourage them to write a python-gnome2 tutorial. Good luck! From bgailer@alum.rpi.edu Tue May 6 16:17:07 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Tue May 6 15:17:07 2003 Subject: [Tutor] scoping issues In-Reply-To: Message-ID: <5.2.0.9.0.20030506131007.030e4ff8@66.28.54.253> --=======5BD222D0======= Content-Type: text/plain; x-avg-checked=avg-ok-2812554E; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 12:03 PM 5/6/2003 -0700, Terry Carroll wrote: >I have a module I'm writing. One method in it maintains a list, call it >mylist. > >I want to set it up so that, if the method is never called, mylist is an >empty list. If it's called, it gets set to the results from that call. > >This is easy: > >mylist = [] > >def meth(): > mylist.append('a') > mylist.append('b') > mylist.append('c') > > >The problem is, I want to re-set mylist on each call to meth() so that it >only has the things from the last call. If I call this twice, I get: > > before first call: > [] > after first call: > ['a', 'b', 'c'] > after second call: > ['a', 'b', 'c', 'a', 'b', 'c'] > >The first two are what I want, the last isn't. > >I tried resetting mylist back to [] in meth(): > > before first call: > [] > after first call: > [] > after second call: > [] > >Well, that's no good. I'm sure everything in meth() is working, but now >(and I'm not sure I fully understand this) there seem to be two "mylist" >variables, modulename.mylist and another that I'm not sure how to even >access. > >So, how can I achieve my goal here? How can I "reset" mylist to a null >list in each invocation of the method? Binding to a variable in a function creates a local variable unless the name is declared global. You have several choices here: def meth(): global mylist mylist = [] mylist.append('a') etc or mylist = [] def meth(): mylist[:] = [] # resets the global; does not rebind mylist.append('a') etc or class mylist(list): # requires Python 2.2? def __init(self): self.append('a') etc x = mylist() # creates an instance of the class which has the characteristics of a list. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======5BD222D0======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2812554E Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003 --=======5BD222D0=======-- From carroll@tjc.com Tue May 6 16:26:01 2003 From: carroll@tjc.com (Terry Carroll) Date: Tue May 6 15:26:01 2003 Subject: [Tutor] scoping issues In-Reply-To: <5.2.0.9.0.20030506131007.030e4ff8@66.28.54.253> Message-ID: On Tue, 6 May 2003, Bob Gailer wrote: > mylist = [] > def meth(): > mylist[:] = [] # resets the global; does not rebind > mylist.append('a') > etc Excellent! This is just what I needed. Thanks, Bob. -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From zak@harlekin-maus.com Tue May 6 16:30:03 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Tue May 6 15:30:03 2003 Subject: [Tutor] Textparsing, a better way? In-Reply-To: <20030506185045.GA28927@houseofspearman.org> References: <1394.192.207.104.206.1052239264.squirrel@mail.harlekin-maus.com> <20030506185045.GA28927@houseofspearman.org> Message-ID: <2933.192.207.104.206.1052249389.squirrel@mail.harlekin-maus.com> > Two text adventrue/interactive fiction systems written in Python (there > may be more): > > Python Universe Builder > http://py-universe.sourceforge.net/ > It claims that its parser is better than Infocom's in some ways*. > > PAWS (Python Adventure Writing System) > http://w3.one.net/~wolf/PAWS.shtml > -- > Norvell Spearman Thanks for the links! Looking through them, it's interesting to see their approach to textparsing. They both go through steps, from finding the verb in the sentence, to finding the preposition, etc. I drew up a state machine, going from one word to the next. I'm not wise enough to know all the advantages and disadvantages compared to the PAWS & PUB methods, save that my method is easier for me to draw on paper :) I'm also loving Python's inherent coolness. My sentence enters the parser like "get the big blue rock and the shiny beetle with the tongs" and comes out a dictionary, like: { 'verb': ['get'], 'dobj': [ {'obj':'rock', 'adj':['big','blue']}, {'obj':'beetle', 'adj':['shiny']} ] 'iprep': ['with'], 'iobj': [ {'obj':'tongs'} ] } If anyone's interested, I'll try and draw up my current state machine. It's not perfect (can't parse all English sentences, nor all the possible text adventure commands, yet), but it's not bad. -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From dyoo@hkn.eecs.berkeley.edu Tue May 6 16:49:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 6 15:49:01 2003 Subject: [Tutor] program that processes tokenized words in xml In-Reply-To: <20030506133045.78326.qmail@web14503.mail.yahoo.com> Message-ID: On Tue, 6 May 2003, Abdirizak abdi wrote: > Hi everyone, I was working on a program that indexes a file that has a > tokenizedwords such as the following: > Similarity-Based Estimation of Word what my > program needs to do is to index the words in between ... I > already set up class that reads the file line by line,Can anyone suggest > how I can incorporate a regular expression for eliminating these tags? > I have attached the program with this e-mail ....Please help and have a > look thanks in advance Hi Abdirizak, Wow, you're doing a lot of language stuff stuff nowdays! Very cool. Out of curiosity: do you know of a good sparse matrix multiplication module? Cameron's question on search engines a few days ago got me interested in doing vector-based search engines. At the moment, I'm using pysparse: http://www.inf.ethz.ch/personal/geus/pyfemax/pysparse.html and I'm getting very awesome results... Yikes, I'm getting too excited about this stuff. Sorry for going off topic! If anyone's interested, I can do a small tutorial on a vector-based search engine in Python now, I think. *grin* Anyway, you can probably use the function re.findall() to grab all words between '' tags. Here's one way to do it: ### >>> import re >>> w_regex = re.compile(r'(.+?)') >>> w_regex.findall('similarity-based Estimation') ['similarity-based', 'Estimation'] ### The trick here is to make sure the regular expression knows that it needs to be "nongreedy". That is, if we give it something like: similarity-based Estimation we want to make sure that it does: similarity-based Estimation |---------------------| |---------------| (match 1) (match 2) and not, similarity-based Estimation |---------------------------------------| (match 1) Compare the results above to the regular expression: w_regex_broken = re.compile(r'(.+)') and the idea of greedy-vs-nongreedy matching should make sense. However, if we're guaranteed that our input is XML, I'd heavily recommend looking into using an XML parser instead: ### >>> import xml.dom.minidom >>> dom = xml.dom.minidom.parseString(''' ... ... similarity-based Estimation ... ''') >>> >>> dom >>> >>> all_word_nodes = dom.getElementsByTagName('W') >>> all_word_nodes [, ] >>> >>> def getText(node): ... text_nodes = [n for n in node.childNodes ... if n.nodeType == n.TEXT_NODE] ... texts = [n.data for n in text_nodes] ... return ''.join(texts) ... >>> map(getText, all_word_nodes) [u'similarity-based', u'Estimation'] ### ... ok, part of this does look more complicated than the regular expression stuff. *grin* But it might be worth learning how to use an XML parser if you're planning do any deep diving into the structure of your documents. Good luck to you! From hodge3@llnl.gov Tue May 6 17:20:03 2003 From: hodge3@llnl.gov (Neil Hodge) Date: Tue May 6 16:20:03 2003 Subject: [Tutor] gnome2 API? In-Reply-To: References: Message-ID: <3EB8188E.8030300@llnl.gov> Brett: Danny Yoo wrote: > > On Tue, 6 May 2003, Brett Kelly wrote: > > >>I'm looking to write a small app to watch my mailboxes and have it run >>in the gnome panel. i've got python2.2-gnome installed, but i can't find >>any sort of api for it. >> > > > Information on the PyGTK mailing list can be found here: > > http://www.daa.com.au/mailman/listinfo/pygtk > > They seem pretty active, so I'd definitely recommend chatting with the > PyGTK folks on this; you may even encourage them to write a python-gnome2 > tutorial. > In addition, google 'pygnome' (if you really want gnome, as opposed to plain old gtk). Neil From norvell@houseofspearman.org Tue May 6 17:29:02 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Tue May 6 16:29:02 2003 Subject: [Tutor] Textparsing, a better way? In-Reply-To: <2933.192.207.104.206.1052249389.squirrel@mail.harlekin-maus.com> References: <1394.192.207.104.206.1052239264.squirrel@mail.harlekin-maus.com> <20030506185045.GA28927@houseofspearman.org> <2933.192.207.104.206.1052249389.squirrel@mail.harlekin-maus.com> Message-ID: <20030506202835.GA29176@houseofspearman.org> On Tuesday, 2003.05.06, 12:29:49 -0700, Zak Arntson wrote: > If anyone's interested, I'll try and draw up my current state machine. > It's not perfect (can't parse all English sentences, nor all the possible > text adventure commands, yet), but it's not bad. I'm definitely interested. Thanks. -- Norvell Spearman From phthenry@earthlink.net Tue May 6 17:50:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Tue May 6 16:50:01 2003 Subject: [Tutor] program that processes tokenized words in xml In-Reply-To: <5.2.1.1.0.20030506155751.02760a98@www.thinkware.se> References: <20030506133045.78326.qmail@web14503.mail.yahoo.com> <5.2.1.1.0.20030506155751.02760a98@www.thinkware.se> Message-ID: <20030506164954.M13810@localhost.localdomain> I like your code a lot! I have been using SAX to parse a lot of XML, and was unaware you could use expat directly. I also didn't know that you could use expat to parse just strings--rather than files. I need to check that certain strings are valid in a parser I have written. I had used regular expressions (knowing it was kind of a kludge), but your code inspired this: import xml.parsers.expat parser = xml.parsers.expat.ParserCreate() import sys # simple function to validate the well-formedness of a string def validate(data): try: parser.Parse(data) return 0 except : sys.stderr.write('tagging text will result in invalid XML\n') return 1 data = 'text' valid = validate(data) Is there a better way? Also, how can I make my except statement more precise? I tried: except ExpatError: with no success Thanks Paul On Tue, May 06, 2003 at 04:39:45PM +0200, Magnus Lyckå wrote: > > At 06:30 2003-05-06 -0700, Abdirizak abdi wrote: > >Can anyone suggest how I can incorporate a regular expression for > >eliminating these tags? > > Don't! > > Regular expressions are not the right tool for the task if we are talking > about XML parsing. There are finely crafted tools particularly for XML in > Python. Use them instead. > > Imagine you have XML data in a string like this and want to extract the > names of the persons (but not the animals): > > data=''' > > John CleeseFunny > Basil Fawlty > > > WandaFish > > > Eric Idle > Funny > > ''' > > Then we can do something like this... > > import xml.parsers.expat > > isPerson = False > isName = False > > def start_element(name, attrs): > global isPerson, isName > if name == 'person': > isPerson = True > elif name == 'name': > isName = True > > def end_element(name): > global isPerson, isName > if name == 'person': > isPerson = False > elif name == 'name': > isName = False > > def char_data(data): > if isPerson and isName: > print data > > parser = xml.parsers.expat.ParserCreate() > parser.StartElementHandler = start_element > parser.EndElementHandler = end_element > parser.CharacterDataHandler = char_data > > parser.Parse(data) > > ...and get: > > John Cleese > Basil Fawlty > Eric Idle > > This won't break if someone starts adding attributes to the > name tags, or if anyone decides to format the file differently, > so that the items you imagined were located on the same row, > is suddenly divided over three rows. If two files represent the > same content from an XML perspective, this program should also > extract the same data. I don't think you can ever fix that with > regular expressions. (At least it will be very hard work.) > > A simple regular expression might well seem to solve the problem > for you, with less code than expat etc, but it will probably be > much more brittle than using a real XML parser. > > I have made the assumption here that persons aren't nested inside > persons, and that names aren't nested inside names, but as long as > that's true, I think this should work as intended. > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The shortest path from thought to working program > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From krier115@student.liu.se Tue May 6 18:09:01 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Tue May 6 17:09:01 2003 Subject: [Tutor] program that processes tokenized words in xml In-Reply-To: <20030506164954.M13810@localhost.localdomain> References: <20030506133045.78326.qmail@web14503.mail.yahoo.com> <5.2.1.1.0.20030506155751.02760a98@www.thinkware.se> <20030506164954.M13810@localhost.localdomain> Message-ID: <20030506210757.GA450@n14.ryd.student.liu.se> On Tue, May 06, 2003 at 04:49:55PM -0400, Paul Tremblay wrote: > Also, how can I make my except statement more precise? > > I tried: > > except ExpatError: > > with no success try except xml.parsers.expat.ExpatError: regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From vicki@stanfield.net Tue May 6 18:09:10 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Tue May 6 17:09:10 2003 Subject: [Tutor] infrared interface through serial port Message-ID: <20030506140836.10487.h010.c000.wm@mail.stanfield.net.criticalpath.net> I am using an application at work that accepts serial input via an attachment to the serial port. We also have an attachment that attaches to the serial port and accepts infrared input. This doesn't work with the current version of the application even though the infrared dongle is attached through the serial port. I assume then that infrared activity must require slightly different handling. Can anyone give me a clue as to where to look for information on fixing this tool. --vicki From alan.gauld@blueyonder.co.uk Tue May 6 18:16:19 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue May 6 17:16:19 2003 Subject: [Tutor] Finding the widget name which generated an event References: <20030506103142.22957.qmail@web41702.mail.yahoo.com> Message-ID: <00be01c31413$e45dc2f0$6401a8c0@xp> > how can i find the widget name that generated an > event? Technically the widget doesn't have a name. Instead there is a variable in your code that references the widget. You could have several names referring to the same widget, in which case which name gets printed? e = Entry(rt) e1 = Entry(rt) e2 = e1 Now does the event on e1 widget print 'e1' or 'e2' since both are valid names for the same object! More pragmatically... > widget rather than widget name. How can i get the > widget name that generated an event? > My coding is given below. > > import Tkinter > def gotFocus(event):... > def lostFocus(event):... > > root = Tkinter.Tk() > > e = Tkinter.Entry() > e1=Tkinter.Entry() You should really pass a parent to the widgets: e = Tkinter.Entry(root) But that doesn't buy you much here. If you want to have some kind of friendly name printed then you need to store the widgets in a dictionary or class: widgets = {} widgets['e'] = Entry(root) widgets['e1'] = Entry(root) Now you can compare the widget id with the objects in the dictionary: for key in widgets.keys(): if id(e.widget) == id(widgets[key]): print "Widget: ", key Another option involves setting setting separate callbacks for each widget: def gotFocus(event, name): print "Widget: ", name e.bind('', lambda ev,nm='e': gotFocus(ev,nm) ) e1.bind('', lambda ev,nm='e1': gotFocus(ev,nm) ) HTH, Alan G. (Back from a very wet vacation!) From tim@johnsons-web.com Tue May 6 18:21:45 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Tue May 6 17:21:45 2003 Subject: [Tutor] quote + value of a variable Message-ID: <20030506212048.GX25289@johnsons-web.com> Hello All: I'm using Python 2.2.2 I'd like to write a function that would take a variable and print out both the name of and the value. Example: >>> mylist = [1,2,3] >>> dbg(mylist) mylist: [1,2,3] # would be shorthand for >>> print 'mylist: ' , mylist mylist: [1, 2, 3] Any ideas appreciated. Pointers to documentations welcome. Regars -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From alan.gauld@blueyonder.co.uk Tue May 6 18:50:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue May 6 17:50:02 2003 Subject: [Tutor] scoping issues References: Message-ID: <00f801c31419$603a0960$6401a8c0@xp> > This is easy: > > mylist = [] > def meth(): > mylist.append('a') > mylist.append('b') > mylist.append('c') > > > The problem is, I want to re-set mylist on each call to meth() so that it > only has the things from the last call. If I call this twice, I get: So move the mylist declaration into the method and then return the result. This is generally a better way to do things anyway: def meth(): mylist = [] mylist.append('a') mylist.append('b') mylist.append('c') return mylist Now you can assign the value anyplace you like: l1 = meth() #->['a','b','c'] l2 = meth() #->['a','b','c'] l1 = meth() #->['a','b','c'] ie not two sets > I tried resetting mylist back to [] in meth(): You needed to declare mylist as global, otrherwise you just created a local variable inside the method and never changed the external one. But using a lobal variable is not good practice, better to do as I did above... > (and I'm not sure I fully understand this) there seem to be two "mylist" > variables, modulename.mylist and another that I'm not sure how to even > access. The other one only existed inside meth(), as soon as you exited meth() it was garbage collected. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@blueyonder.co.uk Tue May 6 18:57:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue May 6 17:57:01 2003 Subject: [Tutor] My tutorial Message-ID: <010b01c3141a$31357cc0$6401a8c0@xp> Hi gang, My online tutor is currently mastered at freenet.co.uk and "mirrored" (sporadically) on crosswinds.net. Crosswinds have just announced they are stopping free service and the Crosswinds version of the web site will therefore disappear later this month. The freenet one will of course remain but anyone using the Crosswinds one should reset their bookmarks ASAP... Similarly anyone linking a web site to mine should repoint their links to freenet. Thanks, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From magnus@thinkware.se Tue May 6 19:23:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 6 18:23:02 2003 Subject: [Tutor] Textparsing, a better way? In-Reply-To: <1394.192.207.104.206.1052239264.squirrel@mail.harlekin-mau s.com> Message-ID: <5.2.1.1.0.20030506201534.02722db8@www.thinkware.se> At 09:41 2003-05-06 -0700, Zak Arntson wrote: >I'm working on my text adventure text parser (think Zork) Again, regular expressions might not be the best approach here. Danny Yoo is the guy who knows where to find code to analyse text sentences in a linguistic fashion. He's provided links for that before. Another approach would be to use the kind of lexical analyzer / parser that we normally use for compilers and code interpreters etc. In the C world, lex/yacc is the most common option, but there are plenty of tools like this for Python. See for instance: http://www.python.org/sigs/parser-sig/ http://www.egenix.com/files/python/mxTextTools.html http://gnosis.cx/TPiP/ http://gnosis.cx/publish/programming/charming_python_14.txt http://gnosis.cx/publish/programming/charming_python_b4.txt http://gnosis.cx/publish/programming/charming_python_b6.txt http://gnosis.cx/publish/programming/charming_python_b11.txt -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From pan@uchicago.edu Tue May 6 19:32:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Tue May 6 18:32:01 2003 Subject: [Tutor] program that processes tokenized words in xml In-Reply-To: <20030506105202.30850.80124.Mailman@mail.python.org> References: <20030506105202.30850.80124.Mailman@mail.python.org> Message-ID: <1052260258.3eb837a212ddb@webmail-b.uchicago.edu> hi all, Although many good teachers in this list had warned not to write your own xml parser but to use xml.dom.minidom stuff instead, I always have doubt why the xml parsing has to be so complicated in the xml.com style. After this issue was raised again earlier today, I couldn't help but did a little coding, and came up with this animal which, in my simple-enough brain capacity, is far easier to use than the built-in stuff. It didn't use anything except the regular expression module re and takes less than 50 lines of code if not counting the comments. The entire file is attached below. Check out the doc string of the class c_panXmlParser for some usages to see how easy it can be. It still needs some modifications before it can be used for real parsing war (for example, need to take the arguments of a tag into considerations, but this shouldn't be too difficult). But, I think life will be much easier with this than with the complicated, confusing builtin xml parser. pan #=============================================================== # # c_panXmlParser # #=============================================================== __version__='030506_1' __author__ ='Runsun Pan' __history__ =''' 030506_1 first draft. Working fine. to do: take argument into consideration: 120 NewAge ''' import re class c_panXmlParser: '''================================================================ Given a xmlDoc: John CleeseFunny Basil Fawlty WandaFish Eric Idle Funny ------------------------------------------------------------------- xml = c_panXmlParser(xmlDoc) # print "\nGetting a person--------" print xml.person[0].name print xml.person[1].function printout: ['John Cleese', 'Basil Fawlty'] ['Funny'] # print "\nGetting all persons--------" for x in xml.person: print 'name=', x.name print 'function=', x.function printout: name= ['John Cleese', 'Basil Fawlty'] function= ['Funny'] name= ['Eric Idle'] function= ['Funny'] # print "\nGetting 'animal'--------" for x in xml.animal: print 'name=', x.name print 'function=', x.function printout: name= ['Wanda'] function= ['Fish'] ------------------------------------------------------------------- if xmlDoc = Wanda Fish means, have nexted 'function' tags: for x in xml.animal: print 'name=', x.name print 'function=', x.function print 'function[0].function=', x.function[0].function gives: name= ['Wanda'] function= [<__main__.c_panXmlParser instance at 0x00F42848>] function[0].function= ['Fish'] ------------------------------------------------------------------- =================================================================== ''' def __init__(self, xmlDoc=[]): self.__dict__['__argNames']=[] if xmlDoc: self.load(xmlDoc) def split(self, xmlDoc): '''================================================================ Given a xmlDoc: John CleeseFunny Basil Fawlty WandaFish Eric Idle Funny Split it into a list: John Cleese Funny Basil Fawlty Wanda Fish Eric Idle Funny Note that all space and newlines are removed. ================================================================ ''' ptn = '(<[a-zA-Z0-9_]+?>)|()' reHead = re.compile(ptn, re.IGNORECASE) return [x.strip() for x in reHead.split(xmlDoc) if x and x.strip()] def load(self, xmlDoc): if type(xmlDoc)==str: xml = self.split(xmlDoc) else: xml = xmlDoc self._head = xml[0] self.tagName = xml[0][1:-1] self._tail = '' % self.tagName i=1 pairs = 1 currentHead = xml[1] currentTail = '' % xml[1][1:-1] iBeg = 1 iEnd = 0 for i in range(2, len(xml)-1): item = xml[i] if item== currentHead: pairs +=1 elif item== currentTail: pairs -=1 if pairs==0: arg = currentHead[1:-1] if (i-iBeg+1)==3: val = xml[iBeg+1] if self.__dict__.has_key(arg): self.__dict__[arg].append(val) else: self.__dict__[arg]= [val] else: L = xml[iBeg:i+1] self.__dict__['__argNames'].append(arg) if self.__dict__.has_key(arg): self.__dict__[arg].append(c_panXmlParser(L)) else: self.__dict__[arg]= [c_panXmlParser(L)] iBeg = i+1 currentHead=xml[i+1] currentTail = '' % xml[i+1][1:-1] if __name__=='__main__': print print print '*'*60 xmlDoc=[ ''' John CleeseFunny Basil Fawlty WandaFish Eric Idle Funny ''', ''' Wanda Fish ''' ] xml = c_panXmlParser(xmlDoc[0]) print '\nxmlDoc[0]\n' print "\nGetting a person--------" print xml.person[0].name print xml.person[1].function print "\nGetting all persons--------" for x in xml.person: print 'name=', x.name print 'function=', x.function print "\nGetting 'animal'--------" for x in xml.animal: print 'name=', x.name print 'function=', x.function xml = c_panXmlParser(xmlDoc[1]) print '\nxmlDoc[1]\n' print "\nGetting 'animal'--------" for x in xml.animal: print 'name=', x.name print 'function=', x.function print 'function[0].function=', x.function[0].function #=============================================================== # # End of c_panXmlParser # #=============================================================== From alan.gauld@blueyonder.co.uk Tue May 6 19:52:03 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue May 6 18:52:03 2003 Subject: [Tutor] quote + value of a variable References: <20030506212048.GX25289@johnsons-web.com> Message-ID: <002b01c31422$2068f9a0$6401a8c0@xp> > I'd like to write a function that would take > a variable and print out both the name of and the > value. Usually a bad idea but if it's for a debug function then that's probably an acceptable exception to the rule. Why not check how pdb does it? > >>> print 'mylist: ' , mylist > mylist: [1, 2, 3] > > Any ideas appreciated. Pointers to > documentations welcome. My first guess would be to trawl the builtins directory and test the id of your variable against the names in there. something like: for name in dir(): if __builtins__[name] is var: print name, var Or however you access the builtins dictionary directly! Alan G. From alan.gauld@blueyonder.co.uk Tue May 6 20:00:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue May 6 19:00:02 2003 Subject: [Tutor] program that processes tokenized words in xml References: <20030506105202.30850.80124.Mailman@mail.python.org> <1052260258.3eb837a212ddb@webmail-b.uchicago.edu> Message-ID: <003401c31423$2885bcd0$6401a8c0@xp> I haven't checked but how does it handle recursive definitions? Like this, say: Jon Fred None That's usually where regex based parsing of XML falls flat. Alan g. From magnus@thinkware.se Tue May 6 20:26:19 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 6 19:26:19 2003 Subject: [Tutor] Gui recommendations requested: Which GUI wxPython or PyQT ? In-Reply-To: <20030506110904.H11574-100000@yamato.yamato.com> References: <5.2.1.1.0.20030506095016.00b55690@www.thinkware.se> Message-ID: <5.2.1.1.0.20030507011432.00bbb058@www.thinkware.se> At 11:16 2003-05-06 -0700, Tony Cappellini wrote: >I've installed Boa & wx Python and am going through the tutorial. >Pretty good functionality for the alpha version. I haven't used Boa seriously. Not at all as GUI builder actually, but I saw that the debugger seemed to work nicely, which is not so common with GUI programs. My best advice is to go through the wxPython demo, and look at the source code for that, and to join the wxpython mailing list. There's also some helpful stuff at the wiki. BTW, you should note that they are changing the library layout, so that it should be possible to write import wx f = wx.Frame(...) instead of the ugly from wxPython.wx import * f = wxFrame(...) as you would today. There are some wrappers already, and if you start coding now, you might perhaps use the new style at once, but I don't think it will work out of the box yet. You need some extras. Concerning Qt, Trolltech is free to licence things the way they want. I assume anyone could take the GPL code and try to port it to Windows, so that there is a GPL version there as well, but that's a lot of work. After all, MFC isn't very similar to the X Window system... I don't think Trolltech has any desire to GPL their Win32 code, and as sole copyright holders of Qt, the viral aspects of GPL won't affect them. They can't loose the right to use their own code by not following GPL. GPL is for the people who license their code. Also, a GPL GUI toolkit is fairly limiting... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From pan@uchicago.edu Tue May 6 20:34:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Tue May 6 19:34:01 2003 Subject: [Tutor] program that processes tokenized words in xml In-Reply-To: <003401c31423$2885bcd0$6401a8c0@xp> References: <20030506105202.30850.80124.Mailman@mail.python.org> <1052260258.3eb837a212ddb@webmail-b.uchicago.edu> <003401c31423$2885bcd0$6401a8c0@xp> Message-ID: <1052263978.3eb8462a5d099@webmail-b.uchicago.edu> =A4=DE=A5=CE Alan Gauld : > I haven't checked but how does it handle recursive definitions? > Like this, say: >=20 > > Jon > > Fred > None > > > >=20 > That's usually where regex based parsing of XML falls flat. >=20 > Alan g. >=20 Try these: >>> from panXmlParser import c_panXmlParser >>> data =3D ''' .. Jon .. .. Fred .. None .. =20 .. =20 .. .. ''' >>> person =3D c_panXmlParser(data) >>> person.son[0].person[0].name ['Fred'] >>> person.son[0].person[0].son ['None'] And these: >>> data =3D ''' .. Jon .. .. .. Fred .. many .. =20 .. .. Pan .. NotYet .. =20 .. =20 .. .. ''' ..=20 >>> person =3D c_panXmlParser(data) >>> person.son[0].person[0].name ['Fred'] >>> person.son[0].person[0].son ['many'] >>> person.son[0].person[1].name ['Pan'] >>> person.son[0].person[1].son ['NotYet'] >>> [x.name for x in person.son[0].person] [['Fred'], ['Pan']] >>> [x.son for x in person.son[0].person] [['many'], ['NotYet']] pan From pan@uchicago.edu Tue May 6 20:45:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Tue May 6 19:45:01 2003 Subject: [Tutor] program that processes tokenized words in xml In-Reply-To: <003401c31423$2885bcd0$6401a8c0@xp> References: <20030506105202.30850.80124.Mailman@mail.python.org> <1052260258.3eb837a212ddb@webmail-b.uchicago.edu> <003401c31423$2885bcd0$6401a8c0@xp> Message-ID: <1052264645.3eb848c5adeb5@webmail-b.uchicago.edu> =A4=DE=A5=CE Alan Gauld : > I haven't checked but how does it handle recursive definitions? > Like this, say: >=20 > > Jon > > Fred > None > > > >=20 > That's usually where regex based parsing of XML falls flat. >=20 > Alan g. Alan, I think I misunderstood your question just now. You asked "how", but not "if it can." [1] First of all the xml doc is splitted into a list: Jon Fred None [2] Then the list is read one by one. A 'state-holder', pairs, is used to determine how many 'pair' of exists.=20 [3] When a header tag is found, (like , but not nor=20 Jon), 'pairs' increase by 1;=20 [4] a tailing tag (, but not nor Jon) found, 'pairs'=20 decrease by 1: if item=3D=3D currentHead: pairs +=3D1 elif item=3D=3D currentTail: pairs -=3D1 [5] When pairs reaches 0, the is the one that is the current closing tail tag. This simple trick makes sure that it won't misunderstan= d=20 an internal as the closing .=20 pan From SWidney@ci.las-vegas.nv.us Tue May 6 20:54:01 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Tue May 6 19:54:01 2003 Subject: [Tutor] adventure games [transforming Basic BASIC to Basic P ython Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC857F@sovereign.ci.las-vegas.nv.us> > This one should be fun: how about the "monster name" generator in the > appendix? > > http://www.atariarchives.org/adventure/appendices.php > > It's short, it's sweet, and it's sort of an instant > gratification thing: as soon as we have it ported, we can start > playing with it, independent of the rest of the system. Here's a first go: I made comments out of all of the original code; added my own comments on what I felt the author was trying to do, etc.; and added some python that works. There are two sections I avoided -- both having to do with GOTO. Here it is (Shield your eyes children! Turn a blind eye!): ##### # 10 REM CHARACTER NAME GENERATOR # 20 RANDOMIZE VAL(RIGHT$(TIME$,2)) # Seed the random-number generator import random # importing random seeds it # with the current time import sys # see Notes below # 30 DIM Z(5) # 40 FOR T = 1 TO 5:READ Z(T):NEXT # Fill an array "Z" with the ASCII codes # for the five vowels A,E,I,O,U Z = [65,69,73,79,85] # 50 FOR H = 1 TO 4 # Loop four times => four names per line for H in range(4): # 60 FOR T = 1 TO 4 + INT(RND(1)*4) # Loop from between 4 to 7 times (== letters per name) # IIRC, RND(1) generates a random float between 0.0 and 1.0 # So INT(RND(1)*4) would randomly generate 0, 1, 2, or 3 for T in range(1, random.randint(5,8)): # 70 B = 0 B = 0 # 80 A = 66 + INT(RND(1)*25) # Generate a random letter of the alphabet and store it in A A = random.randint(66,90) # You have GOT to love randint()! # 90 IF RND(1)>.7 AND (A=69 OR A = 73 OR A = 79 OR A = 85) THEN 80 # 30% of time, check and regenerate the letter if it is E,I,O, or U # No GOTO in python, this will have to be implemented another way # 100 IF (T = 2 OR T = 5 OR T=7) THEN B = Z(INT(RND(1)*5)) # Unconditionally make the second, fifth and seventh letters vowels if T in [2,5,7]: B = random.choice(Z) # Gotta love choice() too! # 110 IF B<>0 THEN LPRINT CHR$(B);:GOTO 130 # 120 LPRINT CHR$(A); # If B contains a value (a mandatory vowel), print it. Otherwise # print the randomly-generated letter (whether vowel or consonant) # Notes: # 1) The GOTO in line 110 would be unneccesary if the author's # version of BASIC supported the IF-THEN-ELSE construct. # 2) In BASIC, a print statement with a trailing semicolon # suppresses a newline. In python, our solution is to 'import sys' # to gain access to stdout if B: sys.stdout.write(chr(B)) else: sys.stdout.write(chr(A)) # 130 NEXT T # Get another letter (python doesn't use NEXT) # 140 LPRINT " "; # Put some space between those words sys.stdout.write(" ") # 150 NEXT H # Make another word # 160 LPRINT # Print a newline sys.stdout.write("\n") # 170 GOTO 50 # GOTO, OH NO! The dreaded infinite loop -- we'll avoid this # 180 DATA 65,69,73,79,85 # Here are the ASCII values for our vowels, which I coded above ##### This prints four names on one line and stops. From here we could wrap this in another loop to print a hard-coded number of lines, OR wrap it in a function definition that lets us specify how many lines we want. Lots of options. Next, I'm going to refactor this even more using the string module to get my letters directly, and take care of line 90, which I skipped. Danny, I'm wondering if this could be made into a a true generator function (as in, from __future__ import ...). What do you think? Scott From SWidney@ci.las-vegas.nv.us Tue May 6 21:56:02 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Tue May 6 20:56:02 2003 Subject: [Tutor] adventure games [transforming Basic BASIC to Basic P ython Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8581@sovereign.ci.las-vegas.nv.us> > This prints four names on one line and stops. From here we > could wrap this in another loop to print a hard-coded number > of lines, OR wrap it in a function definition that lets us > specify how many lines we want. Lots of options. > > Next, I'm going to refactor this even more using the string > module to get my letters directly, and take care of line 90, > which I skipped. Danny, I'm wondering if this could be made > into a true generator function (as in, from __future__ > import ...). What do you think? And here is the function: ##### import string, random, sys all = string.ascii_uppercase vowels = 'AEIOU' consonants = ''.join([x for x in all if x not in vowels]) # Print four names on a line for loop in range(4): # Four to seven letters per name for position in range(1, random.randint(4,7)+1): # The second, fifth & seventh letters should always be vowels # Of the others, 30% of the time, force a consonant if position in [2,5,7]: letter = random.choice(vowels) elif random.random() > 0.7: letter = random.choice(consonants) else: letter = random.choice(all) sys.stdout.write(letter) sys.stdout.write(" ") sys.stdout.write("\n") ##### >From here we could make this a function, maybe one that returns a list of names. Or a module that could either be imported or run standalone. How about a class? Hmmm. Although it generates names, it doesn't remember them; it just sends them to stdout. Lots of options.... Scott From jeff@ccvcorp.com Tue May 6 22:17:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue May 6 21:17:02 2003 Subject: [Tutor] adventure games [transforming Basic BASIC to Basic Python References: <0E5508EBA1620743B409A2B8365DE16FDC8581@sovereign.ci.las-vegas.nv.us> Message-ID: <3EB85F17.7040004@ccvcorp.com> Scott Widney wrote: >>Danny, I'm wondering if this could be made >>into a true generator function (as in, from __future__ >>import ...). What do you think? >> My thought is that there's not much point to that. The value of a generator is that it remembers state in between calls. This doesn't really have any state to remember, so there'd be no real benefit in using a generator. >>From here we could make this a function, maybe one that returns a list of >names. Or a module that could either be imported or run standalone. How >about a class? Hmmm. Although it generates names, it doesn't remember them; >it just sends them to stdout. Lots of options.... > > I'd say the most useful thing would be to have a function that returns a single generated name (building a string instead of writing to stdout). If you need more than one, it's easy enough to call that in a loop. You could put that function in a module and set up an 'if __name__ == "__main__"' section that calls the name-generator four times and writes the output to stdout. That'd give you the same functionality you have now, plus the flexibility of importing it and using the function directly elsewhere. Jeff Shannon Technician/Programmer Credit International From tim@johnsons-web.com Tue May 6 22:27:01 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Tue May 6 21:27:01 2003 Subject: [Tutor] quote + value of a variable In-Reply-To: <002b01c31422$2068f9a0$6401a8c0@xp> References: <20030506212048.GX25289@johnsons-web.com> <002b01c31422$2068f9a0$6401a8c0@xp> Message-ID: <20030507012605.GZ25289@johnsons-web.com> * Alan Gauld [030506 14:54]: > > I'd like to write a function that would take > > a variable and print out both the name of and the > > value. > > Usually a bad idea but if it's for a debug function then that's > probably an acceptable exception to the rule. Why not check > how pdb does it? For debug only, yes. > > >>> print 'mylist: ' , mylist > > mylist: [1, 2, 3] > > > > Any ideas appreciated. Pointers to > > documentations welcome. > > My first guess would be to trawl the builtins directory and > test the id of your variable against the names in there. > > something like: > > for name in dir(): > if __builtins__[name] is var: print name, var > > Or however you access the builtins dictionary directly! This gives me something to work with. Thanks Alan -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From phthenry@earthlink.net Wed May 7 01:09:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Wed May 7 00:09:01 2003 Subject: [Tutor] program that processes tokenized words in xml In-Reply-To: <5.2.1.1.0.20030506155751.02760a98@www.thinkware.se> References: <20030506133045.78326.qmail@web14503.mail.yahoo.com> <5.2.1.1.0.20030506155751.02760a98@www.thinkware.se> Message-ID: <20030507000747.O13810@localhost.localdomain> Your code breaks if I use uniocde. data = u'text \u201c' parser.Parse(data) Traceback (most recent call last): File "/home/paul/lib/python/paul/xml/expat.py", line 50, in ? parser.Parse(data) UnicodeError: ASCII encoding error: ordinal not in range(128) Interstingly, it is not expat itself that seems to be raising the error. Any idea what is going on? Thanks Paul On Tue, May 06, 2003 at 04:39:45PM +0200, Magnus Lyckå wrote: > > At 06:30 2003-05-06 -0700, Abdirizak abdi wrote: > >Can anyone suggest how I can incorporate a regular expression for > >eliminating these tags? > > Don't! > > Regular expressions are not the right tool for the task if we are talking > about XML parsing. There are finely crafted tools particularly for XML in > Python. Use them instead. > > Imagine you have XML data in a string like this and want to extract the > names of the persons (but not the animals): > > data=''' > > John CleeseFunny > Basil Fawlty > > > WandaFish > > > Eric Idle > Funny > > ''' > > Then we can do something like this... > > import xml.parsers.expat > > isPerson = False > isName = False > > def start_element(name, attrs): > global isPerson, isName > if name == 'person': > isPerson = True > elif name == 'name': > isName = True > > def end_element(name): > global isPerson, isName > if name == 'person': > isPerson = False > elif name == 'name': > isName = False > > def char_data(data): > if isPerson and isName: > print data > > parser = xml.parsers.expat.ParserCreate() > parser.StartElementHandler = start_element > parser.EndElementHandler = end_element > parser.CharacterDataHandler = char_data > > parser.Parse(data) > > ...and get: > > John Cleese > Basil Fawlty > Eric Idle > > This won't break if someone starts adding attributes to the > name tags, or if anyone decides to format the file differently, > so that the items you imagined were located on the same row, > is suddenly divided over three rows. If two files represent the > same content from an XML perspective, this program should also > extract the same data. I don't think you can ever fix that with > regular expressions. (At least it will be very hard work.) > > A simple regular expression might well seem to solve the problem > for you, with less code than expat etc, but it will probably be > much more brittle than using a real XML parser. > > I have made the assumption here that persons aren't nested inside > persons, and that names aren't nested inside names, but as long as > that's true, I think this should work as intended. > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The shortest path from thought to working program > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From thomi@thomi.imail.net.nz Wed May 7 02:54:02 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Wed May 7 01:54:02 2003 Subject: [Tutor] programming style question: Message-ID: <20030508175240.67a3b6ed.thomi@thomi.imail.net.nz> Hey! I'm doing a degree course in Dunedin, New Zealand, and as part of this we have to do a pascal assignment. Well, to cut a long story short, i handed in my assignment, and was marked down because i used the following structure for a loop: (obviously i wrote this in pascal): while 1: do_lots_of_things_here() if (condition): break ... Now, the alternative would have (in my mind anyway) been more convoluted, and harder to read. What do you all think? It is a bit off topic, but do you guys think programming style is a personal thing, or should there be set rules? Things like "do i use a for or while loop here? In pascal it's pretty much up to you; both are usable. what do you think? thanks, -- Thomi Richards, thomi@thomi.imail.net.nz From Simon.Wittber@perth.maptek.com.au Wed May 7 03:19:01 2003 From: Simon.Wittber@perth.maptek.com.au (Simon Wittber (Maptek)) Date: Wed May 7 02:19:01 2003 Subject: [Tutor] programming style question: Message-ID: <10F0E58C0018054484E329DC494C4D7F01AE0E@mexper1> Hi Thomi, >while 1: > do_lots_of_things_here() > if (condition): > break I see no problem with using this type of construct, in fact, I believe it is=20 a pretty common to see this sort of thing in Python code. >What do you all think? It is a bit off topic, but do you guys think=20 >programming style is a personal thing, or should there be set rules?=20 For the sake of your grades, I suggest you follow the style set down by your lecturer!=20 At my place of employment, I maintain several different applications in=20 different languages. The style of programming I use should be the same for each application, following the conventions used by programmers before me. Consistency is usually better than correctness, esp. when correctness is defined as my personal taste in code conventions and idioms. Of course, the conventions I use in my personal projects are the most=20 Correct way of doing things, and I'll never change that! Simon. From shalehperry@attbi.com Wed May 7 03:26:03 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed May 7 02:26:03 2003 Subject: [Tutor] programming style question: In-Reply-To: <20030508175240.67a3b6ed.thomi@thomi.imail.net.nz> References: <20030508175240.67a3b6ed.thomi@thomi.imail.net.nz> Message-ID: <200305062325.27030.shalehperry@attbi.com> On Wednesday 07 May 2003 22:52, Thomas CLive Richards wrote: > Hey! > > I'm doing a degree course in Dunedin, New Zealand, and as part of this we > have to do a pascal assignment. Well, to cut a long story short, i handed > in my assignment, and was marked down because i used the following > structure for a loop: (obviously i wrote this in pascal): > note, as much as we hate it, some instructors have preferred styles. It is usually a good idea to just conform to their style -- no matter how stupid. They probably have valid reasons for their style choice. Of course you are in school to learn and any instructor should be willing to explain their rationale. If not, perhaps you should speak to the next higher person. Another comment here on style is you will often run into lame, stupid, weird, broken, and plain odd styles, both in work and in the open source world. Learning to adapt to the local style is a valuable skill to pick up. I have heard from some that they have a hard time getting patches accepted by upstream authors. On more than one occasion I have had someone ask me "did I write this or did you?". This makes getting code accepted a lot easier. The worst example I can give is a person who insisted on 3 space indented C code along with a psuedo Hungarian naming style. > while 1: > do_lots_of_things_here() > if (condition): > break > ... > > Now, the alternative would have (in my mind anyway) been more convoluted, > and harder to read. What do you all think? It is a bit off topic, but do > you guys think programming style is a personal thing, or should there be > set rules? Things like "do i use a for or while loop here? In pascal it's > pretty much up to you; both are usable. what do you think? > With the lecturing out of the way, on to my personal beliefs. I recently had this discussion with a coder on one of my projects (in C++) when while loops started showing up. Seems his coworker believes 'for' is syntactic sugar and only 'while' should be used. We chatted about this for a while and came up with the following. * A while construct is to be used when the code is concerned about a condition being met (or not met). Some typical examples: while input != valid_input: get_more_input() while not complete: do_computation() # computation sets complete to true while not end of line: # or file read_more_date() while 1: handle_event() # sets should_exit if user asks for the program to end if should_exit: break If you have a potentially infinite loop, or just have no idea how long it will last it is probably a while loop. * a for construct should be used when you have a known structure or items and need to potentially access each one. counting loops, list walkers, etc. Basically if you think "iteration" the for loop is probably the right choice. So the following (using C++ because it is the easiest for me to write at 11pm): it = container.begin(); while (it != end) { handle(*it); ++it; } is less obvious to the reader than: for(it = container.begin() ; it != end; ++it) { handle(*it); } // yes, I realize for_each() is a better choice here, but this is an example This matches the typical python usage directly. for item in container: handle(item) From alan.gauld@blueyonder.co.uk Wed May 7 04:39:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Wed May 7 03:39:01 2003 Subject: [Tutor] programming style question: References: <20030508175240.67a3b6ed.thomi@thomi.imail.net.nz> Message-ID: <007601c3146b$a90af670$6401a8c0@xp> > ...marked down because i used the following structure for a loop: > > while 1: > do_lots_of_things_here() > if (condition): > break > ... In Pascal that probably should have been: repeat do_lots_of_things_here() until condition And at the very least it should have been while true .... end not while 1. > Now, the alternative would have (in my mind anyway) been > more convoluted, and harder to read. What do you all think? If you translate one idiom to another directly it often appears convoluted, if you use the native idiom it usually gets clearer. The "while true" idiom in pascal is rarely seen and considered bad practice because thats exactly what the repeat loop is there for. > It is a bit off topic, but do you guys think programming style > is a personal thing, or should there be set rules? There are usually rules, mainly for the sake of consistency. However there is hard evidence to suggest some style issues are important - levels of indentation, location of begin/end markers etc. - See Code Complete by McConnel for more on these. > Things like "do i use a for or while loop here? In pascal it's > pretty much up to you; both are usable. what do you think? Nope. In Pascal there are 3 loops each with a pretty distinct purpose. Using the wrong loop is considered bad style. FOR loops are for iterating over a fixed (or computable) number of items WHILE loops are for iterating over an unknown number of items, and particularly where you may not want to iterate at all. REPEAT loops are for cases where you always want to do the first iteration, but don't know how many others you will need. Alan G. From alan.gauld@blueyonder.co.uk Wed May 7 04:48:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Wed May 7 03:48:02 2003 Subject: [Tutor] programming style question: References: <10F0E58C0018054484E329DC494C4D7F01AE0E@mexper1> Message-ID: <007f01c3146d$0520c3d0$6401a8c0@xp> >>while 1: >> do_lots_of_things_here() >> if (condition): >> break > >I see no problem with using this type of construct, in fact, I believe >it is pretty common to see this sort of thing in Python code. Its common in Python but not at all common in Pascal. > ...following the conventions used by programmers before me. > Consistency is usually better than correctness, This is the main thing. Consistency within code is really important. Wen you visually scan a long listing its much easirer if all the code uses the same indent level, the same placing of block markers etc. For example, old Pascal code often uses this style: for n = 1 to 10 do begin { something here} end OR for n = 1 to 10 do begin { do something} end Wheras research has shown that a better style from a cognitive point of view is: for n = 1 to 10 do begin {do something} end OR (the most Pythonic version!) for n = 1 to 10 do begin {do something} end But if maintining old code it would be worse to try to insert new code with one of the latter styles into code using one of the first 2 stuyles - that would just be confusing. OTOH on a new project it would be best to adopt one of the latter 2 styles for the real cognitive benefits they bring. Alan G. From magnus@thinkware.se Wed May 7 07:16:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 7 06:16:02 2003 Subject: [Tutor] programming style question: In-Reply-To: <20030508175240.67a3b6ed.thomi@thomi.imail.net.nz> Message-ID: <5.2.1.1.0.20030507121019.025ea058@www.thinkware.se> At 17:52 2003-05-08 +1200, Thomas CLive Richards wrote: >while 1: > do_lots_of_things_here() > if (condition): > break >... > >Now, the alternative would have (in my mind anyway) been more convoluted, >and harder to read. The obvious way to code this in Pascal would be: repeat do_lots_of_things_here(); until condition; I would also have reacted to using a while loop here. It does give the impression that you haven't learnt all the basic constructs of Pascal. By using different constructs we give different messages, not only to the compiler, but also to other people reading the code, and the repeat-until loop, is what a Pascal programmer would expect in this case. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From charlie@begeistert.org Wed May 7 07:55:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Wed May 7 06:55:02 2003 Subject: [Tutor] Renaming directories Message-ID: <20030507125458.1896.7@wonderland.1052289410.fake> Dear list, about three years ago I started learning Python the first thing I wanted to do was rename a bunch of files and directories. I wasn't on the list at the time so I can't check the archives... The problem is quite simple I need to rename a bunch of files and directories. I can do the files using os.path.rename() but this gives an error with directories. What are the options? I've done some searching already but couldn't find anything suitable. Thanx Charlie From magnus@thinkware.se Wed May 7 07:58:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 7 06:58:02 2003 Subject: [Tutor] programming style question: In-Reply-To: <200305062325.27030.shalehperry@attbi.com> References: <20030508175240.67a3b6ed.thomi@thomi.imail.net.nz> <20030508175240.67a3b6ed.thomi@thomi.imail.net.nz> Message-ID: <5.2.1.1.0.20030507121756.00bc4c18@www.thinkware.se> At 23:25 2003-05-06 -0700, Sean 'Shaleh' Perry wrote: >I recently had this discussion with a coder on one of my projects (in C++) >when while loops started showing up. Seems his coworker believes 'for' is >syntactic sugar and only 'while' should be used. We chatted about this for a >while and came up with the following. [snip] Right! In C and derived languages, for *is* only an alternate syntax for a while loop, and the fact that you can rewrite... while condition() { a(); b(); c() } ...as... for (; condition(); a(), b(), c()); ...shows us how easy it is for "creative" programmers to abuse the C for loop. In most other languages, for loops have a very different meaning, and can only be used to loop over a sequence of some sort. Often only over a sequence of numbers. Basically a for loop implies: "Do something for every item in some kind of collection". Do something for every number between 2 and 9, or for every odd number between 1 and 15, or do something for every line in that file etc. Just as you said. A while loop is much more general: Do something repeatedly as long as a certain condition exists. This could be for a certain amount of time, until some external event happens, until a problem is solved or found unsolvable or whatever. It might be a good idea to use for-loops in the same context in C, C++, Java, as you would in Pascal, Ada, Basic or Python. This is likely to be the least confusing, even if the syntax doesn't stop you from using a for loop where ever a while loop occurs in C derivates. For-loops are not considered a deprecated feature in C++! Kernighan & Richie says (The C programming language, 2nd ed, p. 14): "The choice between while and for is arbitrary, based on which seems clearer. The for loop is usually appropriate for loops in which the initialization and increment are single statements and logically related, since it is more compact than while and it keeps the loop statement together in one place." This is fairly fuzzy, but certainly has a big overlap with our view in practice. Loops over sequences the way they are used in e.g. Python or Pascal, certainly fits the pattern suggested by K&R, and most other loops don't. Stroustrup pronounces "for(;;)" as the standard way to specify an infinite loop, with "while(true)" as an alternative. (The C++ Programming Language, Special Edition, p. 109). He calls this the "forever" loops. In page 136, he writes: "The for-statement is intended for fairly regular loops. The loop variable, the termination condition, and the expression that updates the loop can be presented 'up front' on a single line. [...] If the loop isn't of the simple ''introduce a loop variable, test the condition, update the loop variable'' variety, it's often better expressed as a while-statement." I think "often" is a clear understatement here... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Wed May 7 08:10:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 7 07:10:02 2003 Subject: [Tutor] Renaming directories In-Reply-To: <20030507125458.1896.7@wonderland.1052289410.fake> Message-ID: <5.2.1.1.0.20030507130552.00bee508@www.thinkware.se> At 12:54 2003-05-07 +0200, Charlie Clark wrote: >The problem is quite simple I need to rename a bunch of files and >directories. I can do the files using os.path.rename() but this gives an >error with directories. What are the options? I've done some searching >already but couldn't find anything suitable. There is no such thing as os.path.rename that I know of. At least not in Python 2.2. os.rename should work though. >>> import os >>> help(os.rename) Help on built-in function rename: rename(...) rename(old, new) -> None Rename a file or directory. It works for me. I don't think we can help you unless you provide more details, such as what OS, what kind of file system and in particular: What is the error message? I can imagine that the directory is locked for some reason. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From charlie@begeistert.org Wed May 7 08:16:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Wed May 7 07:16:02 2003 Subject: [Tutor] Renaming directories In-Reply-To: <5.2.1.1.0.20030507130552.00bee508@www.thinkware.se> References: <5.2.1.1.0.20030507130552.00bee508@www.thinkware.se> Message-ID: <20030507131542.2024.9@wonderland.1052289410.fake> On 2003-05-07 at 13:11:08 [+0200], you wrote: > There is no such thing as os.path.rename that I know of. At least not in > Python 2.2. > > os.rename should work though. duh, sorry. Feels like a "path" function. > >>> import os > >>> help(os.rename) > Help on built-in function rename: > rename(...) > rename(old, new) -> None > Rename a file or directory. > > It works for me. I don't think we can help you unless you provide more > details, such as what OS, what kind of file system and in particular: > What is the error message? > > I can imagine that the directory is locked for some reason. >From the module reference: """Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be removed silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file. Availability: Macintosh, Unix, Windows.""" As I am windows I do get OSError on all directories which I need to rename as some of the programs (like Python) are case sensitive even if Windows itself isn't. Charlie From magnus@thinkware.se Wed May 7 10:05:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 7 09:05:01 2003 Subject: [Tutor] Renaming directories In-Reply-To: <20030507131542.2024.9@wonderland.1052289410.fake> References: <5.2.1.1.0.20030507130552.00bee508@www.thinkware.se> <5.2.1.1.0.20030507130552.00bee508@www.thinkware.se> Message-ID: <5.2.1.1.0.20030507143825.00bd42d8@www.thinkware.se> At 13:15 2003-05-07 +0200, Charlie Clark wrote: >From the module reference: >"""Rename the file or directory src to dst. If dst is a directory, OSError >will be raised. Read carefully: "If dst *is* a directory..." (my emphasis) I.e., if you already have a directory 'a', *and* a directory 'b', os.rename('a', 'b') will cause an OSError. It won't just swipe an existing directory away. If you really want to do that, you have to remove or rename the destination directory first. As furhter noted, you need to do a corresponding operation on simple files as well if you run on Windows. >As I am windows I do get OSError on all directories which I need to rename >as some of the programs (like Python) are case sensitive even if Windows >itself isn't. I don't know what case sensitivity has to do with this. NTFS is certainly case sensitive, even if it doesn't allow the coexistence of files or directories whose names only differ in case. Please tell us what you are *really* trying to do. It's helpful if you show us your code and your failed session, including *exact* error message. See mine below: As you see, I have no problems with this: H:\tmp>ver Microsoft Windows 2000 [Version 5.00.2195] H:\tmp>md test1 H:\tmp>dir test? Volymen i enhet H har etiketten mly Volymens serienummer =E4r 104A-0151 Inneh=E5ll i katalogen H:\tmp 2003-05-07 15:29 test1 0 fil(er) 0 byte 1 katalog(er) 310 804 480 byte ledigt H:\tmp>python -c "import os; os.rename('test1', 'test2')" H:\tmp>dir test? Volymen i enhet H har etiketten mly Volymens serienummer =E4r 104A-0151 Inneh=E5ll i katalogen H:\tmp 2003-05-07 15:29 test2 0 fil(er) 0 byte 1 katalog(er) 310 804 480 byte ledigt H:\tmp>rd test2 But I can't do this (just as expected). BTW, touch is a unix command, available on Windows through cygwin. It just creates an empty file in this case. H:\tmp>md test1 H:\tmp>md TEST2 H:\tmp>touch test1/x1.txt H:\tmp>touch TEST2/x2.txt H:\tmp>python -c "import os; os.rename('test1', 'test2')" Traceback (most recent call last): File "", line 1, in ? OSError: [Errno 13] Permission denied H:\tmp>python -c "import os; os.rename('test1', 'test3')" On Windows I can't rename test1 to test2 if there is already a TEST2, since these names are considered to be equivalent. H:\tmp>python -c "import os; os.rename('test3', 'test1')" H:\tmp>python -c "import os; os.rename('Test1', 'test3')" I'd say this behaves just as one would expect on Windows. I can give source directory name as "Test1", even if it's really "test1", since these are equivalent. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program=20 From a_abdi406@yahoo.com Wed May 7 10:55:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed May 7 09:55:02 2003 Subject: [Tutor] question about merging two programs Message-ID: <20030507132718.94348.qmail@web14503.mail.yahoo.com> --0-812188271-1052314038=:94115 Content-Type: text/plain; charset=us-ascii Hi,I was working on two separate programs one program for file indexingand another for searching the words, I was running them separatelynow I decided to put to together with a single main( ), I set up the program to be run this way: (the main is shown below) first for indexing:C:\TestInd>index-02.py Test Doc.txt |-----------------|--------|-------------| prog dir file to be indexed Second for searching:C:\TestInd>index-02.py Test word |-----------------|--------|-------------| prog dir word to be searched Here is the main part set up to fit the two above possibilities:The searching part works but the indexing part when merged it doesn'twork the program jumps to the else when searching but when asked forindexing it doesn't execute the top section, but it compiles without anyerror. Can anyone spot any upnormalities specialy if I got it right the condition which evalutes if argv[2] in [ '.txt' ] which means if the argument contains substring '.txt' here is the program def main(argv): if len(argv) < 2: sys.stderr.write(usage + "\n") return 1 #------------------------ #Extension = argv[2] if argv[2] in ['.txt']: #print argv[2] indexdir = argv[1] files = argv[2:] myindexer = indexer(indexdir) try: for file in files: print "indexing....", file, sys.stdout.flush() myindexer.index(file) print "...done." finally: print "committing....", sys.stdout.flush() myindexer.commit() print "....done." return 0 thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-812188271-1052314038=:94115 Content-Type: text/html; charset=us-ascii
Hi,
I was working on two separate programs one program for file indexing
and another for searching the words, I was running them separately
now I decided to put to together with a single main( ), I set up the program to be run this way: (the main is shown below)
 
first for indexing:
C:\TestInd>index-02.py Test Doc.txt
                 |-----------------|--------|-------------|
                   prog           dir     file to be indexed
 
Second for searching:
C:\TestInd>index-02.py Test word
                  |-----------------|--------|-------------|
                    prog           dir     word to be searched
 
Here is the main part set up to fit the two above possibilities:
The searching part works but the indexing part when merged it doesn't
work the program jumps to the else when searching but when asked for
indexing it doesn't execute the top section, but it compiles without any
error.  Can anyone spot any upnormalities specialy if I got it right the
condition which evalutes  if argv[2] in [ '.txt' ] which means if the argument contains substring  '.txt'
 
here is the program
 
def main(argv):
    if len(argv) < 2:
        sys.stderr.write(usage + "\n")
        return 1
    #------------------------
    #Extension = argv[2]
   
    if argv[2] in ['.txt']:
      #print argv[2]
      indexdir = argv[1]
      files = argv[2:]
      myindexer = indexer(indexdir)
      try:
        for file in files:
          print "indexing....", file,
          sys.stdout.flush()
          myindexer.index(file)
          print "...done."
      finally:
        print "committing....",
        sys.stdout.flush()
        myindexer.commit()
        print "....done."
      return 0 
 
 
thanks in advance


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-812188271-1052314038=:94115-- From bgailer@alum.rpi.edu Wed May 7 11:23:07 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed May 7 10:23:07 2003 Subject: [Tutor] question about merging two programs In-Reply-To: <20030507132718.94348.qmail@web14503.mail.yahoo.com> Message-ID: <5.2.0.9.0.20030507081952.01a1aae8@66.28.54.253> --=======484B4E7C======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-6D6F1DCD; boundary="=====================_2607469==.ALT" --=====================_2607469==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-6D6F1DCD; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 06:27 AM 5/7/2003 -0700, Abdirizak abdi wrote: >Hi, >I was working on two separate programs one program for file indexing >and another for searching the words, I was running them separately >now I decided to put to together with a single main( ), I set up the >program to be run this way: (the main is shown below) > >first for indexing: >C:\TestInd>index-02.py Test Doc.txt > |-----------------|--------|-------------| > prog dir file to be indexed > >Second for searching: >C:\TestInd>index-02.py Test word > |-----------------|--------|-------------| > prog dir word to be searched > >Here is the main part set up to fit the two above possibilities: >The searching part works but the indexing part when merged it doesn't >work the program jumps to the else when searching but when asked for >indexing it doesn't execute the top section, but it compiles without any >error. Can anyone spot any upnormalities specialy if I got it right the >condition which evalutes if argv[2] in [ '.txt' ] which means if the >argument contains substring '.txt' > >here is the program > >def main(argv): > if len(argv) < 2: > sys.stderr.write(usage + "\n") > return 1 > #------------------------ > #Extension = argv[2] > > if argv[2] in ['.txt']: Replace this with if argv[2].find('.txt') >= 0: > #print argv[2] > indexdir = argv[1] > files = argv[2:] > myindexer = indexer(indexdir) > try: > for file in files: > print "indexing....", file, > sys.stdout.flush() > myindexer.index(file) > print "...done." > finally: > print "committing....", > sys.stdout.flush() > myindexer.commit() > print "....done." > return 0 > > >thanks in advance > > >Do you Yahoo!? >The New >Yahoo! Search - Faster. Easier. Bingo. >--- >Incoming mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003 Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=====================_2607469==.ALT Content-Type: text/html; x-avg-checked=avg-ok-6D6F1DCD; charset=us-ascii Content-Transfer-Encoding: 8bit At 06:27 AM 5/7/2003 -0700, Abdirizak abdi wrote:

Hi,
I was working on two separate programs one program for file indexing
and another for searching the words, I was running them separately
now I decided to put to together with a single main( ), I set up the program to be run this way: (the main is shown below)
 
first for indexing:
C:\TestInd>index-02.py Test Doc.txt
                 |-----------------|--------|-------------|
                   prog           dir     file to be indexed
 
Second for searching:
C:\TestInd>index-02.py Test word
                  |-----------------|--------|-------------|
                    prog           dir     word to be searched
 
Here is the main part set up to fit the two above possibilities:
The searching part works but the indexing part when merged it doesn't
work the program jumps to the else when searching but when asked for
indexing it doesn't execute the top section, but it compiles without any
error.  Can anyone spot any upnormalities specialy if I got it right the
condition which evalutes  if argv[2] in [ '.txt' ] which means if the argument contains substring  '.txt'
 
here is the program
 
def main(argv):
    if len(argv) < 2:
        sys.stderr.write(usage + "\n")
        return 1
    #------------------------
    #Extension = argv[2]
   
    if argv[2] in ['.txt']:

Replace this with
      if argv[2].find('.txt') >= 0:

      #print argv[2]
      indexdir = argv[1]
      files = argv[2:]
      myindexer = indexer(indexdir)
      try:
        for file in files:
          print "indexing....", file,
          sys.stdout.flush()
          myindexer.index(file)
          print "...done."
      finally:
        print "committing....",
        sys.stdout.flush()
        myindexer.commit()
        print "....done."
      return 0 
 
 
thanks in advance


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo.
---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
--=====================_2607469==.ALT-- --=======484B4E7C======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6D6F1DCD Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003 --=======484B4E7C=======-- From dman@dman.ddts.net Wed May 7 11:52:20 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Wed May 7 10:52:20 2003 Subject: [Tutor] Re: Gui recommendations requested: Which GUI wxPython or PyQT ? In-Reply-To: <20030505193724.L1144-100000@yamato.yamato.com> References: <20030506023501.13177.40244.Mailman@mail.python.org> <20030505193724.L1144-100000@yamato.yamato.com> Message-ID: <20030507145731.GA10514@dman.ddts.net> --y0ulUmNC+osPPQO6 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, May 05, 2003 at 07:41:51PM -0700, Tony Cappellini wrote: |=20 | I want to do some GUI apps in Python, mostly for Win32 programs. | Since I don't know either one, I have to start from scratch with both. |=20 | Which is faster to learn ? (I have done some event-driven programming | before) |=20 | Which of the 2 gui's above is better to use, in the long run ? I would choose wxPython. I have experience using GTK (mostly through the gtk-- C++ wrapper) and Swing (mostly in Java but I did one Python-Swing app using jython) and am currently nearly finished with a school project using wxPython (due on Monday!). Swing is a real pain, especially in java :-). GTK is fairly easy to learn and the layout methodology makes a lot of sense. The main problem with it is it is a little more difficult to get running on Windows (IMO, but then again I don't have any MS development tools) but may be easier with python than straight C. wxPython is nicer to use than Swing, the layout methodology is fairly similar to GTK and is easy to grasp as well (and get it to do what you want). As I've been working on this project I've noticed how many "advanced" widgets wxPython provides. It's really convenient when the toolkit does the work for you. Another advantage, if you need to try and "market" your project, is that a wx application will look just like any other MSW application when run on MSW. Your non-technical, and possibly even some technical, users will appreciate that. (personally I prefer GTK even when I'm stuck with Windows, but I'm not a "typical" user) | Are there any comparisons of Python Guis available ? Yes. Just do a search on some web sites. I have this one handy right now. A while back someone wrote a fairly comprehensive comparision, but I don't remember who or where it is. http://wiki.wxwindows.org/wiki.pl?WxWindows_Compared_To_Other_Toolkits -D --=20 Religion that God our Father accepts as pure and faultless is this: to look after orphans and widows in their distress and to keep oneself from being polluted by the world. James 1:27 =20 http://dman.ddts.net/~dman/ --y0ulUmNC+osPPQO6 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj65HtoACgkQiB6vp1xAVUAyoQCeKQDc122CoRN/1eMJ19CINq4h uFMAn0J/EnzzGDGGcEsFlGGrx+hEtcSU =KnFp -----END PGP SIGNATURE----- --y0ulUmNC+osPPQO6-- From dan_nash@hotmail.com Wed May 7 12:06:01 2003 From: dan_nash@hotmail.com (Daniel Nash) Date: Wed May 7 11:06:01 2003 Subject: [Tutor] String matching in 1.5.2 problem Message-ID: I have a python 1.5.2 string matching problem. I have two lists of email addresses: list1 = ["dan@NO-SPAM.company.com","fred@NO-SPAM.company.com"] and another list made up from the contents extracted from an email's headers To:,Cc: & Bcc: list2 =[('', 'support@NO-SPAM.company.com'), ('jim', 'jim@NO-SPAM.company.com'), ('', 'fred@NO-SPAM.comapny.com')] I am trying to write a peice of code that will run in python 1.5.2 to return true if any element in list1 appears in list2. In python2 I had this and it served its purpose: for X,Y in list2: for List1Head in List1: if Y.find(List1Head) == -1: # if false then do nothing print "Is NOT Addressed to: ", List1Head else: print "Is Addressed to: ", List1Head But I have to make it run on 1.5.2 and I get the following message: Traceback (innermost last): File "MAILIN.py", line 55, in ? if Y.find(List1Head) == -1: AttributeError: 'string' object has no attribute 'find' Can anyone tell me how to alter my code to work/improve on my code to only return true on an exact match of an email address rather than a sub string which allows errors as returning ture for MILE.COM WITHIN SMILE.COM? _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From Janssen@rz.uni-frankfurt.de Wed May 7 12:23:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed May 7 11:23:01 2003 Subject: [Tutor] re matching In-Reply-To: <20030501194730.GA32268@boora.com> Message-ID: On Thu, 1 May 2003, Michael Montagne wrote: > I'm trying to quickly parse some errors out of mail.log. [snip some code] > It should make a list of strings representing lines with the word > "Abandoning" on them. Then for each of those strings, look through > the same list of strings for those matching the string. But I can not why research the lines after you already found them? Just put each line into a list within if-statement (beside the date) Sidenote: aList = aList + ["string"] is funktionial, but generate a *new* list on each step. aList.append("string") is conventionally and fast. Michael From reggie@merfinllc.com Wed May 7 12:30:06 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Wed May 7 11:30:06 2003 Subject: [Tutor] String matching in 1.5.2 problem In-Reply-To: References: Message-ID: <1052321640.8693.19.camel@pika> I believe in 1.5.2 you have to import the string module and use the find function. Something like import string ... if string.find(Y, List1Head) == -1: ... This should also work fine in python 2. HTH, On Wed, 2003-05-07 at 08:03, Daniel Nash wrote: > I have a python 1.5.2 string matching problem. > > I have two lists of email addresses: > > list1 = ["dan@NO-SPAM.company.com","fred@NO-SPAM.company.com"] > > and another list made up from the contents extracted from an email's headers > To:,Cc: & Bcc: > > list2 =[('', 'support@NO-SPAM.company.com'), ('jim', > 'jim@NO-SPAM.company.com'), ('', > 'fred@NO-SPAM.comapny.com')] > > I am trying to write a peice of code that will run in python 1.5.2 to return > true if any element in list1 appears in list2. > > In python2 I had this and it served its purpose: > > for X,Y in list2: > for List1Head in List1: > if Y.find(List1Head) == -1: > # if false then do nothing > print "Is NOT Addressed to: ", List1Head > else: > print "Is Addressed to: ", List1Head > > But I have to make it run on 1.5.2 and I get the following message: > > Traceback (innermost last): > File "MAILIN.py", line 55, in ? > if Y.find(List1Head) == -1: > AttributeError: 'string' object has no attribute 'find' > > Can anyone tell me how to alter my code to work/improve on my code to only > return true on an exact match of an email address rather than a sub string > which allows errors as returning ture for MILE.COM WITHIN SMILE.COM? > > _________________________________________________________________ > STOP MORE SPAM with the new MSN 8 and get 2 months FREE* > http://join.msn.com/?page=features/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Reggie From charlie@begeistert.org Wed May 7 13:03:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Wed May 7 12:03:01 2003 Subject: [Tutor] Renaming directories In-Reply-To: <5.2.1.1.0.20030507143825.00bd42d8@www.thinkware.se> References: <5.2.1.1.0.20030507130552.00bee508@www.thinkware.se> <5.2.1.1.0.20030507130552.00bee508@www.thinkware.se> <5.2.1.1.0.20030507143825.00bd42d8@www.thinkware.se> Message-ID: <20030507180215.2346.11@wonderland.1052289410.fake> On 2003-05-07 at 15:05:58 [+0200], you wrote: > Read carefully: "If dst *is* a directory..." (my emphasis) > > I.e., if you already have a directory 'a', *and* a directory 'b', > os.rename('a', 'b') will cause an OSError. It won't just swipe an > existing directory away. If you really want to do that, you have to > remove or rename the destination directory first. > > As furhter noted, you need to do a corresponding operation on simple > files as well if you run on Windows. > > I don't know what case sensitivity has to do with this. NTFS is certainly > case sensitive, even if it doesn't allow the coexistence of files or > directories whose names only differ in case. Oh I'll admit the horrible truth: Windows overwrote part of my BeOS partition when coming out of hibernation (didn't mention it was doing it). Of course, according to Microsoft I'm probably breaking the licence agreement by installing another operating system on _my_ machine anyway so their software is perfectly within its rights to correct matter! While trying to restore a single file from the BeOS with "dd" I made a mistake and BeOS got it's revenge and overwrote some of the windows partition :-( I've found a program which seems to do a reasonable job of restoring things. It seems to have had a problem with filenames: all lowercase have been restored as all uppercase and this affects Python modules in my Zope distro :-( It's a FAT partition so I didn't think this would matter but it does. > Please tell us what you are *really* trying to do. It's helpful if you > show us your code and your failed session, including *exact* error > message. See mine below: import os file_list = [] def clean(file_list, dir, files): for file in files: if file.upper() == file: fp = os.path.join(dir, file) if os.path.isfile(fp): os.rename(fp, fp.lower()) else: file_list.append(fp) ## print "%s needs renaming" %file ## os.rename(file, file.lower()) file_list.append(file) os.path.walk(".", clean, file_list) out = open("dump.txt", "w") out.write("\n".join(file_list)) ##print file_list and these are some of the things which don't get renamed: .\usr\LOCAL\BIN BIN .\usr\LOCAL\DOC DOC .\usr\LOCAL\INCLUDE INCLUDE .\usr\LOCAL\KANNEL KANNEL So it seems it's not possible to rename folders in place in windows using Python. What are my options? What I think I can do is create a new "root" folder and store everything in that using os.renames() which will create the folders required. Sound reasonable? Charlie From dan_nash@hotmail.com Wed May 7 13:29:02 2003 From: dan_nash@hotmail.com (Daniel Nash) Date: Wed May 7 12:29:02 2003 Subject: [Tutor] DB qurey Problem Message-ID: I have a DB with email addresses in it when I do the following qurey: EmailList = db.query("SELECT distinct email FROM users").getresult() I get a list like this : [('dan.nash@company.com',), ('fred.smit@company.com',)] I want to return this list without the extra comma in each element in the list. Can I do this, if so how? Or am I going to have to get rid of it another way? Thanks for your help, Dan _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From rick@niof.net Wed May 7 13:43:02 2003 From: rick@niof.net (Rick Pasotto) Date: Wed May 7 12:43:02 2003 Subject: [Tutor] DB qurey Problem In-Reply-To: References: Message-ID: <20030507163347.GB11156@tc.telocity.com> On Wed, May 07, 2003 at 12:27:48PM -0400, Daniel Nash wrote: > > I have a DB with email addresses in it > > when I do the following qurey: > > EmailList = db.query("SELECT distinct email FROM users").getresult() > > I get a list like this : [('dan.nash@company.com',), > ('fred.smit@company.com',)] > > I want to return this list without the extra comma in each element in the > list. Can I do this, if so how? Or am I going to have to get rid of it > another way? EmailList[0][0] does not have a comma in it. EmailList[1][0] does not have a comma in it. -- "A moral code impossible to practice, a code that demands imperfection or death, has taught you to dissolve all ideas in fog, to permit no firm definitions, to regard any concept as approximate & any rule of conduct as elastic, to hedge on any principle, to compromise on any value, to take the middle of any road." -- Ayn Rand Rick Pasotto rick@niof.net http://www.niof.net From bgailer@alum.rpi.edu Wed May 7 13:53:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed May 7 12:53:02 2003 Subject: [Tutor] DB qurey Problem In-Reply-To: Message-ID: <5.2.0.9.0.20030507104627.026eae48@66.28.54.253> --=======428E16C6======= Content-Type: text/plain; x-avg-checked=avg-ok-6D6F1DCD; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 12:27 PM 5/7/2003 -0400, Daniel Nash wrote: >I have a DB with email addresses in it > >when I do the following qurey: > >EmailList = db.query("SELECT distinct email FROM users").getresult() > >I get a list like this : [('dan.nash@company.com',), >('fred.smit@company.com',)] > >I want to return this list without the extra comma in each element in the >list. EmailList is a list of tuples, one tuple per row. The "extra comma" shows up only when you display the list. This is the same as requiring you to provide a trailing comma when specifying a tuple with one element. If what you are after is a list of strings, do this: EmailList = [row[0] for row in EmailList] The result will be: ['dan.nash@company.com', 'fred.smit@company.com'] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======428E16C6======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6D6F1DCD Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003 --=======428E16C6=======-- From roypython@hotmail.com Wed May 7 14:44:01 2003 From: roypython@hotmail.com (roy ollis) Date: Wed May 7 13:44:01 2003 Subject: [Tutor] What would you recomend a total newbie to do? Message-ID: What are the best resorces to learn python. I'm a non programmer so i wont understand something with alot of tech terms. I have downloaded 2.2.2 and it comes with a tutorial but i was wondering what other tutorials i should buy or download. is there a book that starts for newbies and by the time you get to the end of the book you know even the advanced stuff? And should i have downloaded 2.3.1b instead. i wont know if the programs has a glitch or if it's me so i chose "stable" release? thanks for any help in advance rdo _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From zak@harlekin-maus.com Wed May 7 14:53:02 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Wed May 7 13:53:02 2003 Subject: [Tutor] What would you recomend a total newbie to do? In-Reply-To: References: Message-ID: <2602.192.207.104.206.1052329973.squirrel@mail.harlekin-maus.com> > What are the best resorces to learn python. I'm a non programmer > so i > wont understand something with alot of tech terms. I have downloaded > 2.2.2 and it comes with a tutorial but i was wondering what other > tutorials i should buy or download. is there a book that starts for > newbies and by the time you get to the end of the book you know even > the advanced stuff? And should i have downloaded 2.3.1b instead. i > wont know if the programs has a glitch or if it's me so i chose > "stable" release? > > thanks for any help in advance > rdo My advice would be to stick with 2.2, and come up with your own problems to solve. You've done the tutorial, so now you know the basics of the language. Now pick something fun that will keep your interest. For myself that fun thing is working on little games. I work out a specification for the game, keeping in mind it should be very, very small. Then try to program it. Since you're new to programming, here are some simple games to try writing (if that's the thing you'd like to do): * User guesses a random number. Computer replies "right" or "wrong" * User guesses a random number, if the user is wrong, the computer prompts with "too hi" or "too low" * A Hangman game without graphics (or ASCII art) * A two-player tic-tac-toe (with ASCII art) -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From jeff@ccvcorp.com Wed May 7 14:54:06 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed May 7 13:54:06 2003 Subject: [Tutor] What would you recomend a total newbie to do? References: Message-ID: <3EB948B0.40205@ccvcorp.com> roy ollis wrote: > What are the best resorces to learn python. I'm a non programmer > so i wont understand something with alot of tech terms. I have > downloaded 2.2.2 and it comes with a tutorial but i was wondering what > other tutorials i should buy or download. is there a book that starts > for newbies and by the time you get to the end of the book you know > even the advanced stuff? And should i have downloaded 2.3.1b > instead. i wont know if the programs has a glitch or if it's me so i > chose "stable" release? I think that starting with the latest stable release is a good idea. I would generally recommend newbies to *anything* to avoid beta releases, unless there's a compelling reason. (Admittedly, Python betas tend to be of notably higher quality and stability than a lot of other beta software, especially that from certain commercial producers, but I still think you're best off with a stable release.) There's an entire section on the Python community website (www.python.org) that's devoted specifically to beginning programmers. Check out the resources listed on http://www.python.org/doc/Newbies.html This should give you a pretty good starting point. Feel free to come back here to ask further questions any time you have them. Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Wed May 7 15:03:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed May 7 14:03:02 2003 Subject: [Tutor] String matching in 1.5.2 problem In-Reply-To: Message-ID: On Wed, 7 May 2003, Daniel Nash wrote: > I have a python 1.5.2 string matching problem. > > I have two lists of email addresses: > > list1 = ["dan@NO-SPAM.company.com","fred@NO-SPAM.company.com"] > > and another list made up from the contents extracted from an email's > headers To:,Cc: & Bcc: > > list2 =[('', 'support@NO-SPAM.company.com'), ('jim', > 'jim@NO-SPAM.company.com'), ('', > 'fred@NO-SPAM.comapny.com')] > > I am trying to write a peice of code that will run in python 1.5.2 to return > true if any element in list1 appears in list2. Hi Daniel, Reggie already showed that the 'string.find()' function can help you port your code to Python 1.52. By the way, we may be able to take advantage of dictionaries if we want to see if one thing is an element in another thing. If we represent list2 as a dictionary, ### addr_book = { 'support@NO-SPAM.company.com' : 1, 'jim@NO-SPAM.company.com' : 1, 'fred@NO-SPAM.company.com' : 1 } ### then when we try to see if something in list1 is in list2, that involves a simple dictionary lookup: ### for List1Head in List1: if addr_book.has_key(List1Head): ## Written in Python 1.52 style print "Is Addressed to: ", List1Head else: print "Is NOT Addressed to: ", List1Head ### This code ends up being simpler if we use a data structure like a dictionary. Nested loops make me dizzy, so anything that simplifies the code can only be a good thing. *grin* Hope this helps! From joachim.hengge@gmx.net Wed May 7 15:53:18 2003 From: joachim.hengge@gmx.net (Joachim Hengge) Date: Wed May 7 14:53:18 2003 Subject: [Tutor] What would you recomend a total newbie to do? In-Reply-To: References: Message-ID: <3EB955BC.3010306@gmx.net> for a non-programmer there is an excellent FREE book available at the ibiblio open book project : "How to Think Like a Computer Scientist: Learning with Python" -> see http://www.ibiblio.org/obp/thinkCSpy Have fun Jojo roy ollis wrote: > What are the best resorces to learn python. I'm a non programmer so > i wont understand something with alot of tech terms. I have downloaded > 2.2.2 and it comes with a tutorial but i was wondering what other > tutorials i should buy or download. is there a book that starts for > newbies and by the time you get to the end of the book you know even the > advanced stuff? And should i have downloaded 2.3.1b instead. i wont > know if the programs has a glitch or if it's me so i chose "stable" > release? > > thanks for any help in advance > rdo Belaustrasse 5/3 D-70195 Stuttgart Mobil: +49.160.98637608 Email: joachim.hengge@gmx.net From magnus@thinkware.se Wed May 7 16:10:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 7 15:10:02 2003 Subject: [Tutor] What would you recomend a total newbie to do? In-Reply-To: Message-ID: <5.2.1.1.0.20030507205735.00bcd320@www.thinkware.se> At 17:43 2003-05-07 +0000, roy ollis wrote: > What are the best resorces to learn python. I'm a non programmer so > i wont understand something with alot of tech terms. I have downloaded > 2.2.2 and it comes with a tutorial but i was wondering what other > tutorials i should buy or download. is there a book that starts for > newbies and by the time you get to the end of the book you know even the > advanced stuff? Unless you speak German, I think Alan Gaulds book is the one which is most aimed at beginners. Alan also has a web site here: http://www.freenetpages.co.uk/hp/alan.gauld/ Another book that doesn't assume prior programming skills, but seems a bit more academic, is available here: http://www.ibiblio.org/obp/thinkCSpy/ Since Python is a easier to learn and work with than most other languages, I think you will learn fairly much from any good python book or tutorial, compared with the resources for other languages, but there is always more to learn...so it's all a matter of what you think is advanced. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From joachim.hengge@gmx.net Wed May 7 16:40:02 2003 From: joachim.hengge@gmx.net (Joachim Hengge) Date: Wed May 7 15:40:02 2003 Subject: [Tutor] What would you recomend a total newbie to do? In-Reply-To: <009f01c314cc$f11fe8b0$7840fea9@BillieWages> References: <3EB955BC.3010306@gmx.net> <009f01c314cc$f11fe8b0$7840fea9@BillieWages> Message-ID: <3EB960C6.9070801@gmx.net> there are latex sources, ps, pdf and html versions available. Your printer is responsible for the print version Billie wrote: > The site links to B&N and Amazon for a $24.95 price. Is the "free book" > in print or pdf format? > Billie > > ----- Original Message ----- > *From:* Joachim Hengge > *To:* roy ollis ; tutor@python.org > > *Sent:* Wednesday, May 07, 2003 1:51 PM > *Subject:* Re: [Tutor] What would you recomend a total newbie to do? > > for a non-programmer there is an excellent FREE book available at the > ibiblio open book project : "How to Think Like a Computer Scientist: > Learning with Python" -> see http://www.ibiblio.org/obp/thinkCSpy > Have fun > > Jojo > > > roy ollis wrote: > > What are the best resorces to learn python. I'm a non programmer so > > i wont understand something with alot of tech terms. I have downloaded > > 2.2.2 and it comes with a tutorial but i was wondering what other > > tutorials i should buy or download. is there a book that starts for > > newbies and by the time you get to the end of the book you know even the > > advanced stuff? And should i have downloaded 2.3.1b instead. i wont > > know if the programs has a glitch or if it's me so i chose "stable" > > release? > > > > thanks for any help in advance > > rdo > Belaustrasse 5/3 > D-70195 Stuttgart > > Mobil: +49.160.98637608 > Email: joachim.hengge@gmx.net > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Joachim Hengge Belaustrasse 5/3 D-70195 Stuttgart Mobil: +49.160.98637608 Email: joachim.hengge@gmx.net From bh-wages@swbell.net Wed May 7 17:12:06 2003 From: bh-wages@swbell.net (Billie) Date: Wed May 7 16:12:06 2003 Subject: [Tutor] What would you recomend a total newbie to do? References: <3EB955BC.3010306@gmx.net> <009f01c314cc$f11fe8b0$7840fea9@BillieWages> <3EB960C6.9070801@gmx.net> Message-ID: <018501c314d4$e50ef1d0$7840fea9@BillieWages> That is what I assumed, but just wanted clarification. :) Billie ----- Original Message ----- From: Joachim Hengge To: Billie ; tutor@python.org Sent: Wednesday, May 07, 2003 2:38 PM Subject: Re: [Tutor] What would you recomend a total newbie to do? there are latex sources, ps, pdf and html versions available. Your printer is responsible for the print version Billie wrote: > The site links to B&N and Amazon for a $24.95 price. Is the "free book" > in print or pdf format? > Billie > > ----- Original Message ----- > *From:* Joachim Hengge > *To:* roy ollis ; tutor@python.org > > *Sent:* Wednesday, May 07, 2003 1:51 PM > *Subject:* Re: [Tutor] What would you recomend a total newbie to do? > > for a non-programmer there is an excellent FREE book available at the > ibiblio open book project : "How to Think Like a Computer Scientist: > Learning with Python" -> see http://www.ibiblio.org/obp/thinkCSpy > Have fun > > Jojo > > > roy ollis wrote: > > What are the best resorces to learn python. I'm a non programmer so > > i wont understand something with alot of tech terms. I have downloaded > > 2.2.2 and it comes with a tutorial but i was wondering what other > > tutorials i should buy or download. is there a book that starts for > > newbies and by the time you get to the end of the book you know even the > > advanced stuff? And should i have downloaded 2.3.1b instead. i wont > > know if the programs has a glitch or if it's me so i chose "stable" > > release? > > > > thanks for any help in advance > > rdo > Belaustrasse 5/3 > D-70195 Stuttgart > > Mobil: +49.160.98637608 > Email: joachim.hengge@gmx.net > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Joachim Hengge Belaustrasse 5/3 D-70195 Stuttgart Mobil: +49.160.98637608 Email: joachim.hengge@gmx.net _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From tbstep@tampabay.rr.com Wed May 7 18:24:02 2003 From: tbstep@tampabay.rr.com (Todd Stephens) Date: Wed May 7 17:24:02 2003 Subject: [Tutor] What would you recomend a total newbie to do? In-Reply-To: <018501c314d4$e50ef1d0$7840fea9@BillieWages> References: <3EB960C6.9070801@gmx.net> <018501c314d4$e50ef1d0$7840fea9@BillieWages> Message-ID: <200305071720.45179.tbstep@tampabay.rr.com> On Wednesday 07 May 2003 04:11 pm, Billie wrote: > That is what I assumed, but just wanted clarification. :) > Billie > The actual downloads are in the path http://www.ibiblio.org/obp/thinkCSpy/dist/ Todd Stephens From max_ig@yahoo.com Wed May 7 20:46:01 2003 From: max_ig@yahoo.com (MI) Date: Wed May 7 19:46:01 2003 Subject: [Tutor] Tkinter + Linux = ugly? Message-ID: <20030507234550.70330.qmail@web11308.mail.yahoo.com> Am I wrong ???? ... or Tkinter looks very ugly on Linux? I've run it on Win98 but after migrating to SuSE linux Tkinter apps look depresing!!! Is there any way to make it better?? __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From a_abdi406@yahoo.com Thu May 8 00:25:07 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed May 7 23:25:07 2003 Subject: [Tutor] about parsing xml doc with Reg expression Message-ID: <20030508032433.24692.qmail@web14505.mail.yahoo.com> --0-2126009391-1052364273=:23408 Content-Type: text/plain; charset=us-ascii Hi,As Danny yoo suggested yesterday, I was trying to incorporate reg. _expression to eliminate some xml tags, I tried to implement but whenwhen you use class instance in reg. _expression and you try to check the result of the reg. _expression by using simple print it returns an emptylist with self.line print. but I replaced with normal string it works like as follows: test = aword.findall(self.line) print self.line ----------------> prints normal list with retrieved words My personal opinion: may be it doesn't accept the class instance such as self.line to be manipulated with reg._expression, Can anyone help meexplain why it is doing that and How can I get around this to reach my objective which is removing xml tags and index the tokens which is taken care of by the rest of the program. To understand what I tried is here: class word_iterator: def __init__(self, filename): self.file = open(filename) self.readline() def readline(self): aword = re.compile (r'([^<]+)') self.line = self.file.readline() #already there #print self.line self.line = aword.findall(self.line) #print self.line ----------------> here returns [ ] #self.line = ' '.join(self.line) #print self.line if self.line == '': self.words = None else: self.words = filter(None, self.line.split( ) ) #print self.words #testing def next(self): """ this routine gets the next line of the text to be line form the file input """ while 1: if self.words is None: raise StopIteration elif self.words: return self.words.pop() else: self.readline() thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-2126009391-1052364273=:23408 Content-Type: text/html; charset=us-ascii

Hi,
As Danny yoo suggested yesterday, I was trying to incorporate reg. _expression to eliminate some xml tags, I tried to implement but when
when you use class instance in reg. _expression and you try to check the result of the reg. _expression by using simple print it returns an empty
list with self.line print. but I replaced with normal string it works like as follows:
test = aword.findall(self.line)
print self.line ----------------> prints normal list with retrieved words
 
My personal opinion: may be it doesn't accept the class instance such as self.line to be manipulated with reg._expression, Can anyone help me
explain why it is doing that and How can I get around this to reach my
objective which is removing xml tags and index the tokens which is taken care of by the rest of the program.
 
To understand what I tried is here:
 
class word_iterator:
   
    def __init__(self, filename):
        self.file = open(filename)
        self.readline()
       
    def readline(self):
        aword = re.compile (r'<W>([^<]+)</W>')
      
        self.line = self.file.readline() #already there
        #print self.line  
        self.line = aword.findall(self.line)
        #print self.line ----------------> here returns  [ ]
        #self.line = ' '.join(self.line)
        #print self.line
       
        if self.line == '': self.words = None
        else: self.words = filter(None,  self.line.split( ) )
        #print self.words #testing  
      
        
    def next(self):
        """ this routine gets the next line of the text to be
            line form the file input
        """
        while 1:
            if self.words is None: raise StopIteration
            elif self.words: return self.words.pop()
            else:
                self.readline() 
 
thanks in advance


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-2126009391-1052364273=:23408-- From rmangaliag@slu.edu.ph Thu May 8 03:02:02 2003 From: rmangaliag@slu.edu.ph (ali) Date: Thu May 8 02:02:02 2003 Subject: [Tutor] connecting to odbc References: <0E5508EBA1620743B409A2B8365DE16FDC8579@sovereign.ci.las-vegas.nv.us> Message-ID: <007101c31529$4c415ba0$e019a8c0@slu.edu.ph> i have a problem connecting to my ms access database using odbc??? according to the documentation i should connect using this proforma: ########################### import odbc as o con = o.odbc("connection string") ########################### how do you create a "connection string"??? i tried the "old" way of doing it and it worked... ########################### import odbc as o con = o.odbc("mydsn/uid/pwd") ########################### but i dont know how to connect using the "new" way??? ########################### import odbc as o con = o.odbc("dsn=..........") # <-- here is where my problem is ########################### thanks... ali From rmangaliag@slu.edu.ph Thu May 8 03:22:02 2003 From: rmangaliag@slu.edu.ph (ali) Date: Thu May 8 02:22:02 2003 Subject: [Tutor] weakref curiousity Message-ID: <008301c3152c$037bdfa0$e019a8c0@slu.edu.ph> as i was looking at python codes from different sources, i noticed a module that is quite unknown to me... weakref... i looked for it in the documentation and it's there but no real examples... can someone enlighten me on this part??? :) can you give me "practical" uses of weakref and examples please.... i would really really appreciate it... thanks ali From alan.gauld@blueyonder.co.uk Thu May 8 04:00:05 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Thu May 8 03:00:05 2003 Subject: [Tutor] Tkinter + Linux = ugly? References: <20030507234550.70330.qmail@web11308.mail.yahoo.com> Message-ID: <00d501c3152f$8685d5b0$6401a8c0@xp> > Am I wrong ???? ... or Tkinter looks very ugly on Linux? Tk under *nix looks like Motif. Thus if you run the Motif Window Manager Tkinter apps will look like all the other apps on your desktop. If you run something else (and most folks do nowadays) they will look old fashioned and a bit "chunky". Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@blueyonder.co.uk Thu May 8 04:10:03 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Thu May 8 03:10:03 2003 Subject: [Tutor] What would you recomend a total newbie to do? References: Message-ID: <001601c31530$ee8409b0$6401a8c0@xp> > What are the best resorces to learn python. I'm a non programmer so i > wont understand something with alot of tech terms. I'm biased but think that both my web tutor and book do a good job. For more unbiased reviews of the book refer to Amazon! > I have downloaded 2.2.2 and it comes with a tutorial Its very good but aimed at programmers. My book/website aims to get you up to the point where you can understand the official one... > ...is there a book that starts for newbies and by the > time you get to the end of the book you know even the advanced stuff? Unfortunately no. Its too much to ask of a single book. The Deitel "How to Program..." books try this but personally I think they jump from beginner mode to expert mode too quickly. And they are expensive! Pesonally I'd recommend going through one of the Newbies tutors (eg mine?!) then the official tutor. Then start playing with the examples and exercises. Once you feel comfortable try buying one of the advanced books and probably one of the rerference books out there. Say Programming Python and Pyton in a Nutshell - both published by O'Reilly. > should i have downloaded 2.3.1b instead. i wont know if the programs has a > glitch or if it's me so i chose "stable" release? Nope, stick with 2.2 for now. You won't need any of the 2.3 features for a while and a solid baseline is better for a beginner. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo@hkn.eecs.berkeley.edu Thu May 8 05:51:19 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 8 04:51:19 2003 Subject: [Tutor] about parsing xml doc with Reg expression In-Reply-To: <20030508032433.24692.qmail@web14505.mail.yahoo.com> Message-ID: > def readline(self): > aword = re.compile (r'([^<]+)') > > self.line = self.file.readline() #already there > #print self.line > self.line = aword.findall(self.line) > #print self.line ----------------> here returns [ ] > #self.line = ' '.join(self.line) > #print self.line > if self.line == '': self.words = None > else: self.words = filter(None, self.line.split( ) ) > #print self.words #testing Hmmm... This method looks very verbose to me. > self.line = aword.findall(self.line) > #print self.line ----------------> here returns [ ] What input are you sending into this class instance? Are you sure that it's returning the empty list? Can you show us a test run? There are some oddities in the code, but I can't, for the life of me, see anything that would prevent the findall() from working here. *grin* So we need to see your test case too. Other comments: 1. I don't understand why we need to keep track of the current 'line' in our instance. Can we just make it a local variable? That is, instead of: self.line = self.file.readline() it might be better to just say: line = self.file.readline() unless we really want to keep the state of the current line as part of the instance. Furthermore, since self.words appears to be important, it's good style to initialize it to somthing in our __init__() method: def __init__(self, filename): self.file = open(filename) self.words = None self.readline() 2. The rebinding of the results of aword.findall() also looks a little weird and is potentially confusing. The lines: self.line = self.file.readline() and self.line = aword.findall(self.line) are what concern me: the name 'line' sounds like a string, but it really doesn't sound like a list of things. Are you worried about conserving memory? If so, don't worry about it unless you know it's a problem. Python allows us to rebind names to different kinds of things, but it's often not a good idea. It may be better to make a separate variable --- maybe something like "words" --- to capture the results of findall(). In fact, I think you really do need to use a different variable, since one of the last statements in that readline() function says: if self.line == '': self.words = None And that looks buggy: it is assuming that things look like the world from the perspective of the first statement, self.line = self.file.readline() But as soon as the second statement arrives, self.line = aword.findall(self.line) the world has shifted beneath our feet: every other statement past this one needs to readjust to use self.line as a list. You can dodge the reassignment issue altogether by using a separate variable to capture the words. Hope this helps! From BNDELL001@mail.uct.ac.za Thu May 8 06:05:03 2003 From: BNDELL001@mail.uct.ac.za (UCT Student - BNDELL001) Date: Thu May 8 05:05:03 2003 Subject: [Tutor] a neewbie at python Message-ID: <3EBA1CF6.123BC8AB@mail.uct.ac.za> Hello guys. I am a neewbie at python programming and I am also a first year student doing EEE103W and we use python.We were told to write a program`that works as a calculator which does simple arithmetic operations like +,%,/,* and -. The example our lecturer gave was that if we run our programme as python "name of programme" 23.4 + 17.5 the output shoud be 40.9. I have no idea what to do so can you please advise me guys coz I am afraid of failing my June exam as I have never done python before. Thank you,Ellen. From dyoo@hkn.eecs.berkeley.edu Thu May 8 06:12:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 8 05:12:01 2003 Subject: [Tutor] connecting to odbc In-Reply-To: <007101c31529$4c415ba0$e019a8c0@slu.edu.ph> Message-ID: On Thu, 8 May 2003, ali wrote: > i have a problem connecting to my ms access database using odbc??? Hi Ali, Hmmm... your question is a little specialized; you may want to try asking on the python-win32 mailing list, as this is less about getting Python working and more with getting the ODBC driver working. *grin* Python-win32 can be found here: http://mail.python.org/mailman/listinfo/python-win32 > according to the documentation i should connect using this proforma: Can you point us toward the documentation that you're looking at? We need to focus our search, because there are a few ODBC drivers out there. Until we know more, we have no choice but to guess which one you're using. Since you mentioned MS Access, I tried finding documentation on ODBC from here: http://www.python.org/windows/win32/odbc.html It shows how to create an ODBC connection, and it looks very much like what you're doing now. > how do you create a "connection string"??? > > i tried the "old" way of doing it and it worked... > ########################### > import odbc as o > con = o.odbc("mydsn/uid/pwd") > ########################### This is the way that the link above describes, and if it works, I don't see anything wrong about that. *grin* > but i dont know how to connect using the "new" way??? > ########################### > import odbc as o > con = o.odbc("dsn=..........") # <-- here is where my problem is > ########################### If you're referring to the documentation for mxODBC, http://www.lemburg.com/files/python/mxODBC.html then I don't think it applies! The 'odbc' module that comes standard with PythonWin doesn't appear to use the new format --- it doesn't follow the standard Python DB API --- so if you stick with PythonWin's 'odbc' driver, you don't have to use the "new" connection string format. If you use mxODBC, then you probably do need to follow their approach for creating a new connection, which might look something like, connect(mydsn, user=uid, passwords=pwd) So the problem may be a nonissue after all. *grin* Good luck! From rmangaliag@slu.edu.ph Thu May 8 06:16:02 2003 From: rmangaliag@slu.edu.ph (rmangaliag@slu.edu.ph) Date: Thu May 8 05:16:02 2003 Subject: [Tutor] connecting to odbc Message-ID: <1052386852.3eba262483102@mbox.slu.edu.ph> i just found out that odbc is python-db-api 1 compliant and not dbapi2... so, i think mxodbc is better... thanks danny... Quoting Danny Yoo : > > > On Thu, 8 May 2003, ali wrote: > > > i have a problem connecting to my ms access database using odbc??? > > Hi Ali, > > Hmmm... your question is a little specialized; you may want to try asking > on the python-win32 mailing list, as this is less about getting Python > working and more with getting the ODBC driver working. *grin* > > Python-win32 can be found here: > > http://mail.python.org/mailman/listinfo/python-win32 > > > > according to the documentation i should connect using this proforma: > > Can you point us toward the documentation that you're looking at? We need > to focus our search, because there are a few ODBC drivers out there. > Until we know more, we have no choice but to guess which one you're using. > > > Since you mentioned MS Access, I tried finding documentation on ODBC from > here: > > http://www.python.org/windows/win32/odbc.html > > It shows how to create an ODBC connection, and it looks very much like > what you're doing now. > > > > how do you create a "connection string"??? > > > > i tried the "old" way of doing it and it worked... > > ########################### > > import odbc as o > > con = o.odbc("mydsn/uid/pwd") > > ########################### > > This is the way that the link above describes, and if it works, I don't > see anything wrong about that. *grin* > > > > > but i dont know how to connect using the "new" way??? > > ########################### > > import odbc as o > > con = o.odbc("dsn=..........") # <-- here is where my problem is > > ########################### > > If you're referring to the documentation for mxODBC, > > http://www.lemburg.com/files/python/mxODBC.html > > then I don't think it applies! The 'odbc' module that comes standard with > PythonWin doesn't appear to use the new format --- it doesn't follow the > standard Python DB API --- so if you stick with PythonWin's 'odbc' driver, > you don't have to use the "new" connection string format. > > > If you use mxODBC, then you probably do need to follow their approach for > creating a new connection, which might look something like, > > connect(mydsn, user=uid, passwords=pwd) > > > So the problem may be a nonissue after all. *grin* > > > Good luck! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ------------------------------------------------- Email Service Provided by SLU-Net Saint Louis University ( http://www.slu.edu.ph ) ------------------------------------------------- From dyoo@hkn.eecs.berkeley.edu Thu May 8 06:29:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 8 05:29:01 2003 Subject: [Tutor] a neewbie at python [help for newcomers] In-Reply-To: <3EBA1CF6.123BC8AB@mail.uct.ac.za> Message-ID: On Thu, 8 May 2003, UCT Student - BNDELL001 wrote: > I am a neewbie at python programming and I am also a first year student > doing EEE103W and we use python. [rest of project question cut] Dear Ellen, Please be aware that, since we're a volunteer group of folks who show each other how to use Python effectively. We are morally prohibited from helping in project assignments. I'm saying this up front, and I hope you undetstand our caution. We just had someone here a few weeks ago that asked us to do their homework for them, and I really want to avoid that situation again. We can help point you toward resources that you can use to better learn the language, and you're always welcome to ask questions about confusing points on the language. Have you had a chance to look at the "Newcomers" resources on Python.org? There's a few tutorials there that will help you get started: http://python.org/doc/Newbies.html You can pick and choose which one feels best for you, and try going through it. If you have prior programming experience, you should be able to pick up a lot of the language in a few days. If not, it might take a little longer, but it shouldn't be too rough. Your Teaching Assistant may also be a good resource that you can ask for help. Don't be discouraged: your project actually doesn't sound too difficult. If you read Alan Gauld's tutorial: http://www.freenetpages.co.uk/hp/alan.gauld/ up to the "Branching" chapter, you should know enough to do the project. I think you can realistically work through this in a week or two. If you run into a roadblock while you're learning Python, please feel free to ask questions here, and we'll do our best to help clarify things. Sincerely, Danny Yoo From zmerch@30below.com Thu May 8 10:55:08 2003 From: zmerch@30below.com (Roger Merchberger) Date: Thu May 8 09:55:08 2003 Subject: [Tutor] Python & PostgreSQL Message-ID: <5.1.0.14.2.20030508095137.00ad1b80@mail.30below.com> Any good recommendations as to: 1) which module I should use to access PostgreSQL thru Python? and... 2) if there are any good tutorials out there WRT PostgreSQL & Python? Thanks, Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- sysadmin, Iceberg Computers zmerch@30below.com What do you do when Life gives you lemons, and you don't *like* lemonade????????????? From a_abdi406@yahoo.com Thu May 8 11:23:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Thu May 8 10:23:02 2003 Subject: [Tutor] about parsing xml doc with Reg expression Message-ID: <20030507160738.93484.qmail@web14505.mail.yahoo.com> --0-953404320-1052323658=:91780 Content-Type: text/plain; charset=us-ascii Hi,As Danny yoo suggested yesterday, I was trying to incorporate reg. expression to eliminate some xml tags, I tried to implement but whenwhen you use class instance in reg. expression and you try to check the result of the reg. expression by using simple print it returns an emptylist with self.line print. but I replaced with normal string it works like as follows: test = aword.findall(self.line) print self.line ----------------> prints normal list with retrieved words My personal opinion: may be it doesn't accept the class instance such as self.line to be manipulated with reg.expression, Can anyone help meexplain why it is doing that and How can I get around this to reach my objective which is removing xml tags and index the tokens which is taken care of by the rest of the program. To understand what I tried is here: class word_iterator: def __init__(self, filename): self.file = open(filename) self.readline() def readline(self): aword = re.compile (r'([^<]+)') self.line = self.file.readline() #already there #print self.line self.line = aword.findall(self.line) #print self.line ----------------> here returns [ ] #self.line = ' '.join(self.line) #print self.line if self.line == '': self.words = None else: self.words = filter(None, self.line.split( ) ) #print self.words #testing def next(self): """ this routine gets the next line of the text to be line form the file input """ while 1: if self.words is None: raise StopIteration elif self.words: return self.words.pop() else: self.readline() thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-953404320-1052323658=:91780 Content-Type: text/html; charset=us-ascii
Hi,
As Danny yoo suggested yesterday, I was trying to incorporate reg. expression to eliminate some xml tags, I tried to implement but when
when you use class instance in reg. expression and you try to check the result of the reg. expression by using simple print it returns an empty
list with self.line print. but I replaced with normal string it works like as follows:
 
test = aword.findall(self.line)
print self.line ----------------> prints normal list with retrieved words
 
My personal opinion: may be it doesn't accept the class instance such as self.line to be manipulated with reg.expression, Can anyone help me
explain why it is doing that and How can I get around this to reach my
objective which is removing xml tags and index the tokens which is taken care of by the rest of the program.
 
To understand what I tried is here:
 
class word_iterator:
   
    def __init__(self, filename):
        self.file = open(filename)
        self.readline()
       
    def readline(self):
        aword = re.compile (r'<W>([^<]+)</W>')
      
        self.line = self.file.readline() #already there
        #print self.line  
        self.line = aword.findall(self.line)
        #print self.line ----------------> here returns  [ ]
        #self.line = ' '.join(self.line)
        #print self.line
       
        if self.line == '': self.words = None
        else: self.words = filter(None,  self.line.split( ) )
        #print self.words #testing  
      
        
    def next(self):
        """ this routine gets the next line of the text to be
            line form the file input
        """
        while 1:
            if self.words is None: raise StopIteration
            elif self.words: return self.words.pop()
            else:
                self.readline() 
 
thanks in advance


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-953404320-1052323658=:91780-- From bwinton@latte.ca Thu May 8 11:30:02 2003 From: bwinton@latte.ca (Blake Winton) Date: Thu May 8 10:30:02 2003 Subject: [Tutor] a neewbie at python [help for newcomers] In-Reply-To: References: <3EBA1CF6.123BC8AB@mail.uct.ac.za> Message-ID: <20030508142807.GA11683@latte.ca> * Danny Yoo [030508 05:28]: > > I am a neewbie at python programming and I am also a first year > > student doing EEE103W and we use python. > [rest of project question cut] > > I think you can realistically work through this in a week or two. I would also add that if your professor is giving you questions without giving you the tools needed to solve them, then you should probably have a talk with the professor, since many of your classmates will be in the same boat. Explain to them what you have done, and where your problems are, and I'm sure that you'll get much better help than we will provide, since it will be interactive, and targeted towards you and what you already know. Later, Blake. -- 10:27am up 4 days, 2:06, 1 user, load average: 1.00, 1.00, 1.00 From mail Thu May 8 12:20:02 2003 From: mail (mail) Date: Thu May 8 11:20:02 2003 Subject: [Tutor] Make russian tutorials Message-ID: <11816403096.20030508181903@inbox.ru> Hello tutor, you have really great tutorial, but there are a great deal of learners in Ukraine and Russia. We like this very language but a great deal of information that it is impossible to understand, because we are not native speakers. I wish tutorials were in russian, it would be cool. Best wishes from Ukraine!!!!!! Maks. -- Best regards, mail mailto:komiks@tim.kiev.ua From magnus@thinkware.se Thu May 8 12:52:05 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 8 11:52:05 2003 Subject: [Tutor] connecting to odbc In-Reply-To: <007101c31529$4c415ba0$e019a8c0@slu.edu.ph> References: <0E5508EBA1620743B409A2B8365DE16FDC8579@sovereign.ci.las-vegas.nv.us> Message-ID: <5.2.1.1.0.20030508150301.00bb8b60@www.thinkware.se> At 14:16 2003-05-08 +0800, ali wrote: >i have a problem connecting to my ms access database using odbc??? There are several options here...and they work not only with MS Access, but for all databases you can access via ODBC on you computer. 1. You can use the OBDC module in win32all (or ActivePython) but it's not really maintained as far as I understand. I'd avoid that. (That's the "import odbc" etc.) 2. You can use mxODBC from egenix.com. Note that this requires a paid licence for commercial use. 3. You can use the new adodbapi by Henrik Ekelund. This might be your best choice. See http://adodbapi.sourceforge.net/ 4. You can skip the DB-API all together, and access ADO directly through win32com. See http://www.e-coli.net/pyado.html 5. You can do the same as the previous, but using DAO. See http://starship.python.net/crew/bwilk/access.html mxODBC is the only solutions of these that work in other operating systems than MS Windows. >########################### >import odbc as o >con = o.odbc("connection string") >########################### This looks like the old, unmaintained Odbc module in win32all. I would avoid that. >but i dont know how to connect using the "new" way??? What's the new way? As I said, this is old code, it does not follow the DB-API 2 standard. If you have set up a system DSN called "myDB" in the Windows Control Panel's "Data Source (ODBC)" setup, you can open it using con = o.odbc("myDB") But I suggest that you have a look at adodbapi if you want to follow the standard interface for accessing databases in Python, but only need to run your program on Windows for now. (That seems likely if you work with Access...) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From knguyen@seri.co.uk Thu May 8 13:07:02 2003 From: knguyen@seri.co.uk (Khai Nguyen) Date: Thu May 8 12:07:02 2003 Subject: [Tutor] a neewbie at python Message-ID: <341710540F08E34498A057DEE04DAAD7AA69C0@ex1.seri.co.uk> Dear Ellen, You are lucky that your prof ask you to do this in Python. Like Danny has said you can work through this assignment in max. a week by reading 3 or max 4 basic chapters of a python tutorial. Go to www.python.org download the one tutorial called Python for non-programmer. Even more you can write GUI application immitate a calculator in less then a day as a beginner to any programming stuff. Don't even think you can do it in what ever PASCAL, FORTRAN, C or C++ in such a short time. You will be surprise what this language can do. bye -----Original Message----- From: UCT Student - BNDELL001 [mailto:BNDELL001@mail.uct.ac.za]=20 Sent: Thursday, May 08, 2003 10:02 AM To: tutor@python.org Subject: [Tutor] a neewbie at python Hello guys. I am a neewbie at python programming and I am also a first year student doing EEE103W and we use python.We were told to write a program`that works as a calculator which does simple arithmetic operations like +,%,/,* and -. The example our lecturer gave was that if we run our programme as python "name of programme" 23.4 + 17.5 the output shoud be 40.9. I have no idea what to do so can you please advise me guys coz I am afraid of failing my June exam as I have never done python before. Thank you,Ellen. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor The information contained in this email and in any attachments may be privi= leged and confidential. The information is designated solely for the atten= tion and use of the intended recipient(s). If you are not the intended rec= ipient(s), please be aware that any disclosure, copying, distribution or us= e of the contents of this information is prohibited. If you have received t= his email in error, please notify the sender by telephone or email immediat= ely. From roypython@hotmail.com Thu May 8 13:35:02 2003 From: roypython@hotmail.com (roy ollis) Date: Thu May 8 12:35:02 2003 Subject: [Tutor] how do you get a reply to show up on the list? Message-ID: i sent a couple of questions about alan gauld about his tutorial from the built in reply function for hotmail.com . i think the reply must have been sent directly to him rather than the list. i looked a few few other emails and seen tutor@python.org in the Cc section. is putting the tutor address in the cc box the correct way? the questions for alan were very basic some questions about anan gauld's tutorial "Python version 1.5.2 is the latest release at the time of writing " is it still accurate for python 2.2.2? (first page) "For example you might be producing a document (such as this tutorial) which comprises lots of separate files. Your world processor may produce backup copies of each file as it saves a new version" is world a typo of word or is there something more i need to know? (page 2) _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From python-tutor-list@tagancha.org Thu May 8 14:15:02 2003 From: python-tutor-list@tagancha.org (python-tutor-list@tagancha.org) Date: Thu May 8 13:15:02 2003 Subject: [Tutor] Make russian tutorials] Message-ID: <20030508171409.GC24555@purdue.edu> > Date: Thu, 8 May 2003 18:19:03 +0300 > From: mail > X-Mailer: The Bat! (v1.60c) Personal > To: tutor@python.org > Reply-To: mail > Subject: [Tutor] Make russian tutorials > > Hello tutor, you have really great tutorial, but there are a great > deal of learners in Ukraine and Russia. We like this very language but > a great deal of information that it is impossible to understand, > because we are not native speakers. I wish tutorials were in russian, > it would be cool. > Best wishes from Ukraine!!!!!! > Maks. > -- > Best regards, > mail mailto:komiks@tim.kiev.ua Google is your friend. The first search on "russian python users" gives you a link to the "Russian Python and Zope users group" website at http://zope.net.ru/ whose members have translated some of the Python tutorials and documentation and created a few original original documents on python in Russian. They also have a mailing list in Russian and are very helpful and patient. Alex. -- The lyf so short, the craft so long to lerne. -- Chaucer From bgailer@alum.rpi.edu Thu May 8 14:42:05 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu May 8 13:42:05 2003 Subject: [Tutor] Make russian tutorials In-Reply-To: <11816403096.20030508181903@inbox.ru> Message-ID: <5.2.0.9.0.20030508113938.0267ce50@66.28.54.253> --=======73CC4ABB======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-6C363ED7; boundary="=====================_20544481==.ALT" --=====================_20544481==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-6C363ED7; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 06:19 PM 5/8/2003 +0300, mail wrote: >Hello tutor, you have really great tutorial, but there are a great >deal of learners in Ukraine and Russia. We like this very language but >a great deal of information that it is impossible to understand, >because we are not native speakers. I wish tutorials were in russian, >it would be cool. This just arrived in an e-mail right after your request: http://diveintopython.org/. Dive Into Python is a free Python book for experienced programmers. You can read the book online, or download it in a variety of formats. It is also available in multiple languages. (Including Russian) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=====================_20544481==.ALT Content-Type: text/html; x-avg-checked=avg-ok-6C363ED7; charset=us-ascii Content-Transfer-Encoding: 8bit At 06:19 PM 5/8/2003 +0300, mail wrote:

Hello tutor, you have really great tutorial, but there are a great
deal of learners in Ukraine and Russia. We like this very language but
a great deal of information that it is impossible to understand,
because we are not native speakers. I wish tutorials were in russian,
it would be cool.

This just arrived in an e-mail right after your request: http://diveintopython.org/. Dive Into Python is a free Python book for experienced programmers. You can read the book online, or download it in a variety of formats. It is also available in multiple languages. (Including Russian)

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
--=====================_20544481==.ALT-- --=======73CC4ABB======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6C363ED7 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.478 / Virus Database: 275 - Release Date: 5/6/2003 --=======73CC4ABB=======-- From dyoo@hkn.eecs.berkeley.edu Thu May 8 15:53:18 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 8 14:53:18 2003 Subject: [Tutor] Make russian tutorials In-Reply-To: <11816403096.20030508181903@inbox.ru> Message-ID: On Thu, 8 May 2003, mail wrote: > Hello tutor, you have really great tutorial, but there are a great deal > of learners in Ukraine and Russia. We like this very language but a > great deal of information that it is impossible to understand, because > we are not native speakers. I wish tutorials were in russian, it would > be cool. Hi Maks, By the way, there is a page that's collecting many of the Russian Python resources on Python.org: http://python.org/doc/NonEnglish.html#russian If you find other good tutorials in Russian, please feel free to tell Python.org's webmaster so that they can link it up to the main web site. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Thu May 8 16:04:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 8 15:04:03 2003 Subject: [Tutor] how do you get a reply to show up on the list? In-Reply-To: Message-ID: On Thu, 8 May 2003, roy ollis wrote: > i sent a couple of questions about alan gauld about his tutorial from > the built in reply function for hotmail.com . i think the reply must > have been sent directly to him rather than the list. i looked a few few > other emails and seen tutor@python.org in the Cc section. is putting > the tutor address in the cc box the correct way? the questions for alan > were very basic Hi Roy, Yes, please send your questions to 'tutor@python.org' --- that way, we all can better help you get answers to your questions. By sending to Tutor, you're allowing the community to involve itself. These kinds of mailing lists are set up so that we try to avoid a single-point-of-failure sort of thing. > "Python version 1.5.2 is the latest release at the time of writing " is > it still accurate for python 2.2.2? (first page) Well, it was accurate at the time that Alan wrote that sentence. *grin* There are a few things that have changed, but overall, the language has been pretty stable. If you're interested in reviewing some of the changes between 1.52 and 2.2.2, there's a nice set of summary pages here: http://www.python.org/1.6/#news http://www.python.org/2.0/new-python.html http://www.amk.ca/python/2.1/ http://www.python.org/doc/2.2.2/whatsnew/whatsnew22.html (hmmm... one of the alternative links to the "What's New in Python 2.2" is broken... I'd better tell the webmaster about it so that it gets fixed.) > "For example you might be producing a document (such as this tutorial) > which comprises lots of separate files. Your world processor may produce > backup copies of each file as it saves a new version" is world a typo of > word or is there something more i need to know? (page 2) It's a typo. I hope. *grin* If you have more questions, please feel free to ask. From dyoo@hkn.eecs.berkeley.edu Thu May 8 16:17:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 8 15:17:02 2003 Subject: [Tutor] Entity to UTF-8 [low level C details on regexmodule.c] In-Reply-To: <20030430150054.K31959@localhost.localdomain> Message-ID: On Wed, 30 Apr 2003, Paul Tremblay wrote: > You probably already know this already, but I thought I'd offer it > anyway. > > Your code has the lines: > > patt = '&#([^;]+);' > > ustr = re.sub(patt, ToUTF8, ustr) > > I believe this is ineffecient, because python has to compile the regular > expression each time. This code should be more effecient: > > patt = re.compile(r'&#[^;];') Hi Paul, Actually, there's a very low level implementation detail that, in the common case, improves our situation here. The last time I checked, Python's regular expression engine does cache the last few regular expressions that we use via the functions sub(), match(), and search(). So it might not be so necessary to do an re.compile() in his program. Python's current regular expression engine, 're', uses the internal module 'sre' by default, and there's a section of 'sre' that defines a cache of regular expressions: ### sre.py _cache = {} _cache_repl = {} # some code cut _MAXCACHE = 100 ### So the first 100 regular expressions processed by Python are automatically compiled and saved internally in the 're' module itself. So when we try reusing a particular old regular expression, Python can pick it out of the cache. This caching behavior is not something that we should really depend on, but it's good to know that it's there. [C code ahead] For the curious C programmers among us, in Python 1.52, this sort of caching was much more limited: the old regex engine only cached the very last regular expression! We can look at the relevant function in Modules/regexmodule.c, in the update_cache() function: /******/ static PyObject *cache_pat; static PyObject *cache_prog; static int update_cache(PyObject *pat) { PyObject *tuple = Py_BuildValue("(O)", pat); int status = 0; if (!tuple) return -1; if (pat != cache_pat) { Py_XDECREF(cache_pat); cache_pat = NULL; Py_XDECREF(cache_prog); cache_prog = regex_compile((PyObject *)NULL, tuple); if (cache_prog == NULL) { status = -1; goto finally; } cache_pat = pat; Py_INCREF(cache_pat); } finally: Py_DECREF(tuple); return status; } /******/ Notice that there's some static variables here for maintaining some memory. The idea of update_cache is this: on every call to a regular expression matching function, Python uses update_cache() to check to see if can reuse work that it's done on the very last regex call. If the very last regular expression we used is the same as the one we're doing now, we reuse that regex object without recompiling the expression. Sorry about diving into C code like this! It's just that I thought that this optimization detail was cute: it covers the common case when we're only dealing with a single regular expression repeatedly in a loop. But even so, it apparently made more sense in later versions of Python to yank the cache out of the C code entirely, and to maintain it externally in the 'sre' Python module. Good luck to you! From magnus@thinkware.se Thu May 8 16:39:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 8 15:39:01 2003 Subject: [Tutor] a neewbie at python In-Reply-To: <3EBA1CF6.123BC8AB@mail.uct.ac.za> Message-ID: <5.2.1.1.0.20030508210116.00b82bf0@www.thinkware.se> At 11:01 2003-05-08 +0200, Ellen wrote: >Hello guys. >I am a neewbie at python programming and I am also a first year student >doing EEE103W and we use python.We were told to write a program`that >works as a calculator which does simple arithmetic operations like >+,%,/,* and -. The example our lecturer gave was that if we run our >programme as python "name of programme" 23.4 + 17.5 > the output shoud be 40.9. > >I have no idea what to do so can you please advise me guys coz I am >afraid of failing my June exam as I have never done python before. >Thank you,Ellen. Hi Ellen, I'm sure you will be able to do that before June. Python is something you learn in hours or days if you have been programming in other languages before. Sometimes the worst thing is to get started, but I think you should start by playing a little with python. Probably while reading one of the many tutorials. Then you should be able to get a feeling for what Python can do, and then you just solve the problem, a tiny step at a time... Don't let it overwhelm you. As usual in problem solving of some kind, it's a good strategy to try to divide the problem into parts. In your case, the obvious parts are 1) reading the command line data into your program, 2) performing the calculation, and 3) printing result. I think I'd do this in reverse order in this case, first learn how to print out something, then learn how to do basic calculations, and last learn how to read input from the command line. Actually, I'd probably begin with some very trivial version of the calculation, and get that to work properly from command line to printed output, and then, when that works, try to refine the calculations so that they have all the features you need. Actually, this *can* be written as only two lines of python code, so it's not very advanced... (Actually, regarding the two line version, it all depends on what you expect the calculations to be like. It won't be able to give 5 as a result if you type in "4 + 25%". That requires a few more lines of code.) Good Luck, and have fun with Python. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From pan@uchicago.edu Thu May 8 16:45:02 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Thu May 8 15:45:02 2003 Subject: [Tutor] Sending email from PC In-Reply-To: <20030508160006.30330.19152.Mailman@mail.python.org> References: <20030508160006.30330.19152.Mailman@mail.python.org> Message-ID: <1052423087.3ebab3afc779b@webmail.uchicago.edu> Hi all, I'm trying to setup something such that I can use my browser to run some cgi (pythong based, of course) on my localhost to send emails. I've seen some examples from the net using smtplib: >>> import smtplib >>> s = smtplib.SMTP('localhost') But when I tried it on my machine, it always got me this error: Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\lib\smtplib.py", line 234, in __init__ (code, msg) = self.connect(host, port) File "C:\Python22\lib\smtplib.py", line 283, in connect raise socket.error, msg error: (10061, 'Connection refused') How can I configure my pc for this task? I've seen there's a 'sendmail.dll' in my "c:/winnt/win32" folder. Is that something to do with the sendmail function of the local host? pan From bgailer@alum.rpi.edu Thu May 8 16:51:03 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu May 8 15:51:03 2003 Subject: [Tutor] Creating stock responses to FAQ In-Reply-To: <5.2.1.1.0.20030508210116.00b82bf0@www.thinkware.se> References: <3EBA1CF6.123BC8AB@mail.uct.ac.za> Message-ID: <5.2.0.9.0.20030508134436.03a9ce50@66.28.54.253> --=======4D2337E4======= Content-Type: text/plain; x-avg-checked=avg-ok-6C363ED7; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit I'm amazed & delighted at the number and consistency of responses to Ellen's "a neewbie at python" request. I hope we have not blown her away with the volume or discouraged her. I'm also concerned that we collectively take so much time to say the same thing. I wonder if we could create a "stock" response to such requests, and that one of us (possibly taking turns) could send it to others with similar requests. I would be happy to take that role for the month of May, then pass the baton to someone else for June. What do you think? Perhaps we could do something similar for requests for tutorials. Are there other FAQ you think would merit attention? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======4D2337E4======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6C363ED7 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.478 / Virus Database: 275 - Release Date: 5/6/2003 --=======4D2337E4=======-- From ATrautman@perryjudds.com Thu May 8 16:59:01 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Thu May 8 15:59:01 2003 Subject: [Tutor] Creating stock responses to FAQ Message-ID: <06738462136C054B8F8872D69DA140DB010781@corp-exch-1.pjinet.com> I vote for the book one it seems some months it is answered several times. If I had a decent list of books I'd volunteer but my email is empty of last months answer. Alan -----Original Message----- From: Bob Gailer [mailto:bgailer@alum.rpi.edu] Sent: Thursday, May 08, 2003 2:50 PM To: tutor@python.org Subject: [Tutor] Creating stock responses to FAQ I'm amazed & delighted at the number and consistency of responses to Ellen's "a neewbie at python" request. I hope we have not blown her away with the volume or discouraged her. I'm also concerned that we collectively take so much time to say the same thing. I wonder if we could create a "stock" response to such requests, and that one of us (possibly taking turns) could send it to others with similar requests. I would be happy to take that role for the month of May, then pass the baton to someone else for June. What do you think? Perhaps we could do something similar for requests for tutorials. Are there other FAQ you think would merit attention? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From alan.gauld@blueyonder.co.uk Thu May 8 17:23:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Thu May 8 16:23:02 2003 Subject: [Tutor] a neewbie at python References: <3EBA1CF6.123BC8AB@mail.uct.ac.za> Message-ID: <003c01c3159f$95f1c8e0$6401a8c0@xp> > +,%,/,* and -. The example our lecturer gave was that if we run our > programme as python "name of programme" 23.4 + 17.5 > the output shoud be 40.9. > > I have no idea what to do so can you please advise me guys Well we don't do homework here but I can give you some pointers. You might like to read my python tutor section on "Talking to the User", particularly the part on command line arguments. Also to parse the numbers etc you migt want to look at the string functions such as split, and concepts such as "slicing". These are all covered in my tutor and, in much more detail, in the python documentation. And one last hint, look at the "in" test, as in: if c in "+-*/=": # do something HTH, Have a go, if it doesn't work come back here and ask us some specific questions and we'll try to unravel it for you. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ATrautman@perryjudds.com Thu May 8 17:26:42 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Thu May 8 16:26:42 2003 Subject: [Tutor] programming style question: Message-ID: <06738462136C054B8F8872D69DA140DB010782@corp-exch-1.pjinet.com> While I don't agree I know there are instructors I have worked with only teach one method because it is easier to trouble shoot and therefore grade. I always thought that meant the weren't making the problems hard enough but the always had more seniority. My personal choice is the while loop for all simple incrementing, moving across recordset, and infinite loops as I find them easier to read. The for loop makes a good trigger for complex or unusual increments. But usually the best path is to use what ever has been used in the existing code unless you are lucky enough to be creating new code. Alan -----Original Message----- From: Thomas CLive Richards [mailto:thomi@thomi.imail.net.nz] Sent: Thursday, May 08, 2003 12:53 AM To: tutor@python.org Subject: [Tutor] programming style question: Hey! I'm doing a degree course in Dunedin, New Zealand, and as part of this we have to do a pascal assignment. Well, to cut a long story short, i handed in my assignment, and was marked down because i used the following structure for a loop: (obviously i wrote this in pascal): while 1: do_lots_of_things_here() if (condition): break ... Now, the alternative would have (in my mind anyway) been more convoluted, and harder to read. What do you all think? It is a bit off topic, but do you guys think programming style is a personal thing, or should there be set rules? Things like "do i use a for or while loop here? In pascal it's pretty much up to you; both are usable. what do you think? thanks, -- Thomi Richards, thomi@thomi.imail.net.nz _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dan_nash@hotmail.com Thu May 8 17:26:55 2003 From: dan_nash@hotmail.com (Daniel Nash) Date: Thu May 8 16:26:55 2003 Subject: [Tutor] Multipart Question Message-ID: I came accross this bit of code: if contenttype[:10] == "multipart/": mimemsg = mimetools.Message(sys.__stdin__) boundary = mimemsg.getparam('boundary') ......... What is the significance of the [:10]? Thanks. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From magnus@thinkware.se Thu May 8 17:32:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 8 16:32:01 2003 Subject: [Tutor] Creating stock responses to FAQ In-Reply-To: <5.2.0.9.0.20030508134436.03a9ce50@66.28.54.253> References: <5.2.1.1.0.20030508210116.00b82bf0@www.thinkware.se> <3EBA1CF6.123BC8AB@mail.uct.ac.za> Message-ID: <5.2.1.1.0.20030508221637.02621eb8@www.thinkware.se> At 13:50 2003-05-08 -0600, Bob Gailer wrote: >I'm amazed & delighted at the number and consistency of responses to >Ellen's "a neewbie at python" request. I hope we have not blown her away >with the volume or discouraged her. > >I'm also concerned that we collectively take so much time to say the same >thing. I don't know... Danny said that we can't do her homework, and pointed her to the typical beginner resources. Khai Nguyen said that she was lucky to get this assignment in Python, since it's easy to learn, and suggested Cogliati's tutorial. I suggested that she should try to solve it a small piece at a time, not to get overwhelmed by it, and noted that it can be solved very easily (although that solution might not fully live up to the specification). I certainly don't think this was a discouraging response. It's my impression that she asked an honest and friendly question, and got honest and friendly replies that were as helpful as they can be... There are certainly cases where students obviously try to get school assignments solved under the pretence that it's not an assignment, and there are a few cases where people seem to expect that we are some slaves that will work for free for them. In cases like that, I've sometimes been less friendly. I think that is appropriate. Having said all this, a Tutor-FAQ might still be a good idea. There are certainly frequent questions... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From jeff@ccvcorp.com Thu May 8 18:08:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu May 8 17:08:02 2003 Subject: [Tutor] Sending email from PC References: <20030508160006.30330.19152.Mailman@mail.python.org> <1052423087.3ebab3afc779b@webmail.uchicago.edu> Message-ID: <3EBAC7A7.2090702@ccvcorp.com> pan@uchicago.edu wrote: > Hi all, > > I'm trying to setup something such that I can use my browser > to run some cgi (pythong based, of course) on my localhost > to send emails. [...] > > But when I tried it on my machine, it always got me this error: > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python22\lib\smtplib.py", line 234, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Python22\lib\smtplib.py", line 283, in connect > raise socket.error, msg > error: (10061, 'Connection refused') The trick here is that you need to be connecting to an active SMTP server. Odds are good that you're not running your own SMTP server on your local machine, so you need to find out what your current primary SMTP server is (try checking the settings of your normal email program) and use that name in place of "localhost". If, by some chance, you *are* running an SMTP server, then you'd probably need to check the configuration of that server to see why it might be refusing connections. Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Thu May 8 18:14:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 8 17:14:02 2003 Subject: [Tutor] Multipart Question In-Reply-To: Message-ID: On Thu, 8 May 2003, Daniel Nash wrote: > I came accross this bit of code: > > if contenttype[:10] == "multipart/": > mimemsg = mimetools.Message(sys.__stdin__) > boundary = mimemsg.getparam('boundary') > ......... > > What is the significance of the [:10]? Hi Daniel, That '[:10]' thing is an example of a "slice": it's a way of taking a chunk out of a sequence. The following examples should help clarify the idea: ### >>> numbers = range(42, 47) >>> numbers [42, 43, 44, 45, 46] >>> numbers[2:] [44, 45, 46] >>> numbers[:2] [42, 43] >>> numbers[2:4] [44, 45] >>> numbers[:-1] [42, 43, 44, 45] >>> numbers[-1:] [46] ### So think of a hot butter knife going through the sequence: that's a slice. Slices not only work on lists: they also work on strings, as your example above shows. For more information on slices, we can look at: http://www.python.org/doc/tut/node5.html#SECTION005140000000000000000 and for the nitty-gritty, the Library Reference on the topic of "Sequences": http://www.python.org/doc/lib/typesseq.html (Minor note: in Python 2.3, slices will become more versatile. In the near future, we should be able to reverse a string by doing something like 'mystring[::-1]') By the way, the code above can can be more idiomatically written as: if contenttype.startswith("multipart/"): This has the same effect as the slice-and-compare approach, but using 'startswith()' more clearly describes the intent of the programmer --- checking that contenttype starts with the prefix "multipart/". Hope this helps! From dyoo@hkn.eecs.berkeley.edu Thu May 8 18:33:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 8 17:33:01 2003 Subject: [Tutor] about parsing xml doc with Reg expression In-Reply-To: <20030507160738.93484.qmail@web14505.mail.yahoo.com> Message-ID: > I was trying to incorporate reg. expression to eliminate some xml tags, > I tried to implement but whenwhen you use class instance in reg. > expression and you try to check the result of the reg. expression by [text cut] Hi Abdirizak, You may want to check to see that your email account is working ok. I responded to your question just yesterday: http://mail.python.org/pipermail/tutor/2003-May/022276.html http://mail.python.org/pipermail/tutor/2003-May/022281.html so if you haven't gotten the response in your mailbox yet, you need to talk with your Internet Service Provider and get them to fix their mail system. From D.J.Kniep@chello.nl Thu May 8 18:41:23 2003 From: D.J.Kniep@chello.nl (Dick Kniep) Date: Thu May 8 17:41:23 2003 Subject: [Tutor] Python & PostgreSQL In-Reply-To: <5.1.0.14.2.20030508095137.00ad1b80@mail.30below.com> References: <5.1.0.14.2.20030508095137.00ad1b80@mail.30below.com> Message-ID: <1052429566.4580.20.camel@server.kniep> On Thu, 2003-05-08 at 15:53, Roger Merchberger wrote: > Any good recommendations as to: > > 1) which module I should use to access PostgreSQL thru Python? and... > 2) if there are any good tutorials out there WRT PostgreSQL & Python? Hi there, I am developing a system which uses pyPgSQL. This works excellent. Another possibility is to use ODBC. if under Linux you have to use unixODBC of iODBC. the package to use then is eGenix mxODBC. here are some code snippets to open a database and use it under PostgreSQL. All config.Option(......) are arguments that I get from an INI file. For instance the "config.Option('database','dbms') gives me an uppercased version of the parameter dbms under the heading database. If the dbms parameter contains POSTGRESQL it opens pyPgSQL, otherwise, it opens ODBC. both ways are given here. Note however, that to use ODBC, you also have to install UnixODBC, and configure the ODBC connection. Also, there is a logging module included. Furthermore, I would advise to use SQLDict, an excellent module to access Postgresql. /---snippet ----/ def OpenDatabase(self, config): """ Connect to database """ if config.Option('database','dbms') == "POSTGRESQL": from pyPgSQL import PgSQL from pyPgSQL import libpq try: dbObj = PgSQL.connect(user = strip(config.CurrUser.uid), database=config.Option('database','name',0),host=config.Option('database','host')) except: config.log.critical(config.Option('database','dbms') + ' database kon voor gebruiker ' + config.CurrUser.uid + ' niet geopend worden') config.log.critical('database = ' + config.Option('database','name') + ' host = ' + config.Option('database','host')) wxMessageBox(boodschappen[7], "Fout",style=wxOK|wxICON_ERROR) sys.exit() elif config.Option('database','dbms') == "ODBC": if os.name=="nt" or os.name=="dos": from mx.ODBC.Windows import mxODBC elif os.name == "posix": from mx.ODBC.unixODBC import mxODBC else: config.log.critical('Platform ' + os.name + ' niet ondersteund') wxMessageBox(boodschappen[1], "Fout",style=wxOK|wxICON_ERROR) sys.exit() if config.Option('database','passwd') is None: try: dbObj = mxODBC.connect(config.Option('database','dsn',NONORMALIZE), user=config.CurrUser.uid) except: config.log.critical(config.Option('database','dbms',NONORMALIZE) + ' database kon voor gebruiker ' + config.CurrUser.uid + ' niet geopend worden') config.log.critical('DSN =' + config.Option('database','dsn') ) wxMessageBox(boodschappen[1], "Fout",style=wxOK|wxICON_ERROR) sys.exit() else: try: dbObj = mxODBC.connect(config.Option('database','dsn',NONORMALIZE), user=config.CurrUser.uid, password=config.Option('database','passwd',NONORMALIZE)) except: config.log.critical(config.Option('database','dbms',NONORMALIZE) + ' database kon voor gebruiker ' + config.CurrUser.uid + ' niet geopend worden') config.log.critical('DSN =' + config.Option('database','dsn') ) wxMessageBox(boodschappen[1], "Fout",style=wxOK|wxICON_ERROR) sys.exit() else: config.log.critical('soort connectie (ODBC/POSTGRESQL) onjuist in INI file: ' + config.Option('database','dbms',NONORMALIZE)) wxMessageBox(boodschappen[1], "Fout",style=wxOK|wxICON_ERROR) sys.exit() /--- end snippet----/ Kind regards, Dick Kniep > > Thanks, > Roger "Merch" Merchberger > > -- > Roger "Merch" Merchberger -- sysadmin, Iceberg Computers > zmerch@30below.com > > What do you do when Life gives you lemons, > and you don't *like* lemonade????????????? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From D.J.Kniep@chello.nl Thu May 8 18:43:03 2003 From: D.J.Kniep@chello.nl (Dick Kniep) Date: Thu May 8 17:43:03 2003 Subject: [Tutor] Tkinter + Linux = ugly? In-Reply-To: <00d501c3152f$8685d5b0$6401a8c0@xp> References: <20030507234550.70330.qmail@web11308.mail.yahoo.com> <00d501c3152f$8685d5b0$6401a8c0@xp> Message-ID: <1052429657.4580.22.camel@server.kniep> Take a look at wxPython. It's perfect..... Cheers, D. Kniep On Thu, 2003-05-08 at 09:00, Alan Gauld wrote: > > > Am I wrong ???? ... or Tkinter looks very ugly on Linux? > > Tk under *nix looks like Motif. Thus if you run the Motif > Window Manager Tkinter apps will look like all the other > apps on your desktop. If you run something else (and most > folks do nowadays) they will look old fashioned and a bit > "chunky". > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Thu May 8 18:44:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 8 17:44:02 2003 Subject: [Tutor] Creating stock responses to FAQ In-Reply-To: <5.2.0.9.0.20030508134436.03a9ce50@66.28.54.253> Message-ID: On Thu, 8 May 2003, Bob Gailer wrote: > I'm amazed & delighted at the number and consistency of responses to > Ellen's "a neewbie at python" request. I hope we have not blown her away > with the volume or discouraged her. > > I'm also concerned that we collectively take so much time to say the > same thing. I wonder if we could create a "stock" response to such > requests, and that one of us (possibly taking turns) could send it to > others with similar requests. I would be happy to take that role for the > month of May, then pass the baton to someone else for June. What do you > think? > > Perhaps we could do something similar for requests for tutorials. > > Are there other FAQ you think would merit attention? Hi Bob, I had some kind of "monthly summary of Tutor" idea in the back of my head, sorta like how Dr. Dobbs does weekly summaries of comp.lang.python in their Python-URL series: http://www.ddj.com/topics/pythonurl/ except it would be cool if we could do this on a smaller but more detailed scale, since we have less traffic and more focus than the main general newsgroup. If a group of us could step up and do some sort of summary thing, that might be very useful for newcomers to Python-Tutor. A summary might be even better than a regular FAQ, since, although we do get frequent questions, we often get pretty rare ones too! Talk to you later! From D.J.Kniep@chello.nl Thu May 8 18:44:12 2003 From: D.J.Kniep@chello.nl (Dick Kniep) Date: Thu May 8 17:44:12 2003 Subject: [Tutor] DB qurey Problem In-Reply-To: <20030507163347.GB11156@tc.telocity.com> References: <20030507163347.GB11156@tc.telocity.com> Message-ID: <1052429745.4557.24.camel@server.kniep> You get a tuple back with ONE element. in that case the comma is only there to tell Python that it is a tuple. You won't get any trouble from it. Kind regards, Dick Kniep On Wed, 2003-05-07 at 18:33, Rick Pasotto wrote: > On Wed, May 07, 2003 at 12:27:48PM -0400, Daniel Nash wrote: > > > > I have a DB with email addresses in it > > > > when I do the following qurey: > > > > EmailList = db.query("SELECT distinct email FROM users").getresult() > > > > I get a list like this : [('dan.nash@company.com',), > > ('fred.smit@company.com',)] > > > > I want to return this list without the extra comma in each element in the > > list. Can I do this, if so how? Or am I going to have to get rid of it > > another way? > > EmailList[0][0] does not have a comma in it. > EmailList[1][0] does not have a comma in it. > > -- > "A moral code impossible to practice, a code that demands imperfection > or death, has taught you to dissolve all ideas in fog, to permit no > firm definitions, to regard any concept as approximate & any rule of > conduct as elastic, to hedge on any principle, to compromise on any > value, to take the middle of any road." -- Ayn Rand > Rick Pasotto rick@niof.net http://www.niof.net > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From phthenry@earthlink.net Thu May 8 19:16:02 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Thu May 8 18:16:02 2003 Subject: [Tutor] Entity to UTF-8 [low level C details on regexmodule.c] In-Reply-To: References: <20030430150054.K31959@localhost.localdomain> Message-ID: <20030508181553.E29954@localhost.localdomain> Huh! Funny, but the books always tell you "use re.compile", a rule which I have followed faitfully, even though I only use at most 10 regular expressions in my script. Looks like I can cut out some code! Thanks Paul On Thu, May 08, 2003 at 12:15:46PM -0700, Danny Yoo wrote: > > > > On Wed, 30 Apr 2003, Paul Tremblay wrote: > > > You probably already know this already, but I thought I'd offer it > > anyway. > > > > Your code has the lines: > > > > patt = '&#([^;]+);' > > > > ustr = re.sub(patt, ToUTF8, ustr) > > > > I believe this is ineffecient, because python has to compile the regular > > expression each time. This code should be more effecient: > > > > patt = re.compile(r'&#[^;];') > > > > Hi Paul, > > > Actually, there's a very low level implementation detail that, in the > common case, improves our situation here. The last time I checked, > Python's regular expression engine does cache the last few regular > expressions that we use via the functions sub(), match(), and search(). > So it might not be so necessary to do an re.compile() in his program. > > > Python's current regular expression engine, 're', uses the internal module > 'sre' by default, and there's a section of 'sre' that defines a cache of > regular expressions: > > > ### sre.py > _cache = {} > _cache_repl = {} > # some code cut > _MAXCACHE = 100 > ### > > > So the first 100 regular expressions processed by Python are automatically > compiled and saved internally in the 're' module itself. So when we try > reusing a particular old regular expression, Python can pick it out of the > cache. This caching behavior is not something that we should really > depend on, but it's good to know that it's there. > > > > > > [C code ahead] > > For the curious C programmers among us, in Python 1.52, this sort of > caching was much more limited: the old regex engine only cached the very > last regular expression! We can look at the relevant function in > Modules/regexmodule.c, in the update_cache() function: > > > /******/ > static PyObject *cache_pat; > static PyObject *cache_prog; > > static int > update_cache(PyObject *pat) > { > PyObject *tuple = Py_BuildValue("(O)", pat); > int status = 0; > > if (!tuple) > return -1; > > if (pat != cache_pat) { > Py_XDECREF(cache_pat); > cache_pat = NULL; > Py_XDECREF(cache_prog); > cache_prog = regex_compile((PyObject *)NULL, tuple); > if (cache_prog == NULL) { > status = -1; > goto finally; > } > cache_pat = pat; > Py_INCREF(cache_pat); > } > finally: > Py_DECREF(tuple); > return status; > } > /******/ > > > Notice that there's some static variables here for maintaining some > memory. The idea of update_cache is this: on every call to a regular > expression matching function, Python uses update_cache() to check to see > if can reuse work that it's done on the very last regex call. If the very > last regular expression we used is the same as the one we're doing now, we > reuse that regex object without recompiling the expression. > > > Sorry about diving into C code like this! It's just that I thought that > this optimization detail was cute: it covers the common case when we're > only dealing with a single regular expression repeatedly in a loop. > > > But even so, it apparently made more sense in later versions of Python to > yank the cache out of the C code entirely, and to maintain it externally > in the 'sre' Python module. > > > > > > Good luck to you! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From adam@bostoncoop.net Thu May 8 20:53:03 2003 From: adam@bostoncoop.net (Adam Kessel) Date: Thu May 8 19:53:03 2003 Subject: [Tutor] MIME Parsing/Generating (newbie question) Message-ID: <20030508235246.GB1637@bostoncoop.net> --jRHKVT23PllUwdXP Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable I'm a Python newbie--in fact, today is my first day. I've recently realized how difficult it is to remember what you meant in Perl a year or two after you wrote code, so I thought I'd give Python a try.=20 So far I'm finding it tricky, but I know I need to unlearn some old habits first. The first application I wanted to write would recognize HTML-only emails (e.g., hotmail), turn them into MIME multipart messages, and add a stripped version as the first part. (It would be a procmail filter). =20 My result is below. It seems to work for the most part, except that it loses a little bit of header information. Some of the routing information from Received: lines doesn't make it through. For some reason, I have to manually output get_unixfrom() for this to work. Also, the code (I think) is quite inelegant. =20 Finally, I'm trying to figure out how to make this script parse multiple messages rather than just one. As it stands now, if it is fed more than one message, they all get appended together. Is there another module I need to use? =20 I am wondering if anyone can suggest a better way to do this. Also, can anyone recommend a good source for example code? I learn best by example, and the Python Library Reference has very few of them. =20 Assume that strip() works fine--that's the part that takes out the HTML tags. =20 Thanks so much for any starter tips! ---- msg =3D sys.stdin.read() message =3D email.message_from_string(msg) p =3D email.Parser.Parser() headers =3D p.parsestr(msg,1) newmessage =3D email.MIMEMultipart.MIMEMultipart() for (x,y) in headers.items(): newmessage.add_header(x,y) for x in email.Iterators.typed_subpart_iterator(message): if x.get_content_type() =3D=3D "text/html": newmessage.attach(email.MIMEText.MIMEText(strip(x.get_payload()))) newmessage.attach(x) print message.get_unixfrom() print newmessage.as_string() --- Adam Kessel (adam@bostoncoop.net) --jRHKVT23PllUwdXP Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQE+uu3OdTf3ZklQ6qYRAjY1AJ9VahV3Q7ydQrLZkpTS23NnBI94zACglmNE gl/naq277TBr08mlrHXpr1M= =tw0E -----END PGP SIGNATURE----- --jRHKVT23PllUwdXP-- From magnus@thinkware.se Thu May 8 21:06:21 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 8 20:06:21 2003 Subject: [Tutor] Python & PostgreSQL In-Reply-To: <5.1.0.14.2.20030508095137.00ad1b80@mail.30below.com> Message-ID: <5.2.1.1.0.20030509012954.00b70038@www.thinkware.se> At 09:53 2003-05-08 -0400, Roger Merchberger wrote: >1) which module I should use to access PostgreSQL thru Python? In general, for Python database stuff, look at http://www.python.org/topics/database/ particularly at http://www.python.org/topics/database/modules.html Other relevant sources of information are http://py.vaults.ca/parnassus/apyllo.py/973100124 and http://www.python.org/pypi (which isn't so widely used yet though). Just for PostgreSQL, there are quite a number of options. Beside all the ODBC-related options we have discussed today, there are a number of competing DB-API drivers. Obviously, they all have strong and weak sides, or they wouldn't all exist. First of all, PostgreSQL comes with its own Python interface. See http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=pygresql.html It has two APIs, a newer which is DB-API 2 compatible, and an older, which is not. I guess this is the interface you must use if you want to write PostgreSQL stored procedures in Python, see http://www.postgresql.org/docs/view.php?version=7.3&idoc=1&file=plpython.html I don't know if this is really actively maintained though. Let's just say that the alternatives would hardly exist if the one included with PostgreSQL was problem-free. Then there is the Italian choice: http://initd.org/Software/psycopg "It was written from scratch with the aim of being very small and fast, and stable as a rock. The main advantages of psycopg are that it supports the full Python DBAPI-2.0 and being thread safe at level 2." It uses the GPL license, which might be a hinder for a DB-API. I got the impression that Federico meant that GPL is only "viral" if you link directly to it, which you don't do in Python code, but I would not use this in non-GPL code without a clear permission. The next choice is at http://pypgsql.sourceforge.net/ and this is also an actively maintained module which is fairly widely used. I don't have personal experience, so I can't really compare it when it comes to pewrformance or reliability etc. It uses the more liberal Python licence though, which might be relevant for you. There is also PoPy at http://www.zope.org/Members/tm/ but I don't think this is actively developed any longer. >2) if there are any good tutorials out there WRT PostgreSQL & Python? Actually, any tutorial on Python and SQL databases via the DB-API 2 would be relevant. There are two ways in which the DB-API implementations differ significantly. Connection strings might look different, but more importantly, there are five different versions of parameter styles, see http://www.python.org/peps/pep-0249.html I don't know if all the PostgreSQL drivers use the same style. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Thu May 8 21:54:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 8 20:54:02 2003 Subject: [Tutor] MIME Parsing/Generating (newbie question) In-Reply-To: <20030508235246.GB1637@bostoncoop.net> Message-ID: <5.2.1.1.0.20030509020751.0261f2d0@www.thinkware.se> At 19:52 2003-05-08 -0400, Adam Kessel wrote: >I'm a Python newbie--in fact, today is my first day. I've recently >realized how difficult it is to remember what you meant in Perl a year or >two after you wrote code, so I thought I'd give Python a try. Good thinking! I did that six years ago, and I'm very happy about that. >So far I'm finding it tricky, but I know I need to unlearn some old >habits first. Yep. As Yoda said: "You have to unlearn what you have learnt." >The first application I wanted to write would recognize HTML-only emails >(e.g., hotmail), turn them into MIME multipart messages, and add a >stripped version as the first part. (It would be a procmail filter). That's a fairly ambitious thing to do one your first day. (I bet you didn't write anything like that the first day you coded Perl...) >I am wondering if anyone can suggest a better way to do this. Also, can >anyone recommend a good source for example code? I learn best by example, >and the Python Library Reference has very few of them. The Python cookbook, both the dead tree version from O'Reilly and the one at activestate.com, is very useful. See http://aspn.activestate.com/ASPN/Cookbook/Python/ and search for mime! E.g. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/86676 But I'm not so sure that there are a lot of code examples for the email module, since it's fairly recent. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From wolf_binary@hotmail.com Thu May 8 22:33:01 2003 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Thu May 8 21:33:01 2003 Subject: [Tutor] last email Message-ID: Hi all, Sorry about the last email I sent. I could have sworn I had put a subject in the subject area. Thanks, Cameron _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From dbroadwell@mindspring.com Fri May 9 01:43:02 2003 From: dbroadwell@mindspring.com (David Broadwell) Date: Fri May 9 00:43:02 2003 Subject: [Tutor] Hello Spam (no request in this on, just BG.info) Message-ID: Have to say I've been bad, been using the c.l.p group for the tutoring ... which is purely for enrichment. Started searching for the list when (with a few pointers) 15 lines of code dropped to 21 characters legibly! If its not un-kosher, in the next day or three, I'll post the program I'm working on; a local password database. And I use the term database loosely, it isn't a database, as a collection of encrypted files and the parser for them (script or interactive interface). This was my 'cut my teeth' program, as before this all python was was a fancy interactive interface that (finally) replaced the basic prompt from my old Atari 800 XL. (not that I was ever that good at basic, did far better with batch files) What I'm looking for: Knowledge; if you see a section (in the soon to be posted code) that you KNOW how to do better, faster more efficiently (and preferably not too un-readable) I want to hear it. I like python and am utterly addicted to slices ... and this is about as verbose as I ever get, I usually listen allot. Just had to say HI, my name is David, and I am an addict. I sometimes call myself Mongoose or Amar but its ok, I don't chase all snakes. (especially not one with batteries) -- *poof* From bkd@graphnet.com Fri May 9 02:51:03 2003 From: bkd@graphnet.com (noc) Date: Fri May 9 01:51:03 2003 Subject: [Tutor] parsing errors for try/except handling Message-ID: <02a301c315ee$b490e3e0$5102020a@graphnet.com> I'm working on a new script. I'm reading a file that contains a list of hosts, user ids, and passwords. It's getting parsed into a list of lists like so: [[host, userid, password],[host, userid, password],...] Now I'm telnetting to each host, and issuing some commands, and returning the data: def nfscheck(entry): try: tn=telnetlib.Telnet(entry[0]) except error: response= else: tn.read_until('login: ','15') tn.write(entry[1]+'\n') tn.read_until('Password: ','15') tn.write(entry[2]+'\n') tn.read_until('$','15') tn.write('ls\n') response=tn.read_until('$','15') tn.write('exit\n') finally: return response Now, sometimes these hosts are down for whatever reason, or maybe the list isn't up to date, so I get: File "C:\Python22\lib\telnetlib.py", line 190, in __init__ self.open(host, port) File "C:\Python22\lib\telnetlib.py", line 219, in open raise socket.error, msg error: (10060, 'Operation timed out') I realize that in the last line, I have to use 'error' as the name for the except statement, but how do assign 'Operation timed out' to my response variable? thanks in advance bkd From rmangaliag@slu.edu.ph Fri May 9 03:12:01 2003 From: rmangaliag@slu.edu.ph (ali) Date: Fri May 9 02:12:01 2003 Subject: [Tutor] connecting to odbc References: <0E5508EBA1620743B409A2B8365DE16FDC8579@sovereign.ci.las-vegas.nv.us> <5.2.1.1.0.20030508150301.00bb8b60@www.thinkware.se> Message-ID: <008e01c315f3$e1ef52e0$e019a8c0@slu.edu.ph> thanks for the info, magnus.... what you just gave me is exactly what i need... again... thank you very much... ----- Original Message ----- From: "Magnus Lyck=E5" To: "ali" Cc: Sent: Thursday, May 08, 2003 11:52 PM Subject: Re: [Tutor] connecting to odbc > At 14:16 2003-05-08 +0800, ali wrote: > >i have a problem connecting to my ms access database using odbc??? > > There are several options here...and they work not only with > MS Access, but for all databases you can access via ODBC on you > computer. > > 1. You can use the OBDC module in win32all (or ActivePython) but > it's not really maintained as far as I understand. I'd avoid > that. (That's the "import odbc" etc.) > > 2. You can use mxODBC from egenix.com. Note that this requires > a paid licence for commercial use. > > 3. You can use the new adodbapi by Henrik Ekelund. This might be > your best choice. See http://adodbapi.sourceforge.net/ > > 4. You can skip the DB-API all together, and access ADO directly > through win32com. See http://www.e-coli.net/pyado.html > > 5. You can do the same as the previous, but using DAO. See > http://starship.python.net/crew/bwilk/access.html > > mxODBC is the only solutions of these that work in other > operating systems than MS Windows. > > >########################### > >import odbc as o > >con =3D o.odbc("connection string") > >########################### > > This looks like the old, unmaintained Odbc module in win32all. > I would avoid that. > > >but i dont know how to connect using the "new" way??? > > What's the new way? As I said, this is old code, it does not > follow the DB-API 2 standard. > > If you have set up a system DSN called "myDB" in the Windows > Control Panel's "Data Source (ODBC)" setup, you can open it > using > > con =3D o.odbc("myDB") > > But I suggest that you have a look at adodbapi if you want > to follow the standard interface for accessing databases in > Python, but only need to run your program on Windows for now. > (That seems likely if you work with Access...) > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The shortest path from thought to working program From bkelly@sourcereview.net Fri May 9 04:19:02 2003 From: bkelly@sourcereview.net (Brett Kelly) Date: Fri May 9 03:19:02 2003 Subject: [Tutor] parsing errors for try/except handling In-Reply-To: <02a301c315ee$b490e3e0$5102020a@graphnet.com> References: <02a301c315ee$b490e3e0$5102020a@graphnet.com> Message-ID: <20030509071845.GB22370@inkedmn.homelinux.org> --uZ3hkaAS1mZxFaxD Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable instead of: except error: response=3D maybe try: except Exception, e: response =3D e just a thought, hth brett Sometime around Fri, May 09, 2003 at 01:49:01AM -0400, noc waltzed in like = he freakin' owned the joint and start spouting off about: > I'm working on a new script. >=20 > I'm reading a file that contains a list of hosts, user ids, and passwords. > It's getting parsed into a list of lists like so: > [[host, userid, password],[host, userid, password],...] >=20 > Now I'm telnetting to each host, and issuing some commands, and returning > the data: >=20 > def nfscheck(entry): > try: > tn=3Dtelnetlib.Telnet(entry[0]) > except error: > response=3D > else: > tn.read_until('login: ','15') > tn.write(entry[1]+'\n') > tn.read_until('Password: ','15') > tn.write(entry[2]+'\n') > tn.read_until('$','15') > tn.write('ls\n') > response=3Dtn.read_until('$','15') > tn.write('exit\n') > finally: > return response >=20 > Now, sometimes these hosts are down for whatever reason, or maybe the list > isn't up to date, so I get: >=20 > File "C:\Python22\lib\telnetlib.py", line 190, in __init__ > self.open(host, port) > File "C:\Python22\lib\telnetlib.py", line 219, in open > raise socket.error, msg > error: (10060, 'Operation timed out') >=20 > I realize that in the last line, I have to use 'error' as the name for the > except statement, but how do assign 'Operation timed out' to my response > variable? >=20 > thanks in advance > bkd >=20 >=20 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor --=20 Brett Kelly bkelly@sourcereview.net Want to fall in love with programming all over again? use Python! http://www.python.org --uZ3hkaAS1mZxFaxD Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQE+u1ZVa7gYa9SI8SoRAhlBAJ43/bAJ2DaxRP0VydhqWOoB98AbtACgjf1h XcJrEAdyKU5NtbgkNu8gr+M= =sxRR -----END PGP SIGNATURE----- --uZ3hkaAS1mZxFaxD-- From lonetwin@yahoo.com Fri May 9 04:46:27 2003 From: lonetwin@yahoo.com (lonetwin) Date: Fri May 9 03:46:27 2003 Subject: [Tutor] parsing errors for try/except handling In-Reply-To: <20030509071845.GB22370@inkedmn.homelinux.org> References: <02a301c315ee$b490e3e0$5102020a@graphnet.com> <20030509071845.GB22370@inkedmn.homelinux.org> Message-ID: <200305091328.30962.lonetwin@yahoo.com> Hi all, I lurk around here, since I don't do much python these days. This mail, however caught my interest. Could some guru (and Brett too if it works for him) plz explain this: > > try: > > tn=telnetlib.Telnet(entry[0]) > > except error: > > response= > > else: > > tn.read_until('login: ','15') > > tn.write(entry[1]+'\n') > > tn.read_until('Password: ','15') > > tn.write(entry[2]+'\n') > > tn.read_until('$','15') > > tn.write('ls\n') > > response=tn.read_until('$','15') > > tn.write('exit\n') > > finally: > > return response I was under the impression that you cannot do a try+except+finally in one block. The code should give a SyntaxError while compiling. In fact here's what I get on the interpreter: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >>> try: ... raise Exception('hell') ... except Exception, msg: ... print msg ... else: ... print "foo" ... finally: File "", line 7 finally: ^ SyntaxError: invalid syntax >>> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Confused Steve -- Every silver lining has a cloud around it. From Bruce Dykes" <20030509071845.GB22370@inkedmn.homelinux.org> <200305091328.30962.lonetwin@yahoo.com> Message-ID: <038201c31601$51325fa0$5102020a@graphnet.com> ----- Original Message ----- From: "lonetwin" To: Sent: Friday, May 09, 2003 03:58 Subject: Re: [Tutor] parsing errors for try/except handling > Hi all, > I lurk around here, since I don't do much python these days. This mail, > however caught my interest. Could some guru (and Brett too if it works for > him) plz explain this: > > > try: > > > tn=telnetlib.Telnet(entry[0]) > > > except error: > > > response= > > > else: > > > tn.read_until('login: ','15') > > > tn.write(entry[1]+'\n') > > > tn.read_until('Password: ','15') > > > tn.write(entry[2]+'\n') > > > tn.read_until('$','15') > > > tn.write('ls\n') > > > response=tn.read_until('$','15') > > > tn.write('exit\n') > > > finally: > > > return response > > I was under the impression that you cannot do a try+except+finally in one > block. The code should give a SyntaxError while compiling. In fact here's Yes, it does. My bad. Turns out the finally is redundant in this case the corrected block looks like this: def nfscheck(entry): try: tn=telnetlib.Telnet(entry[0]) except Exception, e: # this is how you capture the error, thanks to Brett. in this case, e usually equals something like=(10065,'getaddrinfo failed') response=e[1] # e[0] is the code, if you want to write custom errors, or use e[1] if the english from the Python is good enough for your uses else: tn.read_until('login: ',15) tn.write(entry[1]+'\n') tn.read_until('Password: ',15) tn.write(entry[2]+'\n') tn.read_until('$',15) tn.write('ls\n') response=tn.read_until('$',15) tn.write('exit\n') return response bkd From rmangaliag@slu.edu.ph Fri May 9 05:15:01 2003 From: rmangaliag@slu.edu.ph (ali) Date: Fri May 9 04:15:01 2003 Subject: [Tutor] funny true or false Message-ID: <000d01c31605$0b7d1460$e019a8c0@slu.edu.ph> yesterday, i tried playing with some if's and while's... then i tried this... and i thought it was funny.... just want you to comment on this... >>> if True: >>> print "test" >>> # of course, this will print "test" >>> if False: >>> print "test" >>> # and of course, this wont... >>> # but when i do this... >>> True = 0 >>> False = 1 >>> # and run the same if's above >>> if True: >>> print "test" >>> # things change... :) weird... >>> if False: >>> print "test" >>> # and of course, this will print "test" isn't this weird and may lead to confusion (of course, is your using True or False as variables and not as constants)... what if you inadvertently assigned a value to True or False... it may lead to confusion... i even tried to assign a list to True or False and it worked... maybe it's just me... :) ali From norvell@houseofspearman.org Fri May 9 05:23:02 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Fri May 9 04:23:02 2003 Subject: [Tutor] funny true or false In-Reply-To: <000d01c31605$0b7d1460$e019a8c0@slu.edu.ph> References: <000d01c31605$0b7d1460$e019a8c0@slu.edu.ph> Message-ID: <20030509082252.GA9781@houseofspearman.org> On Friday, 2003.05.09, 16:29:00 +0800, ali wrote: > isn't this weird and may lead to confusion (of course, is your using True or > False as variables and not as constants)... > > what if you inadvertently assigned a value to True or False... it may lead > to confusion... > > i even tried to assign a list to True or False and it worked... According to the Tutorial, one may override (actually, create an independent local variable with the same name) built-in variables with new values --- not that it's recommended, of course. See the last part of Section 3.1.1 in the Tutorial -- Norvell Spearman From op73418@mail.telepac.pt Fri May 9 08:22:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri May 9 07:22:02 2003 Subject: [Tutor] funny true or false References: <000d01c31605$0b7d1460$e019a8c0@slu.edu.ph> Message-ID: <006d01c3161d$2ff7fdb0$7b100dd5@violante> ----- Original Message ----- From: "ali" To: "Tutor" Sent: Friday, May 09, 2003 9:29 AM Subject: [Tutor] funny true or false > yesterday, i tried playing with some if's and while's... then i tried > this... and i thought it was funny.... just want you to comment on this... > > >>> if True: > >>> print "test" > >>> # of course, this will print "test" > >>> if False: > >>> print "test" > >>> # and of course, this wont... > >>> # but when i do this... > >>> True = 0 > >>> False = 1 > >>> # and run the same if's above > >>> if True: > >>> print "test" > >>> # things change... :) weird... > >>> if False: > >>> print "test" > >>> # and of course, this will print "test" > > isn't this weird and may lead to confusion (of course, is your using True or > False as variables and not as constants)... > > what if you inadvertently assigned a value to True or False... it may lead > to confusion... > > i even tried to assign a list to True or False and it worked... > > maybe it's just me... :) > > ali > Yes. Currently, True, False and None are just builtins (names bound in the builtin namespace), so you can shadow them. Future versions of Python are slated to have them all as keywords, so you won't be able to shadow them anymore. I believe in the upcoming Python 2.3, if you try to assign to None, the interpreter will snarl with a warning. All the best, G. Rodrigues From magnus@thinkware.se Fri May 9 08:22:10 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 9 07:22:10 2003 Subject: [Tutor] parsing errors for try/except handling In-Reply-To: <038201c31601$51325fa0$5102020a@graphnet.com> References: <02a301c315ee$b490e3e0$5102020a@graphnet.com> <20030509071845.GB22370@inkedmn.homelinux.org> <200305091328.30962.lonetwin@yahoo.com> Message-ID: <5.2.1.1.0.20030509123514.00bbaac0@www.thinkware.se> At 04:02 2003-05-09 -0400, Bruce Dykes wrote: >def nfscheck(entry): > try: > tn=telnetlib.Telnet(entry[0]) > except Exception, e: > response=e[1] Not all instances of Exception will have slices. If you get another kind of exception than a socket.error, it's likely that you end up with an IndexError. (It doesn't have to be a mistyping in your code that causes it, even if that's what I demonstrate below.) >>> try: ... tn+=telnetlib.Telnet(entry[0]) ... except Exception, e: ... response = e[1] ... print response ... Traceback (most recent call last): File "", line 4, in ? IndexError: tuple index out of range In this case it was "tn+=..." which caused a NameError, but you can't do e[1] on a NameError, so you get a strange IndexError in the except clause, and no good indication of what you did wrong. The same thing would happen if entry was None for instance. Only catch the exceptions that you are prepared to handle! > else: > tn.read_until('login: ',15) > tn.write(entry[1]+'\n') > tn.read_until('Password: ',15) > tn.write(entry[2]+'\n') > tn.read_until('$',15) > tn.write('ls\n') > response=tn.read_until('$',15) > tn.write('exit\n') > return response What if your "read_until" etc leads to exceptions? Where do you catch that? And with your previous finally version, you might get into situations where you try to return a "response" that wasn't defined. Maybe you should have something like... import telnetlib import socket try: response = "Unexpected Error in ???: Please Contact Support!" try: tn=telnetlib.Telnet(entry[0]) tn.read_until('login: ','15') tn.write(entry[1]+'\n') tn.read_until('Password: ','15') tn.write(entry[2]+'\n') tn.read_until('$','15') tn.write('ls\n') response=tn.read_until('$','15') tn.write('exit\n') except socket.error, e: response = e[1] finally: return response or maybe even better... import telnetlib, socket, traceback, sys try: response = ("If you see this message,\n" "the programmer's wife made a mistake... :(") try: tn=telnetlib.Telnet(entry[0]) tn.read_until('login: ','15') tn.write(entry[1]+'\n') tn.read_until('Password: ','15') tn.write(entry[2]+'\n') tn.read_until('$','15') tn.write('ls\n') response=tn.read_until('$','15') tn.write('exit\n') except socket.error, e: response = e[1] except: response = ("Unexpected Error, please report to admin:\n" + "".join(traceback.format_tb(sys.exc_traceback))) finally: return response The users will hate the "Unexpected Error" message, because it's incomprehensible to them, but in this case, where you are obviously prepared to returned with unfinished business, it's probably better than an exception. It's probably better if the bulk of the error is somehow sent to someone who understands it, and the user is just presented with a less technical error mesaage than a Python traceback, but I'll leave that as an exercise for the reader. Hang on. *Most* of those error messages are more or less incomprehensible to normal users... 'getaddrinfo failed' Huh?, 'Connection refused' What's a "Connection"? Why was it refused? This would make much more sense as "Unable to connect to Telnet server on %s" % entry[0] , 'Operation timed out' Operation? Are we having surgery? I guess they all need refinement, if norma lusers should use the program. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Fri May 9 10:58:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 9 09:58:02 2003 Subject: [Tutor] funny true or false In-Reply-To: <000d01c31605$0b7d1460$e019a8c0@slu.edu.ph> Message-ID: <5.2.1.1.0.20030509132457.00bb6bc8@www.thinkware.se> At 16:29 2003-05-09 +0800, ali wrote: >isn't this weird and may lead to confusion (of course, is your using True or >False as variables and not as constants)... A name is just a name is just a name in Python. You can use it for whatever you like if want to make life miserable. But usually, we don't, since we prefer a calm and happy life. :) >>> True, False, list, str = list, str, True, False >>> x = False(11*13) >>> type(x) >>> x '143' >>> l = True(x) >>> l ['1', '4', '3'] >>> print list, str 1 0 There are lots of things that are permitted but stupid, and there is no way the interpreter/compiler/whatever can stop most of them. Sure, you might prevent some uncommon mistakes, but is it meaningful to try to prevent these kinds of unlikely errors when you can't possibly stop a programmer from writing "a = b + c" when he should really have written "a = b - c"? The flexibility we have in Python in assigning whatever name we want for whatever object we want is a very useful and powerful ability. Personally, I think that injecting "True, False = 'x', []" and verifying that a program doesn't change behaviour could be a reasonable way to make sure that True and False hasn't been used in any ugly way... For more about names and objects, see e.g. http://effbot.org/zone/python-objects.htm -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From joachim.hengge@gmx.net Fri May 9 11:22:01 2003 From: joachim.hengge@gmx.net (Joachim Hengge) Date: Fri May 9 10:22:01 2003 Subject: [Tutor] grouping modules? Message-ID: <3EBBB916.8000807@gmx.net> Hi All, I am wondering if there is some functionality to group modules in Python, similar to Java packages. Or is there another way to organize code into logical units (apart from modules)? Thanks Jojo From Janssen@rz.uni-frankfurt.de Fri May 9 13:47:28 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri May 9 12:47:28 2003 Subject: [Tutor] funny true or false In-Reply-To: <5.2.1.1.0.20030509132457.00bb6bc8@www.thinkware.se> Message-ID: On Fri, 9 May 2003, Magnus Lyck=E5 wrote: > At 16:29 2003-05-09 +0800, ali wrote: > >isn't this weird and may lead to confusion (of course, is your using Tru= e or > >False as variables and not as constants)... > > A name is just a name is just a name in Python. > You can use it for whatever you like if want > to make life miserable. But usually, we don't, > since we prefer a calm and happy life. :) Fair point but you can also do reasonable things this way: defining your own True and False doing the right thing in any context you need. Just think of the python cookbook mentions a None-Type that do in any context nothing (instead of throwing TypeErrors). Michael From jeff@ccvcorp.com Fri May 9 14:13:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri May 9 13:13:03 2003 Subject: [Tutor] grouping modules? References: <3EBBB916.8000807@gmx.net> Message-ID: <3EBBE214.7080406@ccvcorp.com> Joachim Hengge wrote: > Hi All, > > I am wondering if there is some functionality to group modules in > Python, similar to Java packages. Or is there another way to organize > code into logical units (apart from modules)? Yes, there is, and these groupings are called (coincidentally enough ;) ) packages. Look in the standard Python Tutorial. In chapter 6 (Modules), you'll find section 6.4 on packages. Jeff Shannon Technician/Programmer Credit International From beyondthezero@earthlink.net Fri May 9 14:28:06 2003 From: beyondthezero@earthlink.net (Peter Jakubowicz) Date: Fri May 9 13:28:06 2003 Subject: [Tutor] primality testing Message-ID: <5.2.1.1.1.20030509102447.00b274c0@earthlink.net> I've written a small program to test whether a number is prime. But in the back of my mind, I feel it should be simpler and shorter. Can anyone advise. Thanks. from math import sqrt def prime(n): factor = 0 for i in range(2, sqrt(n) + 1): if n % i == 0: factor = factor + 1 break if factor == 0: print "Prime" else: print "Composite" From dana@pixelenvy.ca Fri May 9 15:19:02 2003 From: dana@pixelenvy.ca (Dana Larose) Date: Fri May 9 14:19:02 2003 Subject: [Tutor] primality testing In-Reply-To: <5.2.1.1.1.20030509102447.00b274c0@earthlink.net> Message-ID: On Fri, 9 May 2003, Peter Jakubowicz wrote: > I've written a small program to test whether a number is prime. But in the > back of my mind, I feel it should be simpler and shorter. Can anyone > advise. Thanks. > > from math import sqrt > > def prime(n): > factor = 0 > for i in range(2, sqrt(n) + 1): > if n % i == 0: > factor = factor + 1 > break > if factor == 0: > print "Prime" > else: > print "Composite" > You could probably shorten it to: def prime(n): for in in range(2, sqrt(n)+1): if n % i == 0: return 'Composite' return 'Prime' Essentially the same as yours, but a little shorter. dana. From zak@harlekin-maus.com Fri May 9 17:29:02 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri May 9 16:29:02 2003 Subject: [Tutor] primality testing In-Reply-To: References: <5.2.1.1.1.20030509102447.00b274c0@earthlink.net> Message-ID: <1564.192.206.201.87.1052512138.squirrel@mail.harlekin-maus.com> > On Fri, 9 May 2003, Peter Jakubowicz wrote: > >> I've written a small program to test whether a number is prime. But in >> the back of my mind, I feel it should be simpler and shorter. Can >> anyone advise. Thanks. >> > You could probably shorten it to: > > def prime(n): > for in in range(2, sqrt(n)+1): > if n % i == 0: > return 'Composite' > > return 'Prime' > > Essentially the same as yours, but a little shorter. > > dana. Heck, while you're at it, you can get rid of the zero check: def prime (n): -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From zak@harlekin-maus.com Fri May 9 17:33:07 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri May 9 16:33:07 2003 Subject: [Tutor] primality testing In-Reply-To: References: <5.2.1.1.1.20030509102447.00b274c0@earthlink.net> Message-ID: <1589.192.206.201.87.1052512371.squirrel@mail.harlekin-maus.com> Crud. I hit "tab" and "space" which did the wrong thing. Here's my REAL reply. On second thought, my change was silly. Carry on! :) -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From joachim.hengge@gmx.net Fri May 9 17:35:02 2003 From: joachim.hengge@gmx.net (Joachim Hengge) Date: Fri May 9 16:35:02 2003 Subject: [Tutor] grouping modules? In-Reply-To: <3EBBE214.7080406@ccvcorp.com> References: <3EBBB916.8000807@gmx.net> <3EBBE214.7080406@ccvcorp.com> Message-ID: <3EBC1093.8030109@gmx.net> hi jeff, got it finally, thanks. ;-) my book doesn't cover packages jojo Jeff Shannon wrote: > Joachim Hengge wrote: > >> Hi All, >> >> I am wondering if there is some functionality to group modules in >> Python, similar to Java packages. Or is there another way to organize >> code into logical units (apart from modules)? > > > > Yes, there is, and these groupings are called (coincidentally enough ;) > ) packages. Look in the standard Python Tutorial. In chapter 6 > (Modules), you'll find section 6.4 on packages. > > Jeff Shannon > Technician/Programmer > Credit International > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Joachim Hengge Belaustrasse 5/3 D-70195 Stuttgart Mobil: +49.160.98637608 Email: joachim.hengge@gmx.net From dyoo@hkn.eecs.berkeley.edu Fri May 9 17:45:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 9 16:45:02 2003 Subject: [Tutor] primality testing In-Reply-To: Message-ID: > def prime(n): > for in in range(2, sqrt(n)+1): > if n % i == 0: > return 'Composite' > > return 'Prime' Small typo; Dana meant to use 'i', not 'in', for the statement, for i in range(2, sqrt(n) + 1): There's an alternative way of checking for primality that's very cool; it uses randomness and number theory! There's some code here that shows how to do it: http://www-mitpress.mit.edu/sicp/chapter1/node17.html The code in the link above is written in a language called Scheme, but it's actually not too bad to do the conversion from Scheme to Python. For example, if we see something like this: ;;; Scheme code (define (expmod base exp m) (cond ((= exp 0) 1) ((even? exp) (remainder (square (expmod base (/ exp 2) m)) m)) (else (remainder (* base (expmod base (- exp 1) m)) m)))) ;;; This code in Scheme does something akin to: (base ** exp) % m It does it in a cute way so that we can avoid doing huge products --- it applies the modulo '%' function at the same time that it's calculating the powers, to keep the numbers small and easy to calculate. That expmod function can be translated into Python like this: ### def expmod(base, exp, m): """Calcuates base**exp modulo m.""" if exp == 0: return 1 elif is_even(exp): return square(expmod(base, exp / 2, m)) % m else: return (base * (expmod(base, exp-1, m))) % m ### For those who are interested, here's the complete translation: ### """Primality testing using Fermat's little theorem.""" import random def is_fast_prime(n, times): """Perform the fermat primality test 'times' times on the number n.""" for i in range(times): if not fermat_test(n): return False return True def fermat_test(n): """Tests to see if n is possibly prime. It can give false positives, although it never gives false negatives.""" def try_it(a): return expmod(a, n, n) == a return try_it(1 + random.randrange(n-1)) def is_even(x): """Returns true if x is even.""" return x % 2 == 0 def square(x): """Returns the square of x.""" return x * x def expmod(base, exp, m): """Calcuates base**exp modulo m.""" if exp == 0: return 1 elif is_even(exp): return square(expmod(base, exp / 2, m)) % m else: return (base * (expmod(base, exp-1, m))) % m ### Here's more information on primality tests from MathWorld: http://mathworld.wolfram.com/PrimalityTest.html Hope this helps! From dana@pixelenvy.ca Fri May 9 17:50:06 2003 From: dana@pixelenvy.ca (Dana Larose) Date: Fri May 9 16:50:06 2003 Subject: [Tutor] primality testing In-Reply-To: Message-ID: It's true, I did :) On Fri, 9 May 2003, Danny Yoo wrote: > > > > def prime(n): > > for in in range(2, sqrt(n)+1): > > if n % i == 0: > > return 'Composite' > > > > return 'Prime' > > > Small typo; Dana meant to use 'i', not 'in', for the statement, > > for i in range(2, sqrt(n) + 1): > > > > > > > There's an alternative way of checking for primality that's very cool; > it uses randomness and number theory! There's some code here that shows > how to do it: > > http://www-mitpress.mit.edu/sicp/chapter1/node17.html > > The code in the link above is written in a language called Scheme, but > it's actually not too bad to do the conversion from Scheme to Python. > For example, if we see something like this: > > > ;;; Scheme code > (define (expmod base exp m) > (cond ((= exp 0) 1) > ((even? exp) > (remainder (square (expmod base (/ exp 2) m)) > m)) > (else > (remainder (* base (expmod base (- exp 1) m)) > m)))) > ;;; > > > This code in Scheme does something akin to: > > (base ** exp) % m > > It does it in a cute way so that we can avoid doing huge products --- it > applies the modulo '%' function at the same time that it's calculating the > powers, to keep the numbers small and easy to calculate. > > > That expmod function can be translated into Python like this: > > ### > def expmod(base, exp, m): > """Calcuates base**exp modulo m.""" > if exp == 0: > return 1 > elif is_even(exp): > return square(expmod(base, exp / 2, m)) % m > else: > return (base * (expmod(base, exp-1, m))) % m > ### > > > > > For those who are interested, here's the complete translation: > > ### > """Primality testing using Fermat's little theorem.""" > > import random > > > def is_fast_prime(n, times): > """Perform the fermat primality test 'times' times on the number n.""" > for i in range(times): > if not fermat_test(n): return False > return True > > > def fermat_test(n): > """Tests to see if n is possibly prime. It can give false > positives, although it never gives false negatives.""" > def try_it(a): > return expmod(a, n, n) == a > return try_it(1 + random.randrange(n-1)) > > > def is_even(x): > """Returns true if x is even.""" > return x % 2 == 0 > > > def square(x): > """Returns the square of x.""" > return x * x > > > def expmod(base, exp, m): > """Calcuates base**exp modulo m.""" > if exp == 0: > return 1 > elif is_even(exp): > return square(expmod(base, exp / 2, m)) % m > else: > return (base * (expmod(base, exp-1, m))) % m > ### > > > > Here's more information on primality tests from MathWorld: > > http://mathworld.wolfram.com/PrimalityTest.html > > > Hope this helps! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From zak@harlekin-maus.com Fri May 9 17:59:01 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri May 9 16:59:01 2003 Subject: [Tutor] primality testing In-Reply-To: References: <5.2.1.1.1.20030509102447.00b274c0@earthlink.net> Message-ID: <1898.192.206.201.87.1052513908.squirrel@mail.harlekin-maus.com> > On Fri, 9 May 2003, Peter Jakubowicz wrote: > >> I've written a small program to test whether a number is prime. But in >> the back of my mind, I feel it should be simpler and shorter. Can >> anyone advise. Thanks. >> >> from math import sqrt >> >> def prime(n): >> factor = 0 >> for i in range(2, sqrt(n) + 1): >> if n % i == 0: >> factor = factor + 1 >> break >> if factor == 0: >> print "Prime" >> else: >> print "Composite" Okay, here's an answer that isn't silly. And I've been looking for an excuse to learn how lambda functions work. :) def prime (n): if 0 not in map (lambda a: n % a, range (2, math.sqrt (n) + 1)): return 'p' return 'c' -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From carroll@tjc.com Fri May 9 23:14:01 2003 From: carroll@tjc.com (Terry Carroll) Date: Fri May 9 22:14:01 2003 Subject: [Tutor] Should I subclass UserDict or dict? Message-ID: I'm writing a little class that provides an easy-to-use interface into the Unicode Chinese character database as set out in Unicode.org's Unihan.txt (online at http://www.unicode.org/Public/UNIDATA/Unihan.txt); The file's a bit over 25M, so re-parsing it each time you want to look up something isn't practical. I started out doing this as a dictionary of dictionaries, but there are a few things that make me want to make it its own class (for example, capturing the comments in the file, which document it nicely, and allowing an easy interface to search for a particular value of an attribute). This is primarily for my own use, but I plan on making it generally available just in case anyone else can use it, too. My question (you knw there was a question eventually, right?): Should I inherit from the built-in dict class or from UserDict? On the only platform I plan to run this on, I run Python 2.2.2. I know that dict is only inheritable from starting in 2.2. Is 2.2 pervasive now (my ISP's highest level of Python is 2.1.1, for example), or should I use UserDict to ensure compatibility? Is there really any big advantage of user the built-in dict instead of UserDict? The docs for UserDict say "If you are writing code that does not need to work with versions of Python earlier than Python 2.2, please consider subclassing directly from the built-in dict type." Since it says "please," I thought I should. -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From magnus@thinkware.se Fri May 9 23:15:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 9 22:15:02 2003 Subject: [Tutor] funny true or false Message-ID: <5.2.1.1.0.20030510041543.00badad8@www.thinkware.se> At 18:46 2003-05-09 +0200, Michael Janssen wrote: >Fair point but you can also do reasonable things this way: defining your >own True and False doing the right thing in any context you need. Exactly! I think it's great that Python manages to aid people in writing simple and easy to understand programs without stopping them from doing things in different ways than Guido imagined. I think this is a really good quality in Python. It focuses on making it easy to do the right thing, rather than to try to prevent us from doing things that might be bad. Compare this with Java: You're not allowed to write code which is not part of a class, but you can still write classes that don't capture object-oriented ideas at all. You just get bad old procedural code in a meaningless OO decoration. You're not allowed to use multiple inheritance, since that is sometimes aboused, even in situations where it's very useful. And so on... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Fri May 9 23:30:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 9 22:30:02 2003 Subject: [Tutor] primality testing In-Reply-To: <1898.192.206.201.87.1052513908.squirrel@mail.harlekin-maus .com> References: <5.2.1.1.1.20030509102447.00b274c0@earthlink.net> Message-ID: <5.2.1.1.0.20030510041850.00bc3730@www.thinkware.se> At 13:58 2003-05-09 -0700, Zak Arntson wrote: >def prime (n): > if 0 not in map (lambda a: n % a, range (2, math.sqrt (n) + 1)): > return 'p' > return 'c' Please don't put a space between a function name and the (. See http://www.python.org/peps/pep-0008.html A more "modern" approach is to use list comprehension instead of map and lambda. Also, if we have an expression that returns 0 or 1, we can use these numbers as index in a sequence instead of using an if statement. def prime(n): return ['prime', 'comp'][0 in [n % a for a in range(2, math.sqrt (n) + 1)]] -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Sat May 10 00:02:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 9 23:02:02 2003 Subject: [Tutor] Should I subclass UserDict or dict? In-Reply-To: Message-ID: <5.2.1.1.0.20030510045656.00badc20@www.thinkware.se> At 19:13 2003-05-09 -0700, Terry Carroll wrote: >Should I inherit from the >built-in dict class or from UserDict? Use dict if you don't need to support Python versions < 2.2, and don't plan to make the classes persistent with the ZOPE Object DataBase. >On the only platform I plan to run this on, I run Python 2.2.2. I know >that dict is only inheritable from starting in 2.2. Is 2.2 pervasive now Yes, I think so. >(my ISP's highest level of Python is 2.1.1, for example), or should I use My ISP upgraded to 2.2 when I asked them. Have you asked? (Don't forget to say please. :) >UserDict to ensure compatibility? Is there really any big advantage of >user the built-in dict instead of UserDict? Performance should be better I assume, but please measure. I assume the two classes will be very similar, so I guess you can test both ways. I can't see that this is a big decision though. Surely it's easy to rewrite as inheriting UserDict if there turns out to be problems using dict as a base class. This is after all Python. One of the big advantages with Python is that you can test different versions easily. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From beyondthezero@earthlink.net Sat May 10 00:19:01 2003 From: beyondthezero@earthlink.net (Peter Jakubowicz) Date: Fri May 9 23:19:01 2003 Subject: [Tutor] redundant code In-Reply-To: References: <5.2.1.1.1.20030509102447.00b274c0@earthlink.net> Message-ID: <5.2.1.1.1.20030509200739.00b27290@earthlink.net> Hi. Thanks for all the great advice on testing for primes. The Scheme code is really interesting, though I don't think I'll be writing anything like that anytime soon - I'm just a laid-off editor and banjo player. But I've wanted to be a programmer for a long time, and I've been working through books for a while now (I pretty much own the entire Python library at this point), and I'm starting to write small programs. But then I wonder if there's a better way to do what I've done. Anyway, I've written this little thing to prompt for answers to simple multiplication problems, and I'm wondering if anyone would care to comment on it. It bothers me that I have to use the exact same line twice, but I can't figure out how to change that. Plus it bothers me that the whole thing doesn't fit into one function. Anyway, I'd appreciate any comments. from random import randrange from sys import exit from string import lower def question(): n1 = randrange(1, 10) n2 = randrange(1, 10) answer = int(raw_input('How much is %d times %d? ' % (n1, n2))) while answer != n1 * n2: print "No. Try again." answer = int(raw_input('How much is %d times %d? ' % (n1, n2))) question() print "Yes, that is correct." again = str(raw_input("Would you like another question (type Y or N)?")) if lower(again) == "y": question() else: exit() From greg@gregmchapman.info Sat May 10 01:02:02 2003 From: greg@gregmchapman.info (Greg Chapman) Date: Sat May 10 00:02:02 2003 Subject: [Tutor] redundant code In-Reply-To: <5.2.1.1.1.20030509200739.00b27290@earthlink.net> Message-ID: >there's a better way to do what I've done. Anyway, I've written this little >thing to prompt for answers to simple multiplication problems, and I'm >wondering if anyone would care to comment on it. It bothers me that I have >to use the exact same line twice, but I can't figure out how to change >that. Plus it bothers me that the whole thing doesn't fit into one >function. Anyway, I'd appreciate any comments. I'm something of a newbie myself, so I can't completely answer your question (I can't think of how to make it one function cleanly) but this gets rid of some of the redundant code: from random import randrange from sys import exit from string import lower def question(): n1 = randrange(1, 10) n2 = randrange(1, 10) answer = int(raw_input('How much is %d times %d? ' % (n1, n2))) if answer != n1 * n2: return 1 else: return 0 while 1: if question(): print "No. Try again." else: print "Yes, that is correct." again = str(raw_input("Would you like another question (type Y or N)?")) if lower(again) == "y": pass else: exit() HTH, and I'm sure someone else will chime in with even better ways of doing it. greg From kthet_02@yahoo.com Sat May 10 06:00:02 2003 From: kthet_02@yahoo.com (matt dittsworth) Date: Sat May 10 05:00:02 2003 Subject: Fwd: RE: [Tutor] redundant code Message-ID: <20030510085915.47347.qmail@web21501.mail.yahoo.com> --0-280018374-1052557155=:45755 Content-Type: multipart/alternative; boundary="0-794396427-1052557155=:45755" --0-794396427-1052557155=:45755 Content-Type: text/plain; charset=us-ascii Note: forwarded message attached. Matt DittsworthSemper FiNew Website --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-794396427-1052557155=:45755 Content-Type: text/html; charset=us-ascii



Note: forwarded message attached.


Matt Dittsworth
Semper Fi


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-794396427-1052557155=:45755-- --0-280018374-1052557155=:45755 Content-Type: message/rfc822 X-Apparently-To: kthet_02@yahoo.com via 66.163.169.17; 09 May 2003 21:02:09 -0700 (PDT) Return-Path: Received: from 12.155.117.29 (EHLO mail.python.org) (12.155.117.29) by mta219.mail.scd.yahoo.com with SMTP; 09 May 2003 21:02:09 -0700 (PDT) Received: from localhost.localdomain ([127.0.0.1] helo=mail.python.org) by mail.python.org with esmtp (Exim 4.05) id 19ELYl-0008K6-00; Sat, 10 May 2003 00:02:07 -0400 Received: from rwcrmhc53.attbi.com ([204.127.198.39]) by mail.python.org with esmtp (Exim 4.05) id 19ELYM-0008Hs-00 for tutor@python.org; Sat, 10 May 2003 00:01:42 -0400 Received: from onegreg (12-246-179-136.client.attbi.com[12.246.179.136]) by attbi.com (rwcrmhc53) with SMTP id <2003051004011005300j2gj4e>; Sat, 10 May 2003 04:01:10 +0000 From: "Greg Chapman" To: "Peter Jakubowicz" Cc: Subject: RE: [Tutor] redundant code MIME-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit X-Priority: 3 (Normal) X-MSMail-Priority: Normal X-Mailer: Microsoft Outlook IMO, Build 9.0.6604 (9.0.2911.0) In-Reply-To: <5.2.1.1.1.20030509200739.00b27290@earthlink.net> Importance: Normal X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4807.1700 X-warning: 204.127.198.39 in blacklist at unconfirmed.dsbl.org (http://dsbl.org/listing?ip=204.127.198.39) X-Spam-Status: No, hits=1.3 required=5.0 tests=IN_REP_TO,RCVD_IN_MULTIHOP_DSBL,RCVD_IN_UNCONFIRMED_DSBL,SPAM_PHRASE_01_02 X-Spam-Level: * Sender: tutor-admin@python.org Errors-To: tutor-admin@python.org X-BeenThere: tutor@python.org X-Mailman-Version: 2.0.13 (101270) Precedence: bulk List-Help: List-Post: List-Subscribe: , List-Id: Discussion for learning programming with Python List-Unsubscribe: , List-Archive: X-Original-Date: Fri, 9 May 2003 21:00:57 -0700 Date: Fri, 9 May 2003 21:00:57 -0700 Content-Length: 716 >there's a better way to do what I've done. Anyway, I've written this little >thing to prompt for answers to simple multiplication problems, and I'm >wondering if anyone would care to comment on it. It bothers me that I have >to use the exact same line twice, but I can't figure out how to change >that. Plus it bothers me that the whole thing doesn't fit into one >function. Anyway, I'd appreciate any comments. I'm something of a newbie myself, so I can't completely answer your question (I can't think of how to make it one function cleanly) but this gets rid of some of the redundant code: from random import randrange from sys import exit from string import lower def question(): n1 = randrange(1, 10) n2 = randrange(1, 10) answer = int(raw_input('How much is %d times %d? ' % (n1, n2))) if answer != n1 * n2: return 1 else: return 0 while 1: if question(): print "No. Try again." else: print "Yes, that is correct." again = str(raw_input("Would you like another question (type Y or N)?")) if lower(again) == "y": pass else: exit() HTH, and I'm sure someone else will chime in with even better ways of doing it. greg _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --0-280018374-1052557155=:45755-- From andi@buxach.de Sat May 10 07:44:02 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Sat May 10 06:44:02 2003 Subject: [Tutor] combinations Message-ID: <20030510124242.37fe92d4.andi@buxach.de> This is a multi-part message in MIME format. --Multipart_Sat__10_May_2003_12:42:42_+0200_08267408 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit I wrote a program to print out all kominbations of a given string 123: 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 I had to write a function to check wether a number is in the current possibility yet def partof(needle, heystack): """ is needle in heystack? """ for x in heystack: if needle == x: return 1 return 0 First i tried to do it this way if neddle in heystack: 1. This would be short but is not possible, is it?? Another problem was the recursion for current in range(len(full)): # try all combinations if not partof(current, yet): yet.append(current) # add ne possible element yet = kombies(yet, full)[0:-1] return yet First i tried this yet.append(current) kombies(yet, full) #kombies returns nothing yet = yet[0:-1] #kick the last element to try another But this did not work. 2. Python never got back to the first stage of the recursion. why? attached is the full program as it works -- Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de --Multipart_Sat__10_May_2003_12:42:42_+0200_08267408 Content-Type: application/octet-stream; name="kombis.py" Content-Disposition: attachment; filename="kombis.py" Content-Transfer-Encoding: base64 IyEvdXNyL2Jpbi9weXRob24KaW1wb3J0IHN5cwoKZGVmIHBhcnRvZihuZWVkbGUsIGhleXN0YWNr KToKCSIiIiBpcyBuZWVkbGUgaW4gaGV5c3RhY2s/ICIiIgoJZm9yIHggaW4gaGV5c3RhY2s6CgkJ aWYgbmVlZGxlID09IHg6CgkJCXJldHVybiAxCglyZXR1cm4gMAoKZGVmIHBvc19wcmludCggcG9z aXRpb25zLCBhbGwgKToKCSIiIiBwcmludCB0aGUgbGV0dGVycyBvZiBhbGwgYnkgdGhlIHBvc2l0 aW9ucyAiIiIKCWZvciBwb3MgaW4gcG9zaXRpb25zOgoJCXByaW50IGFsbFtwb3NdLAoJcHJpbnQK CmRlZiBrb21iaWVzKHlldCwgZnVsbCk6CgkiIiIgZmluZCBhbGwga29tYmluYXRpb25zIHJlY3Vy c2l2ZSAiIiIKCWlmIGxlbih5ZXQpID09IGxlbihmdWxsKTogI3dlIGFyZSBmdWxsLCBwcmludCBp dCBvdXQKCQlwb3NfcHJpbnQoIHlldCwgZnVsbCApCgkJcmV0dXJuIHlldAoJCglmb3IgY3VycmVu dCBpbiByYW5nZShsZW4oZnVsbCkpOiAjIHRyeSBhbGwgY29tYmluYXRpb25zCgkJaWYgbm90IHBh cnRvZihjdXJyZW50LCB5ZXQpOgoJCQl5ZXQuYXBwZW5kKGN1cnJlbnQpCgkJCXlldCA9IGtvbWJp ZXMoeWV0LCBmdWxsKVswOi0xXSAKCXJldHVybiB5ZXQKCmlmIF9fbmFtZV9fID09ICJfX21haW5f XyI6Cglrb21iaWVzKFtdLHN5cy5hcmd2WzFdKQoK --Multipart_Sat__10_May_2003_12:42:42_+0200_08267408-- From dan_nash@hotmail.com Sat May 10 08:16:24 2003 From: dan_nash@hotmail.com (Daniel Nash) Date: Sat May 10 07:16:24 2003 Subject: [Tutor] (no subject) Message-ID: I'm still trying to understand mime and multifiles, can some one explain the purpose of the following lines of code in the 12.10.2 MultiFile Example data = StringIO.StringIO() submsg = mimetools.Message(file) try: data = StringIO.StringIO() mimetools.decode(file, data, submsg.getencoding()) except ValueError: continue if submsg.gettype() == mimetype: break file.pop() return data.getvalue() submsg = mimetools.Message(file) try: data = StringIO.StringIO() mimetools.decode(file, data, submsg.getencoding()) except ValueError: continue _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From dan_nash@hotmail.com Sat May 10 08:25:02 2003 From: dan_nash@hotmail.com (Daniel Nash) Date: Sat May 10 07:25:02 2003 Subject: [Tutor] I don't understand example 12.10.2 Message-ID: Sorry about that last message it was sent my mistake!! What I was trying to say was ... I am still trying to get to grips with mime and multipart email messages and was wondering if someone could explain what the follow lines of code from example 12.10.2 (python.org)MultiFile Example: What is this line for? data = StringIO.StringIO() and what is going on here? try: data = StringIO.StringIO() mimetools.decode(file, data, submsg.getencoding()) except ValueError: continue Thanks Dan _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From dan_nash@hotmail.com Sat May 10 09:20:02 2003 From: dan_nash@hotmail.com (Daniel Nash) Date: Sat May 10 08:20:02 2003 Subject: [Tutor] I don't understand example 12.10.2 Message-ID: Following my previous message, I have done a little bit more reading and I think that data is a "string buffer"? But i don't get why the line mimetools.decode(file, data, submsg.getencoding()) doesn't use 'submsg' instead of 'file' for the input Is it something to do with the way file.next() works? Dan _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From zerkani@snet.net Sat May 10 15:05:02 2003 From: zerkani@snet.net (Zerkani) Date: Sat May 10 14:05:02 2003 Subject: [Tutor] DCOracle & ZOracle In-Reply-To: <200305101237.07403.zerkani_user_list@snet.net> References: <200305101237.07403.zerkani_user_list@snet.net> Message-ID: <200305101407.15086.zerkani@snet.net> Does anyone know if there are Debian packages available for DCOracle and ZOracle for python and zope? Any information will be greaty appreciated. Thanks, Z From kikofx@nifty.com Sat May 10 15:11:27 2003 From: kikofx@nifty.com (Tadahiko 'kiko' Uehara) Date: Sat May 10 14:11:27 2003 Subject: [Tutor] os.execl() args? Message-ID: <20030511030535.5987d730.kikofx@nifty.com> Hi everyone, I'm having a hard time to understand this... render = '/usr/local/bin/Render' # <--- this is external program for queue in queueLines: os.execl(render,'',queue) # <--- here variable 'queue' has '/mnt/work/maya/py/scenes/pyTest001.mb' after extract from queueLines. but this returns error message 'Unmatched ".' . However, if i declair variable 'queue = /mnt/work/maya/py/scenes/pyTest001.mb' somewhere in the program, it works. so my question is, 1) Why this doesn't work? Insert 'print queue' after 'for~ :' line, I see the same string '/mnt/work/maya/py/scenes/pyTest001.mb'. I don't understand why this doesn't work. 2) os.execl(render,'',queue) , I had to give arg0 blank. I found the following explanation in the doc... "For the C programmer, this is the argv[0] passed to a program's main(). For example, "os.execv('/bin/echo', ['foo', 'bar'])" will only print "bar" on standard output; "foo"will seem to be ignored." I'm not quite sure what it says.. Though, give argv0 to nothing'' is correct? 3) What would be the main difference using 'os.exec*()' and 'os.system()' ? For my task, both acts like same.. Sorry for long mail and multiple question. -kiko From magnus@thinkware.se Sat May 10 15:21:21 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 10 14:21:21 2003 Subject: [Tutor] I don't understand example 12.10.2 In-Reply-To: Message-ID: <5.2.1.1.0.20030510162423.00be3a90@www.thinkware.se> At 07:23 2003-05-10 -0400, Daniel Nash wrote: >data = StringIO.StringIO() You can see a StringIO object as an in-memory file. See below: >>> import StringIO >>> m = StringIO.StringIO() >>> m.write('Hello, there!\n') >>> m.write('How are you?\n') >>> m.write('I\'m fine\n') >>> m.readlines() [] >>> m.tell() 36 >>> m.seek(0) >>> m.tell() 0 >>> m.readlines() ['Hello, there!\n', 'How are you?\n', "I'm fine\n"] It also has some features files lack, e.g. >>> m.getvalue() "Hello, there!\nHow are you?\nI'm fine\n" The data isn't saved in a file, but the interface is almost exactly like the interface to a file. This means that functions that expect a file object can usually take a StringIO object instead. Note that StringIO is written in Python, and there is an almost identical module called cStringIO which is written in C and thus much faster. I think cStringIO lacks some (not often used) features of StringIO, but it's typically the module people use... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Sat May 10 15:21:33 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 10 14:21:33 2003 Subject: [Tutor] redundant code In-Reply-To: References: <5.2.1.1.1.20030509200739.00b27290@earthlink.net> Message-ID: <5.2.1.1.0.20030510163523.025104e8@www.thinkware.se> At 21:00 2003-05-09 -0700, Greg Chapman wrote: >from random import randrange >from sys import exit >from string import lower This is redundant. Since Python 1.6 (?) you can use "again.lower()" instead of "string.lower(again)". >def question(): > n1 = randrange(1, 10) > n2 = randrange(1, 10) > answer = int(raw_input('How much is %d times %d? ' % (n1, n2))) > if answer != n1 * n2: > return 1 > else: > return 0 This is not the function Peter asked for. You don't let the user answer the same questions several times. But in general Gregs "while 1: ... break" loop is a common Python approach when you have to go through a loop at least once, but there are options... Refering to Peter's code: It's a bit odd that you put the "No. Try again" and "Yes, that is correct" replies in different parts of the code, isn't it? They are a pair, and it's probably better to keep them together, both to make the code easy to understand, and to reduce the risk that we miss something if we have to change the code. raw_input returns a string, so str(raw_input()) is redundant. Untested code follows... from random import randrange # from sys import exit #Why exit? A program exits when it reaches its end. def question(): n1 = randrange(1, 10) n2 = randrange(1, 10) continue = True while continue: answer = int(raw_input('How much is %d times %d? ' % (n1, n2))) if answer == n1 * n2: print "Yes, that is correct." continue = False # Alternative: Use "while 1:" above, and "break" here. else: print "No. Try again." def main(): while 1: question() yesNo = raw_input("Would you like another question (type Y or N)?") if yesNo.lower() != 'y': break if __name__ == '__main__': main() The last is a common idiom which makes it possible to use this code both as a standalone program, and as a module used by other programs. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From bgailer@alum.rpi.edu Sat May 10 16:18:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Sat May 10 15:18:02 2003 Subject: [Tutor] combinations In-Reply-To: <20030510124242.37fe92d4.andi@buxach.de> Message-ID: <5.2.0.9.0.20030510122229.02a350e8@66.28.54.253> At 12:42 PM 5/10/2003 +0200, Andreas Zwinkau wrote: >I wrote a program to print out all kominbations of a given string >123: >1 2 3 >1 3 2 >2 1 3 >2 3 1 >3 1 2 >3 2 1 These are permutations not combinations. >I had to write a function to check wether a number is in the current >possibility yet >def partof(needle, heystack): > """ is needle in heystack? """ > for x in heystack: > if needle == x: > return 1 > return 0 > >First i tried to do it this way > if neddle in heystack: >1. This would be short but is not possible, is it?? > >Another problem was the recursion > for current in range(len(full)): # try all combinations > if not partof(current, yet): > yet.append(current) # add ne possible element > yet = kombies(yet, full)[0:-1] > return yet >First i tried this > yet.append(current) > kombies(yet, full) #kombies returns nothing > yet = yet[0:-1] #kick the last element to try another >But this did not work. >2. Python never got back to the first stage of the recursion. why? > >attached is the full program as it works Try this version: it actually generates each permutation; there's no need to check for duplicates: #!/usr/bin/python import sys def tree(txt, indices=None, result=None): if not result: n = len(txt) indices = range(n) result = ['']*n else: n = len(indices) if n: for i in range(n): indices2 = indices[:] j = indices2.pop(i) result[n-1] = txt[j] tree(txt, indices2, result) else: print ''.join(result) if __name__ == "__main__": tree(sys.argv[1]) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From bgailer@alum.rpi.edu Sat May 10 20:06:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Sat May 10 19:06:02 2003 Subject: [Tutor] combinations In-Reply-To: <5.2.0.9.0.20030510122229.02a350e8@66.28.54.253> References: <20030510124242.37fe92d4.andi@buxach.de> Message-ID: <5.2.0.9.0.20030510164411.02a9ccf0@66.28.54.253> A little more time and effort and a shorter version results: #!/usr/bin/python import sys def tree(txt, result=''): if txt: for i in range(len(txt)): foo(txt[:i] + txt[i+1:], result + txt[i]) else: print result if __name__ == "__main__": tree(list(sys.argv[1])) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From magnus@thinkware.se Sat May 10 21:05:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 10 20:05:02 2003 Subject: [Tutor] combinations In-Reply-To: <5.2.0.9.0.20030510164411.02a9ccf0@66.28.54.253> References: <5.2.0.9.0.20030510122229.02a350e8@66.28.54.253> <20030510124242.37fe92d4.andi@buxach.de> Message-ID: <5.2.1.1.0.20030511020138.00bbbae8@www.thinkware.se> That's cute! At 16:54 2003-05-10 -0600, Bob Gailer wrote: >def tree(txt, result=''): > if txt: > for i in range(len(txt)): > foo(txt[:i] + txt[i+1:], result + txt[i]) I guess that should be "tree", not "foo"... > else: > print result I was thinking...is there any simple iterative (not recursive) solution for this in the general case where we don't have a certain length of the string? Not that recursion is bad in this case, I'm just curious if people see a simple way to do this without recursion. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dyoo@hkn.eecs.berkeley.edu Sat May 10 23:29:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat May 10 22:29:02 2003 Subject: [Tutor] DCOracle & ZOracle In-Reply-To: <200305101407.15086.zerkani@snet.net> Message-ID: On Sat, 10 May 2003, Zerkani wrote: > Does anyone know if there are Debian packages available for DCOracle > and ZOracle for python and zope? Any information will be greaty > appreciated. Hi Zerkani, Wow. This question is REALLY specialized. *grin* The only person I can think of offhand that might be able to answer this is Sean Perry, but he may be busy. Not many of us on Tutor can help you here. To get better help, you may want to ask on the debian-python mailing list: http://lists.debian.org/debian-python/ The folks at debian-python maintain the packages for Python in Debian; I'm positive that someone there can help you find out about those Oracle modules. Good luck to you! From kikofx@nifty.com Sun May 11 03:14:02 2003 From: kikofx@nifty.com (Tadahiko 'kiko' Uehara) Date: Sun May 11 02:14:02 2003 Subject: [Tutor] os.execl() args? In-Reply-To: References: <20030511030535.5987d730.kikofx@nifty.com> Message-ID: <20030511151320.4113e9c3.kikofx@nifty.com> Thank you for replying, David! In my enviroment (Linux,tcsh,python2.2), I don't see path name.. :( ### jem:/home/kiko/docs/python> python args.py lots of arguments here Args were: args.py lots of arguments here ### Basically, My understand for arguments are (optional) parameters which passed to command. ie. 'xv foo.png' (xv is command and foo.png is an argument) execl('xv','','foo.png') or 'mv -r foo foo2' (mv for command, -r , foo , foo2 are arguments) Is this correct? Thanks in advance, -kiko On Sat, 10 May 2003 15:45:53 -0400 "David Broadwell" wrote: > > 2) os.execl(render,'',queue) , I had to give arg0 blank. I found the > following explanation in the doc... > > "For the C programmer, this is the argv[0] passed to a program's main(). For > example, "os.execv('/bin/echo', ['foo', 'bar'])" will only print "bar" on > standard output; "foo"will seem to be ignored." > > I'm not quite sure what it says.. Though, give argv0 to nothing'' is > correct? > > > Well, I'm green to, so I'll answer with code. > > > from sys import argv > > print "Args were:" > for item in argv: > print item > > > $p$g > args.py lots of arguments here > Args were: > D:\mongoose\My Documents\My Code\python\args.py > lots > of > arguments > here > > --- > > sys.argv[0] is the path to the script ... And it's interesting to note that > if you "" a block of args they end up as one arg. > > Sorry, can't really answer the rest. > > -- > > David Broadwell (Amar Shadowpaws) > From micforster@yahoo.com Sun May 11 05:10:04 2003 From: micforster@yahoo.com (Mic Forster) Date: Sun May 11 04:10:04 2003 Subject: [Tutor] factorial In-Reply-To: <20030511151320.4113e9c3.kikofx@nifty.com> Message-ID: <20030511080927.24751.qmail@web13408.mail.yahoo.com> Hi Chaps, Does Python support a factorial function? eg.(below is math notation) n = 10 y = 3 x = n! / y! - 1 x = ? Cheers.... __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From magnus@thinkware.se Sun May 11 05:40:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun May 11 04:40:03 2003 Subject: [Tutor] factorial In-Reply-To: <20030511080927.24751.qmail@web13408.mail.yahoo.com> References: <20030511151320.4113e9c3.kikofx@nifty.com> Message-ID: <5.2.1.1.0.20030511102437.00bbeab0@www.thinkware.se> At 01:09 2003-05-11 -0700, Mic Forster wrote: >Does Python support a factorial function? There is no builtin factorial function, but it's just a series of multiplications, right? There is no way you can make ! an operator in Python though, so it will have to be a function call. Something like fac(i) rather than i! I'm not going to spoon feed you though. We learn by trying, not by being given solutions... Try for yourself and get back if there is some part you don't figure out. A for loop and the range function is probably a good start. Basically there are two fundamental ways to solve this. Either throuh iteration, or though recursion. This is a typical case where recursion is demonstrated, but recursion isn't faster (in Python at least) and it introduces a completely new concept, which might just muddle the issue. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From gerrit@nl.linux.org Sun May 11 05:40:13 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Sun May 11 04:40:13 2003 Subject: [Tutor] factorial In-Reply-To: <20030511080927.24751.qmail@web13408.mail.yahoo.com> References: <20030511151320.4113e9c3.kikofx@nifty.com> <20030511080927.24751.qmail@web13408.mail.yahoo.com> Message-ID: <20030511083824.GA2441@nl.linux.org> > From: Mic Forster > To: tutor@python.org > Subject: [Tutor] factorial > Date: Sun, 11 May 2003 10:10:41 +0200 > Hi Chaps, Hi, > Does Python support a factorial function? > > eg.(below is math notation) > n = 10 > y = 3 > x = n! / y! - 1 > x = ? As I understand it, you can easily write it yourself: 16 >>> def fact(n): 16 ... if n<2: return n 16 ... else: return n*fact(n-1) 16 ... 18 >>> fact(10)/fact(3) - 1 604799 Or is that not what you mean? yours, Gerrit. -- 124. If any one deliver silver, gold, or anything else to another for safe keeping, before a witness, but he deny it, he shall be brought before a judge, and all that he has denied he shall pay in full. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From idiot1@netzero.net Sun May 11 09:57:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun May 11 08:57:02 2003 Subject: [Tutor] permissions and other hairpulls Message-ID: <3EBE4889.9010904@netzero.net> permissions in FreeBSD are the most fustrating aspect of web scripting. Here is an error: Traceback (innermost last): File "/www/www.listville.net/cgi-bin/TLlistmaker2.py", line 195, in ? os.chmod(fullpathtoscript+'/lists/'+mylist,666) OSError: [Errno 79] Inappropriate file type or format: '/www/www.listville.net/cgi-bin/lists/test33' The script is attempting to set the mod to 666 for a file just created and closed. It is created by the script, and examination shows it is 644. Another scipt is trying later to add to it, and failing, for a permissions reason. ALL scripts are 755, owned by nobody:wheel. All such text files are also nobody:wheel, and work fine when 666, but problems when 644. Any suggestions from the brethern? -- end Respectfully, Kirk D Bailey +------------------------------------------------------------+ | Owner Howler Monkey Email: http://www.howlermonkey.net/ | | Inventor of TinyList list server: http://www.tinylist.org/ | | Consulting freestyle Grump: http://www.sacredelectron.org/ | | Remember: When we referr to FREE software, we are talking | | about FREEDOM, not $PRICE$. | +------------------------------------------------------------+ From a_abdi406@yahoo.com Sun May 11 10:09:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Sun May 11 09:09:02 2003 Subject: [Tutor] about Regular Expression Message-ID: <20030511130834.22304.qmail@web14508.mail.yahoo.com> --0-1253465956-1052658514=:22095 Content-Type: text/plain; charset=us-ascii Hi ,I was a working on program that processes xml files, the program has the following:The most likely analysisI want to extract the words in between .. and I set up reg expression which gives me those words: that is o.k ['The', 'most', 'likely', 'analysis', ......] but the program has also a non- word tagged with ..I was trying to set up a reg. expression that eliminates those tagged non-words which are giving me a bit of aproblem.... . , ( ) ' can anyone help me get this reg. expression wright ? thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-1253465956-1052658514=:22095 Content-Type: text/html; charset=us-ascii
Hi ,
I was a working on program that processes xml files, the program has the following:
<W>The</W> <W>most</W> <W>likely</W> <W>analysis</W>
I want to extract the words in between <W>..</W> and  I set up reg expression which gives me those words: that is o.k
 
['The', 'most', 'likely', 'analysis', ......]
 
but the program has also a non- word tagged with <W>..</W>
I was trying to set up a reg. expression that eliminates those tagged non-words which are giving me a bit of aproblem....
 
 <W>.</W> <W>,</W> <W>(</W> <W>)</W> <W>'</W>
 
can anyone help me get this reg. expression wright ?
 
thanks in advance 


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-1253465956-1052658514=:22095-- From Janssen@rz.uni-frankfurt.de Sun May 11 11:06:00 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sun May 11 10:06:00 2003 Subject: [Tutor] about Regular Expression In-Reply-To: <20030511130834.22304.qmail@web14508.mail.yahoo.com> Message-ID: On Sun, 11 May 2003, Abdirizak abdi wrote: [text reflowed] > Hi ,I was a working on program that processes xml files, the program > has the following: > > The most likely analysis > > I want to extract the words in between .. and I > set up reg expression which gives me those words: that is o.k ['The', > 'most', 'likely', 'analysis', ......] but the program has also a non- > word tagged with .. > > I was trying to set up a reg. expression > that eliminates those tagged non-words which are giving me a bit of > aproblem.... > > . , ( ) ' > > can anyone > help me get this reg. expression wright ? thanks in advance Hello Abdirizak, instead of making the regexp complicater and complicater, also consider, to surpress the non-words afterwards: words = [x for x in mixed_words_non_words if x not in tupel('\'"(),.;:!?')] Complicated regexp have the disadvantage of poor readability (and are therefore hard to maintain). Perhaps it's easier to do it in two steps within your programm. Michael From charlie@begeistert.org Sun May 11 11:37:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sun May 11 10:37:01 2003 Subject: [Tutor] DCOracle & ZOracle In-Reply-To: <20030511140600.12564.16102.Mailman@mail.python.org> References: <20030511140600.12564.16102.Mailman@mail.python.org> Message-ID: <20030511163618.1352.2@wonderland.1052642226.fake> > Does anyone know if there are Debian packages available for DCOracle and > ZOracle for python and zope? Any information will be greaty appreciated. Hi Zerkani, you probably want DCOracle2. It's available on the Zope homepage http://www.zope.org I don't know if the is a Debian-specific package I think you just build from source. I suggest you contact zope-db@zope.org if you have any queries as the list is dedicated to RDBMS and ZOPE. Charlie From andi@buxach.de Sun May 11 13:25:01 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Sun May 11 12:25:01 2003 Subject: [Tutor] combinations In-Reply-To: <5.2.1.1.0.20030511020138.00bbbae8@www.thinkware.se> References: <5.2.0.9.0.20030510122229.02a350e8@66.28.54.253> <20030510124242.37fe92d4.andi@buxach.de> <5.2.1.1.0.20030511020138.00bbbae8@www.thinkware.se> Message-ID: <20030907103922.67022f86.andi@buxach.de> Thanks for your help, Bob and Magnus :) Your solutions is just elegant. I guess you have to get experience in recursive methods to find the most elegant way? Whatever i learned something and I'm thankful. Great list this is ;) -- Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From shalehperry@attbi.com Sun May 11 14:24:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun May 11 13:24:02 2003 Subject: [Tutor] permissions and other hairpulls In-Reply-To: <3EBE4889.9010904@netzero.net> References: <3EBE4889.9010904@netzero.net> Message-ID: <200305111023.27519.shalehperry@attbi.com> On Sunday 11 May 2003 05:56, Kirk Bailey wrote: > permissions in FreeBSD are the most fustrating aspect of web scripting. > a good unix book might help here. Using a perm of 666 is almost always a bad idea. Use 664 if you have to group permission. > Here is an error: > Traceback (innermost last): > File "/www/www.listville.net/cgi-bin/TLlistmaker2.py", line 195, in ? > os.chmod(fullpathtoscript+'/lists/'+mylist,666) > OSError: [Errno 79] Inappropriate file type or format: > '/www/www.listville.net/cgi-bin/lists/test33' > most odd. I have no good idea about the cause to this. A few google searches reveal only weird questions from people with NFS issues. If you try to run chmod by hand on the file, does it do anything interesting? > The script is attempting to set the mod to 666 for a file just created and > closed. It is created by the script, and examination shows it is 644. > Another scipt is trying later to add to it, and failing, for a permissions > reason. ALL scripts are 755, owned by nobody:wheel. All such text files are > also nobody:wheel, and work fine when 666, but problems when 644. Any > suggestions from the brethern? most likely group needs permission to write for some reason (not sure what the file is or does). From carroll@tjc.com Sun May 11 16:52:01 2003 From: carroll@tjc.com (Terry Carroll) Date: Sun May 11 15:52:01 2003 Subject: [Tutor] Should I subclass UserDict or dict? In-Reply-To: <5.2.1.1.0.20030510045656.00badc20@www.thinkware.se> Message-ID: On Sat, 10 May 2003, Magnus Lyck=E5 wrote: > At 19:13 2003-05-09 -0700, Terry Carroll wrote: > >Should I inherit from the > >built-in dict class or from UserDict? >=20 > Use dict if you don't need to support Python versions < 2.2, and don't > plan to make the classes persistent with the ZOPE Object DataBase. I guess that's my question: how many likely users would I have running 2.= 1=20 or earlier. > >(my ISP's highest level of Python is 2.1.1, for example), or should I = use >=20 > My ISP upgraded to 2.2 when I asked them. Have you asked? > (Don't forget to say please. :) No, and they probably would. But I'm not complaining, just citing that a= s=20 anecdotal evidence of the fact that 2.2 doesn't seem to be everywhere=20 just yet. (I know a sample of 2, one of which is my own system, is far=20 from statistically significant, of course.) I think I'm going to go with UserDict for the time being, unless I see=20 something in 2.2 classes that I could use; for example, I'm thinking of=20 using properties, too, in which case I need 2.2 classes, and might as wel= l=20 use dict. --=20 Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From magnus@thinkware.se Sun May 11 18:25:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun May 11 17:25:02 2003 Subject: [Tutor] permissions and other hairpulls In-Reply-To: <3EBE4889.9010904@netzero.net> Message-ID: <5.2.1.1.0.20030511224732.00bc23c0@www.thinkware.se> At 08:56 2003-05-11 -0400, Kirk Bailey wrote: >permissions in FreeBSD are the most fustrating aspect of web scripting. This in nothing particular for FreeBSD... >Here is an error: >Traceback (innermost last): > File "/www/www.listville.net/cgi-bin/TLlistmaker2.py", line 195, in ? > os.chmod(fullpathtoscript+'/lists/'+mylist,666) >OSError: [Errno 79] Inappropriate file type or format: >'/www/www.listville.net/cgi-bin/lists/test33' Surely chmod doesn't want decimal 666? It wants octal numbers! That's what the chmod codes are, an octal representation for rwxrwxrwx 110110110 In octal this is 666. To make python interpret it as octal, write 0666. (Or write 438 if you want to confuse people! ;) os.chmod(fullpathtoscript+'/lists/'+mylist,0666) (Who ever said zero means nothing?) 666 is octal 1232, and that's not what you want! >The script is attempting to set the mod to 666 for a file just created and >closed. >It is created by the script, and examination shows it is 644. This is because umask = 022 I guess... >Another scipt is trying later to add to it, and failing, for a permissions >reason. ALL >scripts are 755, owned by nobody:wheel. All such text files are also >nobody:wheel, and >work fine when 666, but problems when 644. Any suggestions from the brethern? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Sun May 11 18:39:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun May 11 17:39:01 2003 Subject: [Tutor] Should I subclass UserDict or dict? In-Reply-To: References: <5.2.1.1.0.20030510045656.00badc20@www.thinkware.se> Message-ID: <5.2.1.1.0.20030511232839.00be8b38@www.thinkware.se> At 12:51 2003-05-11 -0700, Terry Carroll wrote: >I guess that's my question: how many likely users would I have running 2.1 >or earlier. Well, we can hardly tell *you* what *your* users are running. At least not with the information you have given us so far. In general, I see projects dropping 2.1 support. I think Twisted just dropped 2.1 support with their 1.0.5 release this week, to give a high profile example. I think most current Linux/BSD distributions come with Python 2.2, so those who don't have to install it themselves will certainly have 2.2 after the next OS upgrade. On the other hand, there are probably people running Red Hat 6.2 around... (But if you want you can naturally install python 2.2 on Red Hat 6.2 as well.) Python 2.2 has also been declared the "Python In a Tie" version, which is to be maintained for a long time, so that companies that develop with 2.2 knows that they won't have to upgrade for several years. If I didn't have legacy code or *knew* I had a user who for some reason demanded support for a particular version, I would never restrict myself to support versions earlier than 2.2. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dyoo@hkn.eecs.berkeley.edu Sun May 11 19:23:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun May 11 18:23:02 2003 Subject: [Tutor] factorial In-Reply-To: <5.2.1.1.0.20030511102437.00bbeab0@www.thinkware.se> Message-ID: > Basically there are two fundamental ways to solve this. Either throuh > iteration, or though recursion. This is a typical case where recursion > is demonstrated, but recursion isn't faster (in Python at least) and it > introduces a completely new concept, which might just muddle the issue. By the way, there's another way to get a rough estimate of the factorial function, based on some cool approximation theory. Mathworld has a pretty dense article about it: http://mathworld.wolfram.com/StirlingsApproximation.html It gives the improbably wacky function: n! \approx \sqrt{2 \pi} n^{n+1/2} e^{-n} This equation is so strange that it must be true. *grin* Does anyone want to code it in Python and see how it compares to the exact factorial function? From greg@gregmchapman.info Sun May 11 22:18:01 2003 From: greg@gregmchapman.info (Greg Chapman) Date: Sun May 11 21:18:01 2003 Subject: [Tutor] factorial Message-ID: >It gives the improbably wacky function: > > n! \approx > \sqrt{2 \pi} n^{n+1/2} e^{-n} > >This equation is so strange that it must be true. *grin* > > >Does anyone want to code it in Python and see how it compares to the exact >factorial function? Maybe I got the syntax wrong on Danny's approximation version, but the way I did it it's way off. Can anyone tell me if I got the syntax wrong or if the function actually doesn't work well? import math def apFactorial(n): #this should be equivalent to Danny's return ((math.sqrt(2 * math.pi)) * (n**(n+1/2)) * (math.exp(-n))) def reFactorial(n): #this is Gerrit's recursive function from his earlier post if n<2: return n else: return n*reFactorial(n-1) def itFactorial(n): #and here's an iterative version I threw together i = n-1 while i: n = n * i ; i -= 1 return n if __name__ == '__main__': print 'Approximate function:\t %d' % apFactorial(10) print 'Recursive function:\t %d' % reFactorial(10) print 'Iterative function:\t %d' % itFactorial(10) The program output is: Approximate function: 1138007 Recursive function: 3628800 Iterative function: 3628800 From tgrimes@teleport.com Sun May 11 23:02:02 2003 From: tgrimes@teleport.com (TJ) Date: Sun May 11 22:02:02 2003 Subject: [Tutor] factorial In-Reply-To: References: Message-ID: >Maybe I got the syntax wrong on Danny's approximation version, but the way I >did it it's way off. > >Can anyone tell me if I got the syntax wrong or if the function actually >doesn't work well? >def apFactorial(n): #this should be equivalent to Danny's > return ((math.sqrt(2 * math.pi)) * (n**(n+1/2)) * (math.exp(-n))) I played with this a little. Your syntax looks okay to me except you are doing an integer division in this term: (n**(n+1/2)) This is not what you want. Change this term to (n**(n+1/2.0)) or even (n**(n+0.5)) and you will get better results. My results were: Approximate function: 3598695 Recursive function: 3628800 Iterative function: 3628800 TJ From greg@gregmchapman.info Sun May 11 23:19:01 2003 From: greg@gregmchapman.info (Greg Chapman) Date: Sun May 11 22:19:01 2003 Subject: [Tutor] factorial Message-ID: >>Maybe I got the syntax wrong on Danny's approximation version, but the way I >>did it it's way off. >> >>Can anyone tell me if I got the syntax wrong or if the function actually >>doesn't work well? > >>def apFactorial(n): #this should be equivalent to Danny's >> return ((math.sqrt(2 * math.pi)) * (n**(n+1/2)) * (math.exp(-n))) > >I played with this a little. Your syntax looks okay to me except you >are doing an integer division in this term: (n**(n+1/2)) This is not >what you want. Change this term to (n**(n+1/2.0)) or even >(n**(n+0.5)) and you will get better results. > >My results were: >Approximate function: 3598695 >Recursive function: 3628800 >Iterative function: 3628800 hmmm, that does seem to work better. Thanks TJ. greg From idiot1@netzero.net Sun May 11 23:33:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun May 11 22:33:02 2003 Subject: [Tutor] permissions and other hairpulls References: <3EBE4889.9010904@netzero.net> <200305111023.27519.shalehperry@attbi.com> Message-ID: <3EBEEDEF.6070307@netzero.net> Sean 'Shaleh' Perry wrote: > On Sunday 11 May 2003 05:56, Kirk Bailey wrote: > >>permissions in FreeBSD are the most fustrating aspect of web scripting. >> > > > a good unix book might help here. Using a perm of 666 is almost always a bad > idea. Use 664 if you have to group permission. > > >>Here is an error: >>Traceback (innermost last): >> File "/www/www.listville.net/cgi-bin/TLlistmaker2.py", line 195, in ? >> os.chmod(fullpathtoscript+'/lists/'+mylist,666) >>OSError: [Errno 79] Inappropriate file type or format: >>'/www/www.listville.net/cgi-bin/lists/test33' >> > > > most odd. I have no good idea about the cause to this. A few google searches > reveal only weird questions from people with NFS issues. > > If you try to run chmod by hand on the file, does it do anything interesting? > nothing odd whatsoever. Which is odd. > >>The script is attempting to set the mod to 666 for a file just created and >>closed. It is created by the script, and examination shows it is 644. >>Another scipt is trying later to add to it, and failing, for a permissions >>reason. ALL scripts are 755, owned by nobody:wheel. All such text files are >>also nobody:wheel, and work fine when 666, but problems when 644. Any >>suggestions from the brethern? > > > most likely group needs permission to write for some reason (not sure what the > file is or does). > the file is a flat text file, with a bunch of email addresses in it, such as me@here.org you@there.org us@noplace,bet theclub@clubtown.info The idea is to append a new member to the existing file with an open statement. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- end Respectfully, Kirk D Bailey +------------------------------------------------------------+ | Owner Howler Monkey Email: http://www.howlermonkey.net/ | | Inventor of TinyList list server: http://www.tinylist.org/ | | Consulting freestyle Grump: http://www.sacredelectron.org/ | | Remember: When we referr to FREE software, we are talking | | about FREEDOM, not $PRICE$. | +------------------------------------------------------------+ From idiot1@netzero.net Sun May 11 23:46:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun May 11 22:46:02 2003 Subject: [Tutor] Re:Permissions and other hairpulls Message-ID: <3EBF0B6E.8050902@netzero.net> !$%$^*! It worked! Hmmm... when I am in the console and issuing commands, chmod 666 dead.parrot works fine; but when in the program, os.chmod('/pathtoparrotcage.dead.parrot',666) barks like a dog- apparently python does not like decimal data at all. BUT os.chmod('/pathtoparrotcage/dead.parrot',0666) which forces it to interpet it as octal expressed information WORKS LIKE A CHARM! WAHOO! THANKS gang, especially to magnus@thinkware.se for the heads up! Gee, if only the docs or the website had been just a TAD bit clearer about this? -- end Respectfully, Kirk D Bailey +------------------------------------------------------------+ | Owner Howler Monkey Email: http://www.howlermonkey.net/ | | Inventor of TinyList list server: http://www.tinylist.org/ | | Consulting freestyle Grump: http://www.sacredelectron.org/ | | Remember: When we referr to FREE software, we are talking | | about FREEDOM, not $PRICE$. | +------------------------------------------------------------+ From shalehperry@attbi.com Mon May 12 02:11:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon May 12 01:11:02 2003 Subject: [Tutor] Re:Permissions and other hairpulls In-Reply-To: <3EBF0B6E.8050902@netzero.net> References: <3EBF0B6E.8050902@netzero.net> Message-ID: <200305112210.00768.shalehperry@attbi.com> On Sunday 11 May 2003 19:48, Kirk Bailey wrote: > !$%$^*! > It worked! > Hmmm... when I am in the console and issuing commands, chmod 666 > dead.parrot works fine; but when in the program, > os.chmod('/pathtoparrotcage.dead.parrot',666) barks like a dog- apparently > python does not like decimal data at all. BUT > os.chmod('/pathtoparrotcage/dead.parrot',0666) which forces it to interpet > it as octal expressed information WORKS LIKE A CHARM! > > WAHOO! THANKS gang, especially to magnus@thinkware.se for the heads up! > > > Gee, if only the docs or the website had been just a TAD bit clearer about > this? on the console chmod ASSUMES the input you gave it was octal so all is well. I am so used to it I forgot to mention it, thanks to Magnus for noticing. Of course, many of us use the g+w notation instead to avoid the numerical pitfalls. From idiot1@netzero.net Mon May 12 02:23:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Mon May 12 01:23:02 2003 Subject: [Tutor] Re:Permissions and other hairpulls References: <3EBF0B6E.8050902@netzero.net> <200305112210.00768.shalehperry@attbi.com> Message-ID: <3EBF3025.3050807@netzero.net> I only wish the docs had been a tad more explicit. But that was the last hairpull I can find, the thing appears to be rather reliable now. How are you at sh/bourne shell scripting? I need totake the now obsolete installer and turn it into a more potent and complex one for the now more complex tinylist. Cranking out the first one strained my talents to the limits, and this one will be larger and more complex. Anyone else on the list intrested as well? Sean 'Shaleh' Perry wrote: > On Sunday 11 May 2003 19:48, Kirk Bailey wrote: > >>!$%$^*! >>It worked! >>Hmmm... when I am in the console and issuing commands, chmod 666 >>dead.parrot works fine; but when in the program, >>os.chmod('/pathtoparrotcage.dead.parrot',666) barks like a dog- apparently >>python does not like decimal data at all. BUT >>os.chmod('/pathtoparrotcage/dead.parrot',0666) which forces it to interpet >>it as octal expressed information WORKS LIKE A CHARM! >> >>WAHOO! THANKS gang, especially to magnus@thinkware.se for the heads up! >> >> >>Gee, if only the docs or the website had been just a TAD bit clearer about >>this? > > > on the console chmod ASSUMES the input you gave it was octal so all is well. > I am so used to it I forgot to mention it, thanks to Magnus for noticing. > > Of course, many of us use the g+w notation instead to avoid the numerical > pitfalls. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- end Respectfully, Kirk D Bailey +------------------------------------------------------------+ | Owner Howler Monkey Email: http://www.howlermonkey.net/ | | Inventor of TinyList list server: http://www.tinylist.org/ | | Consulting freestyle Grump: http://www.sacredelectron.org/ | | Remember: When we referr to FREE software, we are talking | | about FREEDOM, not $PRICE$. | +------------------------------------------------------------+ From hemanexp@yahoo.com Mon May 12 04:45:25 2003 From: hemanexp@yahoo.com (Python-lover) Date: Mon May 12 03:45:25 2003 Subject: [Tutor] Displaying Toplevel window in user specified location................. Message-ID: <20030512074427.24107.qmail@web41706.mail.yahoo.com> hi, how to place a toplevel window in a loaction specified by the user? I have a button in main window. I want to display a toplevel window in a location ,say (100,100), if i click the button. Thanx. __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From greg@gregmchapman.info Mon May 12 13:15:08 2003 From: greg@gregmchapman.info (Greg Chapman) Date: Mon May 12 12:15:08 2003 Subject: [Tutor] factorial Message-ID: I'm leaving this pretty much intact since it wasn't originally posted to the list. >You may want to try the following. fact(n) and fact2(n) will compute >1000000!. Fact3(n) uses >De Moivre's approximation also called Stirling's approximation and is good >only for about 15 places. > >The output for 15! is shown. >>>>fact(15) >1307674368000L >>>>fact2(15) >1307674368000 >n! for n = 15 >Actual digits 13 >Formula digits 13 >Seconds to calc 0.0 >>>>fact3(15) >1.307674368e+012 >>>> > > >Python has great power. The integer precision is fantastic. Any way to get >float to be arbitrary? >I wish the ^ operator could replace ** for exponentiation AND to be able to >edit script and go right >back in and run without having to close the dos >>> box and re-enter and >then from factorial import >* . should be able to from factorial import * without closing the >>> >session. you should be able to do: >>>reload(factorial) >Have fun > > ># Program factorial.py ># Cino Hilliard hillcino368@hotmail.com ># Compute n! using python and the ConText editor which supports Python ># Fact2 tests the accuracy of my formula for the number of digits in n! ># Fact3 tests the accuracy of my modification of De moivre's Formula ># 1 3 ># N ( -N + 1/(12*N) - 1/(360*N) +. . .) ># N! ~ N * sqrt(2*PI*N) * e ># ># Perm calculates the permutations of n things taken r at a time ># Comb calculates the combinations of n things taken r at a time ># digits = int((n+.5)*log(n)/log(10) - n*log(exp(1.0))/log(10)+.3991)+1 ># usage: >>> from factorial import * >>> fact2(number) ># >from math import * >def fact(n): > f = j = 1 > while j <= n: > f*=j > j+=1 > return f ># digits = int((n+.5)*log(n)/log(10) - n*log(exp(1.0))/log(10)+.3991)+1 ># Test this fantastic formula for digits in n! >def fact2(n): > import time > t1=time.time() > x = fact(n) > t2=time.time() > print x > d = int((n+.5)*log(n)/log(10) - n*log(exp(1.0))/log(10)+.3991)+1 > print "n! for n = ",n > print "Actual digits ",len(str(x)) > print "Formula digits ",d > print "Seconds to calc ",t2 - t1 > ># Test a modification of De moivre's formula for n! >def fact3(n): > series=n > nsqr=n*n > n2pi =n*2*3.1415926535897932 > sqrt2pi = sqrt(n2pi) > ptn = .5/n > tmp = 6 > ptn /= tmp > series -= ptn > tmp=30 > ptn /= nsqr > ptn /= tmp > series += ptn > tmp= 3.49999997364305 > ptn /= nsqr > ptn /= tmp > series -= ptn > tmp = 1.3333346851 > ptn /= nsqr > ptn /= tmp > series += ptn > tmp = exp(series) > stirtmp = (n**n)/tmp > stirling = sqrt2pi*stirtmp > print stirling > >def comb(n,r): > return fact(n)/fact(n-r)/fact(r) > >def perm(n,r): > return fact(n)/fact(n-r) > > >2^3 + 13^3 + 33^3 + 43^3 = 49^3 I assumed that there would be some advantage to using the approximation, so I modified the fact2() function to run and time both the fact() function and the fact3() function: def stopwatch(func, p): #I just thought this would be a neat utility function from time import clock #clock() gives better resolution than time() t1 = clock() x = func(p) t2 = clock() return (x, t2 - t1) def fact2(n): a = stopwatch(fact, n) b = stopwatch(fact3, n) print '%e' % a[0] #I changed this so I could play with bigger numbers print '%e' % b[0] d = int((n+.5)*log(n)/log(10) - n*log(exp(1.0))/log(10)+.3991)+1 print "n! for n = ",n print "Actual digits ",len(str(a[0])) print "Formula digits ",d print "Using fact() time was ",a[1],"sec" print "Using fact3(), time was",b[1],"sec" >>> fact2(100) 9.332622e+157 9.332622e+157 n! for n = 100 Actual digits 158 Formula digits 158 Using fact() time was 0.000508724584506 sec Using fact3(), time was 0.00019527648783 sec but if I switch from scientific notation and force b[0] to long(b[0]), then we can see the lack of precision: >>> fact2(30) 265252859812191058636308480000000 265252859812190167497676244910080 n! for n = 30 Actual digits 33 Formula digits 33 Using fact() time was 0.000237181313423 sec Using fact3(), time was 0.00014834308331 sec so there is definitely a performance benefit, if you're doing a lot of large factorial calculations and only need the 14 significant digits. so I wondered if there would be any application for that. I added a function comb3() which is the same as comb() except that it calls fact3() instead of fact(). >>> x = factorial.comb(100, 5) >>> print x 75287520 >>> y = factorial.comb3(100, 5) >>> print int(y) 75287520 and it looks like for some problems, approximation does come close enough. Interesting stuff. Thanks Cino. greg From carroll@tjc.com Mon May 12 13:44:00 2003 From: carroll@tjc.com (Terry Carroll) Date: Mon May 12 12:44:00 2003 Subject: [Tutor] Should I subclass UserDict or dict? In-Reply-To: <5.2.1.1.0.20030511232839.00be8b38@www.thinkware.se> Message-ID: On Sun, 11 May 2003, Magnus Lyck=E5 wrote: > At 12:51 2003-05-11 -0700, Terry Carroll wrote: > >I guess that's my question: how many likely users would I have running= 2.1 > >or earlier. >=20 > Well, we can hardly tell *you* what *your* users are > running. At least not with the information you have > given us so far. Thanks, Magnus. I didn't mean that I thought you had particularized=20 information about what my potential users were actually running. I was=20 just trying to find out what the *typical* user is running (and assuming=20 I'd be drawing from that same pool). Thanks again. --=20 Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From jeff@ccvcorp.com Mon May 12 14:25:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon May 12 13:25:01 2003 Subject: [Tutor] I don't understand example 12.10.2 References: Message-ID: <3EBFD964.8070306@ccvcorp.com> Daniel Nash wrote: > and what is going on here? > > try: > data = StringIO.StringIO() > mimetools.decode(file, data, submsg.getencoding()) > except ValueError: > continue Magnus already told you about StringIO, so I won't repeat that. For the rest of it, this fragment is hard to analyze out of context. It looks like this must be a segment of a loop, because 'continue' is only valid within a loop. What you have here is an exception block. Python tries to run the code within the 'try:' segment of the block, and that's all that runs if there's no errors detected. However, if something in that segment has a problem, it can throw an exception. Exceptions will normally stop your program, unless you catch them, which is what the 'except' segment is supposed to do. In this case, if there is an exception that is of type 'ValueError', then Python will run the specified bit of code in an attempt to let you recover from the error. The recovery, in this case, consists only of 'continue', which immediately returns to the top of your loop and begins the next iteration of the loop, essentially throwing away whatever has been done so far (since it's somehow invalid, presumably because of a bad submsg). In other words, paraphrasing this fragment in English, it would be something like: "Try to decode the submessage into a new StringIO file-like object. If you run into any invalid values, then skip it and start over again with the next submessage." (I am, of course, only guessing that the loop iterates over submessages, since you didn't show the beginning of the loop...) Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Mon May 12 14:43:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon May 12 13:43:03 2003 Subject: [Tutor] factorial References: Message-ID: <3EBFDDBB.8000203@ccvcorp.com> Greg Chapman wrote: >>I wish [...] to be able to edit script and go right >> >> >>back in and run without having to close the dos >>> box and re-enter and >>then from factorial import >>* . should be able to from factorial import * without closing the >>> >>session. >> >> > >you should be able to do: >>>reload(factorial) > > Actually, given the use of 'from X import *', that won't work, which is just one of *many* reasons to avoid using that style of import. If you simply use 'import factorial', and then refer to the functions as factorial.fact(), factorial.fact2(), etc, then you should be able to reload(factorial) and have any changes to the module become effective within the current Python session. For another reason to avoid using 'from X import *', consider the following: >>> print pow.__doc__ pow(x, y[, z]) -> number With two arguments, equivalent to x**y. With three arguments, equivalent to (x**y) % z, but may be more efficient (e.g. for longs). >>> import math >>> print math.pow.__doc__ pow(x,y) Return x**y (x to the power of y). >>> So there's a built-in pow() function and a math.pow() function, with slightly different semantics. Now, given Cino's usage, the factorial module uses 'import *' to bring all of the math module's names into its namespace, and then in an interactive session brings all of the factorial module's names (which now includes all of the math module's names) into the global namespace. So now math.pow() has been brought into factorial which has been brought into global... and now pow() will refer to math.pow() and not the built-in (three argument) pow(). If you later use pow() with three arguments, expecting to get the built-in version, you'll get an error, and you'll probably have no idea why. This is another one of those "enough rope to hang yourself" features, along with exec/eval(), that might *seem* to make things easier at first but are really best left for special circumstances. The power they give you can be useful, but it can also be dangerous, and it's best to avoid them unless you're really sure that it's the best/only solution to the problem. Jeff Shannon Technician/Programmer Credit International From hillcino368@hotmail.com Mon May 12 15:08:02 2003 From: hillcino368@hotmail.com (cino hilliard) Date: Mon May 12 14:08:02 2003 Subject: [Tutor] factorial Message-ID: Thanks for the reply Jeff, I was taking the easyway out and thus doing more work on the import function. The power ^ idea comes from my use of basic, Pari etc. We were able to do it in BCX which the moderator held out for a long time but clever users perfected the code. Then,I guess asking that Fortran start using ^ vs ** would be pretty much uh? Thanks for you advice. 2^3 + 13^3 + 33^3 + 43^3 = 49^3 >From: "Jeff Shannon" >To: tutor@python.org >CC: Greg Chapman , hillcino368@hotmail.com >Subject: Re: [Tutor] factorial >Date: Mon, 12 May 2003 10:45:31 -0700 > >Greg Chapman wrote: > >>>I wish [...] to be able to edit script and go right >>> >>> >>>back in and run without having to close the dos >>> box and re-enter and >>>then from factorial import >>>* . should be able to from factorial import * without closing the >>> >>>session. >>> >>> >> >>you should be able to do: >>>reload(factorial) >> >> > >Actually, given the use of 'from X import *', that won't work, which is >just one of *many* reasons to avoid using that style of import. > >If you simply use 'import factorial', and then refer to the functions as >factorial.fact(), factorial.fact2(), etc, then you should be able to >reload(factorial) and have any changes to the module become effective >within the current Python session. > >For another reason to avoid using 'from X import *', consider the >following: > > >>> print pow.__doc__ >pow(x, y[, z]) -> number > >With two arguments, equivalent to x**y. With three arguments, >equivalent to (x**y) % z, but may be more efficient (e.g. for longs). > >>> import math > >>> print math.pow.__doc__ >pow(x,y) > >Return x**y (x to the power of y). > >>> > >So there's a built-in pow() function and a math.pow() function, with >slightly different semantics. Now, given Cino's usage, the factorial >module uses 'import *' to bring all of the math module's names into its >namespace, and then in an interactive session brings all of the factorial >module's names (which now includes all of the math module's names) into the >global namespace. So now math.pow() has been brought into factorial which >has been brought into global... and now pow() will refer to math.pow() and >not the built-in (three argument) pow(). If you later use pow() with three >arguments, expecting to get the built-in version, you'll get an error, and >you'll probably have no idea why. > >This is another one of those "enough rope to hang yourself" features, along >with exec/eval(), that might *seem* to make things easier at first but are >really best left for special circumstances. The power they give you can be >useful, but it can also be dangerous, and it's best to avoid them unless >you're really sure that it's the best/only solution to the problem. > >Jeff Shannon >Technician/Programmer >Credit International > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From jeff@ccvcorp.com Mon May 12 15:16:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon May 12 14:16:02 2003 Subject: [Tutor] factorial References: Message-ID: <3EBFE564.80709@ccvcorp.com> cino hilliard wrote: > Thanks for the reply Jeff, > > I was taking the easyway out and thus doing more work on the import > function. > > The power ^ idea comes from my use of basic, Pari etc. We were able to > do it in BCX which the > moderator held out for a long time but clever users perfected the > code. Then,I guess asking that > Fortran start using ^ vs ** would be pretty much uh? Thanks for you > advice. I think that it's really C's fault. C started using ^ as a bitwise XOR operator, and Python borrowed that usage from there. Jeff Shannon Technician/Programmer Credit International From hillcino368@hotmail.com Mon May 12 16:31:15 2003 From: hillcino368@hotmail.com (cino hilliard) Date: Mon May 12 15:31:15 2003 Subject: [Tutor] factorial Message-ID: True, C is the culprit on ^. since BCX is a basic to win32 lcc translator, we were able to "emulate" the pow() function in C with ^ to about a 99% success rate in free style coding ie., sin(30)^x vs (sin(30))^x etc. Parantheses did wonders in the emulation to make the translation to the awkward and somewhat unreadable pow() function. It is fairy clearin my esignature below but for compound expressions it gets hairy. I asked the Win32 lcc to see if ^ could be programmed to no response. Since variables, numbers, constants, and functions are kept track of, it seems to me boolean operators could be tested for to produce correct results. Perhaps a pre parser to scan the source and produce the c code BCX does! Actually, with Python's indentation syntax, a step further would be the use of superscripting as in 3 3 3 3 3 2 + 13 + 33 + 43 = 49 For this we could designate a special font for powers and the interpreter (compilerI wish) would have to detect this. Of course Ascii would be out. Then we could have subscripted arrays etc. we would use the ^ symbol but the editor would superscript for us. subscript? maybe ~ Just dreaming 2^3 + 13^3 + 33^3 + 43^3 = 49^3 2**3 + 13**3 + 33**3 + 43**3 = 49**3 pow(2,3) +pow(13,3) +pow(33,3) +pow(43,3) = pow(49,3) + >From: "Jeff Shannon" >To: tutor@python.org >CC: cino hilliard >Subject: Re: [Tutor] factorial >Date: Mon, 12 May 2003 11:18:12 -0700 > >cino hilliard wrote: > >>Thanks for the reply Jeff, >> >>I was taking the easyway out and thus doing more work on the import >>function. >> >>The power ^ idea comes from my use of basic, Pari etc. We were able to do >>it in BCX which the >>moderator held out for a long time but clever users perfected the code. >>Then,I guess asking that >>Fortran start using ^ vs ** would be pretty much uh? Thanks for you >>advice. > > >I think that it's really C's fault. C started using ^ as a bitwise XOR >operator, and Python borrowed that usage from there. > >Jeff Shannon >Technician/Programmer >Credit International > > _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From magnus@thinkware.se Mon May 12 18:34:00 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 12 17:34:00 2003 Subject: [Tutor] Should I subclass UserDict or dict? In-Reply-To: References: <5.2.1.1.0.20030511232839.00be8b38@www.thinkware.se> Message-ID: <5.2.1.1.0.20030512231019.02955850@www.thinkware.se> At 09:43 2003-05-12 -0700, Terry Carroll wrote: >Thanks, Magnus. I didn't mean that I thought you had particularized >information about what my potential users were actually running. I was >just trying to find out what the *typical* user is running (and assuming >I'd be drawing from that same pool). Sure, but the thing is that I don't think there is such a thing as a typical user in real life. I never met one at least. They are all different. :) I can only tell you that Python 2.2 is well established, and has been in use for a long time. It's after all going to be replaced by 2.3 soon! What you are asking is a bit like "what car should I buy"? How can we tell you that without knowing a whole lot about you? If you don't really know where and how you are going to drive yet, it's not really possible to get a good answer. If you refer to a typical computer user, he hasn't heard of Python, and he's never had it installed on a machine he's used directly. (He's used internet services that run on Python, but that's not the point.) He'll be using the Python version you install on his machine, or he won't use it at all... The typical user who actually knows what python is, is a programmer (whether he's a professional one or not) and he's likely to use 2.2 already, and probably not worried about upgrading if he isn't. Anyway, I wouldn't worry about this. At least not in this case. One of the nice things with Python is that it's so easy to rewrite code. You can easily go for either UserDict or dict and change your mind later. Right? Piece of cake! As time goes, the newer versions will replace the old, and I get a feeling you don't even have a particular set of users yet, so avoiding useful features to make life easier for some hypothetical user that might never materialize seems like a bad idea. You should also realize that if you plan to support version 2.1 you really need to test your code on version 2.1. Are you prepared to do the extra work needed for that, or do you plan to restrict your code so that you don't use 2.2 features, and still not be sure that it works with 2.1? I'd just try to get a good working program using the version I prefer to use as my development environment (which would be 2.2.2 or 2.3b1 today) and worry about hypothetical users later. I certainly promote writing good code, which is intended to work by design, not just by accident. That includes things like using the features of python that minimize the need to code stuff in a platform dependent way, and to avoid things that "happen to work" but could potentially break, such as assuming that files are closed as soon as the file variable goes out of scope etc. But don't avoid good features to stay compatible with an old version unless there is a real need for that. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From alan.gauld@blueyonder.co.uk Mon May 12 19:48:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Mon May 12 18:48:01 2003 Subject: [Tutor] grouping modules? References: <3EBBB916.8000807@gmx.net> Message-ID: <005c01c318d8$8f5fab00$6401a8c0@xp> > I am wondering if there is some functionality to group modules in > Python, similar to Java packages. Or is there another way to organize > code into logical units (apart from modules)? Python does have a package mechanism and indeed some of the library modules use it, for example os.path is a "module within a module", in other words they combine as a package. In Python the mechanism is based on file lovcation and some other conventions. Look at section 6.4 of the official tutorial in the online docs to see how it all works. HTH, Alan G. From shalehperry@attbi.com Mon May 12 21:38:00 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon May 12 20:38:00 2003 Subject: [Tutor] Re:Permissions and other hairpulls In-Reply-To: <3EBF3025.3050807@netzero.net> References: <3EBF0B6E.8050902@netzero.net> <200305112210.00768.shalehperry@attbi.com> <3EBF3025.3050807@netzero.net> Message-ID: <200305121736.32222.shalehperry@attbi.com> On Sunday 11 May 2003 22:24, Kirk Bailey wrote: > I only wish the docs had been a tad more explicit. > But that was the last hairpull I can find, the thing appears to > be rather reliable now. > > How are you at sh/bourne shell scripting? I need totake the now obsolete > installer and turn it into a more potent and complex one for the > now more complex tinylist. Cranking out the first one strained my talents > to the limits, and this one will be larger and more complex. > (unfortunately) I make my living writing shell scripts and doing other sys admin tasks (-: From pan@uchicago.edu Mon May 12 21:50:02 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Mon May 12 20:50:02 2003 Subject: [Tutor] A bug in os.popen() in PythonWin 2.2.2 ??? In-Reply-To: <20030512160005.28218.5794.Mailman@mail.python.org> References: <20030512160005.28218.5794.Mailman@mail.python.org> Message-ID: <1052786954.3ec0410af2c12@webmail.uchicago.edu> Hi all, I wrote a program to run a module codeml.exe (part of PAML package). The idea is to use codeml for a batch analysis following the steps below: 1. Loop thru a data folder and load data files once at a time; 1.meg 2.meg 3.meg ... 2. copy it to a 'data.txt' file which is used by codeml.exe; 3. call codeml.exe and have it do the analysis (it will read the 'data.txt' and output to 'tempout.txt' 4. open 'tempout.txt' and parse it to retrieve some info 5. Do so for all the files (1.meg, 2.meg ...) 6. Save all output to 'output.txt' I use os.popen('[proper path here]codeml.exe') to call codeml. What the codeml.exe does is not the issue here. The strange thing is, when my code was execuded on one computer [A], it works nicely -- the 'output.txt' file recorded different info correcponding to different data files (1.meg, 2.meg ...). But when it runs on a different computer [B], the very same code output an 'output.txt' file which has a list of report with the values ALL the same as the first record. Example of output.txt: On compter [A]: ---------------------- file data ---------------------- 1.meg 0.234 2.meg 0.108 3.meg 0.265 4.meg ... ..... ...... 100.meg .... --------------------- On computer [B]: ---------------------- file data -------- ------------ 1.meg 0.234 2.meg 0.234 3.meg 0.234 4.meg 0.234 ..... ..... 100.meg 0.234 --------------------- ^---- all = that of the first record I have no idea how this could have happened. The only thing I found to be different between [A] and [B] is: [A] PythonWin 2.2.1 [B] PythonWin 2.2.2 ==> the newer the worse ??? Can anyone tell me what's wrong and how to solve it ??? Thx., pan From micforster@yahoo.com Tue May 13 00:44:01 2003 From: micforster@yahoo.com (Mic Forster) Date: Mon May 12 23:44:01 2003 Subject: [Tutor] factorialProcess Message-ID: <20030513034332.49740.qmail@web13403.mail.yahoo.com> Thanks to all those who offered assistance on this matter. I have copied below my thought processes in reaching a satisfactory conclusion. As you'll all be able to see it is not the most efficient method but it does do the job. Also, I can't figure out how to print the last computation only. For example, fac(10) prints a list of values each corresponding to its factorial. All that is required is the final value. Does anyone know how to do this? Cheers. # First attempt and it’s a shocker (but you’ve gotta # start somewhere;) >>> i = 10 >>> def fac(i): for i in range(1,10): i = i*(range(1,10)) print i >>> fac(i) [1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> # Here is another attempt that produces a closer but not correct output >>> def fac(x): b, count = 1, 0 while count < x: print b, b = b*(b+1) count = count + 1 >>> fac(3) # this code will work 1 2 6 >>> fac(10) # but will not work here 1 2 6 42 1806 3263442 10650056950806 113423713055421844361000442 12864938683278671740537145998360961546653259485195806 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185442 # And here’s the third attempt with the correct output. >>> def fac(x): b, count = 1, 1 while count < x: print b, b = b*(count+1) count = count + 1 >>> fac(3) 1 2 >>> fac(10) 1 2 6 24 120 720 5040 40320 362880 >>> __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From dbroadwell@mindspring.com Tue May 13 00:46:52 2003 From: dbroadwell@mindspring.com (David Broadwell) Date: Mon May 12 23:46:52 2003 Subject: [Tutor] A bug in os.popen() in PythonWin 2.2.2 ??? In-Reply-To: <1052786954.3ec0410af2c12@webmail.uchicago.edu> Message-ID: [Tutor worte]On Behalf Of pan@uchicago.edu > I have no idea how this could have happened. The only thing > I found to be different between [A] and [B] is: > [A] PythonWin 2.2.1 > [B] PythonWin 2.2.2 ==> the newer the worse ??? > Can anyone tell me what's wrong and how to solve it ??? No. I'll make no pretence of trying to troubleshoot with what you have said. However, many strange problems can be caused by version mis-matches. But here are a few ideas. Are both systems on the same MOS / install type / patch level / hot fixes? Take a look at what is NEW in 2.2.2 from 2.2.1, did a behavior that your code relies on change? However, you can run a test. Upgrade computer[A] to 2.2.2 ... OR Vice that if it's a mission critical app; Downgrade computer[B] to 2.2.1 Test and bring it back to 2.2.2 ... If it reappears, then you might have a bug to take to the developers list. Be ready to help. (Sorry, I'm a support geek for a living ... document and test and document.) -- David Broadwell From dbroadwell@mindspring.com Tue May 13 00:54:02 2003 From: dbroadwell@mindspring.com (David Broadwell) Date: Mon May 12 23:54:02 2003 Subject: [Tutor] factorialProcess In-Reply-To: <20030513034332.49740.qmail@web13403.mail.yahoo.com> Message-ID: Mic Forster Wrote; > All that is required is the final value. Does anyone know how to do this? > # And heres the third attempt with the correct output. Warning untested code; Origin: >>> def fac(x): b, count = 1, 1 while count < x: print b, b = b*(count+1) count = count + 1 Ah, you printing on every iteration. B will exist outside the scope of your while ... so let's move that print line. Correction; >>> def fac(x): ''' Factorials and INT, prints and returns it ''' b, count = 1, 1 while count < x: b = b*(count+1) count = count + 1 print b return b -- David Broadwell From rmangaliag@slu.edu.ph Tue May 13 02:51:34 2003 From: rmangaliag@slu.edu.ph (ali) Date: Tue May 13 01:51:34 2003 Subject: [Tutor] a software that generates python code Message-ID: <003601c31915$76fcea40$e019a8c0@slu.edu.ph> hi... is there an available software that generates python code from a uml(or anything similar to uml)? thanks... From hemanexp@yahoo.com Tue May 13 02:58:25 2003 From: hemanexp@yahoo.com (Python-lover) Date: Tue May 13 01:58:25 2003 Subject: [Tutor] Getting all items above/below of a selected item.................... Message-ID: <20030513055723.52936.qmail@web41707.mail.yahoo.com> hi, My program has got a stack up of rectangles. Inside each rectangle there is a circle. All rectanlges assigned with a tag called "RECT" and all circles has "Cir" tag. My application needs to provide an option for resizing the rectangles. While resizing the rectagnle, say y2, all rectangles below the edited one should move down respectively. Not only rectangles but also the circles placed in the rectangles. How can i get all rectangles below/above the selected one? I tried with find_above()/find_below(). But they return only one item that is above/below an item. Not all. In the case of find_all(), it returns a tuple all items Which i dont want. In the same manner how i can get all circles below/above a selected rectangle? If posible let me explain with an example. Thanx. __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From magnus@thinkware.se Tue May 13 05:09:20 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 13 04:09:20 2003 Subject: [Tutor] Getting all items above/below of a selected item.................... In-Reply-To: <20030513055723.52936.qmail@web41707.mail.yahoo.com> Message-ID: <5.2.1.1.0.20030513094015.0297dc00@www.thinkware.se> At 22:57 2003-05-12 -0700, Python-lover wrote: > How can i get all rectangles below/above the >selected one? I tried with find_above()/find_below(). >But they return only one item that is above/below an >item. Not all. In the case of find_all(), it returns a >tuple all items Which i dont want. I don't have a clue what you are talking about. I think you have to fill us in on the context. What is find_above and find_below? Are you talking about some GUI toolkit or what? Without really knowing what we are at, it seems that if find_below() finds the next item below, you could move that rectangle, and then use find_below() on *that* to find the next and move that and so on. Something along the lines of this pseudocodish thing... def moveAllBelow(this, deltaX, deltaY): next = this.find_below() if next: next.moveRelative(deltaX, deltaY) moveAllBelow(next, deltaX, deltaY) As I said, I don't really have a clue about what you are talking about, so I'm sure this won't run as it is, but the principle might work. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Tue May 13 06:40:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 13 05:40:02 2003 Subject: [Tutor] a software that generates python code In-Reply-To: <003601c31915$76fcea40$e019a8c0@slu.edu.ph> Message-ID: <5.2.1.1.0.20030513101306.00bee038@www.thinkware.se> At 14:03 2003-05-13 +0800, ali wrote: >is there an available software that generates python code from a uml(or >anything similar to uml)? Sure, but don't expect that to be easier than writing code in Python. ObjectDomain R3 http://www.objectdomain.com/ claims that it does this. It's $495 for the standard edition. You could have a look at http://pyut.sourceforge.net/ , but I don't know what state it's in. ArgoUML http://argouml.tigris.org/ might also be able to do this. It might be a better option to generate UML from code instead. Have a look at PyReverse for that. http://www.logilab.org/pyreverse/ -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Tue May 13 09:08:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 13 08:08:01 2003 Subject: [Tutor] Getting all items above/below of a selected item.................... In-Reply-To: <20030513113329.7999.qmail@web41703.mail.yahoo.com> References: <5.2.1.1.0.20030513094015.0297dc00@www.thinkware.se> Message-ID: <5.2.1.1.0.20030513140330.00b4d430@www.thinkware.se> Hi! I moved this back to the mailing list. BTW, most of us use our real names on this mailing list. That makes communication a bit more natural I think... At 04:33 2003-05-13 -0700, Python-lover wrote: >Hello, > I am using python and Tkinter (for GUI) in my >application. And using a canvas? I think it might be a good idea to keep all your geometrical objects in a normal python list (or possibly dictionary) and loop through that to check for y coordinates or what have you. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From Chris.Dewitt@motorola.com Tue May 13 15:12:02 2003 From: Chris.Dewitt@motorola.com (Dewitt Chris-GCPD001) Date: Tue May 13 14:12:02 2003 Subject: [Tutor] askopenfilename puzzle Message-ID: I am taking over support on a python script written by a former college. The script uses askopenfilename to select a file and everything works fine but there's one thing that puzzles me. After the first time you navigate to a file it remembers where you were, even after you've exited the program, shut down and rebooted the computer. Someplace it's remembering where you last worked and I can't figure out how. Any clues? Thanks, Chris DeWitt From dyoo@acoma.Stanford.EDU Tue May 13 15:12:11 2003 From: dyoo@acoma.Stanford.EDU (Danny Yoo) Date: Tue May 13 14:12:11 2003 Subject: [Tutor] ANN: BayPIGgies meeting Tomorrow! Message-ID: Hi everyone, BayPIGgies: Silicon Valley - San Francisco Bay Area Python Users's Group When: May 14 @ 7:30pm Where: Carnegie Institute of Washington at Stanford University, Palo Alto, CA Agenda: Compedium of talks from PyCon 2003 Speaker: Wesley Chun We will give a high-level overview of some of the talks which were given at the PyCon 2003 Python Community Conference which happened at the end of March in Washington, DC. For more information and directions, see: http://www.baypiggies.net/ Hope to see you there! From beyondthezero@earthlink.net Tue May 13 20:54:02 2003 From: beyondthezero@earthlink.net (Peter Jakubowicz) Date: Tue May 13 19:54:02 2003 Subject: [Tutor] scope problem? Message-ID: <5.2.1.1.1.20030513165017.00b3a9d8@earthlink.net> I'm probably doing something really dumb here, but I just wanted to test this bit of code to generate a list of the prime numbers from 2 to n; but I get an error message saying I haven't defined prime. But haven't I defined it in line 2? def sieve(n): prime = [2] for i in range(2, n + 1): for j in range(2, n + 1): if i % j == 0: pass else: prime.append(i) print prime From dbroadwell@mindspring.com Tue May 13 21:03:01 2003 From: dbroadwell@mindspring.com (David Broadwell) Date: Tue May 13 20:03:01 2003 Subject: [Tutor] scope problem? In-Reply-To: <5.2.1.1.1.20030513165017.00b3a9d8@earthlink.net> Message-ID: Peter Jakubowicz wrote: > But haven't I defined it in line 2? Yes inside sieve. But outside sieve prime is undefined unless you assign it or return it. THIS: prime = [] def sieve(n): prime = [2] for i in range(2, n + 1): for j in range(2, n + 1): if i % j == 0: pass else: prime.append(i) print prime OR THIS: def sieve(n): prime = [2] for i in range(2, n + 1): for j in range(2, n + 1): if i % j == 0: pass else: prime.append(i) return prime prime = sieve(15) print prime From krier115@student.liu.se Tue May 13 21:04:03 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Tue May 13 20:04:03 2003 Subject: [Tutor] scope problem? In-Reply-To: <5.2.1.1.1.20030513165017.00b3a9d8@earthlink.net> References: <5.2.1.1.1.20030513165017.00b3a9d8@earthlink.net> Message-ID: <20030514000326.GA17292@n14.ryd.student.liu.se> On Tue, May 13, 2003 at 04:53:25PM -0700, Peter Jakubowicz wrote: > I'm probably doing something really dumb here, but I just wanted to test > this bit of code to generate a list of the prime numbers from 2 to n; but I > get an error message saying I haven't defined prime. But haven't I defined > it in line 2? > > def sieve(n): > prime = [2] > for i in range(2, n + 1): > for j in range(2, n + 1): > if i % j == 0: > pass > else: > prime.append(i) > print prime prime is only defined in the local scope of the function sieve. Outside this function, on the last line you posted, you try to print prime, but this print statement is totally outside the function and can't see the only-locally-defined prime. My guess is that you want to move the 'print prime' statement into the function? Or maybe return the prime-list and print it after calling the function, which I think is prettier. Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From krier115@student.liu.se Tue May 13 21:21:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Tue May 13 20:21:02 2003 Subject: [Tutor] scope problem? In-Reply-To: References: <5.2.1.1.1.20030513165017.00b3a9d8@earthlink.net> Message-ID: <20030514002024.GA17737@n14.ryd.student.liu.se> On Tue, May 13, 2003 at 08:02:29PM -0400, David Broadwell wrote: > Peter Jakubowicz wrote: > > But haven't I defined it in line 2? > Yes inside sieve. But outside sieve prime is undefined unless you assign it > or return it. > > THIS: > prime = [] > def sieve(n): > prime = [2] > for i in range(2, n + 1): > for j in range(2, n + 1): > if i % j == 0: > pass > else: > prime.append(i) > print prime Actually, this won't work either. The prime that is used inside the function is a new, local, prime. You need to insert the line global prime first in the function for it to use the global one. Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From beyondthezero@earthlink.net Tue May 13 22:08:02 2003 From: beyondthezero@earthlink.net (Peter Jakubowicz) Date: Tue May 13 21:08:02 2003 Subject: [Tutor] scope problem? In-Reply-To: <20030514002024.GA17737@n14.ryd.student.liu.se> References: <5.2.1.1.1.20030513165017.00b3a9d8@earthlink.net> Message-ID: <5.2.1.1.1.20030513180018.00b26ea0@earthlink.net> OK, thanks, but now, testing it, I realize it doesn't do what I wanted it to do. I want it to work like the sieve of Eratosthenes: start with a list populated with the primes from 2 to n + 1, then leave 2 but take out all the multiples of 2, then leave 3 but take out all the multiples of 3, and so on. So if the user enters n, how would I populate the list. This doesn't work: def primeSieve(n): global prime[] = range(n) Why doesn't this work? Thanks. At 02:20 AM 5/14/2003 +0200, you wrote: >On Tue, May 13, 2003 at 08:02:29PM -0400, David Broadwell wrote: > > Peter Jakubowicz wrote: > > > But haven't I defined it in line 2? > > Yes inside sieve. But outside sieve prime is undefined unless you assign it > > or return it. > > > > THIS: > > prime = [] > > def sieve(n): > > prime = [2] > > for i in range(2, n + 1): > > for j in range(2, n + 1): > > if i % j == 0: > > pass > > else: > > prime.append(i) > > print prime > >Actually, this won't work either. The prime that is used inside the >function is a new, local, prime. You need to insert the line > >global prime > >first in the function for it to use the global one. > >Regards, >Kristoffer > >-- >Kristoffer Erlandsson >E-mail: krier115@student.liu.se >ICQ#: 378225 > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From beyondthezero@earthlink.net Tue May 13 22:10:02 2003 From: beyondthezero@earthlink.net (Peter Jakubowicz) Date: Tue May 13 21:10:02 2003 Subject: [Tutor] scope problem? In-Reply-To: <5.2.1.1.1.20030513180018.00b26ea0@earthlink.net> References: <20030514002024.GA17737@n14.ryd.student.liu.se> <5.2.1.1.1.20030513165017.00b3a9d8@earthlink.net> Message-ID: <5.2.1.1.1.20030513180841.00b2b3b8@earthlink.net> Sorry, I meant a list populated with all the integers from 2 to n + 1, not just the primes. At 06:06 PM 5/13/2003 -0700, you wrote: >OK, thanks, but now, testing it, I realize it doesn't do what I wanted it >to do. I want it to work like the sieve of Eratosthenes: start with a list >populated with the primes from 2 to n + 1, then leave 2 but take out all >the multiples of 2, then leave 3 but take out all the multiples of 3, and >so on. So if the user enters n, how would I populate the list. > >This doesn't work: > >def primeSieve(n): > global prime[] = range(n) > >Why doesn't this work? Thanks. > >At 02:20 AM 5/14/2003 +0200, you wrote: >>On Tue, May 13, 2003 at 08:02:29PM -0400, David Broadwell wrote: >> > Peter Jakubowicz wrote: >> > > But haven't I defined it in line 2? >> > Yes inside sieve. But outside sieve prime is undefined unless you >> assign it >> > or return it. >> > >> > THIS: >> > prime = [] >> > def sieve(n): >> > prime = [2] >> > for i in range(2, n + 1): >> > for j in range(2, n + 1): >> > if i % j == 0: >> > pass >> > else: >> > prime.append(i) >> > print prime >> >>Actually, this won't work either. The prime that is used inside the >>function is a new, local, prime. You need to insert the line >> >>global prime >> >>first in the function for it to use the global one. >> >>Regards, >>Kristoffer >> >>-- >>Kristoffer Erlandsson >>E-mail: krier115@student.liu.se >>ICQ#: 378225 >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dbroadwell@mindspring.com Wed May 14 01:19:01 2003 From: dbroadwell@mindspring.com (David Broadwell) Date: Wed May 14 00:19:01 2003 Subject: [Tutor] dictionary-ness ... Message-ID: Well, I'm jumping in tot he dictionary subject feet first. Anyone know of any good tutorials on them? (the plan) As a 'little' project, I'm planning on creating a tool to index all of the words used in files on my HDD. The best schema I have though of so far is dictionary storage as a prelim stage to database ... Wacking down to the 'words' in the files is trivial and with os.path.walk's help, just a few minutes in the interpreter and I can grab the wordlist of the files. Now for the dictionary design, I was planning on as a stage one, the dictionary being keyed on the first two letters of the word. No biggie ... The real question is, let's say I have a ['word', 'wording'] in the list to add to the dictionary, if I'm keying on 'wo' for both of them, I believe I'm going to run into key name clashes. So I went to the next level with the idea, keep the same key schema, but use lists AS my value. Which would look like; dict = {['wo',['word','wording]], ...} Pointers? -- David Broadwell From viswap@Math.net Wed May 14 01:24:01 2003 From: viswap@Math.net (Viswanath P) Date: Wed May 14 00:24:01 2003 Subject: [Tutor] import graphics(gnuplot) for window$. Message-ID: <20030514042314.893523F22@sitemail.everyone.net> Dear all, I have python for window$ installed and gnuplot also. Is it possible to use gnuplot in windows for plotting data online. Thank you, with regards, Viswanath P. _____________________________________________________________ Get your free web-based e-mail account from http://www.Math.net Your online tourguide of Mathematics, with books, links, news, message boards, and much more! _____________________________________________________________ Select your own custom email address for FREE! Get you@yourchoice.com w/No Ads, 6MB, POP & more! http://www.everyone.net/selectmail?campaign=tag From magnus@thinkware.se Wed May 14 08:15:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 14 07:15:02 2003 Subject: [Tutor] scope problem? In-Reply-To: <5.2.1.1.1.20030513180018.00b26ea0@earthlink.net> References: <20030514002024.GA17737@n14.ryd.student.liu.se> <5.2.1.1.1.20030513165017.00b3a9d8@earthlink.net> Message-ID: <5.2.1.1.0.20030514111852.00be6f90@www.thinkware.se> At 18:06 2003-05-13 -0700, Peter Jakubowicz wrote: >def primeSieve(n): > global prime[] = range(n) > >Why doesn't this work? Thanks. What did you think "prime[] = ..." should mean? There is no such thing as using empty square brackets next to a name in Python. (Not that I can think if. At least not here.) This syntax is used for declarations in for instance C, but Python has no declarations. Only the objects have types, not the names. In python, [] means "create an empty list object", and that is placed in the right hand side of a "=", or inside a another object or passed as a parameter etc, but it's not written directly after a name. To understand how names and objects work in Python, read http://effbot.org/zone/python-objects.htm What you seem to have intended should be written as: prime = [] def primeSieve(n): global prime prime = range(n) ... But this is not very good Python code. If you desperately need to use a global "prime", you don't have to use the global statement, since prime is mutable. In other words, there is no reason to rebind the name to a new object, which is what you do above. You can do this instead: prime = [] def primeSieve(n): prime[:] = range(n) While "prime = range(n)" rebinds the name "prime" to a new list object, "prime[x:y] = range(n)" will replace the list elements x to y-1 with the stuff on the right hand side of the equal sign. If you skip x or y, it will use the respective end points of the list. Try it at the interactive prompt. Use "id(prime)" to see when you change "prime" to refer to a different object, and when you don't. But this is still a bad idea. There is no reason to use a global variable at all! Create the list in the local scope and return it to the calling scope with the return statement instead: def primeSieve(n): prime = range(n) ... return prime ... p5 = primeSieve(5) There are several reasons why this is much better that a global scope. First of all, all information should be restricted on a "need to know" basis in a program. This will reduce the number of bugs as the program grows. If you use a lot of globals, you are more likely to make one part of the program mess up another part of the program by mistake. These kinds of bugs can pop up in a very surprising way... Secondly, if your list of primes is stored in a global variable, calling the function a second time will overwrite the current list with new values. Thirdly, by using a function call like above, it's clear that p5 appeared as a result of calling primeSieve. If primeSieve just changes a global variable, it won't be clear in the place where primeSieve is called and prime is used that they are connected. Just wait until your programs become a few hundred lines, and you will appreciate what I'm saying. Let me make a tiny example. Instead of primes, we just have a little function that places a range in a global variable 'l'. >>> l = [] >>> def a(n): ... l[:] = range(n) ... Then we have another function that presents a value in some way. >>> def b(n): ... print n ... Finally, we use these functions to type a sequence of integers. >>> a(5) >>> for i in l: ... b(i) ... 0 1 2 3 4 So far so good. But this isn't really what we want. We really want to write this: 0 0:1 0:1:2 0:1:2:3 0:1:2:3:4 Don't ask me why we want this, just see what happens when we do the "logical thing" to implement it. We obviously rewrite function b to take advantage of function a, which can make a range, just like we want: >>> def b(n): ... a(n+1) ... print ":".join(map(str,l)) ... That odd code after print will return a string with the items in "l" separated by ":", just like we want. >>> a(5) >>> for i in l: ... b(i) ... 0 Only "0"? Dear me! It seems the first call to b (which is b(0)) replace l with [0], and that means that the loop won't finish. It's really fairly simple to fix this though, just loop over a copy of l instead, like this: >>> a(5) >>> for i in l[:]: ... b(i) ... 0 0:1 0:1:2 0:1:2:3 0:1:2:3:4 But the thing is that if you work with global variables, these little stupid problems will pop up all the time, and often it's much less obvious than it was in this case. The big problem is that the fault usually appears in a different place than where you just changed your code. Maybe you won't notice for days if this is a reasonably large program, unless you run extensive automatic tests. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Wed May 14 08:37:17 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 14 07:37:17 2003 Subject: [Tutor] dictionary-ness ... In-Reply-To: Message-ID: <5.2.1.1.0.20030514132154.00bdeb10@www.thinkware.se> At 00:17 2003-05-14 -0400, David Broadwell wrote: >As a 'little' project, I'm planning on creating a tool to index all of the >words used in files on my HDD. >The best schema I have though of so far is dictionary storage as a prelim >stage to database ... Ok. As long as the keys are strings, you can replace the dictionary with a shelve. See http://www.python.org/doc/current/lib/module-shelve.html Another option would be to use an SQL database, maybe SQLite, but that means that you have to learn a little SQL as well. You can use a wrapper like SQLObject to aviod writing a lot of SQL, but you probably need some SQL knowledge anyway. It's a much more powerful database though. It would mean that you get a lot of the query functions for free. >Wacking down to the 'words' in the files is trivial and with os.path.walk's >help, just a few minutes in the interpreter and I can grab the wordlist of >the files. So what is the purpose? Do you want to be able to enter a word and see in what files it occurs, or what? >Now for the dictionary design, I was planning on as a stage one, the >dictionary being keyed on the first two letters of the word. No biggie ... >The real question is, let's say I have a ['word', 'wording'] in the list to >add to the dictionary, if I'm keying on 'wo' for both of them, I believe I'm >going to run into key name clashes. I don't understand the purpose of this. Why key on parts of a word? Why two letters? >So I went to the next level with the idea, keep the same key schema, but use >lists AS my value. Which would look like; >dict = {['wo',['word','wording]], ...} No, it would not look like that. It might look like... dict = {'wo': ['word', 'wording'], ... } ...but I can't see the point in storing anything like that. What is the purpose of this dictionary? There are several python based search engines already. I think a list was posted recently on this mailing list. Perhaps you would learn something from studying some of them. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From moody834@mac.com Wed May 14 13:38:20 2003 From: moody834@mac.com (M) Date: Wed May 14 12:38:20 2003 Subject: [Tutor] Tutor list introduction, goals, ideals... Message-ID: <491ECB68-862A-11D7-919E-003065E73510@mac.com> Hello everyone: At 36 years old, I am just about ready to start learning Python, which will be my first programming language (although - to render a better picture of where my educational level is - I've read _The Pragmatic Programmer_ and have a basic, though untested, understanding of OOP). My platform of choice is OS X (currently I am running 10.2.6 [with Apple's free Dev Tools installed] on a 500MHz DP G4 with 512MB RAM), on which additionally I run OroborOSX and use fink. I've also a computer running SuSE 8.x and Wintendo (read Win2k Pro, Srvc. pk. 3), neither of which has seen any tweaking or customization. My desire to learn Python may be split pretty evenly between fun and community. By the latter, I mean to say that I want to learn Python in part because I want to get involved with a community of souls with whom I feel I share a great deal (even as a newbie, such as I am and have been for some time). I support GNU and the GPL to the degree that I understand the phrase, "Free as in freedom". However, fwiw, I am not the sort of person who carelessly engages in conversations about politics/religion. My goal is, ultimately, to help create beneficial software, using Python (and/or some other programming language), that I may freely distribute to the World. A secondary but no less valuable goal for me is to have much fun along the way. I think /that/ must be a pre-requisite for using Python! :-) Getting involved in a current project is perfectly acceptable to me. Which brings me to this question: If you were just starting out learning your first programming language (or, perhaps, /when/ you first started out, etc.), what might you do to get involved or, at least, self-educate with a goal toward getting involved? That is, what might your initial programming attempt be aimed at accomplishing? Should a person just pick any old thing (e.g., a simple text editor) to work at, or is there something better to start with? Thank you to anyone/everyone who answers this. Please feel free to give me your advice on whatever you think might be useful to me (or anyone in my position). Sincerely, Moody PS: IDLE is very nice. PPS: I am just about ready to go back to school to work on getting a degree in journalism. This is relevant because in the end I think I'd really like to report on tech topics. From rob@jam.rr.com Wed May 14 13:56:02 2003 From: rob@jam.rr.com (Rob Andrews) Date: Wed May 14 12:56:02 2003 Subject: [Tutor] Tutor list introduction, goals, ideals... In-Reply-To: <491ECB68-862A-11D7-919E-003065E73510@mac.com> References: <491ECB68-862A-11D7-919E-003065E73510@mac.com> Message-ID: <3EC2754B.7060604@jam.rr.com> Welcome to the ever-friendly Tutor list. You've already made a good start by coming here at all. There are a host of good tutorials around, and searching for "python tutorial" at google.com demonstrates. If you're interested in working on free software, particularly in Python, but don't have specific ideas as to just what you want to write yet, that's fine. Just write some programs for fun, and/or go to uselesspython.com and hack on some of the other newbie/free programs there. (Some are great and provide much from which to learn, and some are awful, providing a great chance to learn the art of improving that which already exists and sending it back to the site and the original author.) As you get stuck or have questions, feel free to post them to this list, and we will usually go a bit beyond the call of duty to help. -Rob Andrews Newbie For Life > Which brings me to this question: If you were just starting out learning > your first programming language (or, perhaps, /when/ you first started > out, etc.), what might you do to get involved or, at least, self-educate > with a goal toward getting involved? That is, what might your initial > programming attempt be aimed at accomplishing? Should a person just pick > any old thing (e.g., a simple text editor) to work at, or is there > something better to start with? From dbroadwell@mindspring.com Wed May 14 14:50:22 2003 From: dbroadwell@mindspring.com (David Broadwell) Date: Wed May 14 13:50:22 2003 Subject: [Tutor] dictionary-ness ... In-Reply-To: <5.2.1.1.0.20030514132154.00bdeb10@www.thinkware.se> Message-ID: > Ok. As long as the keys are strings, you can replace the dictionary with > a shelve. See http://www.python.org/doc/current/lib/module-shelve.html I'll look into that ... No I'm not after persistence yet, but I'll keep it in mind. > Another option would be to use an SQL database, maybe SQLite, In time, I don't think I'm pythonly ready for that yet. >> Wacking down to the 'words' in the files is trivial and with >> os.path.walk's help, just a few minutes in the interpreter and >> I can grab the wordlist of the files. > So what is the purpose? Do you want to be able to enter a word and > see in what files it occurs, or what? Purpose: Pointless bit-tweedling to gain experience. And the fact that a word list on that order would be enough data for a reasonable load test to a database. > I don't understand the purpose of this. > Why key on parts of a word? It was something I felt I could implement. > Why two letters? I thought having 26 records too few and 17576 too many. So I settled on 676 at max. > No, it would not look like that. It might look like... > dict = {'wo': ['word', 'wording'], ... } Sorry, right. I was typing on the fly. > ...but I can't see the point in storing anything like that. > What is the purpose of this dictionary? A faster way of seeing how many 'w' words I have than a flat list. Also happens to be something (size wise) that I'm comfortable iterating through, the though of the words from over 20000 files in a single list seemed, unwieldy. No, I don't really need to bind it all in a dictionary, but I took this project on with dictionary in mind to combat my learning curve. And I think that it has some practical value, at least to my curiosity as to exactly what is written in my MP3 data structure. > There are several python based search engines already. I think > a list was posted recently on this mailing list. Perhaps you > would learn something from studying some of them. Hey that too. Though it was before I was a subscriber, so I'll have to do a bit of hunting. -- David Broadwell From mike@daboyz.org Wed May 14 18:49:05 2003 From: mike@daboyz.org (Michael Barrett) Date: Wed May 14 17:49:05 2003 Subject: [Tutor] Counting & Sorting Instances In File Message-ID: <20030514214709.GC76924@daboyz.org> Ok, so, I'm not sure why this is giving me such a hard time right now (maybe it's lack of sleep, don't you love those weeks?) but pretty much I'm looking for a good way to go through a logfile of outgoing mail attempts and count the # of mails going to each mail address- and then sort that list so that I can display the top 25. Anyone got any suggestions? This is making me feel like a total idjit. Thanks for your help. -- ________________________________________________________________________ Mike Barrett | "I used to read, now I go to raves." mike@daboyz.org | -- Random MUNI Rider, speaking www.daboyz.org | to my friend Allison. ------------------------+----------------------------------------------- From mike@daboyz.org Wed May 14 19:14:01 2003 From: mike@daboyz.org (Michael Barrett) Date: Wed May 14 18:14:01 2003 Subject: [Tutor] Counting & Sorting Instances In File In-Reply-To: <20030514214709.GC76924@daboyz.org> References: <20030514214709.GC76924@daboyz.org> Message-ID: <20030514221152.GF76924@daboyz.org> I realized (since I've gotten one reply already that pointed it out) that I'm not too clear on just which part of this I need help with. I know how to open the file, grab the data, and then parse it out. I also thought about storing the counts as a dictionary, ie using the addresses as the keys with the 'counts' being the values. The hard (?) part is the sorting. Thats the part I need help with, so assume a dictionary of 'Email': count values. If you can think of a better way of storing the data in memory for my sort, that'd be appreciated as well. Thanks again. On Wed, May 14, 2003 at 02:47:09PM -0700, Michael Barrett wrote: > Ok, so, I'm not sure why this is giving me such a hard time right now (maybe it's lack of sleep, don't you love those weeks?) but pretty much I'm looking for a good way to go through a logfile of outgoing mail attempts and count the # of mails going to each mail address- and then sort that list so that I can display the top 25. Anyone got any suggestions? This is making me feel like a total idjit. > > Thanks for your help. > -- > ________________________________________________________________________ > Mike Barrett | "I used to read, now I go to raves." > mike@daboyz.org | -- Random MUNI Rider, speaking > www.daboyz.org | to my friend Allison. > ------------------------+----------------------------------------------- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ________________________________________________________________________ Mike Barrett | "I used to read, now I go to raves." mike@daboyz.org | -- Random MUNI Rider, speaking www.daboyz.org | to my friend Allison. ------------------------+----------------------------------------------- From adam@bostoncoop.net Wed May 14 20:49:02 2003 From: adam@bostoncoop.net (Adam Kessel) Date: Wed May 14 19:49:02 2003 Subject: [Tutor] IDLE with Vim Keybindings? Message-ID: <20030514234834.GA29371@bostoncoop.net> --MGYHOYXEY6WxJCY8 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Hi All: I just discovered idle, which is pretty exciting. I've noticed, though, that it has emacs-like keybindings. Does anyone know if it's possible to change to vim keybindings, or alternatively if there is any Python development environment that uses vim keybindings? A quick websearch doesn't reveal any answers. (obligatory vim vs. emacs comment omitted). = =20 By the way, although I just started with Python a few days ago, I've written three programs which I think work pretty well, they are all at http://bostoncoop.net/adam/python :=20 addMIMETextToHTMLEmail: if you hate HTML-only email (e.g., from Hotmail) because you use a text-based mailreader like mutt this will turn HTML-only email into a MIME multipart message with a text part and an HTML part. Other utilities I've found will strip out the HTML or convert it to text, but this leaves the HTML as a separate part in case you need it. Typically you would use this as a procmail filter. =20 addTitlesToLinks: this program will take HTML snippets (or a whole web page) and look up each tag that doesn't have a 'target' element for the title of the webpage referred to. It will then add the title to the tag. You can either use the program as a module and call the function addTitlesToLinks, or use it as a filter (and pipe HTML through it). =20 fetchPageAndImages: you can feed this program a URL, a file containing HTML, or pipe HTML into it, and it will go and get each web page that is linked, as well as images on those pages, and pack it all up into a single pickled object. It can also take this object and restore it back to something that could be served to a user. So it's a simple web caching program. It's primarily intended to be part of something larger, but it has some command line options to try it out as a stand-alone program. =20 --Adam --MGYHOYXEY6WxJCY8 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQE+wtXSdTf3ZklQ6qYRAuhrAJ9RLZbVFjD3zA3braaSjaty5cTUbQCfSnn6 TnbMgRa8XObNPxx9Bs2yOZQ= =BPad -----END PGP SIGNATURE----- --MGYHOYXEY6WxJCY8-- From missive@hotmail.com Wed May 14 21:08:02 2003 From: missive@hotmail.com (Lee Harr) Date: Wed May 14 20:08:02 2003 Subject: [Tutor] askopenfilename puzzle Message-ID: >I am taking over support on a python script written by a former college. >The script uses askopenfilename to select a file and everything works fine >but there's one thing that puzzles me. After the first time you navigate >to >a file it remembers where you were, even after you've exited the program, >shut down and rebooted the computer. Someplace it's remembering where >you >last worked and I can't figure out how. > >Any clues? > Maybe. But you are going to have to give us a few more clues first. askopenfilename is not a standard python function, so, maybe you could show us the code for it? Or at least some code? _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From jeff@ccvcorp.com Wed May 14 22:58:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed May 14 21:58:02 2003 Subject: [Tutor] Counting & Sorting Instances In File References: <20030514214709.GC76924@daboyz.org> <20030514221152.GF76924@daboyz.org> Message-ID: <3EC2F48F.8080008@ccvcorp.com> Michael Barrett wrote: > The hard (?) part is the sorting. Thats the part I need help with, so assume a dictionary of 'Email': count values. If you can think of a better way of storing the data in memory for my sort, that'd be appreciated as well. Thanks again. > Doing your counting *is* best done with a dictionary, especially if you make use of the get() method -- for line in logfile: email = parse_email_addr(line) emailcount[email] = emailcount.get(email, 0) + 1 Once you have that dictionary of email:count values, you can convert that to a list and use the list's built-in sort() method. When sorting a list where each element is another list (or a tuple), the first element of the nested list is used to sort on, so the best thing to do is to ensure that that first element is your count. # first, use a list comprehension to create a list of (count, email) pairs email_list = [ (value, key) for key, value in emailcount.items() ] # now sort the list email_list.sort() # to sort from highest count to lowest count, reverse the list email_list.reverse() # now print the first 25 for count, email in email_list[:25]: print "%25s %d" % (email, count) If there's any of this that doesn't make sense, I can explain in a little more detail... Jeff Shannon Technician/Programmer Credit International From adam@bostoncoop.net Wed May 14 23:07:02 2003 From: adam@bostoncoop.net (Adam Kessel) Date: Wed May 14 22:07:02 2003 Subject: [Tutor] IDLE with Vim Keybindings? In-Reply-To: References: <20030514234834.GA29371@bostoncoop.net> Message-ID: <20030515020625.GA32166@bostoncoop.net> --x+6KMIRAuhnl3hBn Content-Type: text/plain; charset=us-ascii Content-Disposition: inline On Wed, May 14, 2003 at 08:53:37PM -0400, David Broadwell wrote: > find EditorWindow.py on your system > it even has the color settings. I see... That's helpful. Do you know if anyone has already done a vim-type set of keybindings before? I'm sure I'm not the first person to prefer vim-bindings. --A --x+6KMIRAuhnl3hBn Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQE+wvYhdTf3ZklQ6qYRAvCAAKDLmI1OPD0xsBzbCIaWc3eMUcRThwCgjYVX RHEWWGqfvGFicE8+rzo9Kv0= =WFml -----END PGP SIGNATURE----- --x+6KMIRAuhnl3hBn-- From scott_list@mischko.com Wed May 14 23:51:02 2003 From: scott_list@mischko.com (Scott Chapman) Date: Wed May 14 22:51:02 2003 Subject: [Tutor] Python & PostgreSQL In-Reply-To: <5.1.0.14.2.20030508095137.00ad1b80@mail.30below.com> References: <5.1.0.14.2.20030508095137.00ad1b80@mail.30below.com> Message-ID: <200305141949.51283.scott_list@mischko.com> Tutorial here: http://www.amk.ca/python/writing/DB-API.html Here's my notes from digging around the internet to make this decision. I settled on pyscopg. These notes start with a quote from someone else's email and some replies to it, etc. Then it goes into the specific libraries. There's a couple web pages cited that do comparisons but the info from those pages is included below also so it's not needed to consult them. I don't have dates on the email quotes but they are relevant. I did this research in early April of this year. Hope this helps: ======== Basically my deciding factor is whether i want to use libpq (pgsql c client lib) or python db-api or if i want to use zope, if db-api i generally would recommend pyscopg as it implements db-api compliance at the c level over libpq. pypgsql is a c extension binding over libpq, with db-api interface written in python. if zope, i would use psycopg as it has extensive testing in that area, and converts to mxDateTimes to ZopeTimes. imho, the two bindings serve different audiences. > imho, i would only use pyscopg or pypgsql. of the four they are under the > most active development. Wrong! PoPy is continuing but slowly its development, exploring new ways to make the driver more powerful. I remind you that PoPy's development has begun in 2000, so adding quickly more and more features becomes difficult. When we began PoPy there was only pygresql. That's right, today there are too much drivers for postgresql, and the PoPy team is ready to merge its work w/ others teams like psycopg team, to have less drivers but more powerful, more featured and more stable! reply: my apologies if i offended, but i wouldn't consider my statement wrong, as i said imho, those two drivers under the most active development. a statement which does not preclude development in the other drivers, just their degree. as the most recent release of popy was over a year ago, and the public cvs is unchanged in over a year, its not hard to see why such a distinction is easy to make. thank you for the history lesson. having just looked at the public cvs of popy, it appears that both pypgsql and psycopg offer more features, i'm curious of what benefit from a *code* perspective you think merging the codebases if feasible will bring. === >What is so important > with PyGreSQL if "everybody" thinks that it shouldn't > be used? several things, when i last used pygresql a couple of years ago, i found its db-api interface to be horribly broken. i believer there have been some fixes to this, in the interim *years*. perhaps most signifigantly from my own perspective is that it plays *very* poorly with zope. to wrt, datetime conversions, and the fact that its zope adapter executed queries serially (which is not nesc. the fault of pygresql) . ==== http://www.python.org/cgi-bin/moinmoin/DbApiModuleComparison?action=show ==== http://www.python.org/cgi-bin/moinmoin/PostgreSQL ==== DB API 2.0 Drivers: ======== PyGresQL - Come with PostgreSQL. ======== URL http://www.druid.net/pygresql/ licence BSD-like platforms Unix, win32 Python versions 1.5.2 thru 2.2 Extensions to DB API: none. Alternative old nonstandard PostgreSQL interface ======== PoPy ======== Latest release: 2.0.8 (Stable) 2001/08/27 37786 bytes URL http://popy.sourceforge.net licence GPL platforms Unix Has Zope DA (Database Adapter) written on top of it. ======== psycopg ======== Latest release: 2003-04-02 Federico Di Gregorio Release 1.3. URL http://initd.org/Software/psycopg http://www.initd.org/software/initd/psycopg licence GPL Python: 1.5.2-2.2+ platforms Unix, win32 (beta) Unix, Windows, MacOS X Extensions to DB API dictfetchone(), dictfetchmany(), dictfechall() methods on the cursor object; these will return dictionaries instead of tuples, so you can access rows by name in stead of by index Quoting styles: format,pyformat Comments ZopeDA available. Written for heavily multithreaded applications in mind. Threading: yes (conn. pooling) Extras: typecasting objects ======== pyPgSQL ======== 2002-12-07: pyPgSQL 2.3 URL http://pypgsql.sourceforge.net licence BSD-like platforms Unix, win32 Unix, Windows, MacOS X Python versions 2.0 thru 2.2 2.1+ Extensions to DB API The fetch methods on cursors return an instances of PgResultSet, which you can use to access rows by index (like in DB-API), dictionary-like or with attributes. This feature can be turned off for a slight performance boost. Support for PostgreSQL notifications in the low-level API. Extras: PgResultSet, typecasting objects, notifications. Quoting styles: pyformat Threads: None. From idiot1@netzero.net Thu May 15 01:08:01 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Thu May 15 00:08:01 2003 Subject: [Tutor] program idea Message-ID: <3EC3130C.8060201@netzero.net> I have abn idea for a tool program. it would read in a script, and write it out again with a line number in a comment at the end of each line, as f1=open(filename,mode) #121 owner=string.strip(f1.readline()) #122 passwd=string.strip(f1.readline()) #123 f1.close() #123 ##124 etc. Line numbering gets VERY confusing if you slip up even a little when doing it by hand. Another would remove such and redo it when creating a new version with new lines in teh script. Any discussion? -- end Respectfully, Kirk D Bailey +------------------------------------------------------------+ | Owner Howler Monkey Email: http://www.howlermonkey.net/ | | Inventor of TinyList list server: http://www.tinylist.org/ | | Consulting freestyle Grump: http://www.sacredelectron.org/ | | Remember: When we referr to FREE software, we are talking | | about FREEDOM, not $PRICE$. | +------------------------------------------------------------+ From krier115@student.liu.se Thu May 15 04:22:03 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Thu May 15 03:22:03 2003 Subject: [Tutor] program idea In-Reply-To: <3EC3130C.8060201@netzero.net> References: <3EC3130C.8060201@netzero.net> Message-ID: <20030515072137.GB1349@n14.ryd.student.liu.se> On Thu, May 15, 2003 at 12:09:48AM -0400, Kirk Bailey wrote: > I have abn idea for a tool program. > it would read in a script, and write it out again with a line number in a > comment at the end of each line, as > > f1=open(filename,mode) #121 > owner=string.strip(f1.readline()) #122 > passwd=string.strip(f1.readline()) #123 > f1.close() #123 > ##124 > > etc. > Line numbering gets VERY confusing if you slip up even a little when doing > it by hand. > > Another would remove such and redo it when creating a new version with new > lines in teh script. > > Any discussion? I really fail to see the need of this. Every editor that call itself an editor can display line numbers and move you to a specified line number by a couple of keypresses. So why would you need this? Maybe you have an other reason, I'd be happy to know. Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From charlie@begeistert.org Thu May 15 04:47:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Thu May 15 03:47:01 2003 Subject: [Tutor] Extracting from password protected zipfiles Message-ID: <20030515094723.2295.4@wonderland.1052981285.fake> Dear list, I've received a bundle of fotos in a zip file from a friend but the file is password protected and neither unzip (5.40) nor gzip(1.2.4) support decryption on my system so I thought I would try Python's own zipfile module. Unfortunately that doesn't seem to work either. Searching the net hasn't revealed much either. As I get an error on attempting to read the data, I guess it's not possible to read and decrypt but I have to pass the password in some form. Any ideas as to whether this possible? Thanx very much Charlie From norvell@houseofspearman.org Thu May 15 05:30:01 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Thu May 15 04:30:01 2003 Subject: [Tutor] Extracting from password protected zipfiles In-Reply-To: <20030515094723.2295.4@wonderland.1052981285.fake> References: <20030515094723.2295.4@wonderland.1052981285.fake> Message-ID: <20030515082922.GA3046@houseofspearman.org> On Thursday, 2003.05.15, 09:47:23 +0200, Charlie Clark wrote: > Dear list, > > I've received a bundle of fotos in a zip file from a friend but the file is > password protected and neither unzip (5.40) nor gzip(1.2.4) support > decryption on my system so I thought I would try Python's own zipfile > module. Unfortunately that doesn't seem to work either. Searching the net > hasn't revealed much either. > > As I get an error on attempting to read the data, I guess it's not possible > to read and decrypt but I have to pass the password in some form. Any ideas > as to whether this possible? The version of unzip on my system (v. 5.41) has a `-P' option where you can specify a password; the man page warns that using this option isn't secure. If the zipfile module doesn't accept passwords when opening a zipped file, then could you use an os.exec*() call and include the password as an argument to unzip? -- Norvell Spearman From darnold02@sprynet.com Thu May 15 08:22:01 2003 From: darnold02@sprynet.com (Don Arnold) Date: Thu May 15 07:22:01 2003 Subject: [Tutor] program idea References: <3EC3130C.8060201@netzero.net> <20030515072137.GB1349@n14.ryd.student.liu.se> Message-ID: <027601c31ad4$1d924520$8c11ba3f@defaultcomp> ----- Original Message ----- From: "Kristoffer Erlandsson" To: "Python Tutorial" ; "Kirk Bailey" Sent: Thursday, May 15, 2003 2:21 AM Subject: Re: [Tutor] program idea > On Thu, May 15, 2003 at 12:09:48AM -0400, Kirk Bailey wrote: > > I have abn idea for a tool program. > > it would read in a script, and write it out again with a line number in a > > comment at the end of each line, as > > > > f1=open(filename,mode) #121 > > owner=string.strip(f1.readline()) #122 > > passwd=string.strip(f1.readline()) #123 > > f1.close() #123 > > ##124 > > > > etc. > > Line numbering gets VERY confusing if you slip up even a little when doing > > it by hand. > > > > Another would remove such and redo it when creating a new version with new > > lines in teh script. > > > > Any discussion? > > I really fail to see the need of this. Every editor that call itself an > editor can display line numbers and move you to a specified line number > by a couple of keypresses. So why would you need this? Maybe you have an > other reason, I'd be happy to know. > Inside the editor, you know how the lines are numbered. But where do those numbers go when you email the code to the Tutor list? It can be quite useful to be able to say "I'm having a problem on line #115." instead of "I'm having a problem in my 'for item in list' loop in the Foo() function when I try to append bar to the list." Much more succint. > Regards, > Kristoffer > > -- > Kristoffer Erlandsson > E-mail: krier115@student.liu.se > ICQ#: 378225 Don From thomi@thomi.imail.net.nz Thu May 15 08:48:21 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Thu May 15 07:48:21 2003 Subject: [Tutor] sorting os.listdir. Message-ID: <20030516234604.307d70dd.thomi@thomi.imail.net.nz> IS there a reason os.listdir doesn't sort it's output? It does seem a little silly. What I'm trying to do now is write a little wrapper function, while will look like this: def listdirectory (path,sort="alphanumeric"): blah blah blah this function will call os.listdir, and then sort through the output, according to the sort parameter. possible sort parameters should include alphanumeric, numeric, ascii (just takes the ascii values of the charecter). Does anyone have any good ideas about how to implement this in an efficient manner? It's going to go in a CGI program which has to list a whole heap of files, so speed and memory usage is a slight issue. hmmm.. isn't there some sort of builtin sort() function somewhere?? only it's not in the builtins section of the docs.... or maybe that was some other language... bah.. too tired :-) -- Thomi Richards, thomi@thomi.imail.net.nz From gerrit@nl.linux.org Thu May 15 09:13:02 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Thu May 15 08:13:02 2003 Subject: [Tutor] sorting os.listdir. In-Reply-To: <20030516234604.307d70dd.thomi@thomi.imail.net.nz> References: <20030516234604.307d70dd.thomi@thomi.imail.net.nz> Message-ID: <20030515121051.GA2407@nl.linux.org> Hi Thomas, Thomas CLive Richards schreef op donderdag 15 mei om 14:00:05 +0000: > IS there a reason os.listdir doesn't sort it's output? It does seem a little silly. It is not necessary, and sometimes it may take a lot of resources. Imagine listing the contents of a very large directory: sorting approx. 10.000 filenames may be very time-consuming. > this function will call os.listdir, and then sort through the output, according to the sort parameter. possible sort parameters should include alphanumeric, numeric, ascii (just takes the ascii values of the charecter). You may want to use cmp for that. It may be better to pass a function as second argument, like a default list sort does. Your code may look like (UNTESTED): def sortedlistdir(d, cmpfunc=cmp): l = os.listdir(d) l.sort(cmpfunc) return l > hmmm.. isn't there some sort of builtin sort() function somewhere?? only it's not in the builtins section of the docs.... or maybe that was some other language... bah.. too tired :-) It is available as a list method: http://www.python.org/dev/doc/devel/lib/typesseq-mutable.html Here, all list methods are documented. Further, the way .sort() works is explained, and it is exactly what you need. You may want to write you own cmp() functions for sorting numeric, because as far as I know, this does not exist yet, at least not in the standard library (it may be a good exercise anyway). yours, Gerrit. -- 172. If her husband made her no gift, she shall be compensated for her gift, and she shall receive a portion from the estate of her husband, equal to that of one child. If her sons oppress her, to force her out of the house, the judge shall examine into the matter, and if the sons are at fault the woman shall not leave her husband's house. If the woman desire to leave the house, she must leave to her sons the gift which her husband gave her, but she may take the dowry of her father's house. Then she may marry the man of her heart. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From bgailer@alum.rpi.edu Thu May 15 10:07:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu May 15 09:07:01 2003 Subject: [Tutor] Counting & Sorting Instances In File In-Reply-To: <3EC2F48F.8080008@ccvcorp.com> References: <20030514214709.GC76924@daboyz.org> <20030514221152.GF76924@daboyz.org> Message-ID: <5.2.0.9.0.20030515070546.02f9a320@66.28.54.253> At 06:59 PM 5/14/2003 -0700, Jeff Shannon wrote: >Michael Barrett wrote: > >> The hard (?) part is the sorting. Thats the part I need help with, >> so assume a dictionary of 'Email': count values. If you can think of a >> better way of storing the data in memory for my sort, that'd be >> appreciated as well. Thanks again. > >Doing your counting *is* best done with a dictionary, especially if you >make use of the get() method -- > >for line in logfile: > email = parse_email_addr(line) > emailcount[email] = emailcount.get(email, 0) + 1 > >Once you have that dictionary of email:count values, you can convert that >to a list and use the list's built-in sort() method. When sorting a list >where each element is another list (or a tuple), the first element of the >nested list is used to sort on Oh? Consider: >>> l = [[3,4], [3,2]] >>> l.sort() >>> l [[3, 2], [3, 4]] >, so the best thing to do is to ensure that that first element is your count. > ># first, use a list comprehension to create a list of (count, email) pairs >email_list = [ (value, key) for key, value in emailcount.items() ] ># now sort the list >email_list.sort() ># to sort from highest count to lowest count, reverse the list >email_list.reverse() ># now print the first 25 >for count, email in email_list[:25]: > print "%25s %d" % (email, count) > >If there's any of this that doesn't make sense, I can explain in a little >more detail... > >Jeff Shannon >Technician/Programmer >Credit International > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > >--- >Incoming mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.478 / Virus Database: 275 - Release Date: 5/6/2003 Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From jtk@yahoo.com Thu May 15 11:38:03 2003 From: jtk@yahoo.com (Jeff Kowalczyk) Date: Thu May 15 10:38:03 2003 Subject: [Tutor] How to leave literal %s in output of formatted string Message-ID: I want to build a format string in code. How do I leave a literal %s in my string formatting output? I can't find any escape code for the % character. (desired output) >>> VendorID = 'ACME' >>> s = '%s Download \%s' % VendorID 'Acme Download %s' From andi@buxach.de Thu May 15 11:42:02 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Thu May 15 10:42:02 2003 Subject: [Tutor] program idea In-Reply-To: <027601c31ad4$1d924520$8c11ba3f@defaultcomp> References: <3EC3130C.8060201@netzero.net> <20030515072137.GB1349@n14.ryd.student.liu.se> <027601c31ad4$1d924520$8c11ba3f@defaultcomp> Message-ID: <20030515164008.55ec4002.andi@buxach.de> > Inside the editor, you know how the lines are numbered. But where do > those numbers go when you email the code to the Tutor list? In Linux i just can type "cat -n myprogram.py" and i get a nice numbering. Is there no Windowstools for this? -- Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From adam@bostoncoop.net Thu May 15 11:48:01 2003 From: adam@bostoncoop.net (Adam Kessel) Date: Thu May 15 10:48:01 2003 Subject: [Tutor] How to leave literal %s in output of formatted string In-Reply-To: References: Message-ID: <20030515144704.GG20100@bostoncoop.net> --k3qmt+ucFURmlhDS Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable This is a suggestion from one newbie to another--I'm sure there's a better way to do this, but this worked:=20 VendorID =3D 'ACME' ReplacementString =3D '%s' s =3D '%s Download %s' % (VendorID, ReplacementString) --Adam On Thu, May 15, 2003 at 10:28:42AM -0400, Jeff Kowalczyk wrote: > I want to build a format string in code. How do I leave a > literal %s in my string formatting output? I can't find any > escape code for the % character. >=20 > (desired output) > >>> VendorID =3D 'ACME' > >>> s =3D '%s Download \%s' % VendorID > 'Acme Download %s' --k3qmt+ucFURmlhDS Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQE+w6hndTf3ZklQ6qYRAsL4AKCRjXpQCDh/lbAjApq+IaVX7cRQJwCghzcy LMoPuV+bD1GpB89mcwh0h20= =12OT -----END PGP SIGNATURE----- --k3qmt+ucFURmlhDS-- From norvell@houseofspearman.org Thu May 15 12:07:05 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Thu May 15 11:07:05 2003 Subject: [Tutor] program idea In-Reply-To: <20030515164008.55ec4002.andi@buxach.de> References: <3EC3130C.8060201@netzero.net> <20030515072137.GB1349@n14.ryd.student.liu.se> <027601c31ad4$1d924520$8c11ba3f@defaultcomp> <20030515164008.55ec4002.andi@buxach.de> Message-ID: <20030515150607.GA5763@houseofspearman.org> On Thursday, 2003.05.15, 16:40:08 +0200, Andreas Zwinkau wrote: > In Linux i just can type "cat -n myprogram.py" and i get a nice > numbering. Is there no Windowstools for this? There is a cat.exe in the package from the following site: http://unxutils.sourceforge.net/ -- Norvell Spearman From krier115@student.liu.se Thu May 15 12:10:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Thu May 15 11:10:02 2003 Subject: [Tutor] How to leave literal %s in output of formatted string In-Reply-To: References: Message-ID: <20030515150821.GA20979@n14.ryd.student.liu.se> On Thu, May 15, 2003 at 10:28:42AM -0400, Jeff Kowalczyk wrote: > I want to build a format string in code. How do I leave a > literal %s in my string formatting output? I can't find any > escape code for the % character. > > (desired output) > >>> VendorID = 'ACME' > >>> s = '%s Download \%s' % VendorID > 'Acme Download %s' > >>> VendorID = 'ACME' >>> s = '%s Download %%s' % VendorID >>> s 'ACME Download %s' >>> print s ACME Download %s Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From lonetwin@yahoo.com Thu May 15 12:16:01 2003 From: lonetwin@yahoo.com (lonetwin) Date: Thu May 15 11:16:01 2003 Subject: [Tutor] program idea In-Reply-To: <3EC3130C.8060201@netzero.net> References: <3EC3130C.8060201@netzero.net> Message-ID: <200305152104.30751.lonetwin@yahoo.com> Hey Kirk, Me, me, me .....me like strings and list comprehension. On Thursday 15 May 2003 09:39 am, Kirk Bailey wrote: > I have abn idea for a tool program. > it would read in a script, and write it out again with a line number in a > comment at the end of each line, as > > f1=open(filename,mode) #121 > owner=string.strip(f1.readline()) #122 > passwd=string.strip(f1.readline()) #123 > f1.close() #123 > ##124 > > etc. > Line numbering gets VERY confusing if you slip up even a little when doing > it by hand. > > Another would remove such and redo it when creating a new version with new > lines in teh script. > > Any discussion? def writeLineNumbers(filename): l = open(filename).readlines() l = [ l[i][:-1] + "\t#%s" % i for i in range(len(l)) ] open("%s.new" % filename).write("\n".join(l)) def stripLineNumbers(filename): l = open(filename).readlines() l = [ l[i][:l[i].rfind('#')] for i in range(len(l)) ] open("%s.new" % filename).write("\n".join(l)) howz that for obfuscated code ?? Anyway to put that open().readline() too in there ?? :) Peace Steve -- Basically my wife was immature. I'd be at home in the bath and she'd come in and sink my boats. -- Woody Allen From jtk@yahoo.com Thu May 15 12:25:01 2003 From: jtk@yahoo.com (Jeff Kowalczyk) Date: Thu May 15 11:25:01 2003 Subject: [Tutor] Re: How to leave literal %s in output of formatted string References: <20030515144704.GG20100@bostoncoop.net> Message-ID: Good point, the direct subsitution will do the trick >>> s = '%s download %s' % (VendorID, '%s') If anyone knows, I'm still curious to know if there is an escape character for %, for more complex cases that may come up in the future. Adam wrote: ------------------- This is a suggestion from one newbie to another--I'm sure there's a better way to do this, but this worked: VendorID = 'ACME' ReplacementString = '%s' s = '%s Download %s' % (VendorID, ReplacementString) From charlie@begeistert.org Thu May 15 13:39:00 2003 From: charlie@begeistert.org (Charlie Clark) Date: Thu May 15 12:39:00 2003 Subject: [Tutor] Re: Extracting from password protected zipfiles In-Reply-To: <20030515160006.19677.22099.Mailman@mail.python.org> References: <20030515160006.19677.22099.Mailman@mail.python.org> Message-ID: <20030515183918.33046.21@wonderland.1052981285.fake> On 2003-05-15 at 18:00:06 [+0200], tutor-request@python.org wrote: > The version of unzip on my system (v. 5.41) has a `-P' option where you > can specify a password; the man page warns that using this option isn't > secure. > > If the zipfile module doesn't accept passwords when opening a zipped > file, then could you use an os.exec*() call and include the password as > an argument to unzip? I found 5.41 so I was able to use that. But the corresponding version of zip doesn't support encryption. Maybe I'll have a look at the source and see whether it's doable. Would be nice to have it. Charlie From jtk@yahoo.com Thu May 15 14:09:02 2003 From: jtk@yahoo.com (Jeff Kowalczyk) Date: Thu May 15 13:09:02 2003 Subject: [Tutor] How to accomplish Dict setdefault(key, (append to existing value list) or (start new list) )? Message-ID: I need to conditionally append an id with setdefault(k,v[id]) to either: - the list that is the existing value v for key k, - or start a new list v a single value of id. Can anyone suggest a more efficient and compact syntax to accomplish this? OrderDates = {} for OrderDate, OrderID in Orders: if OrderDates.has_key(OrderDate): OrderDates.setdefault(OrderDate,OrderDates[OrderDate].append(OrderID)) else: OrderDates.setdefault(OrderDate,[OrderID,]) print OrderDates I'm trying to build up a dictionary of OrderIDs keyed to a date. The iteration part is pseudocode, but my actual code builds several dictionaries this way, and I want to simplify the implementation as much as possible. {'05-02-2003' : ['123456','123457','123458','123459'], '05-03-2003' : ['123460''123460','123460','123460','123460'],} Thanks. From dyoo@hkn.eecs.berkeley.edu Thu May 15 14:35:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 15 13:35:01 2003 Subject: [Tutor] Re: How to leave literal %s in output of formatted string In-Reply-To: Message-ID: On Thu, 15 May 2003, Jeff Kowalczyk wrote: > Good point, the direct subsitution will do the trick > > >>> s = '%s download %s' % (VendorID, '%s') > > If anyone knows, I'm still curious to know if there is an escape > character for %, for more complex cases that may come up in the future. Hi Jeff, To make a '%' stick around after a string formatting operation, we need a way of "escaping" that character. The escape character was arbitrarily chosen to be two ampersands in a row: ### >>> template = "Hi %s, this is a percent sign: %%" >>> template % 'adam' 'Hi adam, this is a percent sign: %' >>> >>> "Hi %s, this is another example: %%s" % "Jeff" 'Hi Jeff, this is another example: %s' ### This system was borrowed from C's 'printf' print formatting function, and I remember how weird it struck me that it used '%%' rather than '\%'... Oh well. *grin* I hope this helps! From reggie@merfinllc.com Thu May 15 14:40:02 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Thu May 15 13:40:02 2003 Subject: [Tutor] How to accomplish Dict setdefault(key, (append to existing value list) or (start new list) )? In-Reply-To: References: Message-ID: <1053020649.13112.6.camel@pika> Jeff, I think this will do the trick for you: OrderDates = {} for OrderDate, OrderID in Orders: OrderDates.setdefault(OrderDate, []).append(OrderID) print OrderDates HTH On Thu, 2003-05-15 at 10:05, Jeff Kowalczyk wrote: > I need to conditionally append an id with setdefault(k,v[id]) to either: > - the list that is the existing value v for key k, > - or start a new list v a single value of id. > > Can anyone suggest a more efficient and compact syntax to accomplish this? > > OrderDates = {} > for OrderDate, OrderID in Orders: > if OrderDates.has_key(OrderDate): > OrderDates.setdefault(OrderDate,OrderDates[OrderDate].append(OrderID)) > else: > OrderDates.setdefault(OrderDate,[OrderID,]) > print OrderDates > > I'm trying to build up a dictionary of OrderIDs keyed to a date. The iteration part is > pseudocode, but my actual code builds several dictionaries this way, and I want to > simplify the implementation as much as possible. > > {'05-02-2003' : ['123456','123457','123458','123459'], > '05-03-2003' : ['123460''123460','123460','123460','123460'],} > > Thanks. > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Reggie From rick@niof.net Thu May 15 14:52:13 2003 From: rick@niof.net (Rick Pasotto) Date: Thu May 15 13:52:13 2003 Subject: [Tutor] Re: How to leave literal %s in output of formatted string In-Reply-To: References: Message-ID: <20030515175125.GB1267@tc.telocity.com> On Thu, May 15, 2003 at 10:33:41AM -0700, Danny Yoo wrote: > > > On Thu, 15 May 2003, Jeff Kowalczyk wrote: > > > Good point, the direct subsitution will do the trick > > > > >>> s = '%s download %s' % (VendorID, '%s') > > > > If anyone knows, I'm still curious to know if there is an escape > > character for %, for more complex cases that may come up in the future. > > Hi Jeff, > > To make a '%' stick around after a string formatting operation, we need a > way of "escaping" that character. The escape character was arbitrarily > chosen to be two ampersands in a row: I think two 'percent' signs (ie, '%%') would work better than two 'and' signs (ie, '&&'). :-) -- "Paper has a genius for multiplication that cannot be equaled anywhere else in nature." -- Hugh Keenleyside Rick Pasotto rick@niof.net http://www.niof.net From jeff@ccvcorp.com Thu May 15 14:57:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu May 15 13:57:03 2003 Subject: [Tutor] Counting & Sorting Instances In File References: <20030514214709.GC76924@daboyz.org> <20030514221152.GF76924@daboyz.org> <5.2.0.9.0.20030515070546.02f9a320@66.28.54.253> Message-ID: <3EC3D57B.8040003@ccvcorp.com> Bob Gailer wrote: > At 06:59 PM 5/14/2003 -0700, Jeff Shannon wrote: > >> When sorting a list where each element is another list (or a tuple), >> the first element of the nested list is used to sort on > > > Oh? Consider: > >>> l = [[3,4], [3,2]] > >>> l.sort() > >>> l > [[3, 2], [3, 4]] In the interests of brevity, I omitted discussing the fact that, if the first elements match, sort() proceeds to sort on the second element, and if those match, on the third, et cetera. My original statement was true, though not quite complete. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Thu May 15 15:07:29 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu May 15 14:07:29 2003 Subject: [Tutor] How to accomplish Dict setdefault(key, (append to existing value list) or (start new list) )? References: Message-ID: <3EC3D798.90206@ccvcorp.com> Jeff Kowalczyk wrote: >I need to conditionally append an id with setdefault(k,v[id]) to either: >- the list that is the existing value v for key k, >- or start a new list v a single value of id. > >Can anyone suggest a more efficient and compact syntax to accomplish this? > >OrderDates = {} >for OrderDate, OrderID in Orders: > if OrderDates.has_key(OrderDate): > OrderDates.setdefault(OrderDate,OrderDates[OrderDate].append(OrderID)) > else: > OrderDates.setdefault(OrderDate,[OrderID,]) > print OrderDates > > You don't need setdefault(), you only need get(). for OrderDate, OrderID in Orders: OldValue = OrderDates.get(OrderDate, []) OrderDates[OrderDate] = OldValue.append(OrderID) I used two lines above for the sake of clarity, so that it's a little easier to see what's happening. The dict method get() will return the value associated with the first argument (OrderDate) if there is such a value, and will return the second argument if there is no such value. So my first line will give either the previous list of orders for that date, or an empty list. Either way, I append the current order ID to the list and put it back in the dictionary. This can all be done in a single line, as well -- for OrderDate, OrderID in Orders: OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID) I've found get() to be invaluable any time that I want to organize a sequence into "buckets" (as you're doing) or count occurrences of something. Jeff Shannon Technician/Programmer Credit International From jtk@yahoo.com Thu May 15 15:51:02 2003 From: jtk@yahoo.com (Jeff Kowalczyk) Date: Thu May 15 14:51:02 2003 Subject: [Tutor] Re: How to accomplish Dict setdefault(key, (append to existing value list) or (start new list) )? References: <3EC3D798.90206@ccvcorp.com> Message-ID: Jeff Shannon wrote: > for OrderDate, OrderID in Orders: > OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID) > I've found get() to be invaluable any time that I want to organize a > sequence into "buckets" (as you're doing) or count occurrences of something. That's really slick, I like it. I'm having some trouble with the one-line version though: Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 >>> Orders = (('2003-05-14','Ord1234'),('2003-05-14','Ord1235'), ('2003-05-15','Ord1236'),('2003-05-16','Ord1237')) >>> OrderDates = {} >>> for OrderDate, OrderID in Orders: ... OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID) Traceback (most recent call last): File "", line 2, in ? AttributeError: 'NoneType' object has no attribute 'append' >>> print OrderDates.get('2003-05-14',[]) None Did I miss something? I seem to be having a that problem (failed late evaluation to list type) a lot lately. From jtk@yahoo.com Thu May 15 16:09:12 2003 From: jtk@yahoo.com (Jeff Kowalczyk) Date: Thu May 15 15:09:12 2003 Subject: [Tutor] Re: How to accomplish Dict setdefault(key, (append to existing value list) or (start new list) )? References: <3EC3D798.90206@ccvcorp.com> Message-ID: I found the surprise, the dictionary key for a date in that format gives strange behavior. >>> print OrderDates.get('2003-05-14',[]) None This works: >>> print OrderDates.get('20030514',[]) [] as does >>> print OrderDates.get(r'2003-05-14',[]) [] What is happening there? Is the string evaluated or tested for hashability somehow? What are the rules? Can you suggest a raw-evaluation syntax for the key in the one-line get(k,[]) version of your example. If it isn't the CCYY-MM-DD format, its going to be some other kind of delimiter... From krier115@student.liu.se Thu May 15 16:35:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Thu May 15 15:35:02 2003 Subject: [Tutor] Re: How to accomplish Dict setdefault(key, (append to existing value list) or (start new list) )? In-Reply-To: References: <3EC3D798.90206@ccvcorp.com> Message-ID: <20030515193440.GA31578@n14.ryd.student.liu.se> On Thu, May 15, 2003 at 02:44:25PM -0400, Jeff Kowalczyk wrote: > Jeff Shannon wrote: > > for OrderDate, OrderID in Orders: > > OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID) > > I've found get() to be invaluable any time that I want to organize a > > sequence into "buckets" (as you're doing) or count occurrences of something. > > That's really slick, I like it. > I'm having some trouble with the one-line version though: > > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > >>> Orders = (('2003-05-14','Ord1234'),('2003-05-14','Ord1235'), > ('2003-05-15','Ord1236'),('2003-05-16','Ord1237')) > >>> OrderDates = {} > >>> for OrderDate, OrderID in Orders: > ... OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID) > Traceback (most recent call last): > File "", line 2, in ? > AttributeError: 'NoneType' object has no attribute 'append' > >>> print OrderDates.get('2003-05-14',[]) > None > > Did I miss something? > > I seem to be having a that problem (failed late evaluation to list type) a lot lately. > Appending to a list doesn't return anything, it changes the list directly and returns None. So what OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID) does is to set OrderDates[OrderDate] to the returned value of append, which is none: >>> OrderDates {'2003-05-14': None} So when you try next time, the get returns None, and you try to append to that. HTH -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From dyoo@hkn.eecs.berkeley.edu Thu May 15 17:35:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 15 16:35:01 2003 Subject: [Tutor] IDLE with Vim Keybindings? In-Reply-To: <20030515020625.GA32166@bostoncoop.net> Message-ID: On Wed, 14 May 2003, Adam Kessel wrote: > On Wed, May 14, 2003 at 08:53:37PM -0400, David Broadwell wrote: > > find EditorWindow.py on your system > > it even has the color settings. > > I see... That's helpful. Do you know if anyone has already done a > vim-type set of keybindings before? I'm sure I'm not the first person > to prefer vim-bindings. Hi Adam, Hmmm! You might want to ask on the IDLEFork mailing list; one of the folks there might be willing to code up a vim-bindings module as an alternative to the emacs key bindings. You can find the IDLEFork mailing list here: http://mail.python.org/mailman/listinfo/idle-dev From jeff@ccvcorp.com Thu May 15 17:53:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu May 15 16:53:02 2003 Subject: [Tutor] Re: How to accomplish Dict setdefault(key, (append to existing value list) or (start new list) )? References: <3EC3D798.90206@ccvcorp.com> <20030515193440.GA31578@n14.ryd.student.liu.se> Message-ID: <3EC3FEC3.4050803@ccvcorp.com> Kristoffer Erlandsson wrote: >Appending to a list doesn't return anything, it changes the list >directly and returns None. So what > >OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID) > >does is to set OrderDates[OrderDate] to the returned value of append, >which is none: > > Why, so it does. You'd think I'd know by now that I shouldn't post untested code. Ah well. So, this leaves us with a couple of options. One is to go back to doing this in several lines, but making the append() into a separate step: for OrderDate, OrderID in Orders: current = OrderDates.get(OrderDate, []) current.append(OrderID) OrderDates[OrderDate] = current Another option is to follow the old maxim that "It's easier to ask forgiveness than permission", and to directly catch the KeyError that happens when we try to access a nonexistent key: for OrderDate, OrderID in Orders: try: OrderDates[OrderDate].append(OrderID) except KeyError: OrderDates[OrderDate] = [OrderID] This calls append() directly on the dictionary contents. If nothing is found for that OrderDate, then we get a KeyError exception, and when that happens we add a new list to the dictionary that contains the current OrderID. Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Thu May 15 18:21:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 15 17:21:01 2003 Subject: [Tutor] How to accomplish Dict setdefault(key, (append to existing value list) or (start new list) )? In-Reply-To: <3EC3D798.90206@ccvcorp.com> Message-ID: > I used two lines above for the sake of clarity, so that it's a little > easier to see what's happening. The dict method get() will return the > value associated with the first argument (OrderDate) if there is such a > value, and will return the second argument if there is no such value. > So my first line will give either the previous list of orders for that > date, or an empty list. Either way, I append the current order ID to > the list and put it back in the dictionary. This can all be done in a > single line, as well -- > > for OrderDate, OrderID in Orders: > OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID) Hi everyone, Ah! There's some confusion here. There are two methods in dictionaries that look like they do similar things: get() setdefault() But the code above is incorrect; Jeff meant to use setdefault(): ### for OrderDate, OrderID in Orders: OrderDates.setdefault(OrderDate, []).append(OrderID) ### The statements above can be rewritten as: ### for date, OrderID in Orders: if date not in OrderDates: OrderDates[date] = [] OrderDates[date].append(OrderId) ### That is, setdefault() will first check to see if the value in the dictionary needs to be initialized, and will set it up to some default if it hasn't been set yet. ### >>> x = {} >>> x.setdefault('one', 1) 1 >>> x {'one': 1} ### And as a shortcut, setdefault() returns that value back to us --- that's where it sorta looks like get(). When we see something like: OrderDates.get(date, []) we can sorta decompose it to: if date in OrderDate: return OrderDate[date] else: return [] (This translation is not quite correct; it should really be an expression, not a set of statements. A closer translation might be: (date in OrderDate and OrderDate[date] or []) except that this is not correct either! Can anyone see why? This is very pertinent to the arguments for the "ternary" conditional expression.) Anyway, the main thing to see is that there is a difference between setdefault() and get()! The setdefault() does make changes to the dictionary, but the get(), by itself, doesn't do so. Going back to the original code: ### for OrderDate, OrderID in Orders: OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID) ### The key to the bug is that: OrderDates.get(OrderDate, []).append(OrderID) is guaranteed to be 'None', since that's what the append() call will return. That is, it's doing something similar to: ### for OrderDate, OrderID in Orders: temp_value = OrderDates.get(OrderDate, []) OrderDates[OrderDate] = temp_value.append(OrderID) ### And that's why we're getting None in all of the OrderDates. If we really wanted to use get(), we can correct the code like this: ### for OrderDate, OrderID in Orders: OrderDates[OrderDate] = OrderDates.get(OrderDate, []) OrderDates[OrderDate].append(OrderID) ### If you have more questions about this, please feel free to ask! From dyoo@hkn.eecs.berkeley.edu Thu May 15 18:41:42 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 15 17:41:42 2003 Subject: [Tutor] Re: How to leave literal %s in output of formatted string In-Reply-To: <20030515175125.GB1267@tc.telocity.com> Message-ID: On Thu, 15 May 2003, Rick Pasotto wrote: > On Thu, May 15, 2003 at 10:33:41AM -0700, Danny Yoo wrote: > > > > > > On Thu, 15 May 2003, Jeff Kowalczyk wrote: > > > > > Good point, the direct subsitution will do the trick > > > > > > >>> s = '%s download %s' % (VendorID, '%s') > > > > > > If anyone knows, I'm still curious to know if there is an escape > > > character for %, for more complex cases that may come up in the > > > future. > > > > Hi Jeff, > > > > To make a '%' stick around after a string formatting operation, we > > need a way of "escaping" that character. The escape character was > > arbitrarily chosen to be two ampersands in a row: > > I think two 'percent' signs (ie, '%%') would work better than two 'and' > signs (ie, '&&'). :-) Hi Rick, Right. Percent signs. Of course. *sheepish grin* Doh. My apologies for doing one thing and saying another. Thanks for the correction! From ATrautman@perryjudds.com Thu May 15 19:01:00 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Thu May 15 18:01:00 2003 Subject: [Tutor] Tutor list introduction, goals, ideals... Message-ID: <06738462136C054B8F8872D69DA140DB010792@corp-exch-1.pjinet.com> Moody, I think it has been said here many times but the best place to begin is http://www.python.org/doc/current/tut/tut.html Even as a programmer with on and off 10 yrs experience I did the whole thing partially to get a 'feel' for how things are done in Python. The thing IMHO we all love about is that things are done a Pythonic way and even if you haven't used a part of Python yet this gives you a starting point. While you do that sketch (on paper) out something would like to do, preferable relating to a hobby or interest. For me exercises get boring quickly and it is easier to focus on finishing something. If you really can't think of anything the calculator, first as a command line tool and then a GUI (Tkinter) based learning tool is always good. As you create your new project in any areas you are having difficulty either ask the tutor list for help or use the large amount of source code available online to see how others have done tasks. Rewrite that for your own tool. Now that you have done some things that work the site How to Think Like a computer scientist I believe is well regarded on this tutor site. I agree. The link is: http://www.ibiblio.org/obp/thinkCSpy/ I'm sure there are many others here who have other insight as I am only a part time Python person. I just hope this gets you started in a useful direction. IDLE will be fine for you for quite a while so I wouldn't worry about the editor at this point. Unless you have a personal favorite of course:) We all do and its really a matter or personal preference and the number of hours a day you use the editor that usually make the decision. IMO powerful editors such as VIM are really only great if you use them a lot. I'll duck now an try to avoid the editor shrapnel:) Hope this helps as an frequent computer systems instructor I think you've chosen the best language to learn with an active users group. Peace Alan -----Original Message----- From: M [mailto:moody834@mac.com] Sent: Wednesday, May 14, 2003 11:37 AM To: tutor@python.org Subject: [Tutor] Tutor list introduction, goals, ideals... Hello everyone: At 36 years old, I am just about ready to start learning Python, which will be my first programming language (although - to render a better picture of where my educational level is - I've read _The Pragmatic Programmer_ and have a basic, though untested, understanding of OOP). My platform of choice is OS X (currently I am running 10.2.6 [with Apple's free Dev Tools installed] on a 500MHz DP G4 with 512MB RAM), on which additionally I run OroborOSX and use fink. I've also a computer running SuSE 8.x and Wintendo (read Win2k Pro, Srvc. pk. 3), neither of which has seen any tweaking or customization. My desire to learn Python may be split pretty evenly between fun and community. By the latter, I mean to say that I want to learn Python in part because I want to get involved with a community of souls with whom I feel I share a great deal (even as a newbie, such as I am and have been for some time). I support GNU and the GPL to the degree that I understand the phrase, "Free as in freedom". However, fwiw, I am not the sort of person who carelessly engages in conversations about politics/religion. My goal is, ultimately, to help create beneficial software, using Python (and/or some other programming language), that I may freely distribute to the World. A secondary but no less valuable goal for me is to have much fun along the way. I think /that/ must be a pre-requisite for using Python! :-) Getting involved in a current project is perfectly acceptable to me. Which brings me to this question: If you were just starting out learning your first programming language (or, perhaps, /when/ you first started out, etc.), what might you do to get involved or, at least, self-educate with a goal toward getting involved? That is, what might your initial programming attempt be aimed at accomplishing? Should a person just pick any old thing (e.g., a simple text editor) to work at, or is there something better to start with? Thank you to anyone/everyone who answers this. Please feel free to give me your advice on whatever you think might be useful to me (or anyone in my position). Sincerely, Moody PS: IDLE is very nice. PPS: I am just about ready to go back to school to work on getting a degree in journalism. This is relevant because in the end I think I'd really like to report on tech topics. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From magnus@thinkware.se Thu May 15 19:45:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 15 18:45:02 2003 Subject: [Tutor] Tutor list introduction, goals, ideals... In-Reply-To: <491ECB68-862A-11D7-919E-003065E73510@mac.com> Message-ID: <5.2.1.1.0.20030516001945.01ee4f18@www.thinkware.se> At 09:37 2003-05-14 -0700, M wrote: >Hello everyone: Hi, and welcome. >Which brings me to this question: If you were just starting out learning >your first programming language (or, perhaps, /when/ you first started >out, etc.), what might you do to get involved or, at least, self-educate >with a goal toward getting involved? That is, what might your initial >programming attempt be aimed at accomplishing? Should a person just pick >any old thing (e.g., a simple text editor) to work at, or is there >something better to start with? Many of us are scratching an itch... writing code because unless we write it, there is something that will continue to annoy us. That's a really good motivator! :) Isn't there anything which you'd like to do that you can't today? And it really just a simple little thing that you maybe do manually time after time, and would like to get done automagically? I started to write plenty of Python when I was a C++ programmer, to reduce the manual labour. Generated code from a CASE tool wasn't quite right and had to be adjusted slightly after every run. I didn't like to do search and replace over and over again... Test files had to be written, tests run, and the result evaluated. Writing scripts for those things made life much easier, and above all, less boring. I'd say: Start small, and try to build the code in such a way that it might be of some kind of use, or at the very least testable, in very small increments. Try to run the code after every handful of lines, and while it might not be useful at every stop of the way, try to see that it run so well that you can always keep track of its state. Some people (and even more teachers) still program in the spirit of the 60's and 70's where you sat with a bunch of paper cards and punched them, and then left them to the computer operator and returned the next day to get an error message from your run... It's not like that now. Being able to get instant feedback on your achievements and your mistakes makes you much more productive than if you try to write a lot before you try it for real. I'd also suggest that you write your first programs like simple filters, just reading and writing text. Don't mess with GUIs to start with. A GUI is something you attach to working application logic, nothing that you mix with your logic. If you liked The Pracmatic Programmer, you might like "The Unix Philosophy" by Mike Gancarz. It's rather much a book in the same spirit. See http://www.thinkware.se/cgi-bin/thinki.cgi/UnixPhilosophy for more about these ideas. And while Hunt and Thomas have written a great book, I imagine it might be a little to much to try to consider all they say as you begin programming. I imagine that you will start to appreciate what they wrote in time though, and probably go back to the book again when you have more real world experience to relate their writing to. At least for me, it seems to be tough to really grasp all they say without getting your feet wet... Good luck! -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From shalehperry@attbi.com Thu May 15 22:23:08 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu May 15 21:23:08 2003 Subject: [Tutor] program idea In-Reply-To: <3EC3130C.8060201@netzero.net> References: <3EC3130C.8060201@netzero.net> Message-ID: <200305151822.26894.shalehperry@attbi.com> On Wednesday 14 May 2003 21:09, Kirk Bailey wrote: > I have abn idea for a tool program. > it would read in a script, and write it out again with a line number in a > comment at the end of each line, as > > f1=open(filename,mode) #121 > owner=string.strip(f1.readline()) #122 > passwd=string.strip(f1.readline()) #123 > f1.close() #123 > ##124 > > etc. > Line numbering gets VERY confusing if you slip up even a little when doing > it by hand. > as others have discussed, the initial writing is easy however .... My main issue is this is likely to spill code over the 80 chars One True Length. Not a huge deal, but something to consider. > Another would remove such and redo it when creating a new version with new > lines in teh script. > this is harder. You have to handle cases like this: i = j + (k * 2) # add joules to twice the constant # 237 which I would expect to be common in script code. I guess a regex like r'#\s\d+$' should cover it. So, here is my version (which looks good in a fixed width font and horrible otherwise): #! /usr/bin/python # 1 # 2 import sys # 3 # 4 def compute_padding(num): # 5 pad = 0 # 6 while num > 0: # 7 num /= 10 # 8 pad += 1 # 9 return pad # 10 # 11 def add_lineno(lines, fp = sys.stdout): # 12 MAX_LEN = 80 # 13 # 14 trailer_gen = "# %%%ds" % compute_padding(len(lines)) # 15 # 16 count = 0 # 17 # 18 for line in lines: # 19 line = line.rstrip() # 20 count += 1 # 21 trailer = trailer_gen % count # 22 output_gen = "%%s%%%ds\n" % (80 - len(trailer) - len(line)) # 23 fp.write(output_gen % (line, trailer)) # 24 # 25 def sub_lineno(lines, fp = sys.stdout): # 26 import re # 27 stripper = re.compile(r'#\s+\d+$') # 28 for line in lines: # 29 fp.write(stripper.sub('', line)) # 30 # 31 if __name__ == '__main__': # 32 if len(sys.argv) > 1 and sys.argv[1] == 'sub': # 33 lines = sys.stdin.readlines() # 34 sub_lineno(lines) # 35 else: # 36 lines = sys.stdin.readlines() # 37 add_lineno(lines) # 38 From shalehperry@attbi.com Thu May 15 22:34:32 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu May 15 21:34:32 2003 Subject: [Tutor] program idea In-Reply-To: <200305151822.26894.shalehperry@attbi.com> References: <3EC3130C.8060201@netzero.net> <200305151822.26894.shalehperry@attbi.com> Message-ID: <200305151831.01950.shalehperry@attbi.com> And here is a version which actually honors MAX_LEN (doh!) as well as deal with cases where the line will be longer than MAX_LEN. The idea is if the line would be to long just skip the line count for that line. There should be enough context to make this be ok. #! /usr/bin/python # 1 # 2 import sys # 3 # 4 def compute_padding(num): # 5 pad = 0 # 6 while num > 0: # 7 num /= 10 # 8 pad += 1 # 9 return pad # 10 # 11 def add_lineno(lines, fp = sys.stdout): # 12 MAX_LEN = 80 # 13 # 14 trailer_gen = "# %%%ds" % compute_padding(len(lines)) # 15 # 16 count = 0 # 17 # 18 for line in lines: # 19 line = line.rstrip() # 20 count += 1 # 21 trailer = trailer_gen % count # 22 pad = MAX_LEN - len(trailer) - len(line) # 23 if pad <= 0: # 24 fp.write("%s\n" % line) # 25 else: # 26 output_gen = "%%s%%%ds\n" % (pad) # this makes the line too long fp.write(output_gen % (line, trailer)) # 28 # 29 def sub_lineno(lines, fp = sys.stdout): # 30 import re # 31 stripper = re.compile(r'#\s+\d+$') # 32 for line in lines: # 33 fp.write(stripper.sub('', line)) # 34 # 35 if __name__ == '__main__': # 36 if len(sys.argv) > 1 and sys.argv[1] == 'sub': # 37 lines = sys.stdin.readlines() # 38 sub_lineno(lines) # 39 else: # 40 lines = sys.stdin.readlines() # 41 add_lineno(lines) # 42 From dbroadwell@mindspring.com Fri May 16 00:46:01 2003 From: dbroadwell@mindspring.com (David Broadwell) Date: Thu May 15 23:46:01 2003 Subject: [Tutor] interesting str behavior ... Message-ID: This will be trivial for most but; I have known strings are iterable for awhile ... However, the code below struck it home. Now I believe they are. >>> from string import letters >>> temp = [] >>> temp.extend(letters) >>> temp ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] Ah learning from mistakes ... I was testing something in the interpreter, and grabbed a string not a list to look at list.extend(). The closest I can code to 'extend' is; >>> temp = [] >>> temp.append([item for item in letters]) >>> temp [['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']] Though that isn't perfect ... it is much the same semantics. ( Just sharing where I stub my toes ... ) -- David Broadwell From idiot1@netzero.net Fri May 16 00:56:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Thu May 15 23:56:02 2003 Subject: [Tutor] permissions reading of a file Message-ID: <3EC3D440.2050903@netzero.net> I know how to SET permissions on a file; how do I READ the existing permissions on an already existing file? -- end Respectfully, Kirk D Bailey +------------------------------------------------------------+ | Owner Howler Monkey Email: http://www.howlermonkey.net/ | | Inventor of TinyList list server: http://www.tinylist.org/ | | Consulting freestyle Grump: http://www.sacredelectron.org/ | | Remember: When we referr to FREE software, we are talking | | about FREEDOM, not $PRICE$. | +------------------------------------------------------------+ From shalehperry@attbi.com Fri May 16 01:33:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri May 16 00:33:02 2003 Subject: [Tutor] permissions reading of a file In-Reply-To: <3EC3D440.2050903@netzero.net> References: <3EC3D440.2050903@netzero.net> Message-ID: <200305152132.08153.shalehperry@attbi.com> On Thursday 15 May 2003 10:54, Kirk Bailey wrote: > I know how to SET permissions on a file; how do I READ the existing > permissions on an already existing file? os.stat() From dyoo@hkn.eecs.berkeley.edu Fri May 16 03:24:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 16 02:24:03 2003 Subject: [Tutor] interesting str behavior ... In-Reply-To: Message-ID: On Thu, 15 May 2003, David Broadwell wrote: > This will be trivial for most but; > > I have known strings are iterable for awhile ... However, the code below > struck it home. Now I believe they are. > > >>> from string import letters > >>> temp = [] > >>> temp.extend(letters) > >>> temp > ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', > 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', > 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', > 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] Hi David, Another neat way to get a similar effect is to 'list' an iterable thing. For example: ### >>> list("hello world") ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] >>> >>> d = {1:'one', 2:'two', 3:'three'} >>> list(d) [1, 2, 3] ### The second example is slightly obscure but cute: dictionaries are iterable: we can march through their keys, ### >>> for key in d: ... print "here's a key", key ... here's a key 1 here's a key 2 here's a key 3 ### and that explains the slightly odd-looking result of list()ing a dictionary. > Ah learning from mistakes ... Fastest way to learn anything, and, most of the time, pretty painless. *grin* > I was testing something in the interpreter, and grabbed a string not a > list to look at list.extend(). > > The closest I can code to 'extend' is; > >>> temp = [] > >>> temp.append([item for item in letters]) > >>> temp > [['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', > 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', > 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', > 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']] > > Though that isn't perfect ... it is much the same semantics. It's also good to see that what we get here makes its own sort of sense. When we append() anything to a list, we make the list grow by one element, no matter what we put into the list. So the length of the 'temp' is one: ### >>> len(temp) 1 ### If we want to make temp 56 elements long, and if we want to do it by using append() only, we've got to do something to let us do a repeated append() that many times. Good luck to you! From K G" Hi All, Please correct me. class Base: def func(self): return "func" def afunc(): return "afunc" Now even though "afunc" features in Base's __dict__, am not able to call the function. Even though am able to acquire a handle to afunc am helpless. I wonder if it makes sense to have such a function defined in a class. I guess we have to use staticmethod() in case we want to define a static method?? bcos that is the effect i was lookign for when i defined afunc(). Coming to bound & unbound methods, 1. they necessarily have to be instance methods (ie something that has 'self' as it's first argument). 2. The same method is supposed to be "bound" if it's called using an instance and unbound if called using the class object except that instance needs to be passed explicitly in the latter case. Now when w'd i use a unbound method? 1. If i have to call super class's methods class Derived(Base): def func(self): Base.func(self) 2. If we have a instance variable and instance method name to be the same, then the only way am able to access the method is by using unbound methods. class Test: def__init__(self): self.name="python" def name(self): return "Test" t = Test() t.name #python t.name() # Flags an error: str not callable Test.name(t) # Works Are there any other situations where unbound methods are applicable? thanks! karthik. ___________________________________________________ Get email that means BUSINESS! me @ mycompany.com. Just Rs.1499/year. To start, click http://www.rediffmailpro.com From krier115@student.liu.se Fri May 16 04:31:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Fri May 16 03:31:02 2003 Subject: [Tutor] permissions reading of a file In-Reply-To: <200305152132.08153.shalehperry@attbi.com> References: <3EC3D440.2050903@netzero.net> <200305152132.08153.shalehperry@attbi.com> Message-ID: <20030516072929.GA771@n14.ryd.student.liu.se> On Thu, May 15, 2003 at 09:32:08PM -0700, Sean 'Shaleh' Perry wrote: > On Thursday 15 May 2003 10:54, Kirk Bailey wrote: > > I know how to SET permissions on a file; how do I READ the existing > > permissions on an already existing file? > > os.stat() os.stat doesn't seem to return the permissions. However, os.access checks them: $ ls -l desktop.jpg -rw-rw-r-- 1 erl erl 533534 Apr 8 15:06 desktop.jpg >>> import os >>> os.access('/home/erl/desktop.jpg', os.R_OK) 1 >>> os.access('/home/erl/desktop.jpg', os.W_OK) 1 >>> os.access('/home/erl/desktop.jpg', os.W_OK|os.R_OK) 1 >>> os.access('/home/erl/desktop.jpg', os.X_OK) 0 The modes you can test for is R_OK (is the file readible?), W_OK (writable?), X_OK (executable?) and F_OK (does the file exist?). You just combine these using inclusive or (|). HTH -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From lonetwin@yahoo.com Fri May 16 04:40:03 2003 From: lonetwin@yahoo.com (lonetwin) Date: Fri May 16 03:40:03 2003 Subject: [Tutor] interesting str behavior ... In-Reply-To: References: Message-ID: <200305161328.15864.lonetwin@yahoo.com> On Friday 16 May 2003 11:52 am, Danny Yoo wrote: > > If we want to make temp 56 elements long, and if we want to do it by using > append() only, we've got to do something to let us do a repeated append() > that many times. > Re: And that is as easy as rearranging the contruct >>> temp.append([item for item in letters]) like so: >>> junk_this = [temp.append(item) for item in letters] >>> temp ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] >>> :) Peace Steve -- A government that is big enough to give you all you want is big enough to take it all away. -- Barry Goldwater From thomi@thomi.imail.net.nz Fri May 16 04:44:01 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Fri May 16 03:44:01 2003 Subject: [Tutor] permissions reading of a file In-Reply-To: <20030516072929.GA771@n14.ryd.student.liu.se> References: <3EC3D440.2050903@netzero.net> <200305152132.08153.shalehperry@attbi.com> <20030516072929.GA771@n14.ryd.student.liu.se> Message-ID: <20030517194157.1eebcf4a.thomi@thomi.imail.net.nz> > The modes you can test for is R_OK (is the file readible?), W_OK > (writable?), X_OK (executable?) and F_OK (does the file exist?). You > just combine these using inclusive or (|). umm... surely '|' is an "or"??? shouldn't it be an "and"?? It's && in C, what is it in python?? -- Thomi Richards, thomi@thomi.imail.net.nz From krier115@student.liu.se Fri May 16 05:03:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Fri May 16 04:03:02 2003 Subject: [Tutor] permissions reading of a file In-Reply-To: <20030517194157.1eebcf4a.thomi@thomi.imail.net.nz> References: <3EC3D440.2050903@netzero.net> <200305152132.08153.shalehperry@attbi.com> <20030516072929.GA771@n14.ryd.student.liu.se> <20030517194157.1eebcf4a.thomi@thomi.imail.net.nz> Message-ID: <20030516080113.GA2130@n14.ryd.student.liu.se> On Sat, May 17, 2003 at 07:41:57PM +1200, Thomas CLive Richards wrote: > > The modes you can test for is R_OK (is the file readible?), W_OK > > (writable?), X_OK (executable?) and F_OK (does the file exist?). You > > just combine these using inclusive or (|). > > umm... surely '|' is an "or"??? > > shouldn't it be an "and"?? It's && in C, what is it in python?? > It should be an or. As in c the operators | and & perform bitwise or and bitwise and, respectively. That is, they compare the bits of two integers two by two using or or and. The way things work in for example os.access now is that os.R_OK = 4 = 0100b, os.W_OK = 2 = 0010b, os.X_OK = 1 = 0001b. So each of these number have one bit each set. What will happen when we perform a bitwise or on two of them? >>> os.R_OK|os.W_OK 6 Which is the same as 0110b. So what python now did was to compare the bits in the number 4 and the number 2, two by two. This teqnique is often used when handling "flags" where you have an integer and it means different things depending on what bits are set. >>> os.R_OK|os.W_OK|os.X_OK 7 Which is the same as 0111b. These bitwise operators are very different from the logic ones (&& and || in c, 'and' and 'or' in python). The logic ones just compare the two operands and return true or false (or some values that are true or false), wheras the bitwise operators perform what I showed above and return a new integer. Hope it makes things clearer. I tried at least ;) Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From thomi@thomi.imail.net.nz Fri May 16 05:06:49 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Fri May 16 04:06:49 2003 Subject: [Tutor] permissions reading of a file In-Reply-To: <20030516080113.GA2130@n14.ryd.student.liu.se> References: <3EC3D440.2050903@netzero.net> <200305152132.08153.shalehperry@attbi.com> <20030516072929.GA771@n14.ryd.student.liu.se> <20030517194157.1eebcf4a.thomi@thomi.imail.net.nz> <20030516080113.GA2130@n14.ryd.student.liu.se> Message-ID: <20030517200341.082573c9.thomi@thomi.imail.net.nz> > Hope it makes things clearer. I tried at least ;) thanks, much better :-) -- Thomi Richards, thomi@thomi.imail.net.nz From adamg@mailbox.hu Fri May 16 05:11:03 2003 From: adamg@mailbox.hu (Adam Groszer) Date: Fri May 16 04:11:03 2003 Subject: [Tutor] how-to do black magic Message-ID: Dear All, How-to do the following. I have a list of properties let's say in a text file. >From this list I'd like to create a class's properties and getter/setter methods with a metaclass. Is this possible? How? example: text file: Name Value class: class sample(base): def setName(self, val): self.__Name=val def getName(self): return self.__Name Name = property(getName, setName, None, 'this is my Name') def setValue(self, val): self.__Value=val def getValue(self): return self.__Value Value = property(getValue, setValue, None, 'this is my Value') something like this, or likely behavior Adam From charlie@begeistert.org Fri May 16 05:15:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri May 16 04:15:02 2003 Subject: [Tutor] Re: Extracting from password protected zipfiles In-Reply-To: <20030515220100.13904.78176.Mailman@mail.python.org> References: <20030515220100.13904.78176.Mailman@mail.python.org> Message-ID: <20030516101509.733.1@wonderland.1053068583.fake> On 2003-05-16 at 00:01:00 [+0200], tutor-request@python.org wrote: > On 2003-05-15 at 18:00:06 [+0200], tutor-request@python.org wrote: > > The version of unzip on my system (v. 5.41) has a `-P' option where you > > can specify a password; the man page warns that using this option isn't > > secure. > > > > If the zipfile module doesn't accept passwords when opening a zipped > > file, then could you use an os.exec*() call and include the password as > > an argument to unzip? > > I found 5.41 so I was able to use that. But the corresponding version of > zip doesn't support encryption. Maybe I'll have a look at the source and > see whether it's doable. Would be nice to have it. I just wanted to make it clear to the list that this is not about hacking password protected zip files but supporting them, the -P option in Unzip. It seems that this isn't supported in the current version of zipfile. If I do manage to get this working and this is a very big if, how would I go about getting it into the standard library? I've started looking at the C-source for unzip and it seems I just need crypt.c, well crypt works fine even on BeOS so I guess it's now just a question of finding out how it's used. I have never ever programmed a line of c :-/ ! Thanx very much Charlie From andi@buxach.de Fri May 16 06:20:02 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Fri May 16 05:20:02 2003 Subject: [Tutor] Tutor list introduction, goals, ideals... In-Reply-To: <491ECB68-862A-11D7-919E-003065E73510@mac.com> References: <491ECB68-862A-11D7-919E-003065E73510@mac.com> Message-ID: <20030516111757.498c3e42.andi@buxach.de> Hi Moody > Which brings me to this question: If you were just starting out > learning your first programming language (or, perhaps, /when/ you > first started out, etc.), what might you do to get involved or, at > least, self-educate with a goal toward getting involved? That is, what > might your initial programming attempt be aimed at accomplishing? > Should a person just pick any old thing (e.g., a simple text editor) > to work at, or is there something better to start with? One thing i understand after reading a lot of articles (Eric Raymonds writings) is that open-source programming is mainly "scratching an itch". If you are honest, computers are ugly to use. You have to learn at least one other language to make it doing what you want! So programming in the open source world is to build solutions for this problem. There are so many little problems, which make my computer experience worse, so i create a little program which handles this problem for me. Then i distribute it, so it can help other people. Perhaps the other people will even enhance my program ... this is open source in my eyes. Example: I needed a program which logs my network traffic every month (12.1. -> 11.2.), because i have a dsl-connection with 5GB traffic limit. This could be done with a simple shell script, because i only had to parse and save the output of ifconfig, but it was a nice python training (regular expressions). Now i only have to type traffic and it prints me the traffic since the last 12. I scratched my itch ;) So the conclusion: Don't seek for nice projects for a newbie, but solve your own little problems. There is always something to be automated... > Thank you to anyone/everyone who answers this. Please feel free to > give me your advice on whatever you think might be useful to me (or > anyone in my position). Don't stay on python. Other languages are sometimes of better use and knowing them a little gives you some enlightment sometimes. Perhaps you will come to a point, where you don't solve a problem through python (or c or perl or ...) but through programming itself and after you solved the problem you think of the best language to implement it. But the most important advice i can give you: HAVE FUN! and after you scratched your itch you feel good ;) -- Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From op73418@mail.telepac.pt Fri May 16 07:57:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri May 16 06:57:02 2003 Subject: [Tutor] how-to do black magic References: Message-ID: <006501c31b99$e8065060$071b0dd5@violante> ----- Original Message ----- From: "Adam Groszer" To: "Tutor@Python. Org" Sent: Friday, May 16, 2003 9:13 AM Subject: [Tutor] how-to do black magic > Dear All, > > How-to do the following. > I have a list of properties let's say in a text file. > From this list I'd like to create a class's properties and getter/setter > methods with a metaclass. > Is this possible? How? > > example: > > text file: > Name > Value > > class: > class sample(base): > def setName(self, val): > self.__Name=val > def getName(self): > return self.__Name > Name = property(getName, setName, None, 'this is my Name') > def setValue(self, val): > self.__Value=val > def getValue(self): > return self.__Value > Value = property(getValue, setValue, None, 'this is my Value') > > something like this, or likely behavior > > Adam > The recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157768 and its (long) discussion should give you a head start. But from what I gather from your specs, you need only a name to specfiy a property, that consists simply in a setting/getting from a "private" attribute. Are you sure you need black magic for just this? Isn't there a simpler way to accomplish whatever you are trying to do, ditching properties altogether? Tell us a little more about your problem. Also, you may have more luck in the python list for this more advanced stuff, you have a wider audience. All the best, G. Rodrigues From adamg@mailbox.hu Fri May 16 08:32:01 2003 From: adamg@mailbox.hu (Adam Groszer) Date: Fri May 16 07:32:01 2003 Subject: [Tutor] how-to do black magic In-Reply-To: <006501c31b99$e8065060$071b0dd5@violante> Message-ID: Thank you, The problem is more sophisticated, but this is my 'basic' problem currently. point zero: I'm not sure, if the metaclass is the best solution for this. I'm lazy :-). I thought instead of writing always the getter/setter methods, the metaclass (??) should do it. Or let's say at a later point I will store the data in a dictionary, not in private properties. But as second point I'll need some kind of meta-information about 'my' properties. Using some kind of list to specify them is the most simple solution. Now either 1. I write the list, 'something' prepares the class 2. I prepare the class, 'something' prepares the list I think the first solution looks better. (I'm thinking of a 'system' which will read/write the objects from/to a relational database and therefore I will need much more information about one property.) I think to create a half-way functional class from a list of properties lies in a metaclass. Again, I'm not 100% sure :-) -----Original Message----- But from what I gather from your specs, you need only a name to specfiy a property, that consists simply in a setting/getting from a "private" attribute. Are you sure you need black magic for just this? Isn't there a simpler way to accomplish whatever you are trying to do, ditching properties altogether? Tell us a little more about your problem. Also, you may have more luck in the python list for this more advanced stuff, you have a wider audience. From magnus@thinkware.se Fri May 16 10:04:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 16 09:04:01 2003 Subject: [Tutor] how-to do black magic In-Reply-To: Message-ID: <5.2.1.1.0.20030516145826.01ecefe0@www.thinkware.se> At 10:13 2003-05-16 +0200, Adam Groszer wrote: > From this list I'd like to create a class's properties and getter/setter >methods with a metaclass. From an object oriented design point of view, using pure data classes, i.e. classes lacking more substantial methods than getters and setters, is a bad idea. It seems to me that you only need one class if the only difference is what attributes you want to store, but you have shared logic. If you settle for a syntax of x.set('name', 'Brian') and x.get('weight') etc, you have a very simple implementation of a single class. Just feed the constructor with a list of allowed attributes for that instance. You can also use __getattr__ to do special things when the attr starts with 'get' or 'set'. You don't *need* a meta class for that. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From charlie@begeistert.org Fri May 16 11:01:34 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri May 16 10:01:34 2003 Subject: [Tutor] Adding support for password protection to zipfile (long) Message-ID: <20030516160145.3348.17@wonderland.1053068583.fake> Dear list, I've started looking at the source to Unzip and I think I've found the appropriate part: #if CRYPT /* GRR: yes, this is highly insecure, but dozens of people * have pestered us for this, so here we go... */ case ('P'): if (negative) { /* negative not allowed with -P passwd */ Info(slide, 0x401, ((char *)slide, LoadFarString(MustGivePasswd))); return(PK_PARAM); /* don't extract here by accident */ } if (uO.pwdarg != (char *)NULL) { /* GRR: eventually support multiple passwords? Info(slide, 0x401, ((char *)slide, LoadFarString(OnlyOnePasswd))); return(PK_PARAM); */ } else { /* first check for "-Ppasswd", then for "-P passwd" */ uO.pwdarg = s; if (*uO.pwdarg == '\0') { if (argc > 1) { --argc; uO.pwdarg = *++argv; if (*uO.pwdarg == '-') { Info(slide, 0x401, ((char *)slide, LoadFarString(MustGivePasswd))); return(PK_PARAM); } /* else pwdarg points at decryption password */ } else { Info(slide, 0x401, ((char *)slide, LoadFarString(MustGivePasswd))); return(PK_PARAM); } } /* pwdarg now points at decryption password (-Ppasswd or * -P passwd); point s at end of passwd to avoid mis- * interpretation of passwd characters as more options */ if (*s != 0) while (*++s != 0) ; } break; Now while I've never worked with C this looks doable to me. Here's my attempt to turn this into Python Assuming unzip is called like this unzip -p secret bilder.zip the Python unzip.py has the same interface python unzip -p secret bilder.zip if sys.argv[1] == "-P": if negative: # what is negative? """I think we check for a password here. This function is called often, let's give it a name call_info""" Info(slide, 0x401, ((char *)slide, # what is slide? LoadFarString(MustGivePasswd)) return PK_PARAM if sys.argv[2]: """This is commented out but seems to refer to several password being supplied which is an error. It only uses call_info anyway""" if len(sys.argv[1]) > 2: """check to see whether we have -P password or -Ppassword""" password = sys.argv[1][2:] if not password: """call_info is called again""" else: """call_info is called again""" As far as I can tell the work is done by this following: #if CRYPT # ifdef PASSWD_FROM_STDIN Info(slide, 0, ((char *)slide, LoadFarString(CompileOptFormat), LoadFarStringSmall(PasswdStdin))); # endif Info(slide, 0, ((char *)slide, LoadFarString(Decryption), CR_MAJORVER, CR_MINORVER, CR_BETA_VER, LoadFarStringSmall(CryptDate))); ++numopts; #endif /* CRYPT */ I think this is something like if crypt: if password: """check the format, assign the password""" """check the encryption version""" mm, apart from the fact that reading command line arguments seems to be a real pain in C compared to Python I think I'm getting somewhere although I've yet to find the part where we actually decrypt the password. Looking at the source of zipfile we find the Zipfile class. As you only need the password to extract individual files, we only need to overwrite the read() or write() methods. Rolling my own extension would be class EncryptedZipfile(zipfile.ZipFile): def __init__(self, password=None): zipfile.ZipFile.__init__(self) self.password = password This is the source for Zipfile.read() def read(self, name): """Return file bytes (as a string) for name.""" if self.mode not in ("r", "a"): raise RuntimeError, 'read() requires mode "r" or "a"' if not self.fp: raise RuntimeError, \ "Attempt to read ZIP archive that was already closed" if self.password: # do the decryption thing zinfo = self.getinfo(name) filepos = self.fp.tell() self.fp.seek(zinfo.file_offset, 0) bytes = self.fp.read(zinfo.compress_size) self.fp.seek(filepos, 0) if zinfo.compress_type == ZIP_STORED: pass elif zinfo.compress_type == ZIP_DEFLATED: if not zlib: raise RuntimeError, \ "De-compression requires the (missing) zlib module" # zlib compress/decompress code by Jeremy Hylton of CNRI dc = zlib.decompressobj(-15) bytes = dc.decompress(bytes) # need to feed in unused pad byte so that zlib won't choke ex = dc.decompress('Z') + dc.flush() if ex: bytes = bytes + ex else: raise BadZipfile, \ "Unsupported compression method %d for file %s" % \ (zinfo.compress_type, name) crc = binascii.crc32(bytes) if crc != zinfo.CRC: raise BadZipfile, "Bad CRC-32 for file %s" % name return bytes I'm not sure whether I'll ever succeed with this but I'd like to try. Any comments on my analysis or assumptions are welcome, please cc: to me as I'm a digest reader. Thanx Charlie From python-tutor-list@tagancha.org Fri May 16 12:17:02 2003 From: python-tutor-list@tagancha.org (Alex) Date: Fri May 16 11:17:02 2003 Subject: [Tutor] log parser speed optimization Message-ID: <20030516151640.GA12818@purdue.edu> --17pEHd4RhPHOinZp Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Hello, I looked at the Tutor archives, but did not find the answer to my question in the time I had, so I hope I can get some pointers here. I've been lurking on the list for a looong time, but still can't remember all the excellent suggestions made by our more experienced pythonistas :) I've an itch of putting all the log files from our ftp server that accumulated over the years into a mysql database, so they could be queried and patterns could be looked for. I decided to write two scripts to do that. The first one parses raw log files and writes parsed data into an output file. I wrote it and it works as needed, but I wonder if I could speed it up. It takes from 75 to 100 seconds to parse 419951 records of type 'xx.xxx.xxx.xxx - xxxx [01/May/2003:07:08:13 -0500] "GET /dir1/subdir1/subdir2/subdir3/file1" 200 5069672\n' into something like '2003-05-01 07:08:13,xxxx,xx.xxx.xxx.xxx,GET,200,/dir1/subdir1/subdir2/subdir3/file1,5069672' which gives me the speed of 4200 to 5600 records per second. However, a 100 seconds is still a relatively long time. I attached the script to this message. If you would be so kind to point me to the bottlenecks in it I would be very grateful. Thank you, Alex. --17pEHd4RhPHOinZp Content-Type: text/plain; charset=us-ascii Content-Disposition: attachment; filename="parseftplog.py" #!/usr/bin/python """This script will parse pure-ftpd logs and write out parsed data for later analysis. Date: Fri May 16 10:08:46 EST 2003 Version: 0.05 ChangeLog: Between ver. 0.04 - 0.05: Fri May 16 10:08:46 EST 2003 Changed container objects into tuples and dictionaries instead of lists where I could. Used 'strip().split()' when parsing raw logfile lines. Changed date and time parsing algorithm and output to produce the folowing format (yyyy-mm-dd hh:mm:ss) suitable for MySQL inserts. Removed an intermediate list. Now it's a 3 step process: - read a line from input file - parse the line and datetime separately - write the line out to the output file Between ver. 0.03 - 0.04: Fri May 2 16:35:40 EST 2003 Added parsing of the date/time into separate list items for more convenience during report generation Between ver. 0.02 - 0.03: Fri May 2 11:14:01 EST 2003 Programmed sorting and removal of duplicates. Data is parsed cleanly and the output is written into a csv file for later analysis by a report-generating scripts. No bugs are seen. Between ver. 0.01 - 0.02: Thr May 1 17:12:33 EST 2003 Corrected parsing scheme. Some '"' were still hanging and data werent separated cleanly. No sorting and removal of duplication are in, yet. Version 0.01: Wed May 1 10:42:27 EST 2003 Whipped up rough python pseudocode that kind of works. """ def usage(prog="purelog"): print """ prog: Parser of pure-ftpd log files prog [-h] [-o ] -h print this message -o file to put the resulting parsed logs into -t run a test with 3 example logs name[s] of the log file to parse """ def parsedate(datetime): modict = {'Jan':'01', 'Feb':'02', 'Mar':'03', 'Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'} tempdt = ":".join(datetime.split('/')).split(':') tempdt[1] = modict[tempdt[1]] tupdt = (tempdt[2],tempdt[1],tempdt[0],tempdt[3],tempdt[4],tempdt[5]) parseddt = '%s-%s-%s %s:%s:%s' % tupdt return parseddt def parseline(logline): inlist = logline.strip().split() datetime = parsedate(inlist.pop(3)[1:]) user = inlist.pop(2) inlist.pop(1) inlist.pop(1) ip = inlist.pop(0) action = inlist.pop(0)[1:] fsize = inlist.pop(-1) result = inlist.pop(-1) fname = " ".join(inlist)[:-1] return "%s,%s,%s,%s,%s,%s,%s" % (datetime, user, ip, action, result, fname, fsize) def testrun(): line1 = 'xx.xxx.xxx.xxx - xxxx [01/May/2003:07:08:13 -0500] "GET /dir1/subdir1/subdir2/subdir3/file1" 200 5069672\n' line2 = 'xxx.xxx.xx.xx - xxxx [12/Sep/2002:12:42:17 -0600] "GET /dir2/subdir1/subdir2/Libraries/10 PCRs for probe generation to get rid of second set of majors.tif" 200 84066\n' line3 = 'xxx.xxx.xx.xx - xxxxxx [29/Jul/2002:16:12:37 -0600] "PUT /dir3/subdir1/sub dir 2/file1" 200 158300\n' pseudofile = [line1,line2,line3] for pseudoline in pseudofile: outline = parseline(pseudoline) + '\n' print outline if __name__=='__main__': import sys, getopt from time import time starttime = time() o, a = getopt.getopt(sys.argv[1:], 'hto:') opts = {} for k,v in o: opts[k] = v if opts.has_key('-h'): usage(); sys.exit() if opts.has_key('-t'): testrun(); sys.exit('Test run completed successfully!') if opts.has_key('-o'): outfilename = opts['-o'] outmode = 'w' outfile = file(outfilename, outmode) else: print 'Output file name is "pureftpd-parsed.log"' outfile = file('pureftpd-parsed.log','w') if len(a) < 1: usage(); sys.exit('log file[s] name/pattern missing') logfiles = a for i in logfiles: print 'Log file to process:', i if i.split('.')[-1] == 'gz': import gzip logfile = gzip.open(i,'rt') else: logfile = file(i,'rt') while 1: line = logfile.readline() if not line: break else: outline = parseline(line) + '\n' outfile.write(outline) outfile.close() endtime = time() runtime = endtime - starttime print 'Your run proceeded for %.2f seconds' % (runtime) sys.exit('All raw log files have been parsed. Goodbye!') --17pEHd4RhPHOinZp-- From charlie@begeistert.org Fri May 16 14:25:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri May 16 13:25:02 2003 Subject: [Tutor] Adding support for password protection to zipfile (long) In-Reply-To: References: Message-ID: <20030516192534.5775.26@wonderland.1053068583.fake> On 2003-05-16 at 19:19:15 [+0200], you wrote: > Hi, > > I've been following your Zip decryption adventure on the list. I did > some poking around and came up with > http://www.pkware.com/products/enterprise/white_papers/appnote.html#8 > which has a pretty good explanation of the decryption process. The > algorithm is given in psuedocode which is much easier, imho, to port to > python than C is. Thanx Greg, I've even discovered that someone else beat me to it: there is a patch for zipfile.py on Sourceforge von Giovanni Bajo but it hasn't been accepted yet. Seeing as I hate reinventing the wheel I'm testing it for him! Charlie From dyoo@hkn.eecs.berkeley.edu Fri May 16 14:38:43 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 16 13:38:43 2003 Subject: [Tutor] interesting str behavior ... (fwd) Message-ID: [Forwarding to Tutor] ---------- Forwarded message ---------- Date: Fri, 16 May 2003 13:27:49 +0530 From: lonetwin To: Danny Yoo Subject: Re: [Tutor] interesting str behavior ... On Friday 16 May 2003 11:52 am, Danny Yoo wrote: > > If we want to make temp 56 elements long, and if we want to do it by using > append() only, we've got to do something to let us do a repeated append() > that many times. > Re: And that is as easy as rearranging the contruct >>> temp.append([item for item in letters]) like so: >>> junk_this = [temp.append(item) for item in letters] >>> temp ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] >>> :) Peace Steve -- A government that is big enough to give you all you want is big enough to take it all away. -- Barry Goldwater From dyoo@hkn.eecs.berkeley.edu Fri May 16 14:49:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 16 13:49:01 2003 Subject: [Tutor] interesting str behavior ... (fwd) In-Reply-To: Message-ID: > > If we want to make temp 56 elements long, and if we want to do it by > > using append() only, we've got to do something to let us do a repeated > > append() that many times. > > > Re: And that is as easy as rearranging the contruct > > >>> temp.append([item for item in letters]) > > like so: > > >>> junk_this = [temp.append(item) for item in letters] > >>> temp > ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', > 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', > 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', > 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] Hello! Although this works, there's a simpler way to do things, without list comprehensions: ### for item in letters: temp.append(item) ### In our enthusiasm for list comprehensions, let's not forget about loops. *grin* Good luck! From ccollier@viawest.net Fri May 16 14:49:16 2003 From: ccollier@viawest.net (ccollier@viawest.net) Date: Fri May 16 13:49:16 2003 Subject: [Tutor] user input without return / non-blocking Message-ID: I'm working on a small console based game. I need to be able to accept input from a user (keyboard/stdin) without having them press return. j = move left, k = move right etc. sys.stdin.read, input, and raw_input don't seem to be the solution I'm looking for, although sys.stdin.read is close. Can anyone point me in the right direction? scouring google and books, cody --------------------- cody collier ccollier@viawest.net From carroll@tjc.com Fri May 16 15:00:02 2003 From: carroll@tjc.com (Terry Carroll) Date: Fri May 16 14:00:02 2003 Subject: [Tutor] how-to do black magic In-Reply-To: Message-ID: On Fri, 16 May 2003, Adam Groszer wrote: > I have a list of properties let's say in a text file. > >From this list I'd like to create a class's properties and getter/setter > methods with a metaclass. > Is this possible? How? Adam -- I've also read the follow-ups, and am not quite sure what you're trying to do. From the sound of it, though, I may have just solved a similar problem. I have a dictionary-like object, Uninan (representing all Unicode CJK characters), each entry of which is another dictionary-like object, UnihanChar (each representing a particular character, each entry of which was a particular characteristic of that character). I have a UnihanChar.Display method that show all information about the character, and displays the character using Tkinter. I wanted to be able to change all the UnihanChars' font by one call to Unihan; I did it by adding a __settatr__ to Unihan: def __setattr__(self, name, value): self.__dict__[name] = value # percolate changes to Font to contained UnihanChar instances if name == 'Font': for entry in self.data.keys(): self.data[entry].Font = value I don't know if this is quite on the lines of what you're doing, but even if not, maybe it will give you some ideas. -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From charlie@begeistert.org Fri May 16 15:21:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri May 16 14:21:02 2003 Subject: [Tutor] Re: Tutor digest, Vol 1 #2438 - 9 msgs In-Reply-To: <20030516160009.10064.85836.Mailman@mail.python.org> References: <20030516160009.10064.85836.Mailman@mail.python.org> Message-ID: <20030516201235.6058.30@wonderland.1053068583.fake> Hey Alex, I'm by no means a whiz at this kind of thing but having read the script it looks like I can make a few suggestions. First of all: have you used profiler? It will tell you where you're spending all your time but my guess is disk access is the biggest problem. You are reading in line by line and I think this is very inefficient. You could use readlines() or probably even better xreadlines() which should stop the computer having to swap to read the file all at once and then loop through the resulting list. Using should also write out at once out.write("\n".join(newlines)) for the same reason. On 2003-05-16 at 18:00:09 [+0200], tutor-request@python.org wrote: > def parsedate(datetime): > modict = {'Jan':'01', 'Feb':'02', 'Mar':'03', 'Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'} > tempdt = ":".join(datetime.split('/')).split(':') > tempdt[1] = modict[tempdt[1]] > tupdt = (tempdt[2],tempdt[1],tempdt[0],tempdt[3],tempdt[4],tempdt[5]) > parseddt = '%s-%s-%s %s:%s:%s' % tupdt > return parseddt Using mxDateTime to do this will probably be a lot faster but even then all these lookups are just in memory so it won't be that noticeable. But I think this function is ugly and could be tidied up. > def parseline(logline): > inlist = logline.strip().split() > datetime = parsedate(inlist.pop(3)[1:]) > user = inlist.pop(2) > inlist.pop(1) > inlist.pop(1) > ip = inlist.pop(0) > action = inlist.pop(0)[1:] > fsize = inlist.pop(-1) > result = inlist.pop(-1) > fname = " ".join(inlist)[:-1] > return "%s,%s,%s,%s,%s,%s,%s" % (datetime, user, ip, action, result, > fname, fsize) This is more work than you need and difficult to read and maintain. There is no need to pop items from the list and using tuple unpacking is even easier. longline = """xx.xxx.xxx.xxx - xxxx [01/May/2003:07:08:13 -0500] "GET /dir1/subdir1/subdir2/subdir3/file1" 200 5069672\n""" ip, user, date, action, fname, result, fsize = longline[:-1].split() all the "popping" (very funny in German by the way) has confused me a bit. You can then tidy up the inidividual sections, parse the datetime and do the return return "%s,%s,%s,%s,%s,%s,%s" % (parsedate(datetime[1:-1]), user, ip, action[1:], result, fname[:-1], fsize) Of course, there are also specialise log file parsing modules for Python which you might like to compare for speed. Have fun Charlie From tjenkins@devis.com Fri May 16 16:20:13 2003 From: tjenkins@devis.com (Tom Jenkins) Date: Fri May 16 15:20:13 2003 Subject: [Tutor] log parser speed optimization In-Reply-To: <20030516151640.GA12818@purdue.edu> References: <20030516151640.GA12818@purdue.edu> Message-ID: <3EC539AA.5050703@devis.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Alex wrote: | Hello, | this message. If you would be so kind to point me to the bottlenecks in | it I would be very grateful. To find the bottlenecks you need to run through the profiler: http://www.python.org/doc/current/lib/profile-instant.html There are 2 spots I identified as potential bottlenecks... | | def parseline(logline): | inlist = logline.strip().split() | datetime = parsedate(inlist.pop(3)[1:]) | user = inlist.pop(2) | inlist.pop(1) | inlist.pop(1) | ip = inlist.pop(0) | action = inlist.pop(0)[1:] | fsize = inlist.pop(-1) | result = inlist.pop(-1) | fname = " ".join(inlist)[:-1] | return "%s,%s,%s,%s,%s,%s,%s" % (datetime, user, ip, action, result, fname, fsize) | you are popping values out of inlist. this is equivalent to: x = inlist[i]; del inlist[i] the del call is unnecessary. so replace all your pops with the appropriate slice. | while 1: | line = logfile.readline() | if not line: | break classic way to read files. also slow. look at xreadlines. - -- Tom Jenkins devIS - Development Infostructure http://www.devis.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.0-nr2 (Windows XP) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQE+xTmqV7Yk9/McDYURApuUAJ9xDmCkJhBfqJkbma5XqP/9/4bTCwCguKqb 4nlWuO5mSOoWNPoiMzC1MbA= =VO/0 -----END PGP SIGNATURE----- From hall@ouhep1.nhn.ou.edu Fri May 16 16:57:05 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Fri May 16 15:57:05 2003 Subject: [Tutor] general explanation of xml.sax and its usage Message-ID: Hi Folks, A while back I posted on here asking for ways to parse XML into a python dictionary. Several people suggested xml.sax, but since the documentation seemed to be a bit more complex than I really needed (I only needed to get very simple XML) I abandoned that, and instead wrote my own little script that just sorted xml into a dictionary by just reading the text. That worked well for its purpose, and continues to do so. However, now for another utility, I need to be able to parse much more complicated XML into some kind of python object. I am now looking at the docs for xml.sax, and still, the docs make it appear more complicated than it probably is. Can anyone point me to some sample code using xml.sax which is commented, so that I may see it in use. Or just a smiplified explanation of how to use the objects in xml.sax would be very helpful. Thanks in advance Ike -- From dyoo@hkn.eecs.berkeley.edu Fri May 16 17:57:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 16 16:57:01 2003 Subject: [Tutor] user input without return / non-blocking In-Reply-To: Message-ID: On Fri, 16 May 2003 ccollier@viawest.net wrote: > I'm working on a small console based game. I need to be able to accept > input from a user (keyboard/stdin) without having them press return. j > = move left, k = move right etc. > > sys.stdin.read, input, and raw_input don't seem to be the solution I'm > looking for, although sys.stdin.read is close. > > Can anyone point me in the right direction? Hi Cody, Here you go: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 The code from the link provides a function called 'getch()' that should behave the way you expect. But if you're interested in programming games, you might want to look into PyGame as well: http://pygame.org/ It'll let you write graphical games, and provides functions for doing keyboard input too. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Fri May 16 18:18:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 16 17:18:02 2003 Subject: [Tutor] general explanation of xml.sax and its usage In-Reply-To: Message-ID: On Fri, 16 May 2003, Isaac Hall wrote: > I need to be able to parse much more complicated XML into some kind of > python object. I am now looking at the docs for xml.sax, and still, the > docs make it appear more complicated than it probably is. Can anyone > point me to some sample code using xml.sax which is commented, so that I > may see it in use. Or just a smiplified explanation of how to use the > objects in xml.sax would be very helpful. Hi Issac, Have you looked into a DOM approach? DOM parsers take an XML document and create a Python object that looks like a tree. SAX, on the other hand, is something that emits events as it walks across an XML file, so it requires you to maintain the structure of the document manually. Python provides a nice module called pulldom that's sorta a hybrid between SAX and DOM: it is very much a middle ground module between the two. There's a short blurb about it here: http://www.prescod.net/python/pulldom.html and there's also a short article on pulldom on IBM's developerWorks web site: http://www-106.ibm.com/developerworks/xml/library/x-tipulldom.html?dwzone=xml If you want, show us a sample document that you're planning to work with, and we can talk about how one can run through that XML document with an XML parser. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Fri May 16 18:25:04 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 16 17:25:04 2003 Subject: [Tutor] log parser speed optimization [files are iterable] In-Reply-To: <3EC539AA.5050703@devis.com> Message-ID: > the del call is unnecessary. so replace all your pops with the > appropriate slice. > > | while 1: > | line = logfile.readline() > | if not line: > | break > > classic way to read files. also slow. look at xreadlines. Hi Tom, I wouldn't be so sure about the slowness here. I think the code here, as it stands, should perform ok. Intuition about performance is always iffy: we really do need to see the results of a 'profile' before trying to prematurely optimize every corner of the log parser. That being said, let's look at that looping code. *grin* The code above can be rewritten to take advantage of a file's iterability. We can write the top code as: ### for line in logfile: ... ### This may or may not be faster than the original code, but at least it's slightly simpler. This iterating approach works in Python 2.2, and is the preferred way to go line-by-line through a file. 'xreadlines', on the other hand, is about to be deprecated, so we should avoid using it: http://www.python.org/doc/current/lib/module-xreadlines.html Hope this helps! From tjenkins@devis.com Fri May 16 19:03:01 2003 From: tjenkins@devis.com (Tom Jenkins) Date: Fri May 16 18:03:01 2003 Subject: [Tutor] log parser speed optimization [files are iterable] In-Reply-To: References: Message-ID: <3EC55FEE.8030502@devis.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Danny Yoo wrote: | | I wouldn't be so sure about the slowness here. I think the code here, as | it stands, should perform ok. Intuition about performance is always iffy: | we really do need to see the results of a 'profile' before trying to | prematurely optimize every corner of the log parser. | i agree wholeheartedly. rereading what i wrote, realized i didn't say what i thought i said... "There are 2 spots I identified as potential bottlenecks..." could be read as "after running through profile i identified 2 spots as potential bottlenecks..." i didn't run anything through the profiler. What i should have said was... "There are 2 spots the I'm suspicious could be potential bottlenecks..." | preferred way to go line-by-line through a file. 'xreadlines', on the | other hand, is about to be deprecated, so we should avoid using it: ack - -- Tom Jenkins devIS - Development Infostructure http://www.devis.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.0-nr2 (Windows XP) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQE+xV/tV7Yk9/McDYURAlheAJ9sEA8U+TRv4XMaOjGsUwTUGRcCdwCeImX8 A78LO3Xu7ay6RlVM4kt0xK0= =4TXl -----END PGP SIGNATURE----- From phthenry@earthlink.net Fri May 16 19:15:03 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Fri May 16 18:15:03 2003 Subject: [Tutor] general explanation of xml.sax and its usage In-Reply-To: References: Message-ID: <20030516181440.M29954@localhost.localdomain> On Fri, May 16, 2003 at 02:54:57PM -0500, Isaac Hall wrote: > Hi Folks, > > A while back I posted on here asking for ways to parse XML into a python > dictionary. Several people suggested xml.sax, but since the documentation > seemed to be a bit more complex than I really needed (I only needed to get > very simple XML) I abandoned that, and instead wrote my own little script > that just sorted xml into a dictionary by just reading the text. That > worked well for its purpose, and continues to do so. However, now for > another utility, I need to be able to parse much more complicated XML into > some kind of python object. I am now looking at the docs for xml.sax, and > still, the docs make it appear more complicated than it probably is. Can > anyone point me to some sample code using xml.sax which is commented, so > that I may see it in use. Or just a smiplified explanation of how to use > the objects in xml.sax would be very helpful. > > Thanks in advance > Hi Ike I am writing a lot of scripts that use SAX. SAX is very simple to use. The basic idea is that each time the start of an element is found, SAX gives you a name, and a dictionary of attributes. Each time character data is found, it simply gives you the character data. And each time the end of an element is found, SAX gives you the name That is essentially all SAX does. However, it is powerful because it separates content from XML markup. You also don't have to worry about the form of the XML. SAX sees and as identical. Here is an example script that simply copies an XML file. Paul #!/usr/bin/python import xml.sax.saxutils import xml.sax # turn on this line if you want to disablenamespaces ##from xml.sax.handler import feature_namespaces import codecs class CopyTree(xml.sax.saxutils.DefaultHandler): """ A simple class that simply copies a tree """ def __init__(self, write_obj): self.__character = "" self.__write_obj = write_obj def startElement(self, name, attrs): """ Logic: The SAX driver uses this function when if finds a beginning tag. """ self.__write_character() self.__name = name open_tag = '<%s' % name keys = attrs.keys() for key in keys: att = key value = attrs[key] open_tag += ' %s="%s"' % (att, value) open_tag += '>' self.__write_obj.write(open_tag) def __write_character(self): """ Logic: simply writet he block of character data. Note: you could do whatever you wanted with the data. For example, you could say: if self.__name == 'February': return_data = self.__handle_Feb_data() This would allow you to look at data just between certain tags. """ self.__write_obj.write(self.__character) self.__character = '' def characters(self, character): """ Logic: The SAX driver uses this method whenever it finds character data. You do not know how much character data it will dump at a time. It could be one character, on a thousand. """ self.__character += character def endElement(self, name): """ Logic: The SAX driver uses this method whenever it finds the end of an element. """ self.__write_character() self.__write_obj.write('' % name) if __name__ == '__main__': (utf8_encode, utf8_decode, utf8_reader, utf8_writer) = codecs.lookup("utf-8") # create a write object output = '/home/paul/paultemp/test_output.xml' write_obj = utf8_writer(open(output, 'w')) # set up a parser object parser_obj = xml.sax.make_parser() # turn on this line if you want to disable namespaces ##parser.setFeature(feature_namespaces, 0) # create a content_handler object content_handler = CopyTree(write_obj = write_obj) # pass the object you just created to SAX parser_obj.setContentHandler(content_handler) # use SAX to parse the file file = '/home/paul/paultemp/test.xml' parser_obj.parse(file) write_obj.close() -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From python-tutor-list@tagancha.org Fri May 16 19:25:02 2003 From: python-tutor-list@tagancha.org (Alex) Date: Fri May 16 18:25:02 2003 Subject: [Tutor] log parser speed optimization [files are iterable] In-Reply-To: <3EC55FEE.8030502@devis.com> References: <3EC55FEE.8030502@devis.com> Message-ID: <20030516222402.GA15026@purdue.edu> * Tom Jenkins [2003-05-16 18:02:22 -0400]: > Danny Yoo wrote: > | > | I wouldn't be so sure about the slowness here. I think the code here, as > | it stands, should perform ok. Intuition about performance is always iffy: > | we really do need to see the results of a 'profile' before trying to > | prematurely optimize every corner of the log parser. > | > i agree wholeheartedly. rereading what i wrote, realized i didn't say > what i thought i said... > "There are 2 spots I identified as potential bottlenecks..." could be > read as "after running through profile i identified 2 spots as potential > bottlenecks..." > > i didn't run anything through the profiler. What i should have said was... > "There are 2 spots the I'm suspicious could be potential bottlenecks..." > > | preferred way to go line-by-line through a file. 'xreadlines', on the > | other hand, is about to be deprecated, so we should avoid using it: > > ack I apologize, but when "gzip" module is used to open a compressed file I can't just iterate over it. I get an error about iterating over a non-sequence. Hence I have to stick to the original "readline()" method I used, as I understand it because gzipped file is not iterable. Thank you, Alex. -- The lyf so short, the craft so long to lerne. -- Chaucer - Life's not fair, but the root password helps. -- BOFH From Michael Montagne Fri May 16 19:31:31 2003 From: Michael Montagne (Michael Montagne) Date: Fri May 16 18:31:31 2003 Subject: [Tutor] DateTime and MySQLdb Message-ID: <20030516223037.GA26375@boora.com> How do I insert a DateTime object into a datetime column in a mysql table using mysqldb. I have this to start but I know it won't work. odt is a DateTime object. cursor.execute("INSERT INTO readings (readingdate,systolic,diastolic,pulse,comments) VALUES (odt,%d,%d,%d,%s)",(systolic,diastolic,pulse,comments)) -- Michael Montagne http://www.themontagnes.com 503.226.1575 -- From magnus@thinkware.se Fri May 16 19:55:13 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 16 18:55:13 2003 Subject: [Tutor] askopenfilename puzzle In-Reply-To: Message-ID: <5.2.1.1.0.20030517004541.01f5b830@www.thinkware.se> At 00:06 2003-05-15 +0000, Lee Harr wrote: >>I am taking over support on a python script written by a former college. >>The script uses askopenfilename to select a file and everything works fine >>but there's one thing that puzzles me. After the first time you navigate to >>a file it remembers where you were, even after you've exited the program, >>shut down and rebooted the computer. Someplace it's remembering where >you >>last worked and I can't figure out how. >askopenfilename is not a standard python function, so, maybe you >could show us the code for it? Or at least some code? Yes it is! But Tkinter is still poorly documented. It's a function in tkFileDialog.py. I'm not sure this magic happens in Python at all though. I would guess it's Tcl/Tk that manipulates the registry if we're talking Windows. As you can see in tkFileDialog.py, askopenfile uses the class Open, which contains the line: 'command = "tk_getOpenFile"' I think you have to look up tk_getOpenFile in the Tcl/Tk documentation to figure out the magic behind this, although I don't quite see the solution here... >-initialdir directory >Specifies that the files in directory should be displayed when the dialog >pops up. If this parameter is not specified, then the files in the current >working directory are displayed. If the parameter specifies a relative >path, the return value will convert the relative path to an absolute path. >This option may not always work on the Macintosh. This is not a bug. >Rather, the General Controls control panel on the Mac allows the end user >to override the application default directory. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Fri May 16 20:06:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 16 19:06:01 2003 Subject: [Tutor] How to leave literal %s in output of formatted string In-Reply-To: Message-ID: <5.2.1.1.0.20030517010757.01f41dd0@www.thinkware.se> At 10:28 2003-05-15 -0400, Jeff Kowalczyk wrote: >I want to build a format string in code. How do I leave a >literal %s in my string formatting output? I can't find any >escape code for the % character. Did you look in the manual? http://www.python.org/doc/current/lib/typesseq-strings.html -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Fri May 16 20:33:20 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 16 19:33:20 2003 Subject: [Tutor] log parser speed optimization In-Reply-To: <3EC539AA.5050703@devis.com> References: <20030516151640.GA12818@purdue.edu> <20030516151640.GA12818@purdue.edu> Message-ID: <5.2.1.1.0.20030517012959.00bdce00@www.thinkware.se> At 15:19 2003-05-16 -0400, Tom Jenkins wrote: >To find the bottlenecks you need to run through the profiler: Agreed. It might also be a good idea to use the new hotshot profiler. It's included but not documented in 2.2, but I think the "in development docs" will turn out useful. The hotshot profiler is written in C, so profiling is much faster, and has much less impact on the times. On the other hand, it collects more data, so you might end up with a statistics file that is very slow to open... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dyoo@hkn.eecs.berkeley.edu Fri May 16 20:44:10 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 16 19:44:10 2003 Subject: [Tutor] [gzip files can be iterable with some work] In-Reply-To: <20030516222402.GA15026@purdue.edu> Message-ID: On Fri, 16 May 2003, Alex wrote: > > | preferred way to go line-by-line through a file. 'xreadlines', on the > > | other hand, is about to be deprecated, so we should avoid using it: > > I apologize, Hi Alex, No problem, no need to apologize. > but when "gzip" module is used to open a compressed file I can't just > iterate over it. I get an error about iterating over a non-sequence. > Hence I have to stick to the original "readline()" method I used, as I > understand it because gzipped file is not iterable. ??! Yikes. That sounds like a bug; files should support the iterator interface. Checking now... nope, you're right. It looks like the iterator interface for gzip files was neglected in Python 2.2. Let me see if they've fixed it in 2.3... ok, it looks like they fixed the module in Python 2.3. http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Lib/gzip.py?rev=1.34.2.1&content-type=text/vnd.viewcvs-markup So at least the problem is fixed in the future. *grin* But since we're still working in the now, with 2.2, we can still do a workaround. If you want to be able to do: for line in file: we can cook up a customized class that'll do the trick. Here's a module called fileiter that will add iterator support to files that come out of gzip: ### """fileiter: provides iterator support to legacy file-like objects. Danny Yoo (dyoo@hkn.eecs.berkeley.edu) Just call FileIter on your file-like object, and like magic, it'll be iterable! """ class FileIter: """A compatibility class that adds iterator support to a file-like object. The file-like object just needs to support readline().""" def __init__(self, fileobj): """fileobj is the object we wish to wrap our iterator support around.""" self.fileobj = fileobj def __getattr__(self, attr): """Delegates all attribute access to the real file object.""" return getattr(self.fileobj, attr) def __iter__(self): return self def next(self): line = self.readline() if line: return line else: raise StopIteration def opengzip(filename): """Open a gzipped file, and return an iterable file-like object of that file.""" return FileIter(gzip.open(filename)) ### Here's example use of the module: ### >>> import fileiter >>> f = fileiter.opengzip('words.gz') >>> for line in f: ... if line.startswith('foo'): ... print line, ... food foods foodstuff foodstuffs fool fooled foolhardy fooling foolish foolishly foolishness foolproof fools foot footage football footballs footbridge footed footer footers footfall foothill foothold footing footman footnote footnotes footpath footprint footprints footstep footsteps ### I hope this simplifies some of your file-reading code with gzip. Good luck to you! From micforster@yahoo.com Fri May 16 23:37:03 2003 From: micforster@yahoo.com (Mic Forster) Date: Fri May 16 22:37:03 2003 Subject: [Tutor] factorial and vpython Message-ID: <20030517023603.59183.qmail@web13405.mail.yahoo.com> Hello, Factorials can be calculated using vpython: http://www.vpython.org/webdoc/visual/factorial.html Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> from visual.factorial import * Visual-2003-03-15 >>> factorial(5) 120.0 >>> factorial(120) 6.6895029134491239e+198 >>> factorial(10) 3628800.0 __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From jamesdean@hotmail.com Sat May 17 06:55:03 2003 From: jamesdean@hotmail.com (james dean) Date: Sat May 17 05:55:03 2003 Subject: [Tutor] Stdin email question Message-ID: I'm trying to read an email message from stdin. I can get the email headers: headers = rfc822.Message(sys.stdin) I can get the message body: body = sys.stdin.read() but I can't for the life of me get the whole message headers and body in one go. How can I do this please. James _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From bounty_hunter@softhome.net Sat May 17 11:18:02 2003 From: bounty_hunter@softhome.net (Jango Fett) Date: Sat May 17 10:18:02 2003 Subject: [Tutor] using python as scriptin laguage for games Message-ID: <1053181253.27092.8.camel@ns.eht.scu.tur.cu> Im making some research about scripting languages to use with a game project, but i cant find any documentation about how to embed and use a python interpreter in a C application, how to exchange variables between scripts and host application and such things. Can somebody give me an overview about this or point me to a tutorial specifically oriented to using python as scripting language for games? -- Roger D. Vargas ICQ: 117641572 Linux User: 180787 * Much to learn you still have * Master Yoda, AOTC From magnus@thinkware.se Sat May 17 13:15:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 17 12:15:02 2003 Subject: [Tutor] DateTime and MySQLdb In-Reply-To: <20030516223037.GA26375@boora.com> Message-ID: <5.2.1.1.0.20030517172251.01f0de50@www.thinkware.se> At 15:30 2003-05-16 -0700, Michael Montagne wrote: >How do I insert a DateTime object into a datetime column in a mysql >table using mysqldb. Are you talking about mx.DateTime objects? That should work just the same as most other objects. You use %s in the SQL code and put the DateTime object in the parameter list. >I have this to start but I know it won't work. odt is a DateTime object. > >cursor.execute("INSERT INTO readings >(readingdate,systolic,diastolic,pulse,comments) VALUES >(odt,%d,%d,%d,%s)",(systolic,diastolic,pulse,comments)) No, that wouldn't work. There are two problems (apart from the very long line)... You need to do: cursor.execute("""INSERT INTO readings (readingdate, systolic, diastolic, pulse, comments) VALUES (%s, %s, %s, %s, %s)""", (odt, systolic, diastolic, pulse, comments)) (You don't need to break the lines like I did of course, but such long lines as you use makes the code difficult to read.) I.e. you must pass in odt in the same way as the other parameters, and for MySQLdb I think you need to use %s for all parameters, never %d etc. That %s is needed instead of %d is due to a misunder- standing of the DB-API spec, which wasn't perfectly clear. There is currently a discussion about this on the db-sig mailing list. Not only MySQLdb, but also a few other DB interfaces have the same limitation. As you might notice, parameter passing in MySQLdb is very similar to using the normal python %-operator, and in fact it's implemented using that. For instance, having ... >>> a = "Good" >>> b = "Morning" >>> c = "Sir" Consider the difference between... >>> print "a %s, %s!" % (b, c) a Morning, Sir! ... and ... >>> print "%s %s, %s!" % (a, b, c) Good Morning, Sir! The only text inside the SQL-string that is interpreted in some way is the %s (or possibly other % format codes). Writing "...VALUES (odt,..." in the SQL code means that you send the text "odt" instead of a date, and without quoting by the way. That's a syntax error for MySQLdb. But unless you have a completely different MySQLdb module that I have, you will get: "TypeError: an integer is required" before you get near the MySQL engine because they numeric values are cast to strings in the db interface code before they are passed into the SQL string. So first of all: change all %d to %s. Note that "cursor.execute(sql_string, (a,b,c))" is NOT the same as "cursor.execute(sql_string % (a,b,c))" though. Use comma, not percent. The main difference is that strings will be escaped and quoted by the execute method if you pass them in correctly. I.e "can't" will turn into "'can''t'" which is what SQL wants. The downside is that you have to type %s for all parameters, regardless of type, at least for MySQLdb, sqlite and one of the PostgreSQL drivers, but as long as you just remember that, things should work. (Well, *this* should work...there's always another bug lurking around the corner. :) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Sat May 17 13:22:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 17 12:22:01 2003 Subject: [Tutor] Stdin email question In-Reply-To: Message-ID: <5.2.1.1.0.20030517181958.01f0c2d0@www.thinkware.se> At 09:53 2003-05-17 +0000, james dean wrote: >I'm trying to read an email message from stdin. > >I can get the email headers: > > headers = rfc822.Message(sys.stdin) > >I can get the message body: > > body = sys.stdin.read() > > >but I can't for the life of me get the whole message headers and body in >one go. Surely... the_whole_thing = sys.stdin.read() ...will give you the whole shebang if you don't move the file pointer by using "headers = rfc822.Message(sys.stdin)" first? BTW, I think the rfc822 module is a bit old.Maybe you should have a look at the email package instead. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Sat May 17 13:26:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 17 12:26:01 2003 Subject: [Tutor] using python as scriptin laguage for games In-Reply-To: <1053181253.27092.8.camel@ns.eht.scu.tur.cu> Message-ID: <5.2.1.1.0.20030517182419.01f3ba90@www.thinkware.se> At 10:20 2003-05-17 -0400, Jango Fett wrote: >Im making some research about scripting languages to use with a game >project, but i cant find any documentation about how to embed and use a >python interpreter in a C application, how to exchange variables between >scripts and host application and such things. Can somebody give me an >overview about this or point me to a tutorial specifically oriented to >using python as scripting language for games? The general documentation for embedding python in a c program is here: http://python.org/doc/current/ext/embedding.html It's not specifically about games though. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dan_nash@hotmail.com Sat May 17 15:11:01 2003 From: dan_nash@hotmail.com (Daniel Nash) Date: Sat May 17 14:11:01 2003 Subject: [Tutor] Stdin email question Message-ID: >>Surely... >>the_whole_thing = sys.stdin.read() >>...will give you the whole shebang if you don't move the >>file pointer by using "headers = rfc822.Message(sys.stdin)" >>first? Ok so if I do this first, the_whole_thing = sys.stdin.read() then headers = rfc822.Message(sys.stdin) No longer works because of the file pointer How can I fix this? Dan _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From alan.gauld@blueyonder.co.uk Sat May 17 17:14:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat May 17 16:14:01 2003 Subject: [Tutor] using python as scriptin laguage for games References: <1053181253.27092.8.camel@ns.eht.scu.tur.cu> Message-ID: <00d001c31cb0$d55ed690$6401a8c0@xp> > Im making some research about scripting languages to use with a game > project, but i cant find any documentation about how to embed and use a > python interpreter in a C application Hmm, you must be looking in a funny place because the main python web site has lots of info on this. Indeed the standard documentation includes details too. And virtually every book published beyond beginner level has at least one chapter. Try looking on www.python.org Go to the documentation and look under "Extending and Embedding" Also try the SIGs where there is a group looking at C++ bindings for Python, they might be able to help too. Finally try searching GOogle for "Embedding Python in C", I got 11 pages of links and almost all of the first 2 pages were relevant. Finally if you are working on MS Windows you should look at Mark Hammond's O'Reilly book which shows how yto interact with COM from Python and how to embed within C++, Delphi and VB applications. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From mike@daboyz.org Sun May 18 01:09:02 2003 From: mike@daboyz.org (Michael Barrett) Date: Sun May 18 00:09:02 2003 Subject: [Tutor] Counting & Sorting Instances In File In-Reply-To: <3EC2F48F.8080008@ccvcorp.com> References: <20030514214709.GC76924@daboyz.org> <20030514221152.GF76924@daboyz.org> <3EC2F48F.8080008@ccvcorp.com> Message-ID: <20030518040551.GA74005@daboyz.org> Thanks for all your help with this. :) On Wed, May 14, 2003 at 06:59:43PM -0700, Jeff Shannon wrote: > Michael Barrett wrote: > > > The hard (?) part is the sorting. Thats the part I need help with, so > > assume a dictionary of 'Email': count values. If you can think of a > > better way of storing the data in memory for my sort, that'd be > > appreciated as well. Thanks again. > > > > Doing your counting *is* best done with a dictionary, especially if you > make use of the get() method -- > > for line in logfile: > email = parse_email_addr(line) > emailcount[email] = emailcount.get(email, 0) + 1 > > Once you have that dictionary of email:count values, you can convert > that to a list and use the list's built-in sort() method. When sorting > a list where each element is another list (or a tuple), the first > element of the nested list is used to sort on, so the best thing to do > is to ensure that that first element is your count. > > # first, use a list comprehension to create a list of (count, email) pairs > email_list = [ (value, key) for key, value in emailcount.items() ] > # now sort the list > email_list.sort() > # to sort from highest count to lowest count, reverse the list > email_list.reverse() > # now print the first 25 > for count, email in email_list[:25]: > print "%25s %d" % (email, count) > > If there's any of this that doesn't make sense, I can explain in a > little more detail... > > Jeff Shannon > Technician/Programmer > Credit International > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ________________________________________________________________________ Mike Barrett | Calvin: "May Contain Adult Situations?" What mike@daboyz.org | does that mean? www.daboyz.org | Hobbes: Oh, you know. Paying bills. Going | to work. Taking responsibility. ------------------------+----------------------------------------------- From idiot1@netzero.net Sun May 18 02:54:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun May 18 01:54:02 2003 Subject: [Tutor] Stdin email question References: Message-ID: <3EC71EDD.2000600@netzero.net> more. Reading in 'Learning Python', I see many wise words of clarity. you can use sys.stdin.read(), sys.stdin,readline(), or sys.stdin.readlines() message=sys.stdin.readlines() should definately hand you the entire message, MINUS the envlope data, which the smtp server ate for lunch. Now riddle me this: whyfor do you want to grok the entire thing undigested? If you simply want to capture the message for examination, why not just feed it to a file? To do it takes a simple alias: aliasname:/pathtofile/filename the file should be existant, and be writable by your Mail Transmission Agent (MTA, frequently Sendmail). IF THE PATH HAS ANY S P A C E S IN IT, YOU MUST BRACKET IT IN "QUOTES". aliasname:"/path to file/filename" Like that. Hmmm, are you trying to write a mail filtering script??? Or what? (this is getting intresting...) james dean wrote: > > I'm trying to read an email message from stdin. > > I can get the email headers: > > headers = rfc822.Message(sys.stdin) > > I can get the message body: > > body = sys.stdin.read() > > > but I can't for the life of me get the whole message headers and body in > one go. > > How can I do this please. > > James > > _________________________________________________________________ > The new MSN 8: smart spam protection and 2 months FREE* > http://join.msn.com/?page=features/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- end Respectfully, Kirk D Bailey +------------------------------------------------------------+ | Owner Howler Monkey Email: http://www.howlermonkey.net/ | | Inventor of TinyList list server: http://www.tinylist.org/ | | Consulting freestyle Grump: http://www.sacredelectron.org/ | | Remember: When we referr to FREE software, we are talking | | about FREEDOM, not $PRICE$. | +------------------------------------------------------------+ From idiot1@netzero.net Sun May 18 02:54:11 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun May 18 01:54:11 2003 Subject: [Tutor] Stdin email question References: Message-ID: <3EC72086.5050105@netzero.net> Daniel Nash wrote: > >>> Surely... >> > >>> the_whole_thing = sys.stdin.read() >> > >>> ...will give you the whole shebang if you don't move the >>> file pointer by using "headers = rfc822.Message(sys.stdin)" >>> first? >> > > Ok so if I do this first, > > the_whole_thing = sys.stdin.read() > > then > > headers = rfc822.Message(sys.stdin) > > No longer works because of the file pointer > It ate the data, there is nothing there waiting to be delivered, it done got et already by stdin when you did the read. The hunk of data that was sitting there waiting for stdin to swallow done got swallowed already. > How can I fix this? > I *THINK* I know a way, but it's gonna make ya scream. Go read the rfc822 module. SOMEPLACE in there is a sys.stdin.readlines() statement, and it dumps the data into a named variable. NAME YOUR DESTINATION VARIABLE THAT. With any luck you can not invoke something that will read the stdin, which woud of course result in a output of '' (null string) as there is no input pending to read! and THAT would stick '' into all the functions looking at that variable. Anyone with a better idea? It's late, I am firing on 1 cylinder and a large full bent pipe of Carter hall, and my eyeballs itch. > Dan > > _________________________________________________________________ > The new MSN 8: advanced junk mail protection and 2 months FREE* > http://join.msn.com/?page=features/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- end Respectfully, Kirk D Bailey +------------------------------------------------------------+ | Owner Howler Monkey Email: http://www.howlermonkey.net/ | | Inventor of TinyList list server: http://www.tinylist.org/ | | Consulting freestyle Grump: http://www.sacredelectron.org/ | | Remember: When we referr to FREE software, we are talking | | about FREEDOM, not $PRICE$. | +------------------------------------------------------------+ From idiot1@netzero.net Sun May 18 04:17:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun May 18 03:17:02 2003 Subject: [Tutor] line numbering program discloses shebang screw! Message-ID: <3EC733E6.3000201@netzero.net> The shebang is the special first line that the os examines to discover teh path to the intended interpeter for an executable script. Gang, when you ad this to the end of the shebang: # 1 You get all sorts of ungodly commotion and confusion. LINE NUMBERING PROGRAMS WILL KILL SCRIPTS. So I included a test in the numbering loop which tests to see if linecount>1, and it will not add the comment if line number is 1. I am running 1.5.2 until the server upgrade later on next month. Could someone running version 2+ please see if they can kill a script this way? ALSO, measuring the length of a line with len(stringvariable) is not so good, as a tab is 1 char- but displays as 4,6,8, or however you have your virtual terminal set up. The result has that nice collum of numbers at the right edge all over the place, according to how many tabs were spacing out the original COMMENT I had inserted previously. (and the viking corus all inhaled deeply, put down their spam, and as one sang, WELL STOP USING TABS!) Seems I ought to write a program to look for tabs and count them and make adjustments accordingly? -- end Respectfully, Kirk D Bailey +------------------------------------------------------------+ | Owner Howler Monkey Email: http://www.howlermonkey.net/ | | Inventor of TinyList list server: http://www.tinylist.org/ | | Consulting freestyle Grump: http://www.sacredelectron.org/ | | Remember: When we referr to FREE software, we are talking | | about FREEDOM, not $PRICE$. | +------------------------------------------------------------+ From magnus@thinkware.se Sun May 18 04:36:37 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun May 18 03:36:37 2003 Subject: [Tutor] Stdin email question In-Reply-To: <3EC72086.5050105@netzero.net> References: Message-ID: <5.2.1.1.0.20030518093434.01ee79c0@www.thinkware.se> At 01:56 2003-05-18 -0400, Kirk Bailey wrote: >Go read the rfc822 module. >SOMEPLACE in there is a sys.stdin.readlines() statement, and it dumps the >data into a named variable. NAME YOUR DESTINATION VARIABLE THAT. >With any luck you can not invoke something that will read the stdin, which >woud of course result in a output of '' (null string) as there is no input >pending to read! and THAT would stick '' into all the functions looking at >that variable. Don't do this. Relying on the internals of another module means that you violate Parnas' Principle, one of the most important principles in programming. (Search the web for more info.) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From greg@gregmchapman.info Sun May 18 04:39:01 2003 From: greg@gregmchapman.info (Greg Chapman) Date: Sun May 18 03:39:01 2003 Subject: [Tutor] line numbering program discloses shebang screw! Message-ID: >(and the viking corus all inhaled deeply, put down their spam, and as one sang, > WELL STOP USING TABS!) I thought that was scripture by now. :) >Seems I ought to write a program to look for tabs and count them and make adjustments >accordingly? my python 2.2 distro (ActiveState for win32) has a script 'untabify.py' that does just that. I don't know if it's in the standard distro or if that's something that ActiveState added. but it might be worth looking. greg From magnus@thinkware.se Sun May 18 04:48:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun May 18 03:48:02 2003 Subject: [Tutor] Stdin email question In-Reply-To: Message-ID: <5.2.1.1.0.20030518093946.01f52620@www.thinkware.se> At 14:10 2003-05-17 -0400, Daniel Nash wrote: >Ok so if I do this first, > >the_whole_thing = sys.stdin.read() > >then > >headers = rfc822.Message(sys.stdin) > >No longer works because of the file pointer > >How can I fix this? Just put "sys.stdin.seek(0)" between. Then you can place your reads in whatever order you like. "seek" will move the current position in a file or file-like object. It's like wind/rewind on a VCR. It has a sister called "tell" that informs you of the current position. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From gerrit@nl.linux.org Sun May 18 05:18:02 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Sun May 18 04:18:02 2003 Subject: [Tutor] line numbering program discloses shebang screw! In-Reply-To: <3EC733E6.3000201@netzero.net> References: <3EC733E6.3000201@netzero.net> Message-ID: <20030518081633.GA2470@nl.linux.org> Kirk Bailey schreef op zondag 18 mei om 09:18:19 +0000: > I am running 1.5.2 until the server upgrade later on next month. Could > someone running version 2+ please see if they can kill a script this way? It's the same: 10:13:58:2:gerrit@stopcontact:/tmp$ ./hello.py /usr/bin/python: can't open file '# 1' 10:13:59:2:gerrit@stopcontact:/tmp$ cat hello.py #!/usr/bin/python # 1 print "Hello, world!" # 2 I'm not sure whether Python can do anything against this. I don't think it can. > Seems I ought to write a program to look for tabs and count them and make > adjustments accordingly? Aren't you just looking for tabnanny? tabnanny -- Detection of ambiguous indentation For the time being this module is intended to be called as a script. However it is possible to import it into an IDE and use the function check() described below. Warning: The API provided by this module is likely to change in future releases; such changes may not be backward compatible. yours, Gerrit. -- 165. If a man give to one of his sons whom he prefers a field, garden, and house, and a deed therefor: if later the father die, and the brothers divide the estate, then they shall first give him the present of his father, and he shall accept it; and the rest of the paternal property shall they divide. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From summariesofhate@comcast.net Sun May 18 16:28:03 2003 From: summariesofhate@comcast.net (TERRENCE WALKER) Date: Sun May 18 15:28:03 2003 Subject: [Tutor] Newbie python programmer here. Message-ID: <849de384b3e8.84b3e8849de3@icomcast.net> Hi everyone, I just started programming in python and just started subscribing to this mailing list as well. I look forward to gathering and sharing ideas and learning too. Anyhow, here is my first question. I have a function that is supposed to reverse all the letters in a word. That is what I want it to do anyhow. I can't seem to get it right. What am I doing wrong? def reverse(name): name = "aname" for i in name: print i[-1] I know this is trivial to you more experienced people. But I really want to learn this language. Thanks for the help. Jarrod p.s. this mail will always have the name Terrence on it my name is Jarrod. From Janssen@rz.uni-frankfurt.de Sun May 18 17:24:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sun May 18 16:24:02 2003 Subject: [Tutor] Newbie python programmer here. In-Reply-To: <849de384b3e8.84b3e8849de3@icomcast.net> Message-ID: On Sun, 18 May 2003, TERRENCE WALKER wrote: > Hi everyone, I just started programming in python and just started Hi Jarrod, nice to meet you. > subscribing to this mailing list as well. I look forward to gathering > and sharing ideas and learning too. Anyhow, here is my first question. > I have a function that is supposed to reverse all the letters in a word. > That is what I want it to do anyhow. I can't seem to get it right. What > am I doing wrong? A good exercise for the beginner (because it has to do with for-loops and builtins datatypes). Since the standard-library has already a function to do this (string.swapcase) it would be nonsense to recode it comlpetly for you (that means take you the possibility to learn). So I give just some hints and you're free to chat with us about further problems, experiences: 1. name = "aname": Its overwrites "name" in any case and you can't give another "name" as a parameter to the function (I assume this was clear to you and meant for testing). 2. "print" automatically append newline-character. This is why the output is scattered over severall lines. Even surpressing the newline with a trailing comma ("print i,") doesn't help much, because print continues to seperate the output via spaces. Solutions are: write directly to "standart out" via sys.stdout.write(i) (This means: use the "write" method of the "file-like-object" stdout provideed by the "sys modul) or gather the characters into a new helper-string and print it out as whole: for i in name: helper = "" helper = "" + i print helper 3. i[-1] (take the last character from a sequence of characters) is needless, because i is set to a single character within the for loop. 4. You need some logic to turn the case (of course ;-). Look out for "isupper" and "islower" string-methods: {Python-Doc}/lib/string-methods.html Michael > > def reverse(name): > name = "aname" > for i in name: > print i[-1] > > I know this is trivial to you more experienced people. But I really want > to learn this language. Thanks for the help. > > Jarrod > p.s. this mail will always have the name Terrence on it my name is Jarrod. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dbroadwell@mindspring.com Sun May 18 17:55:01 2003 From: dbroadwell@mindspring.com (David Broadwell) Date: Sun May 18 16:55:01 2003 Subject: [Tutor] Newbie python programmer here. In-Reply-To: <849de384b3e8.84b3e8849de3@icomcast.net> Message-ID: TERRENCE-jarrod wrote: Hi everyone, I just started programming in python and just started subscribing to this mailing list as well. I look forward to gathering and sharing ideas and learning too. Anyhow, here is my first question. I have a function that is supposed to reverse all the letters in a word. That is what I want it to do anyhow. I can't seem to get it right. What am I doing wrong? def reverse(name): name = "aname" for i in name: print i[-1] Well: let's look at what your code really does: a n a m e First you define reverse as being called with name, yet in the next line, overwrite it with a string. Not good if you intend to reverse anything but aname, but not bad as a testing idea, just skip the calling with name. It iterates through it forward, not bad that is one way. def reverse(): or skip specifically assigning name to 'aname' and call reverse('aname') instead. So given the string 'aname' how can we iterate through it backwards? What do we know about it: >>> name = 'aname' >>> len(name) 5 Hm, 5 units in length. How about: >>> length = len(name) >>> while length > 0: # print the character between length and length-1 print name[length-1:length] length = length -1 # we've been here decrease length e m a n a which as a function looks like: def reverse(name): ''' this function reverses a string and prints it. ''' length = len(name) while length > 0: # print the character between length and length-1 print name[length-1:length] length = length -1 # we've been here decrease length return 1 Well I did skip a few steps to get to that logic. So I recommend starting up the interpreter, and seeing what slices can do for you. There are about as many ways to solve this problem as there are programmers. Complete with using the built in list.reverse() str.join, but slices are strait-forward and easy to test. Also, I recommend at least as many good tutorials as you can read starting on www.python.org. Good luck. > p.s. this mail will always have the name Terrence on it my name is Jarrod. Why? -- David Broadwell From magnus@thinkware.se Sun May 18 18:12:07 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun May 18 17:12:07 2003 Subject: [Tutor] Newbie python programmer here. In-Reply-To: <849de384b3e8.84b3e8849de3@icomcast.net> Message-ID: <5.2.1.1.0.20030518225610.01f50dd0@www.thinkware.se> At 12:26 2003-05-18 -0700, TERRENCE WALKER wrote: >I have a function that is supposed to reverse all the letters in a word. The typical Python way to do this is to turn the string into a list, reverse the list, and then turn the list into a string. >>> def revString(s): ... l = list(s) ... l.reverse() ... return "".join(l) ... >>> print revString('Hello') olleH That "list(s)" turns any given sequence (for instance a string) into a list is not so strange I guess. You should note that the string-methods .reverse() (and .sort()) modifies the actual object they are applied to. It's common for methods to return a result, and many people expect reverse to return the reversed list. In that case you would do "myReversedList = myList.reverse()", but this doesn't work. The reason is that lists might be very big. If reverse and sort always returned a new list, you might waste a lot of memory. Thus, they modify the current list. If you want to keep the unreversed list, you need to make a copy, and reverse that. The third line is a bit odd. Strings have methods that return new strings. aString.join(aList) means "Join all strings (or characters) in aList with me (aString in this case) as separator between them. In other words, using the empty string "".join(l) will turn l into a string. One day, you might want to use your reversed string without printing it, so it's probably better to make a function that returns the reveresed string, and to have the print statement outside that. It makes the function useful in more situations. Thus we return the reversed string, instead of printing it inside the function. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From hillcino368@hotmail.com Sun May 18 18:17:01 2003 From: hillcino368@hotmail.com (cino hilliard) Date: Sun May 18 17:17:01 2003 Subject: [Tutor] Newbie python programmer here. Message-ID: Hi Terrence, Try This: def reverse(name): ln = len(name)-1 # Range starts with 0. Have to compensate rstr = "" for i in range(ln): rstr = rstr + name[ln-i] print name[ln-i]; print name[0] # Range starts with 0 rstr = rstr + name[0] print rstr Python 2.3a1 (#38, Dec 31 2002, 17:53:59) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>from reverse import * >>>reverse("123456789") 9 8 7 6 5 4 3 2 1 987654321 >>> 2^3 + 13^3 + 33^3 + 43^3 = 49^3 >From: TERRENCE WALKER >To: tutor@python.org >Subject: [Tutor] Newbie python programmer here. >Date: Sun, 18 May 2003 12:26:43 -0700 > >Hi everyone, I just started programming in python and just started >subscribing to this mailing list as well. I look forward to gathering >and sharing ideas and learning too. Anyhow, here is my first question. >I have a function that is supposed to reverse all the letters in a word. >That is what I want it to do anyhow. I can't seem to get it right. What >am I doing wrong? > >def reverse(name): > name = "aname" > for i in name: > print i[-1] > >I know this is trivial to you more experienced people. But I really want >to learn this language. Thanks for the help. > >Jarrod >p.s. this mail will always have the name Terrence on it my name is Jarrod. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From adam@bostoncoop.net Sun May 18 23:09:50 2003 From: adam@bostoncoop.net (Adam Kessel) Date: Sun May 18 22:09:50 2003 Subject: [Tutor] Custom (non-standard) SGML Parser and OOP Problem Message-ID: <20030518195541.GA2824@joehill.bostoncoop.net> --azLHFNyN32YCQGCU Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable I'm writing a custom SGML parser. I started to do it from scratch, but then it occurred to me that I ought not to reinvent the wheel (the wheel being sgmllib). =20 I want to use sgmllib-like parsing, but I only want to recognize tags matching: <$tag$> sgmllib is, of course, looking for <[A-Za-z] to start tags, so these sorts of tags are not detected. I'd also like to not have to deal with any tags other than <$tag$>. I discovered I could violate a central tenet of OOP and get this to work, by putting the following in my code: sgmllib.starttagopen =3D re.compile('<[>\$]') (etc.) That is, overwriting the regexps used in sgmllib to locate tags. But this seems like a dangerous way to do things. Putting the following in my parser __init__ doesn't work: self.starttagopen =3D re.compile('<[>\$]') Because starttagopen is not defined in sgmllib.SGMLParser, but in sgmllib itself. =20 What's the right way to do this? My question, boiled down, is: how to use sgmllib functionality but overwrite sgmllib internals without being a bad programmer? =20 --Adam Kessel --azLHFNyN32YCQGCU Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQE+x+U9dTf3ZklQ6qYRAkOAAKDIbN0CzQEucydygpxBdZMK+6muBgCdGbuI +JlGIZaxcM6p2auKnqxh71c= =LFg/ -----END PGP SIGNATURE----- --azLHFNyN32YCQGCU-- From idiot1@netzero.net Sun May 18 23:26:35 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun May 18 22:26:35 2003 Subject: [Tutor] detab to delouse before de numbers go in (groan) Message-ID: <3EC81918.8020802@netzero.net> ok, files using taqbs confuse composition software. So we pull them out and insert spaces instead. def removetabs(string1): outstring='' for x in string1: if x=='\t': x=' ' outstring=outstring+x return outstring read in a file you wish to add line numbers to into a list variable, and walk the list with this routine. THEN do the line numbering ritual with full viking garb and chorus. AND DON'T NUMBER LINE 1!!!!!!!!!!! -- end Respectfully, Kirk D Bailey +------------------------------------------------------------+ | Owner Howler Monkey Email: http://www.howlermonkey.net/ | | Inventor of TinyList list server: http://www.tinylist.org/ | | Consulting freestyle Grump: http://www.sacredelectron.org/ | | Remember: When we referr to FREE software, we are talking | | about FREEDOM, not $PRICE$. | +------------------------------------------------------------+ From dyoo@hkn.eecs.berkeley.edu Mon May 19 03:08:00 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 19 02:08:00 2003 Subject: [Tutor] Stdin email question [sys.stdin is unseekable / try StringIO] In-Reply-To: <5.2.1.1.0.20030518093946.01f52620@www.thinkware.se> Message-ID: On Sun, 18 May 2003, Magnus [iso-8859-1] Lyck=E5 wrote: > At 14:10 2003-05-17 -0400, Daniel Nash wrote: > >Ok so if I do this first, > > > >the_whole_thing =3D sys.stdin.read() > > > >then > > > >headers =3D rfc822.Message(sys.stdin) > > > >No longer works because of the file pointer > > > >How can I fix this? > > Just put "sys.stdin.seek(0)" between. Then you can place your reads in > whatever order you like. "seek" will move the current position in a file > or file-like object. It's like wind/rewind on a VCR. It has a sister > called "tell" that informs you of the current position. Hi everyone, This would work... except that it's 'sys.stdin': Python itself doesn't know how to travel in time! ### >>> import sys >>> sys.stdin.seek(0) Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 29] Illegal seek ### More formally, we'd say that sys.stdin is a file-like object that's not "seekable". So trying to rewind our standard input to the beginning is a no-go. I think this only affects special file-like objects like sys.stdin and sys.stdout; if it were a regular vanilla file, the seek() would be applicable. (The limitation is a technical issue: if sys.stdin were seekable, then Python would have to memorize everything that came through sys.stdin. To do this in the general case would be prohibitively expensive --- even with gigabytes of memory --- so that's why it doesn't let us seek() stdin.) > >Ok so if I do this first, > >the_whole_thing =3D sys.stdin.read() > >then > >headers =3D rfc822.Message(sys.stdin) > > > >No longer works because of the file pointer > > > >How can I fix this? We know now that sys.stdin is unseekable. However, there is a a workaround: one way we can fix this is to use an intermediate file object that can be seek()ed. There's a way of disguising a string as a file through the "StringIO" module: http://www.python.org/doc/lib/module-StringIO.html StringIO's one of those modules that looks really odd the first time we see it, but it's useful for a case like this: ### from StringIO import StringIO the_whole_thing =3D sys.stdin.read() msg_file =3D StringIO(msg_file) headers =3D rfc822.Message(msg_file) ### And now we can safely do a msg_file.seek(0) here to retrieve the original message body. Since our 'file-like' object is a string, Python has no problems seeking through it. Out of curiosity, though: have you seen the 'fp' attribute that's in our message object? rfc822.Message doesn't just give us the headers: the message body does live in there too. The bottom of: http://www.python.org/doc/lib/message-objects.html briefly mentions it. So we might be able to do something like this: ### from StringIO import StringIO the_whole_thing =3D sys.stdin.read() msg_file =3D StringIO(msg_file) msg =3D rfc822.Message(msg_file) print "The body of our message is:", msg.fp.read() print "And here are our headers:", msg.headers ### Hope this clears things up! If you have more questions, please feel free to ask. From dyoo@hkn.eecs.berkeley.edu Mon May 19 03:12:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 19 02:12:01 2003 Subject: [Tutor] Stdin email question [sys.stdin is unseekable / try StringIO] In-Reply-To: Message-ID: > StringIO's one of those modules that looks really odd the first time we > see it, but it's useful for a case like this: > > > ### > from StringIO import StringIO > > the_whole_thing = sys.stdin.read() > msg_file = StringIO(msg_file) ^^^^^^^^ > headers = rfc822.Message(msg_file) > ### Argh. And it would look less odd if I didn't mess up the example too. *grin* Please forgive me. I meant to write: ### from StringIO import StringIO the_whole_thing = sys.stdin.read() msg_file = StringIO(the_whole_thing) headers = rfc822.Message(msg_file) ### The same correction applies here: > from StringIO import StringIO > > the_whole_thing = sys.stdin.read() > msg_file = StringIO(msg_file) > msg = rfc822.Message(msg_file) > > print "The body of our message is:", msg.fp.read() > print "And here are our headers:", msg.headers This should be: ### from StringIO import StringIO the_whole_thing = sys.stdin.read() msg_file = StringIO(the_whole_thing) msg = rfc822.Message(msg_file) print "The body of our message is:", msg.fp.read() print "And here are our headers:", msg.headers ### Again, my apologies. From dyoo@hkn.eecs.berkeley.edu Mon May 19 03:27:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 19 02:27:02 2003 Subject: [Tutor] using python as scriptin laguage for games In-Reply-To: <00d001c31cb0$d55ed690$6401a8c0@xp> Message-ID: On Sat, 17 May 2003, Alan Gauld wrote: > > Im making some research about scripting languages to use with a game > > project, but i cant find any documentation about how to embed and use > > a python interpreter in a C application > > Hmm, you must be looking in a funny place because the main python web > site has lots of info on this. Indeed the standard documentation > includes details too. And virtually every book published beyond beginner > level has at least one chapter. Hi everyone, At the same time, some people might say that embedding Python in another application is a slightly advanced topic. *grin* (Side note: during the last Baypiggies meeting, someone had mentioned that the popular RPG 'Freedom Force' uses Python as it's scripting engine, so there's a practical real-world example of embedding Python in a game.) Jango, there's a article on Gamesutra on embedding Python in a game: http://www.gamasutra.com/features/20020821/dawson_pfv.htm I think the original presentation is here: http://www.cygnus-software.com/papers/gamescriptinginpython.html Let's see... Googling for more on this topic brings up a book called "Game Programming with Python" that's coming out this October! http://www.charlesriver.com/titles/pythongame.html Too bad that the future isn't here yet. *grin* Finally, there a link to this subject on PythonWiki, http://www.python.org/cgi-bin/moinmoin/GameProgramming I hope this helps! From magnus@thinkware.se Mon May 19 06:47:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 19 05:47:02 2003 Subject: [Tutor] detab to delouse before de numbers go in (groan) In-Reply-To: <3EC81918.8020802@netzero.net> Message-ID: <5.2.1.1.0.20030519113106.01f66ef8@www.thinkware.se> At 19:36 2003-05-18 -0400, Kirk Bailey wrote: >ok, files using taqbs confuse composition software. So we pull them out >and insert spaces instead. > >def removetabs(string1): > outstring='' > for x in string1: > if x=='\t': > x=' ' > outstring=outstring+x > return outstring This won't do the right thing if there is a mix of tabs and spaces in the code. For Python, the following are all equivalent: a=5 a=5 a=5 a=5 Tab doesn't move a certain amount of positions forward, it fills up to the next column with a position that is evenly divisible by 8. But you don't need any advanced code to fix that. Know thy library! >>> help(str.expandtabs) Help on method_descriptor: expandtabs(...) S.expandtabs([tabsize]) -> string Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. The simplest way to convert a file is to use the supplied script in the python source distribution: Tools/scripts/untabify.py It's in ActivePython, but I don't know if it's in other binary distributions. It's certainly in CVS though. http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Tools/scripts/untabify.py -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Mon May 19 07:01:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 19 06:01:01 2003 Subject: [Tutor] Custom (non-standard) SGML Parser and OOP Problem In-Reply-To: <20030518195541.GA2824@joehill.bostoncoop.net> Message-ID: <5.2.1.1.0.20030519114943.01f66d48@www.thinkware.se> At 15:55 2003-05-18 -0400, Adam Kessel wrote: >What's the right way to do this? My question, boiled down, is: how to >use sgmllib functionality but overwrite sgmllib internals without being a >bad programmer? I don't know if there is a perfect way, since you are obviously bending sgmllib into being something it's not supposed to be. What you want to parse isn't legal SGML, right? I guess you could simply make a copy of sgmllib, call it something else, and modify that. Then you won't be affected if sgmllib changes its implementation so that your fix will no longer apply. I think that's the best solution. The backside is that you won't get improvements to sgmllib available to your code, but maybe that's not a big loss. Since markupbase is not a documented module, but internal for sgmllib and HTMLParser, you'd better make a renamed copy of that as well and import and use that in your modified version of sgmllib. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Mon May 19 07:16:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 19 06:16:01 2003 Subject: [Tutor] Stdin email question [sys.stdin is unseekable / try StringIO] In-Reply-To: References: <5.2.1.1.0.20030518093946.01f52620@www.thinkware.se> Message-ID: <5.2.1.1.0.20030519120846.01f34c88@www.thinkware.se> At 23:06 2003-05-18 -0700, Danny Yoo wrote: >This would work... except that it's 'sys.stdin': Python itself doesn't >know how to travel in time! That's what I thought, and I was just about to write about StringIO, but then I made a small test, it worked! [mly@kaunas tmp]$ python r2.py < r2.py import sys print sys.stdin.read() print sys.stdin.tell() sys.stdin.seek(0) print sys.stdin.tell() print sys.stdin.read() 122 0 import sys print sys.stdin.read() print sys.stdin.tell() sys.stdin.seek(0) print sys.stdin.tell() print sys.stdin.read() This works both in Unix and in Win2k. But it obviously depends on how you pass things in to stdin... (Which isn't so strange if you think about it. sys.stdin is just a filedescriptor. What's special isn't the filedescriptor, but what you pass to it. A pipe and a file is not the same...) [mly@kaunas tmp]$ cat r2.py | python r2.py import sys print sys.stdin.read() print sys.stdin.tell() sys.stdin.seek(0) print sys.stdin.tell() print sys.stdin.read() Traceback (most recent call last): File "r2.py", line 3, in ? print sys.stdin.tell() IOError: [Errno 29] Illegal seek In Windows 2000, it's more devious, because there if fails without any error message: P:\python\tmp>type r2.py | python r2.py import sys print sys.stdin.read() print sys.stdin.tell() sys.stdin.seek(0) print sys.stdin.tell() print sys.stdin.read() 0 0 I humbly apologize... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From charlie@begeistert.org Mon May 19 07:35:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Mon May 19 06:35:01 2003 Subject: [Tutor] Custom (non-standard) SGML Parser and OOP Problem In-Reply-To: <20030519100101.4537.38088.Mailman@mail.python.org> References: <20030519100101.4537.38088.Mailman@mail.python.org> Message-ID: <20030519123515.2995.6@wonderland.1053326580.fake> On 2003-05-19 at 12:01:01 [+0200], tutor-request@python.org wrote: > I discovered I could violate a central tenet of OOP and get this to work, > by putting the following in my code: > > sgmllib.starttagopen =3D re.compile('<[>\$]') > (etc.) > > That is, overwriting the regexps used in sgmllib to locate tags. But this > seems like a dangerous way to do things. Putting the following in my > parser __init__ doesn't work: > > self.starttagopen =3D re.compile('<[>\$]') > > Because starttagopen is not defined in sgmllib.SGMLParser, but in sgmllib > itself. =20 > > What's the right way to do this? My question, boiled down, is: how to > use sgmllib functionality but overwrite sgmllib internals without being a > bad programmer? Good question. I think you're approach is pretty good and I don't think it's violating too much. When you import something you get your own copy to do with as you will and you can overwrite module functions just like you do class methods. What you might want to do is make sure it is clear that you are customizing and use import as to give the module a special name import sgmllib as custom_sgml custom_sgml.starttagopen = re.compile('<[>\$]') That signals to anyone reading the code that you're doing something funny. Charlie From pythonhuangwei@yahoo.com.cn Mon May 19 10:25:02 2003 From: pythonhuangwei@yahoo.com.cn (=?gb2312?q?wei=20huang?=) Date: Mon May 19 09:25:02 2003 Subject: [Tutor] how to learn programming,and how to use python as the first one u program? Message-ID: <20030518142235.2325.qmail@web15101.mail.bjs.yahoo.com> --0-1859617990-1053267755=:769 Content-Type: text/plain; charset=gb2312 Content-Transfer-Encoding: 8bit i am a new learner, even do not have much knowledge in C & C++ i will be very appreciated if some one tell me which book i should read ps:this is my first mail in the mail list,thanks all --------------------------------- Do You Yahoo!? "Ïà¼û²»ÈçÁÄÌì!²»³öÃÅÒ»ÑùÃæ¶ÔÃ棡ÍøÂçÉãÏñÍ·¶Ô¶ÔÅÉËÍÖÐ~¸Ï¿ìÓÃÄãµÄÑÅ»¢µçÓÊÕʺŲÎÓë°É¡­¡­ --0-1859617990-1053267755=:769 Content-Type: text/html; charset=gb2312 Content-Transfer-Encoding: 8bit
i am a new learner, even do not have much knowledge in C & C++
i will be very appreciated if some one tell me which book i should read
ps:this is my first mail in the mail list,thanks all



Do You Yahoo!?
"Ïà¼û²»ÈçÁÄÌì!²»³öÃÅÒ»ÑùÃæ¶ÔÃ棡ÍøÂçÉãÏñÍ·¶Ô¶ÔÅÉËÍÖÐ~¸Ï¿ìÓÃÄãµÄÑÅ»¢µçÓÊÕʺŲÎÓë°É¡­¡­ --0-1859617990-1053267755=:769-- From rob@jam.rr.com Mon May 19 10:38:01 2003 From: rob@jam.rr.com (Rob Andrews) Date: Mon May 19 09:38:01 2003 Subject: [Tutor] how to learn programming,and how to use python as the first one u program? In-Reply-To: <20030518142235.2325.qmail@web15101.mail.bjs.yahoo.com> References: <20030518142235.2325.qmail@web15101.mail.bjs.yahoo.com> Message-ID: <3EC8DE64.9070205@jam.rr.com> wei huang wrote: > i am a new learner, even do not have much knowledge in C & C++ i will > be very appreciated if some one tell me which book i should read > ps:this is my first mail in the mail list,thanks all Welcome! You don't have to start with a book, although there are some really good ones available now. http://www.freenetpages.co.uk/hp/alan.gauld has some very nice material for someone learning programming in Python from scratch. (And it has a book version, as well, which may interest you.) There are also quite a few other Python tutorials of different kinds available. And, of course, we're happy to help on the list. -Rob Andrews From ovidiu.bivolaru@ravantivirus.com Mon May 19 11:35:02 2003 From: ovidiu.bivolaru@ravantivirus.com (Ovidiu Bivolaru) Date: Mon May 19 10:35:02 2003 Subject: [Tutor] Regexp question Message-ID: <1053354615.6181.2.camel@ovidiu.rav.local> --=-qYenDobwLOVqa9A6RZ1C Content-Type: text/plain Content-Transfer-Encoding: quoted-printable Hi all, I'm trying to parse some HTML forms to get the values from "name" and "value" attributes and then to add them in a list. I'm encountering a problem with the regular expressions and I can't figure out why the expression is invalid. Bellow is the code that I'm using: for lines in buffer.readlines(): print lines regexp =3D 'value=3D"(.*)?"\s*name\s*=3D\s*"(.*:\d+:\d+)?"' print regexp p =3D re.search(regexp,lines) The error message is: p =3D re.search(regexp,lines) File "/usr/lib/python2.2/sre.py", line 137, in search return _compile(pattern, flags).search(string) File "/usr/lib/python2.2/sre.py", line 229, in _compile raise error, v # invalid expression error: nothing to repeat Can anybody tell me what is wrong with the regular expression?? Also, are any other possibilities to parse the HTML using functions already implemented (i.e. HTMLPasrse module) ?? Thanks, Ovidiu --=-qYenDobwLOVqa9A6RZ1C Content-Type: application/pgp-signature; name=signature.asc Content-Description: This is a digitally signed message part -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQA+yOp3jQG4unFXu9sRAjVgAJ9E3QPIemKJXP6FCR1OdPjc/ELo5wCgpGYH S8bYTcsu6mv6VQW+X3vekow= =oeCQ -----END PGP SIGNATURE----- --=-qYenDobwLOVqa9A6RZ1C-- From krier115@student.liu.se Mon May 19 11:51:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Mon May 19 10:51:02 2003 Subject: [Tutor] Regexp question In-Reply-To: <1053354615.6181.2.camel@ovidiu.rav.local> References: <1053354615.6181.2.camel@ovidiu.rav.local> Message-ID: <20030519144954.GA21128@n14.ryd.student.liu.se> On Mon, May 19, 2003 at 05:30:15PM +0300, Ovidiu Bivolaru wrote: > Hi all, > > I'm trying to parse some HTML forms to get the values from "name" and > "value" attributes and then to add them in a list. I'm encountering a > problem with the regular expressions and I can't figure out why the > expression is invalid. > > Bellow is the code that I'm using: > for lines in buffer.readlines(): > print lines > regexp = 'value="(.*)?"\s*name\s*=\s*"(.*:\d+:\d+)?"' > print regexp > p = re.search(regexp,lines) > > The error message is: > p = re.search(regexp,lines) > File "/usr/lib/python2.2/sre.py", line 137, in search > return _compile(pattern, flags).search(string) > File "/usr/lib/python2.2/sre.py", line 229, in _compile > raise error, v # invalid expression > error: nothing to repeat > > Can anybody tell me what is wrong with the regular expression?? Also, > are any other possibilities to parse the HTML using functions already > implemented (i.e. HTMLPasrse module) ?? > The first '?' in your regexp shouldn't be there. Since '*' means "0 or more times" the part "(.*)?" of your regexp says "(any character zero or more times) zero or one time", using some weird paranthesis-notation. So remove that '?' and you won't get the error message. Note that I haven't checked your regexp so it matches what you think, I just got rid of the error message. HTH, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From ovidiu.bivolaru@ravantivirus.com Mon May 19 12:00:02 2003 From: ovidiu.bivolaru@ravantivirus.com (Ovidiu Bivolaru) Date: Mon May 19 11:00:02 2003 Subject: [Tutor] Regexp question In-Reply-To: <20030519144954.GA21128@n14.ryd.student.liu.se> References: <1053354615.6181.2.camel@ovidiu.rav.local> <20030519144954.GA21128@n14.ryd.student.liu.se> Message-ID: <1053356102.6239.4.camel@ovidiu.rav.local> --=-gN7Gv/TbSH+7XjSyYVgG Content-Type: text/plain Content-Transfer-Encoding: quoted-printable Thanks a lot :) !! That's it ! Regards, Ovidiu On Mon, 2003-05-19 at 17:49, Kristoffer Erlandsson wrote: > On Mon, May 19, 2003 at 05:30:15PM +0300, Ovidiu Bivolaru wrote: > > Hi all, > >=20 > > I'm trying to parse some HTML forms to get the values from "name" and > > "value" attributes and then to add them in a list. I'm encountering a > > problem with the regular expressions and I can't figure out why the > > expression is invalid. > >=20 > > Bellow is the code that I'm using: > > for lines in buffer.readlines(): > > print lines > > regexp =3D 'value=3D"(.*)?"\s*name\s*=3D\s*"(.*:\d+:\d+)?"' > > print regexp > > p =3D re.search(regexp,lines) > >=20 > > The error message is: > > p =3D re.search(regexp,lines) > > File "/usr/lib/python2.2/sre.py", line 137, in search > > return _compile(pattern, flags).search(string) > > File "/usr/lib/python2.2/sre.py", line 229, in _compile > > raise error, v # invalid expression > > error: nothing to repeat > >=20 > > Can anybody tell me what is wrong with the regular expression?? Also, > > are any other possibilities to parse the HTML using functions already > > implemented (i.e. HTMLPasrse module) ?? > >=20 >=20 > The first '?' in your regexp shouldn't be there. Since '*' means "0 or > more times" the part "(.*)?" of your regexp says "(any character zero or > more times) zero or one time", using some weird paranthesis-notation. So > remove that '?' and you won't get the error message. Note that I haven't > checked your regexp so it matches what you think, I just got rid of the > error message. >=20 > HTH, > Kristoffer --=-gN7Gv/TbSH+7XjSyYVgG Content-Type: application/pgp-signature; name=signature.asc Content-Description: This is a digitally signed message part -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) iD8DBQA+yPBGjQG4unFXu9sRAnpwAJ0ZN2GQoA3vNI8Ezdm+R2Plh+QSyQCfeMmp bWCXeMbkXDusk93sb3ywOss= =CvGP -----END PGP SIGNATURE----- --=-gN7Gv/TbSH+7XjSyYVgG-- From magnus@thinkware.se Mon May 19 12:37:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 19 11:37:01 2003 Subject: [Tutor] Regexp question In-Reply-To: <1053354615.6181.2.camel@ovidiu.rav.local> Message-ID: <5.2.1.1.0.20030519170209.00b4e998@www.thinkware.se> At 17:30 2003-05-19 +0300, Ovidiu Bivolaru wrote: >Hi all, > >I'm trying to parse some HTML forms to get the values from "name" and >"value" attributes and then to add them in a list. I'm encountering a >problem with the regular expressions and I can't figure out why the >expression is invalid. > >Bellow is the code that I'm using: > for lines in buffer.readlines(): > print lines > regexp = 'value="(.*)?"\s*name\s*=\s*"(.*:\d+:\d+)?"' In general you need to double your backslashes or use raw strings, or python will try to interpret bacslashes instead of passing them to the re module. In these particular cases I don't think it matters, because \s and \d don't mean anything, but in general, using raw strings for re's is best. Also, and more importantly in this case, for non-greedy searches, the ? should come directly after the + or *; not after the ) which ends the group. Also, it's the '.*' which is nasty! In other words: regexp = r'value="(.*?)"\s*name\s*=\s*"(.*?:\d+:\d+)"' The ? to make the .*'s non-greedy are important as soon as there is more than one possible match in the code: >>> import re >>> regexp = r'value="(.*)"\s*name\s*=\s*"(.*:\d+:\d+)"' >>> x = 'value="x1" name="y1:1:2" value="x2" name="y2:1:2"' >>> re.findall(regexp, x) [('x1" name="y1:1:2" value="x2', 'y2:1:2')] Oops! By default re's try to match as much as they can. Add question marks! >>> regexp = r'value="(.*?)"\s*name\s*=\s*"(.*?:\d+:\d+)"' >>> re.findall(regexp, x) [('x1', 'y1:1:2'), ('x2', 'y2:1:2')] That's better! >are any other possibilities to parse the HTML using functions already >implemented (i.e. HTMLPasrse module) ?? In general, using home brewn re's to parse HTML is not a good idea. You can use HTMLParser or sgmllib for HTML, or an XML parser for XHTML. Just imagine that someone writes 'name = "x:1:2" value = "y" instead of 'value = "y" name = "x:1:2"'. From an HTML point of view it's the same thing, but for your re, it's not. Does your code handle line breaks everywhere that HTML does? For HTML, VALUE= is the same as value=. Is it for your re? Look at this as an alternative: >>> import htmllib, formatter >>> h = '
' >>> class myHTMLParser(htmllib.HTMLParser): ... def start_div(self, attrs): ... print attrs ... >>> p = myHTMLParser(formatter.NullFormatter()) >>> p.feed(h) [('value', 'T'), ('name', 'Guido')] [('name', 'Tim'), ('value', 'G')] You mean that you are parsing the actual HTML forms, not the data passed as the form is processed, right? If you work with a CGI script you should obviously be using the cgi module, and not parse HTML at all. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Mon May 19 13:14:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 19 12:14:03 2003 Subject: [Tutor] how to learn programming,and how to use python as the first one u program? In-Reply-To: <20030518142235.2325.qmail@web15101.mail.bjs.yahoo.com> Message-ID: <5.2.1.1.0.20030519174141.01ed9ef8@www.thinkware.se> At 22:22 2003-05-18 +0800, =?gb2312?q?wei=20huang?= wrote: >i am a new learner, even do not have much knowledge in C & C++ Well, C is much harder than Python, and C++ is much, much harder, so you are doing things in the right order. I wish Python had been around when I still didn't know much C... :) >i will be very appreciated if some one tell me which book i should read >ps:this is my first mail in the mail list,thanks all One book aimed at beginners which is rarely mentioned here, but in my opinion a decent buy is Chris Fehily's "Python Visual Quickstart Guide". See http://www.peachpit.com/vqs/python/ -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From gerrit@nl.linux.org Mon May 19 16:51:22 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Mon May 19 15:51:22 2003 Subject: [Tutor] how to learn programming,and how to use python as the first one u program? In-Reply-To: <20030518142235.2325.qmail@web15101.mail.bjs.yahoo.com> References: <20030518142235.2325.qmail@web15101.mail.bjs.yahoo.com> Message-ID: <20030519194810.GA3192@nl.linux.org> wei huang schreef op maandag 19 mei om 15:25:33 +0000: > i am a new learner, even do not have much knowledge in C & C++ > i will be very appreciated if some one tell me which book i should read > ps:this is my first mail in the mail list,thanks all Congratulations on finding Python as a first language! *Five* years ago, I started using Python. It is very cool to look what my questions were back then: http://www.google.nl/groups?q=group:comp.lang.python+author:Gerrit+author:Holl&hl=nl&lr=&ie=UTF-8&oe=UTF-8&as_drrb=b&as_mind=12&as_minm=5&as_miny=1981&as_maxd=19&as_maxm=12&as_maxy=1998&filter=0 I can not understand what I didn't know... I didn't know the difference between terms like interactive, interpreter, compiler, scripting, editor, programming language. A question like "How does the following def look in edit?" illustrates that very well. You can ask your questions here, you are very welcome! yours, Gerrit. -- 195. If a son strike his father, his hands shall be hewn off. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From alan.gauld@blueyonder.co.uk Mon May 19 17:20:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Mon May 19 16:20:02 2003 Subject: [Tutor] Newbie python programmer here. References: <849de384b3e8.84b3e8849de3@icomcast.net> Message-ID: <002e01c31e43$fdd98900$6401a8c0@xp> > That is what I want it to do anyhow. I can't seem to get it right. What > am I doing wrong? > > def reverse(name): This defines a function called reverse which takes a parameter 'name'. Thus to use it you call: reverse('Jarrod') > name = "aname" This overwrites the name with 'aname' which I assume you just put there to make testing easier? > for i in name: > print i[-1] This takes each letter in 'aname' and prints it. Try this approach. Start at the end of the string and work back to zero: def reverse(name): index = len(name) while index > 0: print name[index], # comma stops newline index = index - 1 That will print the letters with spaces in between but in the order we want. To avoid the spaces we can use a temporary string: def reverse(name): index = len(name) - 1 # subtract 1 to account for zero start result = "" # start with it empty while index >= 0: result = result + name[index] # add the current letter index = index - 1 print result To make the function more reusable you might also want to return the result rather than printing it, like so: def reverse(name): index = len(name) - 1 # subtract 1 to account for zero start result = "" # start with it empty while index >= 0: result = result + name[index] # add the current letter index = index - 1 return result Now we can use it like this: >>> print reverse('fooey') yeoof >>> temp = reverse('Terrence') >>> print temp ecnerreT Its usually a good idea to separate printing from calculations or operations on data. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@blueyonder.co.uk Mon May 19 17:24:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Mon May 19 16:24:01 2003 Subject: [Tutor] how to learn programming,and how to use python as the first one u program? References: <20030518142235.2325.qmail@web15101.mail.bjs.yahoo.com> Message-ID: <004401c31e44$6402a450$6401a8c0@xp> > i am a new learner, even do not have much knowledge > in C & C++ i will be very appreciated if some one > tell me which book i should read Much as I'd like to recommend my own book, if you have even a slight knowledge of any other programming language then just use the Python tutorial that comes as standard. Its very good and many people find that it is all thats needed. Anything you don't understand then just ask here. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From shalehperry@attbi.com Mon May 19 21:47:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon May 19 20:47:01 2003 Subject: [Tutor] line numbering program discloses shebang screw! In-Reply-To: <3EC733E6.3000201@netzero.net> References: <3EC733E6.3000201@netzero.net> Message-ID: <200305191745.54148.shalehperry@attbi.com> On Sunday 18 May 2003 00:19, Kirk Bailey wrote: > The shebang is the special first line that the os examines to discover teh > path to the intended interpeter for an executable script. > > Gang, when you ad this to the end of the shebang: > > # 1 > > You get all sorts of ungodly commotion and confusion. > > LINE NUMBERING PROGRAMS WILL KILL SCRIPTS. > depends on how the OS handles the part after #!. Some have a character limit, others just pass the whole deal on. My assumption was you wanted to print or email the output not use it as a functioning script afterwards (-: From absmythe@ucdavis.edu Mon May 19 22:53:06 2003 From: absmythe@ucdavis.edu (ashleigh smythe) Date: Mon May 19 21:53:06 2003 Subject: [Tutor] easy newbie questions: text file to list? Message-ID: <1053370209.9606.341.camel@nate.ucdavis.edu> Hello. I have a text file that looks like this: Y16911 AF202148 U81576 AF202159 ... I can get Python2.2 on my Linux to read the file with file.read() which makes it look like this: 'Y16911\nAF202148\nU81576\n...' I would like to turn these items into a list (that I can save, not just work with in the interpreter) but I'm confused about strings and pickling etc. I know that to save a list I have to pickle it (and I've succeeded at that for another list) but how do I get these into a list? Do I have to convert these things to strings first (I guess it is one big string now)? I know that pickling turns things into strings but they have all kinds of funny characters in them when I look at a pickled file (with say cat) so it doesn't seem like that's the way to make it a list. Thanks for any help/documentation pointers! Ashleigh *************************** Ashleigh B. Smythe Graduate Research Assistant Department of Nematology UC Davis Davis, CA 95616 phone 530-754-4321 email absmythe@ucdavis.edu From mongo57a@comcast.net Mon May 19 23:44:11 2003 From: mongo57a@comcast.net (andy surany) Date: Mon May 19 22:44:11 2003 Subject: [Tutor] easy newbie questions: text file to list? Message-ID: <006501c31e81$b25c1720$2502a8c0@emily.ewndsr01.nj.comcast.net> Hi Ashleigh, Try file.readline in a loop until EOF. Initialize the list before the loop (mylist=[]) and add the line to the list after the readline within the loop (mylist.append(your_line)). So it could look something like this: file.open(filename,'r') file.seek(0) mylist=[] while 1: text=file.readline() if not text: break # this get you out when EOF occurs mylist.append(text) HTH. Regards, Andy -----Original Message----- From: ashleigh smythe To: tutor@python.org Date: Monday, May 19, 2003 9:53 PM Subject: [Tutor] easy newbie questions: text file to list? >Hello. I have a text file that looks like this: > >Y16911 >AF202148 >U81576 >AF202159 >... > >I can get Python2.2 on my Linux to read the file with file.read() which >makes it look like this: >'Y16911\nAF202148\nU81576\n...' > >I would like to turn these items into a list (that I can save, not just >work with in the interpreter) but I'm confused about strings and >pickling etc. I know that to save a list I have to pickle it (and I've >succeeded at that for another list) but how do I get these into a list? >Do I have to convert these things to strings first (I guess it is one >big string now)? I know that pickling turns things into strings but >they have all kinds of funny characters in them when I look at a pickled >file (with say cat) so it doesn't seem like that's the way to make it a >list. > >Thanks for any help/documentation pointers! > >Ashleigh > > > >*************************** >Ashleigh B. Smythe >Graduate Research Assistant >Department of Nematology >UC Davis >Davis, CA 95616 >phone 530-754-4321 >email absmythe@ucdavis.edu > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bgailer@alum.rpi.edu Mon May 19 23:49:19 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Mon May 19 22:49:19 2003 Subject: [Tutor] easy newbie questions: text file to list? In-Reply-To: <1053370209.9606.341.camel@nate.ucdavis.edu> Message-ID: <5.2.0.9.0.20030519204408.03ceb748@66.28.54.253> At 06:50 PM 5/19/2003 +0000, ashleigh smythe wrote: >Hello. I have a text file that looks like this: > >Y16911 >AF202148 >U81576 >AF202159 >... > >I can get Python2.2 on my Linux to read the file with file.read() which >makes it look like this: >'Y16911\nAF202148\nU81576\n...' > >I would like to turn these items into a list 1) file.readlines(). That will give you a list of lines with \n at the end of each line. 2) file.read().split('\n'). That will give you a list of lines without \n at the end. [snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From jeff@ccvcorp.com Tue May 20 00:05:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon May 19 23:05:02 2003 Subject: [Tutor] easy newbie questions: text file to list? References: <1053370209.9606.341.camel@nate.ucdavis.edu> Message-ID: <3EC99BD4.6000705@ccvcorp.com> ashleigh smythe wrote: >Hello. I have a text file that looks like this: > >Y16911 >AF202148 >U81576 >AF202159 >... > >I can get Python2.2 on my Linux to read the file with file.read() which >makes it look like this: >'Y16911\nAF202148\nU81576\n...' > >I would like to turn these items into a list (that I can save, not just >work with in the interpreter) but I'm confused about strings and >pickling etc. I know that to save a list I have to pickle it (and I've >succeeded at that for another list) but how do I get these into a list? > > As someone else already said, you can either take the string you have and split() it on '\n', or you can use file.readlines() to read the entire thing into a list to begin with. But why do you think you need to pickle this file? You say that you want to save it... but isn't it already saved? You can get the information you want from the text file just as easily as you could from a pickle. A pickle might be warranted after you've done some extensive processing on each element of the list... but even there, it's quite possibly just as easy to write the list into another plain text file (and read it back in in the same way that you did this one) instead of pickling it. Be careful about deciding too strongly on any particular tool before you've figured out an overall path to a solution. In this case, from what you've said so far, it doesn't look (to me) like a pickle is likely to be the ideal tool to use. The best way to make your data persistent (store it long-term) will depend on just what form the data takes and what you want to do with it, and data this simple is probably not a good match for a somewhat-complex storage tool like pickle. Jeff Shannon Technician/Programmer Credit International From pan@uchicago.edu Tue May 20 02:44:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Tue May 20 01:44:01 2003 Subject: [Tutor] re module fails to handle text > 16142 characters ??? In-Reply-To: <20030515220100.13904.78176.Mailman@mail.python.org> References: <20030515220100.13904.78176.Mailman@mail.python.org> Message-ID: <1053409396.3ec9c0742316b@webmail.uchicago.edu> The other day I was using re to do some parsing and found that one of the text that I tried to parse returned an error : return reObj.findall(doc)[0] RuntimeError: maximum recursion limit exceeded After some painful debugging, I found: let S = len(doc) 1. When S > 16143: re.find function failed; 2. When S = 16143: failed too 3. When S = 16142: successful. This was tested by deleting ANY character in that 16143-long doc. I am using Python 2.2.1. Is this a known-bug??? I would really like to post the entire code here but it's very long, so I think it's better to ask first to see if it's a known bug. pan From krier115@student.liu.se Tue May 20 04:56:34 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Tue May 20 03:56:34 2003 Subject: [Tutor] re module fails to handle text > 16142 characters ??? In-Reply-To: <1053409396.3ec9c0742316b@webmail.uchicago.edu> References: <20030515220100.13904.78176.Mailman@mail.python.org> <1053409396.3ec9c0742316b@webmail.uchicago.edu> Message-ID: <20030520075410.GA650@n14.ryd.student.liu.se> On Tue, May 20, 2003 at 12:43:16AM -0500, pan@uchicago.edu wrote: > The other day I was using re to do some parsing and > found that one of the text that I tried to parse returned > an error : > > return reObj.findall(doc)[0] > RuntimeError: maximum recursion limit exceeded > > After some painful debugging, I found: > > let S = len(doc) > > 1. When S > 16143: re.find function failed; > 2. When S = 16143: failed too > 3. When S = 16142: successful. This was tested by deleting ANY > character in that 16143-long doc. > > I am using Python 2.2.1. Is this a known-bug??? > > I would really like to post the entire code here but it's very > long, so I think it's better to ask first to see if it's a known > bug. > > pan I have gotten this too on large files. I think it occurs when the qualifers match hordes of text. It seems like the internals of the re module uses recursion somewhere when matching these and when you match against too large chunks of texts you recurse too deep and run into a limit to prevent you from running out of stack space. I'm not sure at this, but it is how it seems to me. If I'm right the solutions are to either increase the maximum recursion depth limit (no idea how to do that though :), split your text into smaller pieces or make your qualifiers match less somehow. Hope it helps a bit at least :) -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From magnus@thinkware.se Tue May 20 04:58:10 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 20 03:58:10 2003 Subject: [Tutor] easy newbie questions: text file to list? In-Reply-To: <006501c31e81$b25c1720$2502a8c0@emily.ewndsr01.nj.comcast.n et> Message-ID: <5.2.1.1.0.20030520092859.01e64548@www.thinkware.se> At 23:41 2003-05-19 -0400, andy surany wrote: >file.open(filename,'r') I think you mean "file = open(filename, 'r')" but in 2.2 and up, that's a bad idea. Avoid using "file" as a variable name. "file" is a type, and works as a constructor. It thus replaces "open". "f = file(filename,'r')" is better. >file.seek(0) Why do you need this if you just opened the file? >mylist=[] >while 1: > text=file.readline() > if not text: break # this get you out when EOF occurs > mylist.append(text) I think the alternatives below are simpler. Note that I use the builtin file here. It's not a variable name like above. mylist = [] for line in file(filename): mylist.append(line) or just one line: mylist = file(filename).readlines() As Bob wrote, this will leave line end characters in the end of line. He suggested using "file.read().split('\n')" but if this is a proper text file, i.e. with a line feed in the end of the last line, you will end up with an extra empty string in the end as you can see below: >>> s = "line1\nline2\nline3\n" >>> s.split('\n') ['line1', 'line2', 'line3', ''] Another option for removing line endings (and other trailing whitespace) is to do this: mylist = [row.rstrip() for row in file(filename).readlines()] This might be a bit much to fathom all at once though. The "aList = [ for in ] construct is called list comprehension, and it's a short form of aList = [] for in : aList.append() (There is also a conditional "if" part in list comprehension that I don't use here.) As usual, Jeff says something clever. Data might persist much longer than your programs, and while ASCII pickles are readable, they aren't at all as simple as the plain original text file. Having ones data available as simple text files is very useful. See also http://www.thinkware.se/cgi-bin/thinki.cgi/UnixPhilosophy -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From norvell@houseofspearman.org Tue May 20 05:06:54 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Tue May 20 04:06:54 2003 Subject: [Tutor] re module fails to handle text > 16142 characters ??? In-Reply-To: <20030520075410.GA650@n14.ryd.student.liu.se> References: <20030515220100.13904.78176.Mailman@mail.python.org> <1053409396.3ec9c0742316b@webmail.uchicago.edu> <20030520075410.GA650@n14.ryd.student.liu.se> Message-ID: <20030520080510.GA8245@houseofspearman.org> On Tuesday, 2003.05.20, 09:54:10 +0200, Kristoffer Erlandsson wrote: > If I'm right the solutions are to either increase the maximum > recursion depth limit (no idea how to do that though :), split your > text into smaller pieces or make your qualifiers match less somehow. > > Hope it helps a bit at least :) Here's one way: >>> import sys >>> sys.getrecursionlimit() 1000 >>> sys.setrecursionlimit(2000) >>> sys.getrecursionlimit() 2000 >>> I found how to do that in the Source, Misc/cheatsheet. -- Norvell Spearman From gerrit@nl.linux.org Tue May 20 06:54:02 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Tue May 20 05:54:02 2003 Subject: [Tutor] easy newbie questions: text file to list? In-Reply-To: <1053370209.9606.341.camel@nate.ucdavis.edu> References: <1053370209.9606.341.camel@nate.ucdavis.edu> Message-ID: <20030520095314.GA2478@nl.linux.org> ashleigh smythe schreef op dinsdag 20 mei om 03:53:43 +0000: > I would like to turn these items into a list (that I can save, not just > work with in the interpreter) but I'm confused about strings and > pickling etc. There is a string method that does exactly that: 9 >>> s = "aaa\nbbb\nccc" 10 >>> s.splitlines() ['aaa', 'bbb', 'ccc'] 11 >>> s.splitlines(True) # keep the newlines [aaa\n', 'bbb\n', 'ccc'] > Thanks for any help/documentation pointers! All string methods are documented at: http://www.python.org/dev/doc/devel/lib/string-methods.html yours, Gerrit. -- 39. He may, however, assign a field, garden, or house which he has bought, and holds as property, to his wife or daughter or give it for debt. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From gerrit@nl.linux.org Tue May 20 06:56:44 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Tue May 20 05:56:44 2003 Subject: [Tutor] Newbie python programmer here. In-Reply-To: <002e01c31e43$fdd98900$6401a8c0@xp> References: <849de384b3e8.84b3e8849de3@icomcast.net> <002e01c31e43$fdd98900$6401a8c0@xp> Message-ID: <20030520095522.GB2478@nl.linux.org> Alan Gauld schreef op maandag 19 mei om 22:20:20 +0000: > > That is what I want it to do anyhow. I can't seem to get it right. > What > > am I doing wrong? > > > > def reverse(name): [cut excellent help] For your information: In Python 2.3, you can do string[::-1]. yours, Gerrit. -- 202. If any one strike the body of a man higher in rank than he, he shall receive sixty blows with an ox-whip in public. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From magnus@thinkware.se Tue May 20 07:27:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 20 06:27:01 2003 Subject: [Tutor] easy newbie questions: text file to list? In-Reply-To: <20030520095314.GA2478@nl.linux.org> References: <1053370209.9606.341.camel@nate.ucdavis.edu> <1053370209.9606.341.camel@nate.ucdavis.edu> Message-ID: <5.2.1.1.0.20030520122458.01eb4eb0@www.thinkware.se> At 11:53 2003-05-20 +0200, Gerrit Holl wrote: > 9 >>> s = "aaa\nbbb\nccc" > 10 >>> s.splitlines() >['aaa', 'bbb', 'ccc'] > 11 >>> s.splitlines(True) # keep the newlines >[aaa\n', 'bbb\n', 'ccc'] Right! Didn't think of that. It's much better than "s.split(\n')" First of all, you don't get the "empty string in the end" problem that I mentioned before, and secondly, it handles both \n (unix) \r (mac) and \r\n (Windows etc) as line separators: >>> a = "dfgf\rdfgdfg\r\ndfgdfg\n" >>> a.splitlines() ['dfgf', 'dfgdfg', 'dfgdfg'] -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From bgailer@alum.rpi.edu Tue May 20 09:32:17 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Tue May 20 08:32:17 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <20030520095314.GA2478@nl.linux.org> References: <1053370209.9606.341.camel@nate.ucdavis.edu> <1053370209.9606.341.camel@nate.ucdavis.edu> Message-ID: <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> I've been noticing deficiencies in the official Python documentation. What's the procedure to request and/or contribute fixes and improvements? Examples: at http://www.python.org/dev/doc/devel/lib/string-methods.html 1-decode and encode have an encoding parameter. It is not explained. 2-expandtabs "tab characters are expanded" expanded is not defined. It takes an experiment to find out what this means. 3-translate "mapped through the given translation table" Huh? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From scott_list@mischko.com Tue May 20 12:24:10 2003 From: scott_list@mischko.com (Scott Chapman) Date: Tue May 20 11:24:10 2003 Subject: [Tutor] OOA and OOD resources? Message-ID: <200305192125.06445.scott_list@mischko.com> I'm learning python and oo at the same time. I'm currently looking for more grounding in practical ooa and ood. The basic question is "How do I know what to make objects out of and what are the pitfalls of doing it this way vs. that way?" I have read various chunks here and there, saying things like, "Inheritance is not good because it creates dependencies", or "Aggregation is good but it's a pain to implement the proxy methods". Then we have the Extreme camp which says, "Sstart with a few objects and reiteratively ooa and ood as you go along". I realize that some of this is being distilled as patterns (and I like what little I've seen of the Extreme camp). That's great if you know what they are and where to apply them. I tend to be a very-big-picture thinker. I like to have a framework to hang things on rather than starting at it piecemiel. Is there a solid set of general principles for ooa and ood that I can begin to build upon? Are there any textbooks out there that start with oo (even ooa and ood) and build from there? I see that introductory books deal with the language elements and a basically procedural orientation, then add oo later as "advanced". I'd love to see a textbook that starts on oo and builds on it. I'm fairly sure that no such book exists for Python but I'd love to be proven wrong! Cordially, Scott From lonetwin@yahoo.com Tue May 20 13:26:03 2003 From: lonetwin@yahoo.com (lonetwin) Date: Tue May 20 12:26:03 2003 Subject: [Tutor] OOA and OOD resources? In-Reply-To: <200305192125.06445.scott_list@mischko.com> References: <200305192125.06445.scott_list@mischko.com> Message-ID: <200305202203.16037.lonetwin@yahoo.com> Hi Scott, Quick answers to your question - > Are there any textbooks out there that start with oo (even ooa and ood) and > build from there? I see that introductory books deal with the language > elements and a basically procedural orientation, then add oo later as > "advanced". I'd love to see a textbook that starts on oo and builds on it. 1) http://diveintopython.org/index.html "Dive into python", does not really ^start^ from OO but (from the preface): """ This book is not for newbies, for wimps, or For Dummies. It assumes a lot about you. * You know at least one real object-oriented language, like Java, C++, or Delphi. * You know at least one scripting language, like Perl, Visual Basic, or JavaScript. """ 2) http://jamesthornton.com/eckel/TIPython/html/Index.htm "Thinking in Python", this is actually incomplete, but if you know Java, have a look also at Thinking in Java and Thinking in patterns. Me, I learned my python using diveintopython + the official tutorial (after a series of short romances that began with the Unix shell and went on to C). I also had attempted to learn C++ using Bruce Eckel's Thinking in C++. What I ended up getting from Thinking in C++, is a excellent feel of OO. I can atleast say that I can understand (if not reliably design) OO. I guess, I'm just too dense (yet) for C++. Anyways, the point being, maybe there any real python books out that that start with OO, tho' if you already know C++/Java or are ready to learn either of 'em, I'd highly recommend Bruce Eckel's books. (http://www.mindview.net/) HTH Steve -- Never be afraid to tell the world who you are. - Anonymous From mike@daboyz.org Tue May 20 13:51:37 2003 From: mike@daboyz.org (Michael Barrett) Date: Tue May 20 12:51:37 2003 Subject: [Tutor] httplib/ssl/certificates Message-ID: <20030520164846.GB4946@daboyz.org> So I've been asked to look for a way to monitor my companies SSL websites to watch the certificates and send an email off to us admins when the certificate is about to expire. I've used httplib to monitor our https sites before, but I don't see any way of analyzing the certifcate that the website returns, or even a place where it might be stored. Anyone have any experience with doing this? I think it'd be a pretty useful tool. Thanks in advance. -- ________________________________________________________________________ Mike Barrett | Calvin: "May Contain Adult Situations?" What mike@daboyz.org | does that mean? www.daboyz.org | Hobbes: Oh, you know. Paying bills. Going | to work. Taking responsibility. ------------------------+----------------------------------------------- From hall@ouhep1.nhn.ou.edu Tue May 20 16:33:14 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Tue May 20 15:33:14 2003 Subject: [Tutor] try/except question Message-ID: Hi list :) I have a quick question/problem with try/excet statements. I have a method which tries to do some operation. I want to do something different for 2 possible exceptions that can be raised. What I do looks something like this (string is a string variable that gets passed to the method) try: a=eval(string) except(OverflowError): a=long(string) except(NameError): a=string return a The problem I am having is that this still crashes/exits on a NameError. Is it illegal to put 2 except statements after a try? If so, how can I condense the 2 excepts into one? Or is it some other problem I have overlooked? Thanks again in advance Ike -- From alan.gauld@blueyonder.co.uk Tue May 20 16:38:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue May 20 15:38:01 2003 Subject: [Tutor] Newbie python programmer here. References: <849de384b3e8.84b3e8849de3@icomcast.net> <002e01c31e43$fdd98900$6401a8c0@xp> <20030520095522.GB2478@nl.linux.org> Message-ID: <007b01c31f07$46fbe010$6401a8c0@xp> > For your information: In Python 2.3, you can do string[::-1]. > > yours, > Gerrit. Not having looked at 2.3 yet what exactly does that do? I assume it slices starting from the back somehow but I don't think the syntax is exactly obvious...? Alan G. From jeff@ccvcorp.com Tue May 20 16:52:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue May 20 15:52:02 2003 Subject: [Tutor] try/except question References: Message-ID: <3ECA87C4.7020503@ccvcorp.com> Isaac Hall wrote: >try: > a=eval(string) >except(OverflowError): > a=long(string) >except(NameError): > a=string > >return a > >The problem I am having is that this still crashes/exits on a NameError. >Is it illegal to put 2 except statements after a try? > No, it's perfectly legal to have multiple except statements catching different types of exceptions, just as you're trying to do here. However, you shouldn't have the exception type in parentheses. try: a = eval(string) except OverflowError: a = long(string) except NameError: a = string Also, please insert my standard rant about overuse of eval() -- I strongly doubt that it is the best thing to use in this case. You're probably better off determining the type you want to convert string to, and using the proper built-in type constructor (as you do with your OverflowError handler), instead of using eval(). Your code might be slightly longer, but it will be easier to understand and a *lot* safer to use -- both in terms of catching bugs and in terms of potential exploits by malicious users. Jeff Shannon Technician/Programmer Credit International From gerrit@nl.linux.org Tue May 20 16:53:04 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Tue May 20 15:53:04 2003 Subject: [Tutor] Newbie python programmer here. In-Reply-To: <007b01c31f07$46fbe010$6401a8c0@xp> References: <849de384b3e8.84b3e8849de3@icomcast.net> <002e01c31e43$fdd98900$6401a8c0@xp> <20030520095522.GB2478@nl.linux.org> <007b01c31f07$46fbe010$6401a8c0@xp> Message-ID: <20030520195212.GA3840@nl.linux.org> Alan Gauld schreef op dinsdag 20 mei om 21:38:00 +0000: > > For your information: In Python 2.3, you can do string[::-1]. > > > > yours, > > Gerrit. > > Not having looked at 2.3 yet what exactly does that do? > I assume it slices starting from the back somehow but I don't > think the syntax is exactly obvious...? Python 2.3 adds a third place in the slice. The third number is the step size. "Hello"[::-1] reverses Hello, because it starts at the end: 11 >>> from string import letters 12 >>> letters[2:20] 'cdefghijklmnopqrst' 13 >>> letters[2:20:3] 'cfilor' 14 >>> letters[20:2] '' 15 >>> letters[20:2:-1] 'utsrqponmlkjihgfed' 16 >>> letters[::] 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' 17 >>> letters[::-1] 'ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba' yours, Gerrit. -- 107. If the merchant cheat the agent, in that as the latter has returned to him all that had been given him, but the merchant denies the receipt of what had been returned to him, then shall this agent convict the merchant before God and the judges, and if he still deny receiving what the agent had given him shall pay six times the sum to the agent. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From gerrit@nl.linux.org Tue May 20 17:02:22 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Tue May 20 16:02:22 2003 Subject: [Tutor] Newbie python programmer here. In-Reply-To: <007b01c31f07$46fbe010$6401a8c0@xp> References: <849de384b3e8.84b3e8849de3@icomcast.net> <002e01c31e43$fdd98900$6401a8c0@xp> <20030520095522.GB2478@nl.linux.org> <007b01c31f07$46fbe010$6401a8c0@xp> Message-ID: <20030520200009.GA3861@nl.linux.org> Alan Gauld schreef op dinsdag 20 mei om 21:38:44 +0000: > > For your information: In Python 2.3, you can do string[::-1]. > > Not having looked at 2.3 yet what exactly does that do? > I assume it slices starting from the back somehow but I don't > think the syntax is exactly obvious...? It is documented at: http://www.python.org/doc/2.3b1/whatsnew/section-slices.html http://www.python.org/dev/doc/devel/ref/types.html yours, Gerrit. -- 124. If any one deliver silver, gold, or anything else to another for safe keeping, before a witness, but he deny it, he shall be brought before a judge, and all that he has denied he shall pay in full. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From alan.gauld@blueyonder.co.uk Tue May 20 17:02:38 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue May 20 16:02:38 2003 Subject: [Tutor] OOA and OOD resources? References: <200305192125.06445.scott_list@mischko.com> Message-ID: <008b01c31f09$15202220$6401a8c0@xp> > grounding in practical ooa and ood. The basic question is "How do I know > what to make objects out of and what are the pitfalls of doing it this way > vs. that way?" That is indeed the basic question in OOAD. It is not easily solved and needs practice. Nonetheless there arecs0m4e good books which give guidance. My personal favourites are: 1) Coad/Yourdon OOA and OOD(2 related books) Unfortunately the notation is now obsolete(replaced by UML) and the books have about 30-50% overlap and are quite expensive. But they are very readable for beginners. 2) OOP By Timothy Budd - Really about programming rather than design per se but a really good intro IMHO. 3) OOA & D by Grady Booch Seminal book on the topic but really aimed at experienced designers. 4) OO Software Construction by Meyer Massive tome full of readable wisdom on all things OO. Repays close study. 5) Object Design: Roles, Responsibilities, and Collaboration by Wirfs-Brock This is really important in emphasising the need to focus on behaviour and responsibilities in defining a system. Highly recommended but only after you have a good grasp of OOP. > I have read various chunks here and there, saying things like, > "Inheritance is not good because it creates dependencies", > or "Aggregation is good but it's a pain to implement the proxy methods". Distrust all generalisations, Each technique has its place. The trick is to know which and when. The books above all address these issues. > things on rather than starting at it piecemiel. Is there a solid set of > general principles for ooa and ood that I can begin to build upon? Yes, and much of it is available onine. Unfortunately a lot of hype is online too! :-( Thats why i'd recommend the above books. > I'd love to see a textbook that starts on oo and builds on it. I tried that with my book but to be honest, once you get down to writing methods its basic procedural thinking. Objects don't make sense at the level that beginners start at. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From beyondthezero@earthlink.net Tue May 20 17:17:20 2003 From: beyondthezero@earthlink.net (Peter Jakubowicz) Date: Tue May 20 16:17:20 2003 Subject: [Tutor] spell/grammar checking Message-ID: <5.2.1.1.1.20030520131215.00b26e48@earthlink.net> Hi, I've been playing around with the guessing game and word counting case studies in Alan Gauld's book, expanding them, and I am wondering where people get the words for their spell checkers. Do programmers sit down and actually write huge dictionary files, or are there things like that available online? Thanks, Peter From hall@ouhep1.nhn.ou.edu Tue May 20 17:35:02 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Tue May 20 16:35:02 2003 Subject: [Tutor] spell/grammar checking In-Reply-To: <5.2.1.1.1.20030520131215.00b26e48@earthlink.net> Message-ID: Hi Peter, I never thought about this before....But now that you have me thinking a bit, I will offer my opinion. More than likely, at one time, someone or a group of someones sat down and actually coded in most of the words in the english (and other) languages into some kind of database (likely a database...maybe other things). No doubt, there is probably some sort of access to this/these database(s) online. However, I would venture a guess that because of the massive data entry effort involved in creating such a thing, more than likely, you might have to pay to be able to just get a listing of 'all the words'. I did a quick search on google for dictionaries, and found that most of them online only allow you to look up words (for free of course). However, I found that the mirriam-webster site might be useful in a spell-checking sort of way, meaning all you need to code is the use/reading of the webpages :) I tried looking up the word 'theese' which of course does not exist, and mirriam webster returned the following choices that I may have wanted instead: 1. Thess 2. Thais 3. these 4. thews 5. those 6. thous 7. thus 8. thaws 9. thatches 10. Thurs but as far as getting your own dictionary on your hard drive for a python script to access....Im still not quite sure how to do this... Here is the mirriam-webster site, for your perusal: http://www.m-w.com/netdict.htm Ike On Tue, 20 May 2003, Peter Jakubowicz wrote: > Hi, > > I've been playing around with the guessing game and word counting case > studies in Alan Gauld's book, expanding them, and I am wondering where > people get the words for their spell checkers. Do programmers sit down and > actually write huge dictionary files, or are there things like that > available online? Thanks, Peter > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From magnus@thinkware.se Tue May 20 17:50:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 20 16:50:03 2003 Subject: [Tutor] OOA and OOD resources? In-Reply-To: <200305192125.06445.scott_list@mischko.com> Message-ID: <5.2.1.1.0.20030520194305.01ef4cc8@www.thinkware.se> At 21:25 2003-05-19 -0700, Scott Chapman wrote: >I'm learning python and oo at the same time. I'm currently looking for more >grounding in practical ooa and ood. The basic question is "How do I know >what to make objects out of and what are the pitfalls of doing it this way >vs. that way?" > >I have read various chunks here and there, saying things like, >"Inheritance is >not good because it creates dependencies", or "Aggregation is good but it's a >pain to implement the proxy methods". Inheritance means IS-A, such as "employee IS A person", and aggregation means HAS-A, like "a car HAS A motor". You don't use either or. You use what is appropriate in a particular case. The problem with inheritance occurs when it's used out of it's proper place. It sometimes seems convenient to make a car object behave as a motor object, but it's not really a good idea in the long run... Inheritance should only be used to model a specialization hierarchy. A Car is not a special kind of Motor. A Car is a special kind of Vehicle. This doesn't mean that whoever makes a Car class should inherit from a Vehicle class. But by using inheritance well, you will notice that you will remove a lot of duplication of code. If you have the same code duplicated in two classes, it's possible that one should inherit the other, or that both should inherit a common base class. But only if the general rules above apply... Maybe the right thing is to put the shared code in a third classes that the two classes that previously contained the code just uses or has as an aggregate. >Are there any textbooks out there that start with oo (even ooa and ood) and >build from there? I see that introductory books deal with the language >elements and a basically procedural orientation, then add oo later as >"advanced". I'd love to see a textbook that starts on oo and builds on it. There are two books I'd like to recommend on Object-Orientation. Neither use Python, but they are certainly applicable for Python programmers. * Bertrand Meyer: Object-Oriented Software Construction * Arthur Riel: Object-Oriented Design Heuristics Meyer is somewhat of a fanatic :) and you should take his writing with a pinch of salt. If you want someone who always weighs his words, and presents different alternatives, you won't like Meyer. He strongly believes in his tenets. The book contains a certain amount of propaganda for his own language "Eiffel". It's a thick book. About 1250 bible thin pages. Riel seems more reasonable, and his book less than 400 pages. I think it's the best description on how to design classes that I've seen. Natuarally, there are things one can question here as well, but he has a lot of good ideas, a if you read through this book, I hope that you will get a feeling for how to distribute the data structures and logic you need into a set of useful classes. Of course, nothing will ever replace real world experience... >I'm fairly sure that no such book exists for Python but I'd love to be proven >wrong! I think you are right. :( The concept of creating objects is enough for several book. Teaching an obscure ;) language at the same time is maybe not the best idea (unless it's the author's pet language, as Eiffel for Meyer :). The concept of OO is fairly orthogonal to the programming language Python. I do think that Python would be a fairly good language to use to explain OO in, although there are a lot of limitations in most other OO languages that Python doesn't have, such as polymorphism limited by inheritance, so other languages are likely to be frustrating to people who learnt OO through Python... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Tue May 20 17:59:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 20 16:59:01 2003 Subject: [Tutor] try/except question In-Reply-To: Message-ID: <5.2.1.1.0.20030520225616.01ee3e68@www.thinkware.se> Jeff made a number of good points as usual, but I have some more to add. At 14:31 2003-05-20 -0500, Isaac Hall wrote: >try: > a=eval(string) Don't you want a = int(string) here? Why else do you think you might get an OverflowError? eval('99999999999999999999') will simply return a long. >except(OverflowError): > a=long(string) >except(NameError): > a=string > >return a > >The problem I am having is that this still crashes/exits on a NameError. Do you really have a variable called "string"? If you don't, you will get a NameError in the try block, go to the last except block, and get a new NameError there... :) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From ATrautman@perryjudds.com Tue May 20 18:05:02 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Tue May 20 17:05:02 2003 Subject: [Tutor] spell/grammar checking Message-ID: <06738462136C054B8F8872D69DA140DB01079C@corp-exch-1.pjinet.com> Peter, It's not just a list of words you needs which you pretty much need to pay for either in lost time or a dictionary file. The other technique is to parse several long text manuscripts that are typed well and loading all non-duplicate words for your dictionary. This can be very effective in making a specific parser for a limited field (medical specialties and law come to mind). However if this is a learning experience the formula / parsing techniques for selecting and or indexing related words is really interesting. The exercise of determining the suggestions is interesting after all you can't just look for the words with the fewest differences in letters to be useful. There are common misspelling mistakes to consider etc. The ideal is context sensitive correction to suggest based on not only common errors, letter closeness, and related words. In short, you don't need a lot of words for your dictionary to be a great project. You need several that are extremely close based on all the conditions above and more I'm sure you can come up with to write an interesting program. You can also use Word or M-W site for good clusters of words to add for you checker. HTH and keeps you interested, fuzzy logic and limited AI are favorite personal subjects. Alan Hi, I've been playing around with the guessing game and word counting case studies in Alan Gauld's book, expanding them, and I am wondering where people get the words for their spell checkers. Do programmers sit down and actually write huge dictionary files, or are there things like that available online? Thanks, Peter _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From python@jaydorsey.com Tue May 20 18:10:22 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Tue May 20 17:10:22 2003 Subject: [Tutor] spell/grammar checking In-Reply-To: <5.2.1.1.1.20030520131215.00b26e48@earthlink.net> References: <5.2.1.1.1.20030520131215.00b26e48@earthlink.net> Message-ID: <200305201709.40257.python@jaydorsey.com> Check out the 12 Dicts package here: http://wordlist.sourceforge.net/ I've successfully made a python CGI-script which put all of the words in one of those packages into a dictionary and parsed a string of text and compared the string. If you want the code to it let me know and I'll see if I can dig it up. On Tuesday 20 May 2003 16:14, Peter Jakubowicz wrote: > Hi, > > I've been playing around with the guessing game and word counting case > studies in Alan Gauld's book, expanding them, and I am wondering where > people get the words for their spell checkers. Do programmers sit down and > actually write huge dictionary files, or are there things like that > available online? Thanks, Peter -- Jay Dorsey python at jay dorsey dot com From magnus@thinkware.se Tue May 20 18:46:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 20 17:46:02 2003 Subject: [Tutor] spell/grammar checking In-Reply-To: <5.2.1.1.1.20030520131215.00b26e48@earthlink.net> Message-ID: <5.2.1.1.0.20030520233608.01ee53b0@www.thinkware.se> At 13:14 2003-05-20 -0700, Peter Jakubowicz wrote: >I've been playing around with the guessing game and word counting case >studies in Alan Gauld's book, expanding them, and I am wondering where >people get the words for their spell checkers. There is probably a plain text word file called /usr/share/dict/words on a Linux system near you... Mine has 45402 words from Aarhus to Zurich. :) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From alan.gauld@blueyonder.co.uk Tue May 20 19:57:03 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue May 20 18:57:03 2003 Subject: [Tutor] spell/grammar checking References: Message-ID: <00bd01c31f23$0d82acd0$6401a8c0@xp> > bit, I will offer my opinion. More than likely, at one time, someone or a > group of someones sat down and actually coded in most of the words in the > english (and other) languages into some kind of database The Unix dictionary - which is a text file called 'words' I believe! - was indeed coded by someone but very cleverly because the RAM at the time was only 48K and the initial dictionary was bigger than this! Some very clever code was needed to only store root words and a set of standard extensins. Jon Bentley discusses it in his book Progreamming Pearls... recommended reading to all. > but as far as getting your own dictionary on your hard drive for a python > script to access....Im still not quite sure how to do this... On unix the words file is still there and I believe may now be extended by a user dictionary stored somewhere else. By accessing both of these you mauy be able to do something. Most word processors also do the same, Adobe FrameMaker DTP program for example, uses a plain text word list for its User added words Try "man spell" on a Unix box... > > .... Do programmers sit down and > > actually write huge dictionary files, Yes but only once. Recall from my book that one characteristic of a good programmer is lazinesss - don't do a thing twice! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@blueyonder.co.uk Tue May 20 20:00:19 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue May 20 19:00:19 2003 Subject: [Tutor] spell/grammar checking References: <06738462136C054B8F8872D69DA140DB01079C@corp-exch-1.pjinet.com> Message-ID: <00c201c31f23$88547a60$6401a8c0@xp> > ..... The other technique is to > parse several long text manuscripts that are typed well and loading all > non-duplicate words for your dictionary. This is a good point. Kernighan and Pike in their book "The Practice of Programming" give an example of a random text generator which uses a similar technique in reverse to ensure the text approximates to real English. You might find some ideas by looking at how they did that. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From magnus@thinkware.se Tue May 20 21:45:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 20 20:45:02 2003 Subject: [Tutor] spell/grammar checking In-Reply-To: <00c201c31f23$88547a60$6401a8c0@xp> References: <06738462136C054B8F8872D69DA140DB01079C@corp-exch-1.pjinet.com> Message-ID: <5.2.1.1.0.20030521023600.01ecc2b8@www.thinkware.se> At 23:59 2003-05-20 +0100, Alan Gauld wrote: >This is a good point. Kernighan and Pike in their book >"The Practice of Programming" give an example of a random text >generator >which uses a similar technique in reverse to ensure the text >approximates to real English. You might find some ideas by looking >at how they did that. Ah, the Markov Chain program. I have a python implementation at http://www.thinkware.se/cgi-bin/thinki.cgi/MarkovChain , so you don't need to buy the book. It will create rather amusing texts if you feed it something reasonable. I once used a similar program (travesty) to generate an email based on emails from two female friends who for some reason used to CC me a lot of their gossip email. They were amazed of the interesting things I told them. There were some twists that they didn't quite understand, but in all it seems they were interested... :) BTW Alan, I tried Ardbeg's "Lord of the Isles" some time ago. Bliss!!! Completely outstanding in my opinion. First time I felt that I could happily imagine paying =A3100 for 70cl of Malt. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program=20 From tim.one@comcast.net Tue May 20 22:27:01 2003 From: tim.one@comcast.net (Tim Peters) Date: Tue May 20 21:27:01 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> Message-ID: [Bob Gailer] > I've been noticing deficiencies in the official Python documentation. > What's the procedure to request and/or contribute fixes and > improvements? At the bottom of every page of the HTML docs, you'll see this line: See "About this document..." for information on suggesting changes. Click on the link, and it will take you to, e.g., http://www.python.org/dev/doc/devel/lib/about.html If you find errors, it's *most* helpful to (as the link above says) submit bug reports to SourceForge. The email address goes to Fred Drake's inbox, and he really doesn't have much time for this anymore. It's much better to record problems on the bug tracker, where other volunteers can help too. If you *really* want to help, consider learning how to create doc patches -- everything in PythonLand eventually gets done by someone contributing their time and talents. From pan@uchicago.edu Tue May 20 23:44:02 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Tue May 20 22:44:02 2003 Subject: [Tutor] re module fails to handle text > 16142 characters ??? In-Reply-To: References: Message-ID: <1053484986.3ecae7ba59f1b@webmail.uchicago.edu> Thx to all those replied. I did use a minimal-match construct ( .*? ) like what Tim mentioned (see below). Since Tim's reply somehow didn't show up on the list (even though in his email to me the tutor@python.org did show up on the "cc:" field of my email program) so I am forwarding his explanation to you guys. pan Quoting Tim Peters : > [pan@uchicago.edu] > > The other day I was using re to do some parsing and > > found that one of the text that I tried to parse returned > > an error : > > > > return reObj.findall(doc)[0] > > RuntimeError: maximum recursion limit exceeded > > > > After some painful debugging, I found: > > > > let S = len(doc) > > > > 1. When S > 16143: re.find function failed; > > 2. When S = 16143: failed too > > 3. When S = 16142: successful. This was tested by deleting ANY > > character in that 16143-long doc. > > > > I am using Python 2.2.1. Is this a known-bug??? > > You're probably using a minimal-match construct in the regexp, like > > .*? > > Minimal matches are done using recursion, proportional to the length of the > substring they're trying to match. If so, it's a limitation of the > implementation, but isn't considered to be a bug -- that's just the way it > works. If you had infinite memory, it wouldn't complain . It's akin > to trying to write a 20 gigabyte file on a system with a 1 gigabyte disk. > > > I would really like to post the entire code here but it's very > > long, so I think it's better to ask first to see if it's a known > > bug. > > Only one statement in your code is relevant: the regular expression. For > example, this program should fail for you too: > > """ > import re > > pattern = re.compile('x*?z') > print pattern.match('x' * 50000 + 'z') > """ > > It's almost always possible to rewrite a regular expression in a way that > doesn't require unbounded recursion, but how to do so in all possible cases > is a book-length topic. Some are easy, such as the example above: minimal > match doesn't accomplish anything there, and the regexp > > x*z > > matches the same stuff without using a minimal match operator. The latter > regexp can be used to match strings with millions of characters with no > problems. > > A more common transformation is from (for example) > > \(.*?\) > > to > > \([^)]*\) > > Again the latter spelling can match parenthesized text with millions of > characters, but the former will die after some thousands (the exact limit > depends on your platform -- it runs out of room in C's stack for more > recursive calls, and the amount of memory devoted to the C stack depends on > your platform). > > Minimal matches can be convenient but are limited in how long a substring > they can match. Another way to get unbounded recursion is with a regexp > that stacks up too many backtracking points, but that's even harder to > explain. Friedl's book "Mastering Regular Expressions" (O'Reilly) is an > excellent intro to the topic. > From pan@uchicago.edu Wed May 21 01:31:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Wed May 21 00:31:01 2003 Subject: [Tutor] re module fails to handle text > 16142 characters ??? In-Reply-To: References: Message-ID: <1053491427.3ecb00e3b995f@webmail.uchicago.edu> > Since this is the Tutor list, how about showing us the actual regexp you > used? Then we can try to rewrite it in such a way that you won't bump into > the recursion limit. This could be easy, hard, or impossible, but in any > case should be educational . I was trying to parse an 'archive message' such as those messages in the Tutor list, in an attempt to write an "archive reader". The message body is wrapped within : some header ... ... message body here ... some footer ... It turns out to be a somewhat universal format been used in many different list archives. My idea was to take that message body and present it in a customized way. The following is the a function that I used to grab it: def getSection(doc, startTag, endTag, mustHave='', ignoreCase=1, returnTags=0): if ignoreCase: flag = re.DOTALL | re.IGNORECASE else: flag = re.DOTALL if returnTags: ptn= '(%s.*?%s.*?%s)' %(startTag, mustHave, endTag) else: ptn= '%s(.*?%s.*?)%s' %(startTag, mustHave, endTag) reObj = re.compile(ptn, flag) return reObj.findall(doc)[0] So if I load a message from an archive site, save it to 'msg', and use: msgBody = getSection ( msg, '', ') that should give me the message body. As I mentioned earlier, this way of parsing the text raised a maximum recursion error when the len(msg) is > 16142. After identifying the source of error with the help from you guys, I actually modified the code as: msgBody = msg.split('')[1].split('')[0] which is working nicely. As for 'how to modify the regex approach to avoid the max recursion error', I really have no idea.... pan From davidrogers@telus.net Wed May 21 03:54:02 2003 From: davidrogers@telus.net (David Rogers) Date: Wed May 21 02:54:02 2003 Subject: [Tutor] Absolute newbie - Transliteration Message-ID: Hi I'm an absolute newbie - this is my first attempt with Python or any "real" language, so my advance apologies for any stupid comments. I joined the list just to ask this question, after doing a little searching in the list archives and the documentation and not being able to find out what I want to know. I'm trying make scripts to transliterate a file from (Unicode) Cyrillic characters to each of - Roman script, and - International Phonetic Alphabet (more Unicode). (Whether I end up with separate scripts, one for each transliteration, or one script for all with a bigger dictionary/list/table, is not important to me.) The transliteration will not always be one-to-one in terms of the number of characters, for example the "ch" sound is one letter in Russian but corresponds to two letters in English. I have found the following in the Python web documentation... > translate(table[, deletechars]) > > > Return a copy of the string where all characters occurring in the > optional argument deletechars are removed, and the remaining > characters have been mapped through the given translation table, which > must be a string of length 256. ...but I don't understand what format my table needs to be in, or even if this accommodates Unicode, or the problem of one character sometimes translating to two. If I'm completely on the wrong track here, somebody laugh now before it's too late. :-) What I don't want is a pointer to a non-modifiable Cyrillic-to-Roman transliteration application, because I want to re-use what I do here when I make other transliteration tables to speed up IPA transcription from other languages too. I love IPA. :-) On the other hand, if somebody has already done something like what I want, in a script I can modify for other uses, then I'm all ears. (Some of me is ears all the time.) I'm happy to make the lists, dictionary entries, or whatever format they need to be in - I just want to know how to get Python to read this stuff and then give me back the right thing. I'm using Mac OS X, if it makes any difference. Many thanks David Rogers From lonetwin@yahoo.com Wed May 21 05:36:01 2003 From: lonetwin@yahoo.com (lonetwin) Date: Wed May 21 04:36:01 2003 Subject: [Tutor] spell/grammar checking In-Reply-To: <00c201c31f23$88547a60$6401a8c0@xp> References: <06738462136C054B8F8872D69DA140DB01079C@corp-exch-1.pjinet.com> <00c201c31f23$88547a60$6401a8c0@xp> Message-ID: <200305211423.30445.lonetwin@yahoo.com> Hi all, Just a random comment on this subject. There are a lot of 'dict' servers (eg: the MIT dict server) out there on the net whose protocol (RFC 2229) also allows one to do a spell check (MATCH command) . On my linux box I have a client application called 'gdict' that uses the MIT dict server to do word/spell lookups. Also little googling showed me this: http://melkor.dnp.fmph.uniba.sk/~garabik/serpento/README serpento (for the lack of better name) is a dict (RFC 2229) server written in python. http://gopher.quux.org:70/devel/dictclient This is a new library for interacting with Dict servers. * It defines three classes -- Connection, Database, and Definition. * It supports all common Dict server requests, including definitions, * matching, and getting information about available databases, * capabilities, etc. You can use it to communicate to a local * or remote dictd database. http://gopher.quux.org:70/devel/dictdlib Dictionary creation library More at http://www.dict.org/links.html Nice huh ?? :-) Peace Steve -- Never be afraid to tell the world who you are. - Anonymous From Janssen@rz.uni-frankfurt.de Wed May 21 07:25:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed May 21 06:25:02 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> Message-ID: On Tue, 20 May 2003, Bob Gailer wrote: > I've been noticing deficiencies in the official Python documentation. > What's the procedure to request and/or contribute fixes and improvements? a bugreport with category Documentation: http://sourceforge.net/bugs/?group_id=3D5470 Best is to suggest new text. Your examples was also the hard bits for me. I make some more comments: > > Examples: at http://www.python.org/dev/doc/devel/lib/string-methods.html > 1-decode and encode have an encoding parameter. It is not explained. Possibly add something that explains where to find valid encodings. string-methods is possibly not the right place to explain what an encoding is, but I feel like that the Library Reference should mentioned/explain it. > 2-expandtabs "tab characters are expanded" expanded is not defined. It > takes an experiment to find out what this means. It is already explained: "Return a copy of the string where all tab characters are expanded using spaces". "Expand" means "replace one with many". I believe this is clear. > 3-translate "mapped through the given translation table" Huh? a translation table is pretty wired. Best to explain with: "As returned by string.maketrans()": >>> print string.maketrans("ACEGIK","______") ??!"#$%&'()*+,-./0123456789:;<=3D>?@_B_D_F_H_J_LMNOPQRSTUVWXYZ[\]^_` abcdefghijklmnopqrstuvwxyz{|}~=A1=A2=A3=A4=A5=A6=A7=A8=A9=AA=AB=AC=AD=AE=AF= =B0=B1=B2=B3=B4=B5=B6=B7=B8=B9=BA=BB=BC=BD=BE=BF=C0=C1=C2=C3=C4 =C5=C6=C7=C8=C9=CA=CB=CC=CD=CE=CF=D0=D1=D2=D3=D4=D5=D6=D7=D8=D9=DA=DB=DC=DD= =DE=DF=E0=E1=E2=E3=E4=E5=E6=E7=E8=E9=EA=EB=EC=ED=EE=EF=F0=F1=F2=F3=F4=F5=F6= =F7=F8=F9=FA=FB=FC=FD=FE=FF ---> please note the "_B_D_F_H_J_L" part. Target of the whole activity is to replace more than one char in one step: '123456789'.replace('1','2').replace('2','3').replace('3','4') #and so on is ugly, inefficient and possibly results not as wanted ;-). Better: tr_tbl =3D string.maketrans('123456789','234567890') '123456789'.translate(tr_tbl) Back to your point: "translation table, which must be a string of length 256" isn't enough for an explanation. But what else? Should those topics better covered in the/ in a Tutorial? Michael > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From charlie@begeistert.org Wed May 21 09:12:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Wed May 21 08:12:02 2003 Subject: [Tutor] Struggling with os.exec Message-ID: <20030521141218.2531.11@wonderland.1053502983.fake> Dear list, I have a little script which changes directories for me via os.execl but I can't seem to get it to work properly #! /bin/env python import sys, os from BeOS import fsquery try: arg = sys.argv[1] except: arg = raw_input("What you want? ") q = fsquery.query("name = %s" %arg) choices = {} total = len(q) print "%s results" % total for i in range(total): choices[str(i)] = q[0] print "%s ) %s" %(i, q[0]) go = raw_input("Which you want? ") os.execl("cd", % choices[go]) sys.exit() Where fsquery is a BeOS specific module that searches for files - similar to os.find() but more flexible. I keep getting strange errors with execl and I don't really understand why. Either I get AttributeError: 'module' object has no attribute 'excecl' or File "/boot/home/config/lib/python2.2/os.py", line 266, in execl execv(file, args) OSError: [Errno -2147459069] No such file or directory Would be great to know what I'm doing wrong. Thanx Charlie From pythontutor@venix.com Wed May 21 09:43:02 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed May 21 08:43:02 2003 Subject: [Tutor] Struggling with os.exec References: <20030521141218.2531.11@wonderland.1053502983.fake> Message-ID: <3ECB73DA.1060900@venix.com> This doesn't answer your question, but couldn't you use: os.chdir(choices[go]) rather than os.execl. One possible cause for your execl problem is that cd may not be an executable. Usually cd is a command within a shell (I have no BeOS experience). In that case, os.system("cd %s" % choices[go]) might work for you. However, os.chdir should be the best option. The books, "Python Standard Library" and "Python in a Nutshell" cover these topics. Charlie Clark wrote: > Dear list, > > I have a little script which changes directories for me via os.execl but I > can't seem to get it to work properly > > #! /bin/env python > > import sys, os > from BeOS import fsquery > > try: > arg = sys.argv[1] > except: > arg = raw_input("What you want? ") > > q = fsquery.query("name = %s" %arg) > > choices = {} > total = len(q) > > print "%s results" % total > for i in range(total): > choices[str(i)] = q[0] > print "%s ) %s" %(i, q[0]) > > go = raw_input("Which you want? ") > > os.execl("cd", % choices[go]) > sys.exit() > > Where fsquery is a BeOS specific module that searches for files - similar > to os.find() but more flexible. > > I keep getting strange errors with execl and I don't really understand why. > Either I get > AttributeError: 'module' object has no attribute 'excecl' > > or > > File "/boot/home/config/lib/python2.2/os.py", line 266, in execl > execv(file, args) > OSError: [Errno -2147459069] No such file or directory > > Would be great to know what I'm doing wrong. > > Thanx > > Charlie > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From neh@attbi.com Wed May 21 10:58:01 2003 From: neh@attbi.com (Neil Hodge) Date: Wed May 21 09:58:01 2003 Subject: [Tutor] Odd AttributeError Message-ID: <1053525387.2219.13.camel@zeus.localdomain> All: I have the following code: def __init__(self, file, name='unknown filename', as_tuple=0): . . . print 'printing as_tuple:', as_tuple print 'defining self.as_tuple . . .' self.as_tuple = as_tuple print 'printing self.as_tuple: ', self.as_tuple and the following output: printing as_tuple: 0 defining self.as_tuple . . . printing self.as_tuple: Traceback (most recent call last): File "./id3-tagger.py", line 93, in ? main() File "./id3-tagger.py", line 68, in main id3info = ID3(file) File "./ID3.py", line 211, in __init__ print 'printing self.as_tuple: ', self.as_tuple AttributeError: ID3 instance has no attribute 'as_tuple' So, why does self.as_tuple not exist right after I defined it? Thanks. Neil From charlie@begeistert.org Wed May 21 12:02:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Wed May 21 11:02:02 2003 Subject: [Tutor] Struggling with os.exec In-Reply-To: <3ECB73DA.1060900@venix.com> References: <20030521141218.2531.11@wonderland.1053502983.fake> <3ECB73DA.1060900@venix.com> Message-ID: <20030521170147.3169.16@wonderland.1053502983.fake> On 2003-05-21 at 14:40:58 [+0200], you wrote: > This doesn't answer your question, but couldn't you use: > os.chdir(choices[go]) > rather than os.execl. No, because this only changes the directory within Python. This script is to replace a shell script. > One possible cause for your execl problem is that cd may not be an > executable. Usually cd is a command within a shell (I have no BeOS > experience). In that case, os.system("cd %s" % choices[go]) might work > for you. However, os.chdir should be the best option. The books, > "Python Standard Library" and "Python in a Nutshell" cover these topics. I have both and read them both first but couldn't find enlightenment. BeOS has a bash (2.03) shell so this is essentially a "posix" question and "cd" is obviously a built-in command. Is it still possible to call "cd" from within Python? Charliey From pythontutor@venix.com Wed May 21 12:18:02 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed May 21 11:18:02 2003 Subject: [Tutor] Odd AttributeError References: <1053525387.2219.13.camel@zeus.localdomain> Message-ID: <3ECB9850.7020402@venix.com> The secret could be in the lines you left out. file is not a good variable name since it is also a python type. Your code works: (i changed file to filex) class ID3: def __init__(self, filex, name='unknown filename', as_tuple=0): print 'printing as_tuple:', as_tuple print 'defining self.as_tuple . . .' self.as_tuple = as_tuple print 'printing self.as_tuple: ', self.as_tuple filex = file(r'c:\autoexec.bat','rt') ID3(filex) >>> printing as_tuple: 0 defining self.as_tuple . . . printing self.as_tuple: 0 Neil Hodge wrote: > All: > > I have the following code: > > def __init__(self, file, name='unknown filename', as_tuple=0): > . > . > . > print 'printing as_tuple:', as_tuple > print 'defining self.as_tuple . . .' > self.as_tuple = as_tuple > print 'printing self.as_tuple: ', self.as_tuple > > and the following output: > > printing as_tuple: 0 > defining self.as_tuple . . . > printing self.as_tuple: > Traceback (most recent call last): > File "./id3-tagger.py", line 93, in ? > main() > File "./id3-tagger.py", line 68, in main > id3info = ID3(file) > File "./ID3.py", line 211, in __init__ > print 'printing self.as_tuple: ', self.as_tuple > AttributeError: ID3 instance has no attribute 'as_tuple' > > So, why does self.as_tuple not exist right after I defined it? Thanks. > > Neil > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From neh@attbi.com Wed May 21 12:40:02 2003 From: neh@attbi.com (Neil Hodge) Date: Wed May 21 11:40:02 2003 Subject: [Tutor] Odd AttributeError In-Reply-To: <3ECB9850.7020402@venix.com> References: <1053525387.2219.13.camel@zeus.localdomain> <3ECB9850.7020402@venix.com> Message-ID: <1053531540.2219.34.camel@zeus.localdomain> LLoyd: On Wed, 2003-05-21 at 08:16, Lloyd Kvam wrote: > The secret could be in the lines you left out. file is not a good > variable name since it is also a python type. Undoubtedly. This is someone else's code that I am modifying; I will change the "file" variable name. > Your code works: > (i changed file to filex) > > class ID3: > def __init__(self, filex, name='unknown filename', as_tuple=0): > print 'printing as_tuple:', as_tuple > print 'defining self.as_tuple . . .' > self.as_tuple = as_tuple > print 'printing self.as_tuple: ', self.as_tuple > > filex = file(r'c:\autoexec.bat','rt') > ID3(filex) > > >>> printing as_tuple: 0 > defining self.as_tuple . . . > printing self.as_tuple: 0 > Interesting; apparently your comment about the problem being elsewhere is the case. OK, here is all of the code in that class up until that point: class ID3: genres = [ "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", etc. . . . ] def __init__(self, f, name='unknown filename', as_tuple=0): if type(f) in string_types: self.filename = f # We don't open in r+b if we don't have to, to allow read-only access self.f = open(f, 'rb') self.can_reopen = 1 elif hasattr(f, 'seek'): # assume it's an open file if name == 'unknown filename' and hasattr(f, 'name'): self.filename = f.name else: self.filename = name self.f = f self.can_reopen = 0 self.d = {} print 'printing as_tuple:', as_tuple print 'defining self.as_tuple . . .' self.as_tuple = as_tuple print 'printing self.as_tuple: %d ' % self.as_tuple And here is the output: printing as_tuple: 0 defining self.as_tuple . . . Traceback (most recent call last): File "./id3-tagger.py", line 93, in ? main() File "./id3-tagger.py", line 68, in main id3info = ID3(f) File "./ID3.py", line 212, in __init__ print 'printing self.as_tuple: %d ' % self.as_tuple AttributeError: ID3 instance has no attribute 'as_tuple' Frankly, I do not see anything prior to the error in the code that would contribute to this, but obviously something is going wrong. Let me know what you think. Neil From bgailer@alum.rpi.edu Wed May 21 12:46:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed May 21 11:46:01 2003 Subject: [Tutor] Absolute newbie - Transliteration In-Reply-To: Message-ID: <5.2.0.9.0.20030521094305.027c04f8@66.28.54.253> At 11:51 PM 5/20/2003 -0700, David Rogers wrote: >Hi > >I'm an absolute newbie - this is my first attempt with Python or any >"real" language, so my advance apologies for any stupid comments. I >joined the list just to ask this question, after doing a little searching >in the list archives and the documentation and not being able to find out >what I want to know. > >I'm trying make scripts to transliterate a file from (Unicode) Cyrillic >characters to each of >- Roman script, and >- International Phonetic Alphabet (more Unicode). > >(Whether I end up with separate scripts, one for each transliteration, or >one script for all with a bigger dictionary/list/table, is not important >to me.) > >The transliteration will not always be one-to-one in terms of the number >of characters, for example the "ch" sound is one letter in Russian but >corresponds to two letters in English. > >I have found the following in the Python web documentation... > >>translate(table[, deletechars]) >> >> >>Return a copy of the string where all characters occurring in the >>optional argument deletechars are removed, and the remaining characters >>have been mapped through the given translation table, which must be a >>string of length 256. > > >...but I don't understand what format my table needs to be in, or even if >this accommodates Unicode, or the problem of one character sometimes >translating to two. If I'm completely on the wrong track here, somebody >laugh now before it's too late. :-) > > >What I don't want is a pointer to a non-modifiable Cyrillic-to-Roman >transliteration application, because I want to re-use what I do here when >I make other transliteration tables to speed up IPA transcription from >other languages too. I love IPA. :-) > >On the other hand, if somebody has already done something like what I >want, in a script I can modify for other uses, then I'm all ears. >(Some of me is ears all the time.) I'm happy to make the lists, >dictionary entries, or whatever format they need to be in - I just want to >know how to get Python to read this stuff and then give me back the right >thing. > >I'm using Mac OS X, if it makes any difference. translate() is for ASCII not Unicode. My best guess is a dictionary. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From dedoleo@hotmail.com Wed May 21 13:41:23 2003 From: dedoleo@hotmail.com (David Scott) Date: Wed May 21 12:41:23 2003 Subject: [Tutor] FTP Disconnect Message-ID: How can I use a python script to disconnect an FTP session from another program (because the other program, or Windows, is not closing the socket or whatever)? -------------------------------------- dedoleo@hotmail.com http://groups.msn.com/WalledCity _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From bgailer@alum.rpi.edu Wed May 21 14:36:27 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed May 21 13:36:27 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: References: <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> Message-ID: <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> At 12:23 PM 5/21/2003 +0200, Michael Janssen wrote: >On Tue, 20 May 2003, Bob Gailer wrote: >[snip] > > 2-expandtabs "tab characters are expanded" expanded is not defined. It > > takes an experiment to find out what this means. > >It is already explained: >"Return a copy of the string where all tab characters are expanded using >spaces". "Expand" means "replace one with many". I believe this is clear. So one would expect 'a\tab\tabc\tabcd\t'.expandtabs() to produce 'a ab abc adcd ' where there are 8 spaces between each word? But that's NOT what happens. So the definition is not explicit enough. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From tutor@python.org Wed May 21 14:39:24 2003 From: tutor@python.org (Tim Peters) Date: Wed May 21 13:39:24 2003 Subject: [Tutor] re module fails to handle text > 16142 characters ??? In-Reply-To: <1053409396.3ec9c0742316b@webmail.uchicago.edu> Message-ID: [pan@uchicago.edu] > The other day I was using re to do some parsing and > found that one of the text that I tried to parse returned > an error : > > return reObj.findall(doc)[0] > RuntimeError: maximum recursion limit exceeded > > After some painful debugging, I found: > > let S = len(doc) > > 1. When S > 16143: re.find function failed; > 2. When S = 16143: failed too > 3. When S = 16142: successful. This was tested by deleting ANY > character in that 16143-long doc. > > I am using Python 2.2.1. Is this a known-bug??? You're probably using a minimal-match construct in the regexp, like .*? Minimal matches are done using recursion, proportional to the length of the substring they're trying to match. If so, it's a limitation of the implementation, but isn't considered to be a bug -- that's just the way it works. If you had infinite memory, it wouldn't complain . It's akin to trying to write a 20 gigabyte file on a system with a 1 gigabyte disk. > I would really like to post the entire code here but it's very > long, so I think it's better to ask first to see if it's a known > bug. Only one statement in your code is relevant: the regular expression. For example, this program should fail for you too: """ import re pattern = re.compile('x*?z') print pattern.match('x' * 50000 + 'z') """ It's almost always possible to rewrite a regular expression in a way that doesn't require unbounded recursion, but how to do so in all possible cases is a book-length topic. Some are easy, such as the example above: minimal match doesn't accomplish anything there, and the regexp x*z matches the same stuff without using a minimal match operator. The latter regexp can be used to match strings with millions of characters with no problems. A more common transformation is from (for example) \(.*?\) to \([^)]*\) Again the latter spelling can match parenthesized text with millions of characters, but the former will die after some thousands (the exact limit depends on your platform -- it runs out of room in C's stack for more recursive calls, and the amount of memory devoted to the C stack depends on your platform). Minimal matches can be convenient but are limited in how long a substring they can match. Another way to get unbounded recursion is with a regexp that stacks up too many backtracking points, but that's even harder to explain. Friedl's book "Mastering Regular Expressions" (O'Reilly) is an excellent intro to the topic. From tim_one@email.msn.com Wed May 21 14:39:45 2003 From: tim_one@email.msn.com (Tim Peters) Date: Wed May 21 13:39:45 2003 Subject: [Tutor] re module fails to handle text > 16142 characters ??? In-Reply-To: <1053484986.3ecae7ba59f1b@webmail.uchicago.edu> Message-ID: [pan@uchicago.edu] > Thx to all those replied. I did use a minimal-match construct > ( .*? ) like what Tim mentioned (see below). > > Since Tim's reply somehow didn't show up on the list (even though > in his email to me the tutor@python.org did show up on the "cc:" > field of my email program) so I am forwarding his explanation to > you guys. The msg didn't show up here because it's being held for moderator approval -- I didn't send it using the email account I used to subscribe to the list. I don't even remember which account that is anymore, so this msg will probably get held too. It will show up eventually. Since this is the Tutor list, how about showing us the actual regexp you used? Then we can try to rewrite it in such a way that you won't bump into the recursion limit. This could be easy, hard, or impossible, but in any case should be educational . From godoy@ieee.org Wed May 21 14:39:59 2003 From: godoy@ieee.org (Jorge Godoy) Date: Wed May 21 13:39:59 2003 Subject: [Tutor] Handling international characters Message-ID: Hi! I'm having problems with some characters in two distinct places: * wxPython * pgdb (PostgreSQL access module) For wxPython it seems to me that all my characters are converted to Unicode, even if the XRC file states that they are encoded in iso-8859-1. The result is that some wxStaticText show up with messed text on chars like '=E7', '=B0', etc. Is there something I can do to use iso-8859-1 with it (it would cause me some problems to have to switch to UTF-8 due to some collaborators and multiplatform stuff on a project)?=20 (Please, note that I'm using the XRC and not coding it directly in Python, where strings are printed correctly... I suspect that there's something related to the minidom/XML stuff...) With regards to pgdb, the result is a little better: I see the Unicode code, but I don't see the correct char (I see them correctly with psql, so this is not a database problem). One sample output is: ---------------------------------------------------------------------- [['Jorge', 'Godoy'], ['Juliano', 'Godoy'], ['\xc9rica', 'Balaniuc']] ---------------------------------------------------------------------- The '\xc9' should be an '=C9'.=20 I've already added the following statement (from http://savannah.gnu.org/cgi-bin/viewcvs/gnue/gnue/common/src/datasources/= drivers/postgresql/pygresql/Driver.py?rev=3D1.41&content-type=3Dtext/vnd.= viewcvs-markup ) to my code: ---------------------------------------------------------------------- cursor.execute("SET CLIENT_ENCODING TO 'iso-8859-1'") ---------------------------------------------------------------------- (and case variations such as 'ISO-...', 'Iso-...' and even 'ISO8859-1', but I had no success with that) I'm also following --- in both cases --- the PEP-263 recommendation of specifying the encoding used in my source code as 'iso-8859-1'.=20 Any hints would be greatly appreciated. If you'd like a sample of source code and/or database entries, I can provide you with that. TIA, --=20 Godoy. From rick@niof.net Wed May 21 14:47:02 2003 From: rick@niof.net (Rick Pasotto) Date: Wed May 21 13:47:02 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> References: <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> Message-ID: <20030521174607.GW1267@tc.telocity.com> On Wed, May 21, 2003 at 11:34:55AM -0600, Bob Gailer wrote: > At 12:23 PM 5/21/2003 +0200, Michael Janssen wrote: > > >On Tue, 20 May 2003, Bob Gailer wrote: > >[snip] > >> 2-expandtabs "tab characters are expanded" expanded is not defined. It > >> takes an experiment to find out what this means. > > > >It is already explained: > >"Return a copy of the string where all tab characters are expanded using > >spaces". "Expand" means "replace one with many". I believe this is clear. > > So one would expect 'a\tab\tabc\tabcd\t'.expandtabs() to produce > 'a ab abc adcd ' where there are 8 spaces > between each word? But that's NOT what happens. So the definition is not > explicit enough. Perhaps you are too young to have used tab stops on a typewriter. -- "Education is an admirable thing, but it is well to remember that nothing that is worth knowing can be taught." -- Oscar Wilde Rick Pasotto rick@niof.net http://www.niof.net From absmythe@ucdavis.edu Wed May 21 14:53:01 2003 From: absmythe@ucdavis.edu (ashleigh smythe) Date: Wed May 21 13:53:01 2003 Subject: [Tutor] easy newbie questions: text file to list? In-Reply-To: <20030520095314.GA2478@nl.linux.org> References: <1053370209.9606.341.camel@nate.ucdavis.edu> <20030520095314.GA2478@nl.linux.org> Message-ID: <1053514143.28257.11.camel@nate.ucdavis.edu> Thanks to everybody for their help on turning my text file into a list. Gerrit's tip on the string method splitlines() worked great and seems to be the easiest answer for me but I liked seeing everyone else's different ideas. You guys weren't kidding when you say there's more than one way to do things with Python! I'm a little clearer on pickle now so thanks for those tips too. Ashleigh *************************** Ashleigh B. Smythe Graduate Research Assistant Department of Nematology UC Davis Davis, CA 95616 phone 530-754-4321 email absmythe@ucdavis.edu From bgailer@alum.rpi.edu Wed May 21 15:30:03 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed May 21 14:30:03 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <20030521174607.GW1267@tc.telocity.com> References: <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> Message-ID: <5.2.0.9.0.20030521122417.038e3e78@66.28.54.253> At 01:46 PM 5/21/2003 -0400, Rick Pasotto wrote: >On Wed, May 21, 2003 at 11:34:55AM -0600, Bob Gailer wrote: > > At 12:23 PM 5/21/2003 +0200, Michael Janssen wrote: > > > > >On Tue, 20 May 2003, Bob Gailer wrote: > > >[snip] > > >> 2-expandtabs "tab characters are expanded" expanded is not defined. It > > >> takes an experiment to find out what this means. > > > > > >It is already explained: > > >"Return a copy of the string where all tab characters are expanded using > > >spaces". "Expand" means "replace one with many". I believe this is clear. > > > > So one would expect 'a\tab\tabc\tabcd\t'.expandtabs() to produce > > 'a ab abc adcd ' where there are 8 spaces > > between each word? But that's NOT what happens. So the definition is not > > explicit enough. > >Perhaps you are too young to have used tab stops on a typewriter. Quite the opposite; I learned typing on a Royal in Junior High. I even got in trouble with the teacher when I was playing with the tab mechanism before we had officially covered it. Regardless I did fail to relate the tab character to its historical beginnings. I do think that documentation should be as independent as possible from such allusions so that one can get the definition without extra wondering. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From jeff@ccvcorp.com Wed May 21 15:31:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed May 21 14:31:03 2003 Subject: [Tutor] Struggling with os.exec References: <20030521141218.2531.11@wonderland.1053502983.fake> <3ECB73DA.1060900@venix.com> <20030521170147.3169.16@wonderland.1053502983.fake> Message-ID: <3ECBC689.6010509@ccvcorp.com> Charlie Clark wrote: >On 2003-05-21 at 14:40:58 [+0200], you wrote: > > >>This doesn't answer your question, but couldn't you use: >> os.chdir(choices[go]) >>rather than os.execl. >> >> > >No, because this only changes the directory within Python. This script is >to replace a shell script. > I'm not completely certain, but I believe that os.execl() will do the same thing. Python runs in a child process of your shell session, and AFAIK a child process cannot change the environment of its parent. A shell script, on the other hand, can run within the shell session and so *can* modify the environment. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Wed May 21 15:38:07 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed May 21 14:38:07 2003 Subject: [Tutor] Documentation concerns. References: <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> Message-ID: <3ECBC817.7020400@ccvcorp.com> Bob Gailer wrote: > At 12:23 PM 5/21/2003 +0200, Michael Janssen wrote: > >> On Tue, 20 May 2003, Bob Gailer wrote: >> [snip] >> > 2-expandtabs "tab characters are expanded" expanded is not defined. It >> > takes an experiment to find out what this means. >> >> It is already explained: >> "Return a copy of the string where all tab characters are expanded using >> spaces". "Expand" means "replace one with many". I believe this is >> clear. > > > So one would expect 'a\tab\tabc\tabcd\t'.expandtabs() to produce > 'a ab abc adcd ' where there are 8 spaces > between each word? But that's NOT what happens. So the definition is > not explicit enough. No, one would (or at least, one SHOULD) expect that each tab would expand to enough spaces to place the beginning of the next word at the next 8-character boundary, i.e. the next tabstop. Or, to put it another way, for any string 'X', the length of 'X\t'.expandtabs() will be some multiple of 8, regardless of the length of 'X'. The standard meaning of tab is "advance to the next tabstop", and Python defines tabstops as occurring every 8 characters, so this is very much in keeping with the commonly understood usage of tabs. Jeff Shannon Technician/Programmer Credit International From alan.gauld@blueyonder.co.uk Wed May 21 16:00:03 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Wed May 21 15:00:03 2003 Subject: [Tutor] Struggling with os.exec References: <20030521141218.2531.11@wonderland.1053502983.fake> <3ECB73DA.1060900@venix.com> <20030521170147.3169.16@wonderland.1053502983.fake> Message-ID: <012001c31fcb$21fb10f0$6401a8c0@xp> > has a bash (2.03) shell so this is essentially a "posix" question and "cd" > is obviously a built-in command. Is it still possible to call "cd" from > within Python? You might need to do "bash -c 'cd /foo/bar'" or somesuch instead. Just a guess, so probably wrong! :-/ Alan G From gerrit@nl.linux.org Wed May 21 16:57:21 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Wed May 21 15:57:21 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <3ECBC817.7020400@ccvcorp.com> References: <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <3ECBC817.7020400@ccvcorp.com> Message-ID: <20030521195606.GA2760@nl.linux.org> Jeff Shannon schreef op woensdag 21 mei om 20:40:44 +0000: > >>> 2-expandtabs "tab characters are expanded" expanded is not defined. It > >> > >>It is already explained: > >>"Return a copy of the string where all tab characters are expanded using > >>spaces". "Expand" means "replace one with many". I believe this is > >>clear. > > > >So one would expect 'a\tab\tabc\tabcd\t'.expandtabs() to produce > >'a ab abc adcd ' where there are 8 spaces > >between each word? But that's NOT what happens. So the definition is > >not explicit enough. > > The standard meaning of > tab is "advance to the next tabstop", and Python defines tabstops as > occurring every 8 characters, so this is very much in keeping with the > commonly understood usage of tabs. Maybe the Python docs should link to a place where this is explained, as RFC's are linked also. Is this a good idea? yours, Gerrit. -- 228. If a builder build a house for some one and complete it, he shall give him a fee of two shekels in money for each sar of surface. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From hemanexp@yahoo.com Thu May 22 05:06:13 2003 From: hemanexp@yahoo.com (Python-lover) Date: Thu May 22 04:06:13 2003 Subject: [Tutor] Validity check for different data types....................... Message-ID: <20030522080357.48374.qmail@web41904.mail.yahoo.com> --0-1572837701-1053590637=:47363 Content-Type: text/plain; charset=us-ascii hi, I am using python and Tkinter in my application. My problem is as follows. I am using "tkSimpleDiallog" widget to display some values. I have placed 10 entry widgets in the dialog box. Among 10 entry widgets some widgets must have only string values and some others must hold intergers and others hold floats. I expect validity checks for "KeyRelease" event for all entry eidgets. Now the problem is "do i need to have 10 validity check routines one for each entry widget? or having 3 routines (one for string, one for int,one for float) is enough?". My sample program is given below:*********************************************class SampleDialog(tkSimpleDialog.Dialog): def __init__( self, parent, title, name) : self.name = name[:] tkSimpleDialog.Dialog.__init__( self, parent, title) def body(self,master): self.SampleEntry0=Entry(master) self.SampleEntry0.insert(0,self.name[0]) self.SampleEntry0.pack() self.SampleEntry0.bind('',self.validate_check) self.SampleEntry1=Entry(master) self.SampleEntry1.insert(0,self.name[1]) self.SampleEntry1.pack() def apply(self): self.name[0]=self.SampleEntry0.get() self.name[1]=self.SampleEntry1.get() def validate_check(self,event): try: chk=self.SampleEntry0.get() if chk: chkval = string.atoi(chk) print "No Error",chk return 1 except ValueError: tkMessageBox.showwarning("Bad input", Illegal values") return 0 Here i showed you only 2 entry widgets. First entry widget "SampleEntry0" holds float and second one "SampleEntry1" holds string. The routine "validate_check" checks whether the 1st entry is float or not for evry keyrelease. Suppose if i have another entry widget say "SampleEntry2" which also holds a float, how can i change the above "validate_check" routine so that it will be used for all entry widgets that hold floats? Or do i have to repeat the same routine by only changing the line "chk = self.SampleEntry0.get() ? It is not easy to manage when number of widgets is increased. Moreover is it possible to send the value that a entry widget has, to an event handler using "event binding"? I tried the same with "lambda". But instead of the value i got entry widgets instance number. The code is given below. self.SampleEntry0.bind('', lambda arg1=self.SampleEntry0.get(): self.validate_check(arg1)) #********* Event handler def validate_check(self,arg1): print arg1 So, how can i overcome above problems? Expecting your valuable comments.Thanx. --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-1572837701-1053590637=:47363 Content-Type: text/html; charset=us-ascii
hi,
 
  I am using python and Tkinter in my application. My problem is as follows. I am using "tkSimpleDiallog" widget to display some values. I have placed 10 entry widgets in the dialog box. Among 10 entry widgets some widgets must have only string values and some others must hold intergers and others hold floats. I expect validity checks  for "KeyRelease" event for all entry eidgets. Now the problem is "do i need to have 10 validity check routines one for each entry widget? or  having 3 routines (one for string, one for int,one for float) is enough?".
 
  My sample program is given below:
*********************************************
class SampleDialog(tkSimpleDialog.Dialog):
    def __init__( self, parent, title, name) :
        self.name = name[:]
        tkSimpleDialog.Dialog.__init__( self, parent, title)
        def body(self,master):
            self.SampleEntry0=Entry(master)
            self.SampleEntry0.insert(0,self.name[0])
           self.SampleEntry0.pack()
           self.SampleEntry0.bind('<KeyRelease>',self.validate_check)
           self.SampleEntry1=Entry(master)
           self.SampleEntry1.insert(0,self.name[1])
           self.SampleEntry1.pack()
             
    def apply(self):
            self.name[0]=self.SampleEntry0.get()       
            self.name[1]=self.SampleEntry1.get()
   
    def validate_check(self,event):
       try:
             chk=self.SampleEntry0.get()
              if chk:
                       chkval = string.atoi(chk)
                       print "No Error",chk
                       return 1
             except ValueError:
                     tkMessageBox.showwarning("Bad input", Illegal values")
             return 0
 
     Here i showed you only 2 entry widgets. First entry widget "SampleEntry0" holds float and second one "SampleEntry1" holds string. The routine "validate_check" checks whether the 1st entry is float or not for evry keyrelease. Suppose if i have another entry widget  say "SampleEntry2" which also holds a float, how can i change the above "validate_check" routine so that it will be used for all entry widgets that hold floats? Or do i have to repeat the same routine by only changing the line "chk = self.SampleEntry0.get() ? It is not easy to manage when number of widgets is increased.
 
    Moreover is it possible to send the value that a entry widget has, to an event handler using "event binding"? I tried the same with  "lambda". But instead of the value i got entry widgets instance number. The code is
given below.
 
self.SampleEntry0.bind('<KeyRelease>',
            lambda
            arg1=self.SampleEntry0.get():
            self.validate_check(arg1))
 
#*********  Event handler
 
    def validate_check(self,arg1):
        print arg1
 
 So, how can i overcome above problems?  Expecting your valuable comments.
Thanx.


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-1572837701-1053590637=:47363-- From alan.gauld@blueyonder.co.uk Thu May 22 06:01:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Thu May 22 05:01:02 2003 Subject: [Tutor] Documentation concerns. References: <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> Message-ID: <013801c32040$9fb80960$6401a8c0@xp> > So one would expect 'a\tab\tabc\tabcd\t'.expandtabs() to produce > 'a ab abc adcd ' where there are 8 spaces > between each word? But that's NOT what happens. So the definition is not > explicit enough. No, that would be converting tabs into 8 chars but expand fills the space with up to 8 chars. I must admit it behaves exactly as I would expect: >>> result = '' >>> for c in range(50): ... if c % 8 == 0: result += '|' ... else: result += '-' ... >>> print result |-------|-------|-------|-------|-------|-------|- >>> 'a ab abc abcd '.expandtabs() 'a ab abc abcd ' >>> What else did you think it might do Bob? Alan G. From alan.gauld@blueyonder.co.uk Thu May 22 06:14:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Thu May 22 05:14:02 2003 Subject: [Tutor] Validity check for different data types....................... References: <20030522080357.48374.qmail@web41904.mail.yahoo.com> Message-ID: <001801c32042$70fb65c0$6401a8c0@xp> > I expect validity checks for "KeyRelease" event for all entry > widgets. Now the problem is "do i need to have 10 validity check > routines one for each entry widget? or having 3 routines > (one for string, one for int,one for float) is enough?". 3 should suffice. You can call the routines from your entry handlers. def isString(s): return type(s) == type('') def isInteger(i): return type(i) == type(7) def isFloat(f): return type(f) == type(7.0) Entries = {} for e in range(10): Entries[e] = Entry(.....) if e % 3 == 0: bind(, Entries[e], lambda e: isString(e.value)) elif e % 2 == 0: bind(, Entries[e], lambda e: isInteger.value()) else: bind(, Entries[e], lambda e: isFloat(e.value()) Creates 10 entries with some checking integers, some strings etc. You probably want to control which entry does what rather more methodically than that but you get the idea... Your type checking might want to be a tad more sophisticated too! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From hemanexp@yahoo.com Thu May 22 10:21:02 2003 From: hemanexp@yahoo.com (Python-lover) Date: Thu May 22 09:21:02 2003 Subject: [Tutor] Validity check for different data types...................... Message-ID: <20030522072950.13007.qmail@web41903.mail.yahoo.com> --0-159316275-1053588590=:11956 Content-Type: text/plain; charset=us-ascii hi, I am using python and Tkinter in my application. My problem is as follows. I am using "tkSimpleDiallog" widget to display some values. I have placed 10 entry widgets in the dialog box. Among 10 entry widgets some widgets must have only string values and some others must hold intergers and others hold floats. I expect validity checks for "KeyRelease" event for all entry eidgets. Now the problem is "do i need to have 10 validity check routines one for each entry widget? or having 3 routines (one for string, one for int,one for float) is enough?". My sample program is given below:*******************************************class SampleDialog(tkSimpleDialog.Dialog): def __init__( self, parent, title, name) : self.name = name[:] tkSimpleDialog.Dialog.__init__( self, parent, title) def body(self,master): self.SampleEntry0=Entry(master) self.SampleEntry0.insert(0,self.name[0]) self.SampleEntry0.pack() self.SampleEntry0.bind('',self.validate_check) self.SampleEntry1=Entry(master) self.SampleEntry1.insert(0,self.name[1]) self.SampleEntry1.pack() def apply(self): self.name[0]=self.SampleEntry0.get() self.name[1]=self.SampleEntry1.get() def validate_check(self,event): try: chk=self.SampleEntry0.get() if chk: chkval = string.atoi(chk) print "No Error",chk return 1 except ValueError: tkMessageBox.showwarning("Bad input", Illegal values") return 0 Here i showed you only 2 entry widgets. First entry widget "SampleEntry0" holds float and second one "SampleEntry1" holds string. The routine "validate_check" checks whether the 1st entry is float or not for evry keyrelease. Suppose if i have another entry widget say "SampleEntry2" which also holds a float, how can i change the above "validate_check" routine so that it will be used for all entry widgets that hold floats? Or do i have to repeat the same routine by only changing the line "chk = self.SampleEntry0.get() ? It is not easy to manage when number of widgets is increased. Moreover is it possible to send the value that a entry widget has, to an event handler using "event binding"? I tried the same with "lambda". But instead of the value i got entry widgets instance number. The code is given below. self.SampleEntry0.bind('', lambda arg1=self.SampleEntry0.get(): self.validate_check(arg1)) #********* Event handler def validate_check(self,arg1): print arg1 So, how can i overcome above problems? Expecting your valuable comments. Thanx. --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-159316275-1053588590=:11956 Content-Type: text/html; charset=us-ascii
hi,
 
  I am using python and Tkinter in my application. My problem is as
follows. I am using "tkSimpleDiallog" widget to display some values. I
have placed 10 entry widgets in the dialog box. Among 10 entry widgets
some widgets must have only string values and some others must hold
intergers and others hold floats. I expect validity checks  for
"KeyRelease" event for all entry eidgets. Now the problem is "do i need
to have 10 validity check routines one for each entry widget? or 
having 3 routines (one for string, one for int,one for float) is
enough?".
 
  My sample program is given below:
*******************************************
class SampleDialog(tkSimpleDialog.Dialog):
    def __init__( self, parent, title, name) :
        self.name = name[:]
        tkSimpleDialog.Dialog.__init__( self, parent, title)
        def body(self,master):
            self.SampleEntry0=Entry(master)
            self.SampleEntry0.insert(0,self.name[0])
            self.SampleEntry0.pack()
            self.SampleEntry0.bind('<KeyRelease>',self.validate_check)
            self.SampleEntry1=Entry(master)
            self.SampleEntry1.insert(0,self.name[1])
            self.SampleEntry1.pack()
             
    def apply(self):
            self.name[0]=self.SampleEntry0.get()       
            self.name[1]=self.SampleEntry1.get()
   
    def validate_check(self,event):
       try:
             chk=self.SampleEntry0.get()
              if chk:
                       chkval = string.atoi(chk)
                       print "No Error",chk
                       return 1
             except ValueError:
                     tkMessageBox.showwarning("Bad input", Illegal
values")
             return 0
    
      Here i showed you only 2 entry widgets. First entry widget
"SampleEntry0" holds float and second one "SampleEntry1" holds string. The routine "validate_check" checks whether the 1st entry is float or not for evry keyrelease. Suppose if i have another entry widget  say
"SampleEntry2" which also holds a float, how can i change the above
"validate_check" routine so that it will be used for all entry widgets
that hold floats? Or do i have to repeat the same routine by only
changing the line "chk = self.SampleEntry0.get() ? It is not easy to
manage when number of widgets is increased.
 
    Moreover is it possible to send the value that a entry widget has,
to an event handler using "event binding"? I tried the same with 
"lambda". But instead of the value i got entry widgets instance number.
The code is given below.
 
self.SampleEntry0.bind('<KeyRelease>',
            lambda
            arg1=self.SampleEntry0.get():
            self.validate_check(arg1))
 
#*********  Event handler
 
    def validate_check(self,arg1):
        print arg1
 
 So, how can i overcome above problems?  Expecting your valuable
comments.
 
Thanx.


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-159316275-1053588590=:11956-- From charlie@begeistert.org Thu May 22 12:03:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Thu May 22 11:03:02 2003 Subject: [Tutor] Struggling with os.exec In-Reply-To: <012001c31fcb$21fb10f0$6401a8c0@xp> References: <20030521141218.2531.11@wonderland.1053502983.fake> <3ECB73DA.1060900@venix.com> <20030521170147.3169.16@wonderland.1053502983.fake> <012001c31fcb$21fb10f0$6401a8c0@xp> Message-ID: <20030522170315.635.1@wonderland.1053615256.fake> On 2003-05-21 at 20:59:40 [+0200], you wrote: > > has a bash (2.03) shell so this is essentially a "posix" question > and "cd" > > is obviously a built-in command. Is it still possible to call "cd" > from > > within Python? > > You might need to do "bash -c 'cd /foo/bar'" or somesuch instead. > > Just a guess, so probably wrong! :-/ That works without the 's but has seems to call the function "cd" as a process in it's own write, ie. with it's own environment variables. What I need to do is to be able to change the variables in the parent process, the one from which Python is called. I thought this would be easy but it's turning into a real challenge... ie., I'm still open for ideas! Charlie (currently working through the online manual for the bash shell) From rick@niof.net Thu May 22 12:12:02 2003 From: rick@niof.net (Rick Pasotto) Date: Thu May 22 11:12:02 2003 Subject: [Tutor] Struggling with os.exec In-Reply-To: <20030522170315.635.1@wonderland.1053615256.fake> References: <20030521141218.2531.11@wonderland.1053502983.fake> <3ECB73DA.1060900@venix.com> <20030521170147.3169.16@wonderland.1053502983.fake> <012001c31fcb$21fb10f0$6401a8c0@xp> <20030522170315.635.1@wonderland.1053615256.fake> Message-ID: <20030522151108.GZ1267@tc.telocity.com> On Thu, May 22, 2003 at 05:03:15PM +0200, Charlie Clark wrote: > > On 2003-05-21 at 20:59:40 [+0200], you wrote: > > > has a bash (2.03) shell so this is essentially a "posix" question > > > and "cd" is obviously a built-in command. Is it still possible to > > > call "cd" from within Python? > > > > You might need to do "bash -c 'cd /foo/bar'" or somesuch instead. > > > > Just a guess, so probably wrong! :-/ > > That works without the 's but has seems to call the function "cd" as a > process in it's own write, ie. with it's own environment variables. > What I need to do is to be able to change the variables in the parent > process, the one from which Python is called. I thought this would be > easy but it's turning into a real challenge... It is also impossible. A child process *cannot* alter its parent's environment. -- "A man who has nothing he is willing to fight for, nothing which he cares more about than he does his own personal safety, is a miserable creature, who has no chance of being free unless made and kept so by the exertions of men better than himself. As long as justice and injustice have not terminated their ever- renewing fight...human beings must be willing...to do battle for the one against the other." -- John Stuart Mill Rick Pasotto rick@niof.net http://www.niof.net From zmerch@30below.com Thu May 22 14:13:02 2003 From: zmerch@30below.com (Roger Merchberger) Date: Thu May 22 13:13:02 2003 Subject: [Tutor] Struggling with os.exec In-Reply-To: <20030522170315.635.1@wonderland.1053615256.fake> References: <012001c31fcb$21fb10f0$6401a8c0@xp> <20030521141218.2531.11@wonderland.1053502983.fake> <3ECB73DA.1060900@venix.com> <20030521170147.3169.16@wonderland.1053502983.fake> <012001c31fcb$21fb10f0$6401a8c0@xp> Message-ID: <5.1.0.14.2.20030522125812.029d6360@mail.30below.com> Rumor has it that Charlie Clark may have mentioned these words: >On 2003-05-21 at 20:59:40 [+0200], you wrote: > > > has a bash (2.03) shell so this is essentially a "posix" question > > and "cd" > > > is obviously a built-in command. Is it still possible to call "cd" > > from > > > within Python? > > > > You might need to do "bash -c 'cd /foo/bar'" or somesuch instead. > > > > Just a guess, so probably wrong! :-/ > >That works without the 's but has seems to call the function "cd" as a >process in it's own write, ie. with it's own environment variables. What I >need to do is to be able to change the variables in the parent process, the >one from which Python is called. I thought this would be easy but it's >turning into a real challenge... ie., I'm still open for ideas! AFAIK, it's a "you can't get there from here" problem. I needed to do the same thing to 'cd' into a hashed directory structure on our mailserver, where the structure info is stored in a PostgreSQL database. My [admittedly lameish] hack was this: I created a program who's output was to just spit out the correct directory for the userid, in this case 'cdmail' is the name of my proggie. Call that program in backticks to 'cd', like this: cd `cdmail thisuser` This will execute the program 'cdmail' and it'll output the correct directory - 'cd' will take this info, and cd there. It's a PITA, but it works [well, mostly;kinda...] HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- sysadmin, Iceberg Computers zmerch@30below.com What do you do when Life gives you lemons, and you don't *like* lemonade????????????? From dedoleo@hotmail.com Thu May 22 15:51:20 2003 From: dedoleo@hotmail.com (David Scott) Date: Thu May 22 14:51:20 2003 Subject: [Tutor] tutorial 5.1.3 Message-ID: In the Python Tutorial (the one that comes with Python), in section 5.1.3, there is something that I do not understand: >>>def f(x): return x % 2 != 0 and x % 3 != 0 ... >>>filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23] That example is used to compute primes. >From what I understand, the "return" statement is returning the tested value (passed in from the range) if it passes both tests. However, it seems to me that the return statement would return either a 1 or a 0 and nothing else, because of the "and". return (test expression) and (test expression). If both are true, then the "and" is true. else, the entire statement is false. What am I missing or misunderstanding here? -------------------------------------- dedoleo@hotmail.com http://groups.msn.com/WalledCity _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From jamesdean@hotmail.com Thu May 22 15:58:56 2003 From: jamesdean@hotmail.com (james dean) Date: Thu May 22 14:58:56 2003 Subject: [Tutor] Read only buffer tuple ? Message-ID: Hi all, I have a file writing problem. I am extracting some text from a database and opening a file to write it to and I get this error. f.write(msg[0]) TypeError: read-only buffer, tuple Here is the code I am using: sql = "SELECT message FROM email WHERE emailid='%s'" % (rows[0]) msg = con1.query(sql).getresult() f = open('temp','w') f.write(msg[0]) f.close What am I doing wrong? Thanks for your help. _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From bgailer@alum.rpi.edu Thu May 22 16:00:05 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu May 22 15:00:05 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <013801c32040$9fb80960$6401a8c0@xp> References: <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> Message-ID: <5.2.0.9.0.20030522124918.0491ae58@66.28.54.253> I'd like to put this thread to bed. My concern was how to get documentation updated, and that has been answered. Alan asked what I expected. And to me that is the problem in general, having to guess or expect. What I expect (or at least desire) is those few more words that tell me what happens so I don't have to guess. I think this is also crucial for newcomers who want to use the language effectively. I come from a long history of dealing with inadequate documentation. The average for me is about 1 hour of lost time dealing with problems in MY program due missing or incorrect information. Most of the document suppliers were not interested in updating when a problem was discovered NOR interested in strategies for improving documentation. Python is my first Open Source development tool and it offers a way for me to improve things. For that I'm grateful. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From pythontutor@venix.com Thu May 22 16:14:02 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Thu May 22 15:14:02 2003 Subject: [Tutor] tutorial 5.1.3 References: Message-ID: <3ECD20FB.2090704@venix.com> filter returns the list element if f returns true. filter doesn't return f. So the elements from range(2,25) are what get returned by filter. If f(element) returns 0, then the element is omitted from the result list. David Scott wrote: > In the Python Tutorial (the one that comes with Python), in section > 5.1.3, there is something that I do not understand: > >>>> def f(x): return x % 2 != 0 and x % 3 != 0 >>> > ... > >>>> filter(f, range(2, 25)) >>> > [5, 7, 11, 13, 17, 19, 23] > > That example is used to compute primes. > >> From what I understand, the "return" statement is returning the tested >> value > > (passed in from the range) if it passes both tests. However, it seems to > me that the return statement would return either a 1 or a 0 and nothing > else, because of the "and". > > return (test expression) and (test expression). If both are true, then > the "and" is true. else, the entire statement is false. > > What am I missing or misunderstanding here? > > > > -------------------------------------- > dedoleo@hotmail.com > http://groups.msn.com/WalledCity > > _________________________________________________________________ > Help STOP SPAM with the new MSN 8 and get 2 months FREE* > http://join.msn.com/?page=features/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From gerrit@nl.linux.org Thu May 22 16:17:12 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Thu May 22 15:17:12 2003 Subject: [Tutor] tutorial 5.1.3 In-Reply-To: References: Message-ID: <20030522191506.GA2962@nl.linux.org> Hi David, David Scott schreef op donderdag 22 mei om 20:51:42 +0000: > >From what I understand, the "return" statement is returning the tested > >value > (passed in from the range) if it passes both tests. However, it seems to me > that the return statement would return either a 1 or a 0 and nothing else, > because of the "and". > > return (test expression) and (test expression). If both are true, then the > "and" is true. else, the entire statement is false. > > What am I missing or misunderstanding here? The 'and' operator in Python has the feature that is returns the true operand if either is true. This can be useful in some occasions: for example: m = "%d apple%s" % (n, (n!=1 and 's' or '')) This is documented in the reference manual: """The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned. """ Source: http://www.python.org/dev/doc/devel/ref/Booleans.html yours, Gerrit. -- 157. If any one be guilty of incest with his mother after his father, both shall be burned. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From magnus@thinkware.se Thu May 22 23:22:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 22 22:22:01 2003 Subject: [Tutor] Absolute newbie - Transliteration In-Reply-To: Message-ID: <5.2.1.1.0.20030522235615.01eff008@www.thinkware.se> At 23:51 2003-05-20 -0700, David Rogers wrote: >I'm an absolute newbie - this is my first attempt with Python or any >"real" language, so my advance apologies for any stupid comments. You are very welcome, I hope you will enjoy Python as much as we do. > I joined the list just to ask this question, after doing a little > searching in the list archives and the documentation and not being able > to find out what I want to know. It's always nice with people who do their homework. :) >I'm trying make scripts to transliterate a file from (Unicode) Cyrillic >characters to each of >- Roman script, and >- International Phonetic Alphabet (more Unicode). > >(Whether I end up with separate scripts, one for each transliteration, or >one script for all with a bigger dictionary/list/table, is not important >to me.) >The transliteration will not always be one-to-one in terms of the number >of characters, for example the "ch" sound is one letter in Russian but >corresponds to two letters in English. I have a feeling, it might not be completely trivial to do this at all. But that depends... If it's always one russian letter being translated into one or more roman / IPA symbol, it's no problem. I just consulted my wife who knows Russian, and it seems you should be able to do this. The only two letter combination she could think of is some "soft" indicator that is only used to modify the preceeding consonant. I'm sure you know this. If you had gone the other direction, it would be much harder. For instance, it's not trivial to determine if the letter combination "sh" is the sh-sound. Compare "dishes" with "dishonor". Transliteration of English to cyrillic or phonetic letters seems to reqire a lot of contextual aid... If we ignore this little softener for a while, you really just need a dictionary. Use cyrillic as keys, and the other script as value. A tiny excerpt matching my knowledge of the cyrillic alphabet would be cyr2rom = {'C': 'S', 'P': 'R'} Then a simple (but far from optimal) algorithm would be: rom_text = "" cyr_text = "..." for letter in cyr_text: rom_text = rom_text + cyr2rom[letter] Of course, values in the dictionary might well be more than one character. If you want to do both roman and IPA at once, you could do something like: cyr2rom_ipa = {'C': ('S', u'...'), ('P': ('R', u'...')} rom_text = "" ipa_text = "" cyr_text = "..." for letter in cyr_text: rom_text = rom_text + cyr2rom_ipa[letter][0] ipa_text = ipa_text + cyr2rom_ipa[letter][1] Your main problem is that little softing symbol (that looks a bit like 'b'). Somehow, you need to look ahead, to see if that's coming after the current consonant, or perhaps it's easier to handle that whe it comes, and make a correction after the fact. While we're at it, doing "s = s + c" with strings in a big loop, is very ineffective, since you create new string objects all the time. It's much better to use a list, append to that, and to turn it into a string when all the processing is done. This also helps this soft- fix. Then it will look something like this: cyr2rom_ipa = {'C': ('S', u'...'), ('P': ('R', u'...')} soft_cyr2rom_ipa = {'N': ('NJ', u'...'), ...} soft_symbol = u'...' rom_text = [] ipa_text = [] cyr_text = "..." for letter in cyr_text: if letter == soft_symbol: 'Replace the last letter with a soft version. For 'roman I guess it's something like "N => NJ". rom_text[-1] = soft_cyr2rom_ipa[rom_text[-1]][0] ipa_text[-1] = soft_cyr2rom_ipa[rom_text[-1]][1] else: rom_text.append(cyr2rom_ipa[letter][0]) ipa_text.append(cyr2rom_ipa[letter][1]) rom_text = "".join(rom_text) ipa_text = "".join(ipa_text) Perhaps it's better to use the previous cyrillic letter rather than the (hard) one that you translated to for the softening. That means that the keys to soft_cyr2rom_ipa will be different, and you need to keep the previous cyrillic letter in a variable. cyr2rom_ipa = {'C': ('S', u'...'), ('P': ('R', u'...')} soft_cyr2rom_ipa = {u'...': ('NJ', u'...'), ...} soft_symbol = u'...' rom_text = [] ipa_text = [] cyr_text = "..." for letter in cyr_text: if letter == soft_symbol: #Replace the last letter with a soft version. For #roman I guess it's something like "N => NJ". #This should always come after a consonant. (Always last in word?) rom_text[-1] = soft_cyr2rom_ipa[previous_letter ][0] ipa_text[-1] = soft_cyr2rom_ipa[previous_letter ][1] else: rom_text.append(cyr2rom_ipa[letter][0]) ipa_text.append(cyr2rom_ipa[letter][1]) previous_letter = letter rom_text = "".join(rom_text) ipa_text = "".join(ipa_text) >I have found the following in the Python web documentation... > >>translate(table[, deletechars]) Never mind that as Bob said. >>Return a copy of the string where all characters occurring in the >>optional argument deletechars are removed, and the remaining characters >>have been mapped through the given translation table, which must be a >>string of length 256. This isn't the best piece of documentation in Pythondom. It's a hint that the table must be a 256 character string though. Each symbol in a normal 8 bit string has a value between 0 and 255. E.g. >>> ord('A') 65 >>> chr(65) 'A' What happens is that the numeric value of each character in your text string is used to find a character in the "table". That's the replacement value. So, translate basically does this: def translate(s, table, deletechars=""): result = "" for char in s: if char not in deletechars: result = result + table[ord(char)] return result if table = "A" * 256, then all will be translated to "A". If table = "".join([chr((x+5)%256) for x in range(256)]) then A => F, b => G etc. >...but I don't understand what format my table needs to be in, or even if >this accommodates Unicode, or the problem of one character sometimes >translating to two. If I'm completely on the wrong track here, somebody >laugh now before it's too late. :-) I hope I led you onto the track again. >What I don't want is a pointer to a non-modifiable Cyrillic-to-Roman >transliteration application, because I want to re-use what I do here when >I make other transliteration tables to speed up IPA transcription from >other languages too. I love IPA. :-) I think most other languages are much, much harder than Russian. :( English is hopeless. Laugh, Garage, Women... Swedish is fairly hopeless as well. I think you realize by now (if not before) that the amount of shared code for a thing like this is fairly small. From Russian seems to be truly trivial compared to translitteration from most western European languages. For English, you would need to build in a major understanding of the language. I don't know if the information you need to include can be described in a much shorter format than the output you would generate from a really big word list. And if that's the case, it's obviously rather futile... I assume there is linguistic research done in that sector though. Danny Yoo usually knows these things... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dan_nash@hotmail.com Thu May 22 23:22:22 2003 From: dan_nash@hotmail.com (Daniel Nash) Date: Thu May 22 22:22:22 2003 Subject: [Tutor] exceptions.AttributeError :ignored Message-ID: I was wondering if anyone could tell me what sort of error I am looking for here? I am experimenting with classes/object and I was wondering what ignored meant? And what the problems is likley to be? Cheers. Traceback (innermost last): File "dbclassify.py", line 263, in ? main() File "dbclassify.py", line 249, in main db = DB(dbname) File "dbclassify.py", line 27, in __init__ self.hash = anydbm.open(name, "c") File "/usr/lib/python1.5/anydbm.py", line 86, in open return mod.open(file, flag, mode) File "/usr/lib/python1.5/dbhash.py", line 8, in open return bsddb.hashopen(file, flag, mode) bsddb.error: (22, 'Invalid argument') Exception exceptions.AttributeError: 'num_good' in ignored _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From magnus@thinkware.se Thu May 22 23:44:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 22 22:44:01 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> References: <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> Message-ID: <5.2.1.1.0.20030523014134.01e7c648@www.thinkware.se> At 11:34 2003-05-21 -0600, Bob Gailer wrote: >So one would expect 'a\tab\tabc\tabcd\t'.expandtabs() to produce >'a ab abc adcd ' where there are 8 spaces >between each word? No. That is not what one would expect, because that's not what tabs are. It would be pointless to have such a thing as a tab character if it just meant the same as eight spaces. >But that's NOT what happens. So the definition is not explicit enough. A Python manual might not be the place to explain what tabs are. But I suppose that depends entirely on what knowledge you expect the reader of the manual to have beforehand. Try typing the tab key at different places in a normal word processor. You will notice that it will not always move you forward as many characters or millimeters or what have you. The same happens in a plain text editor. It depends on what position you start. The tab key (and tab character) will bring you to the next tab stop, which is at a certain position along the line, either measured in columns if it's a normal editor for fixed fonts, or in inches (or cm etc) for a word processor. Try the code below in your python interpreter. >>> a = 'a\tab\tabc\tabcd\t' >>> print a a ab abc abcd >>> print a.expandtabs() a ab abc abcd >>> Both lines with a, ab, abc etc might not look the same in your email program, depending on how it handles tabs, but it should look the same in your python interpreter, and in any normal text editor with a tab setting of 8 if you copy the text to that. If you have a different tab setting like 4 in your editor, the lines below should match instead: >>> print a a ab abc abcd >>> print a.expandtabs(4) a ab abc abcd Unfortunately, common explanations such as http://www.webopedia.com/TERM/T/tab_stop.html doesn't exactly explain tab settings in the context of simple text files. Since the question pops up, some kind of reference to an explanation of tabs mighr be in place, even if it has nothing to do with Python or programming. Tab stop have certainly existed since long before electronic computers... I've seen a professional programmer (lously, but paid) use the tab key in notepad as he prepared a test file that was based on fixed position text. He was so baffled when his text ended up in the wrong fields, and his lines were shorter than expected. It didn't occur to him that pressing tab didn't insert a sequence of spaces. It's not at all unreasonable to believe that potential Python programmers don't understand tabs, and since tabs vs spaces have such a central role in Python due to the significant indentation, it's probably a good idea to explain what tabs are anyway. Perhaps as an appendix. Both "expandtabs" and the descriptions of indentation in the tutorial could refer to that. Hm... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From bgailer@alum.rpi.edu Thu May 22 23:46:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu May 22 22:46:02 2003 Subject: [Tutor] Read only buffer tuple ? In-Reply-To: Message-ID: <5.2.0.9.0.20030522204208.04669f50@66.28.54.253> At 06:55 PM 5/22/2003 +0000, james dean wrote: >Hi all, I have a file writing problem. > >I am extracting some text from a database and opening a file to write it >to and I get this error. > >f.write(msg[0]) >TypeError: read-only buffer, tuple > >Here is the code I am using: > >sql = "SELECT message FROM email WHERE emailid='%s'" % (rows[0]) >msg = con1.query(sql).getresult() >f = open('temp','w') >f.write(msg[0]) >f.close > >What am I doing wrong? Please show us what msg[0] looks like. Is it a string? Most data base queries are returned as a sequence of rows, and each row is a sequence. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From neh@attbi.com Thu May 22 23:49:31 2003 From: neh@attbi.com (Neil Hodge) Date: Thu May 22 22:49:31 2003 Subject: [Tutor] Odd AttributeError In-Reply-To: <5.2.1.1.0.20030523012723.01f0ac70@www.thinkware.se> References: <5.2.1.1.0.20030523012723.01f0ac70@www.thinkware.se> Message-ID: <1053658065.1801.7.camel@zeus.localdomain> Magnus: On Thu, 2003-05-22 at 16:40, Magnus LyckÃ¥ wrote: > At 06:56 2003-05-21 -0700, Neil Hodge wrote: > >So, why does self.as_tuple not exist right after I defined it? Thanks. > > Because you didn't really define it? Is a __setattr__ method defined > for the class? Does it eat your definition? > > See below: > > >>> class X: > ... def __init__(self, x): > ... self.x = x > ... print "self.x is", self.x > ... def __setattr__(self, attr, val): > ... pass > ... > >>> x = X(42) > self.x is > Traceback (most recent call last): > File "", line 1, in ? > File "", line 4, in __init__ > AttributeError: X instance has no attribute 'x' > This is someone else's code I am trying to learn and update. Yes, there is a __setattr__ method defined. I have this vague feeling that there are some pre-defined names that invoke certain behavior, but I am not familiar with them (__getitem__, __setitem__, __dict__, __del__, __str__, and __setattr__ are all defined). I guess now is the time to learn. Could you point me to a reference that lists all of these, and defines their behavior/purpose? Thanks. Neil From magnus@thinkware.se Fri May 23 00:18:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 22 23:18:03 2003 Subject: [Tutor] easy newbie questions: text file to list? In-Reply-To: <1053514143.28257.11.camel@nate.ucdavis.edu> References: <20030520095314.GA2478@nl.linux.org> <1053370209.9606.341.camel@nate.ucdavis.edu> <20030520095314.GA2478@nl.linux.org> Message-ID: <5.2.1.1.0.20030523011621.01f39ac0@www.thinkware.se> At 10:49 2003-05-21 +0000, ashleigh smythe wrote: >You guys weren't kidding when you say there's more >than one way to do things with Python! No, No. It's for *Perl* that the motto is: "There is more than one way to do it". For Python, there are 19 mottos, and one of them is: "There should be one-- and preferably only one --obvious way to do it." unfortunately, the next motto is: "Although that way may not be obvious at first unless you're Dutch." The diversity in replies is basically a failure. Either in Python or in us. ;) To learn more, open a python interpreter and type: >>> import this -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Fri May 23 00:31:05 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 22 23:31:05 2003 Subject: [Tutor] Handling international characters In-Reply-To: Message-ID: <5.2.1.1.0.20030523024205.01efbff0@www.thinkware.se> At 10:36 2003-05-21 -0300, Jorge Godoy wrote: >[['Jorge', 'Godoy'], ['Juliano', 'Godoy'], ['\xc9rica', 'Balaniuc']] It allways looks like that in a list. The content of the list is displayed using the __repr__ method, not the __str__ method. Test for yourself if you do something like: >>> a =3D 'Ol=E9' >>> a 'Ol\xe9' >>> print a Ol=E9 >>> print [a] ['Ol\xe9'] -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program=20 From bgailer@alum.rpi.edu Fri May 23 00:45:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu May 22 23:45:02 2003 Subject: [Tutor] easy newbie questions: text file to list? In-Reply-To: <5.2.1.1.0.20030523011621.01f39ac0@www.thinkware.se> References: <1053514143.28257.11.camel@nate.ucdavis.edu> <20030520095314.GA2478@nl.linux.org> <1053370209.9606.341.camel@nate.ucdavis.edu> <20030520095314.GA2478@nl.linux.org> Message-ID: <5.2.0.9.0.20030522213918.04665758@66.28.54.253> At 01:20 AM 5/23/2003 +0200, Magnus Lyck=E5 wrote: >At 10:49 2003-05-21 +0000, ashleigh smythe wrote: >>You guys weren't kidding when you say there's more >>than one way to do things with Python! > >No, No. It's for *Perl* that the motto is: >"There is more than one way to do it". > >For Python, there are 19 mottos, and one of them is: > >"There should be one-- and preferably only one --obvious way to do it." > >unfortunately, the next motto is: > >"Although that way may not be obvious at first unless you're Dutch." > >The diversity in replies is basically a failure. Either in Python or >in us. ;) To learn more, open a python interpreter and type: > > >>> import this I notice that this is not in the module index. Are there other gems like=20 this that are hidden? Interesting content: "Explicit is better than implicit." "Readability counts." "In the face of ambiguity, refuse the temptation to guess." I guess these ideas could be applied to documentation. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 From davidrogers@telus.net Fri May 23 00:47:01 2003 From: davidrogers@telus.net (David Rogers) Date: Thu May 22 23:47:01 2003 Subject: [Tutor] Absolute newbie - Transliteration In-Reply-To: <5.2.1.1.0.20030522235615.01eff008@www.thinkware.se> Message-ID: Thank you, Mr. Lyck=E5, for your very helpful and detailed answer. I'll=20= chew on it for a while and see what happens. > I have a feeling, it might not be completely trivial to do this at = all. > But that depends... I see how much complication one could get into. My goal here is to=20 make it faster for myself to transcribe the text of songs, which are=20 usually not too long - that means (I think) that I can have the script=20= do the obvious stuff, and leave the "special" things to do myself. Not=20= a perfect solution, but a drudgery-remover nonetheless. > Your main problem is that little softing symbol (that looks a bit > like 'b'). Somehow, you need to look ahead, to see if that's coming > after the current consonant, or perhaps it's easier to handle that > whe it comes, and make a correction after the fact. Can I put some letter-combinations that include the 'soft' symbol at=20 the beginning of my dictionary, and have them evaluated first, thus=20 bypassing the single-letter entries that come later? Or does a=20 dictionary work in non-sequential order? > I think most other languages are much, much harder than Russian. :( > > English is hopeless. Laugh, Garage, Women... Swedish is fairly = hopeless > as well. Clearly, I'm only going to be able to use this on languages I already=20 know at least a little, so that I can correct the results afterward. =20= (btw, I think Laugh Garage Women would make an excellent name for a=20 band...) > I think you realize by now (if not before) that the amount of shared > code for a thing like this is fairly small. =46rom Russian seems to be > truly trivial compared to translitteration from most western European > languages. For English, you would need to build in a major=20 > understanding > of the language. I don't know if the information you need to include=20= > can > be described in a much shorter format than the output you would=20 > generate > from a really big word list. And if that's the case, it's obviously=20 > rather > futile... I assume there is linguistic research done in that sector=20 > though. > Danny Yoo usually knows these things... I think you're right about the general futility of a project like this,=20= for use by real translators or anything like that. For my little=20 project of transcribing song texts to make them easier for non-native=20 speakers of those languages, I think it will save me some time, since I=20= only have to do the simple stuff once, in the dictionary, and can then=20= concentrate on fixing the exceptions. For me, not knowing how to use Python yet, the "shared code" amounts to=20= (1) seeing examples of the possible dictionary formats, and (2) samples=20= of the incantations required to get stuff back out of them. :-) You've given me that and much more besides, and now it's time for me to=20= experiment and see if I can get it to work. I'll post again with=20 details if I get a half-decent result. Again, thank you very much. David= From magnus@thinkware.se Fri May 23 01:24:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 23 00:24:02 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <5.2.0.9.0.20030522124918.0491ae58@66.28.54.253> References: <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> Message-ID: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> At 12:57 2003-05-22 -0600, Bob Gailer wrote: >What I expect (or at least desire) is those few more words that tell me >what happens so I don't have to guess. But you don't *have* to guess. You just have to *try*. This is also a very relevant aspect of python. It's so simple to fire up the interpreter (actually, there is always a running Python interpreter on my machine) and try it out, just like you obviously did. Perhaps the Python documentation needs to contain even more suggestions to try out and experiment with features. On the other hand, It's very easy to forget how tricky things might be before we get to grips with them. After all, most things are trivial when we have understood them. The need for the documentation if mainly to get there...but usually written by those who long forgot how it was... Perhaps it's a bad reflex to say that "this has nothing to do with Python". Some time ago I suggested that some more documentation was added concerning installation of pysqlite on Linux as non-root, and I got the reply that this wasn't really a pysqlite issue, so it didn't belong in their docs. The thing was that I've been working with Linux since 1994 and with Python since 1997, and I've installed a number of Python modules at my ISP where I don't have root access, and pysqlite was the first time I ran into trouble, and had to make a bigger effort to figure out what was wrong, and do things differently than documented. In deciding whether to put something in the docs or not, the important issue is probably not whether it's "a python issue" or not, but whether it will help the reader succeed in his Python programming efforts or not. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dyoo@hkn.eecs.berkeley.edu Fri May 23 01:24:15 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 23 00:24:15 2003 Subject: [Tutor] Read only buffer tuple ? [data structures / close()ing a file] In-Reply-To: Message-ID: > What we may want to do, then, is just extract the first element of the > row: > > > ### > sql = "SELECT message FROM email WHERE emailid='%s'" % (rows[0]) > result_set = con1.query(sql).getresult() > first_row = msg[0] ^^^^^^ > first_message = first_row[0] > ### *cough* Doh. Um... I meant, ### sql = "SELECT message FROM email WHERE emailid='%s'" % (rows[0]) result_set = con1.query(sql).getresult() first_row = result_set[0] first_message = first_row[0] ### Sorry about the mistake; it's hard to test pseudocode. *grin* From dyoo@hkn.eecs.berkeley.edu Fri May 23 01:25:13 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 23 00:25:13 2003 Subject: [Tutor] Read only buffer tuple ? [data structures / close()ing a file] In-Reply-To: Message-ID: On Thu, 22 May 2003, james dean wrote: > Hi all, I have a file writing problem. > > I am extracting some text from a database and opening a file to write it > to and I get this error. > > f.write(msg[0]) > TypeError: read-only buffer, tuple > > Here is the code I am using: > > sql = "SELECT message FROM email WHERE emailid='%s'" % (rows[0]) > msg = con1.query(sql).getresult() > f = open('temp','w') > f.write(msg[0]) > f.close > > What am I doing wrong? Hi James, I'll assume for the moment that 'msg' contains a list of tuples. A query to an SQL database should return a "result set" list, and each element of that result set will be itself a tuple. The reasons for this is consistancy; if we do the query: """select emailid, message from email whrere emailid=%s""" vs. """select message from email whrere emailid=%s""" the structure returned by the database layer will have the same kind of shape. We can take comfort that our result set will look like: [ row1, row2, row3, ] And, even if our rows only consist of a single column, each row will always be a tuple: row = (1, 'this is a test'), vs row = ('this is a test',) What we may want to do, then, is just extract the first element of the row: ### sql = "SELECT message FROM email WHERE emailid='%s'" % (rows[0]) result_set = con1.query(sql).getresult() first_row = msg[0] first_message = first_row[0] ### Some of us may consider this verbose though; if we can safely assume that the query is always successful, we can compress this down to: ### sql = "SELECT message FROM email WHERE emailid='%s'" % (rows[0]) first_msg = con1.query(sql).getresult()[0][0] ### And if not, we'll have to do some checks. One other thing: that last statement in the program: > f.close is missing parentheses: without parentheses, functions don't fire off in Python. It might seem a little odd or verbose, but when we learn more about Python, we can talk about why Python offers that option of naming but not automatically activating a function. So when we want to close a file, we use: f.close() even if we don't send any parameters over. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Fri May 23 01:26:43 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 23 00:26:43 2003 Subject: [Tutor] tutorial 5.1.3 In-Reply-To: Message-ID: On Thu, 22 May 2003, David Scott wrote: > In the Python Tutorial (the one that comes with Python), in section > 5.1.3, there is something that I do not understand: > > >>>def f(x): return x % 2 != 0 and x % 3 != 0 > ... > >>>filter(f, range(2, 25)) > [5, 7, 11, 13, 17, 19, 23] > > That example is used to compute primes. Hi David, (Just wanted to point out that f() doesn't detect primes by itself: f(25) will return True since it's neither divisible by two or three... but 25 is still not prime.) > From what I understand, the "return" statement is returning the tested > value (passed in from the range) if it passes both tests. It might help if we parenthesize everything there, so that the result of the return statement is clearer, if a little more cluttered: ### def f(x): return ((x % 2 != 0) and (x % 3 != 0)) ### The return statement, return [expr] returns the value of that [expr] part, and not necessarily the parameter 'x'. In the statement above, return ((x % 2 != 0) and (x % 3 != 0)) we'd say that ((x % 2 != 0) and (x % 3 != 0)) is the "subexpression" part of that statement, and the result of the subexpression is what is given back to the caller. (Once we have more confidence that we understand how Python is grouping things, we'd go without the parentheses: x % 2 != 0 and x % 3 != 0 ) > However, it seems to me that the return statement would return either a > 1 or a 0 and nothing else, because of the "and". Yes, exactly. But it's not just because of the 'and' part. If we had left it as: ### def f(x): return (x % 2 != 0) ### then the value that's being returned is still the one that's the result of the expression: (x % 2 != 0) and not just the 'x' part. It might help if the expression was one where 'x' wasn't visually the first part of the return value, like: ### def double_of_x(x): return 2 * x ### > return (test expression) and (test expression). If both are true, then > the "and" is true. else, the entire statement is false. > > What am I missing or misunderstanding here? You got the right idea. Try doing some more functions interactively, and the idea of what 'return' does should solidify. By the way exploring functions with filter() adds slightly more complexity, so I'd recommend playing around with filter() after you get function return values down. Good luck to you! From godoy@metalab.unc.edu Fri May 23 01:37:03 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Fri May 23 00:37:03 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> ( =?iso-8859-1?q?Magnus_Lyck=E5's_message_of?= "Fri, 23 May 2003 02:35:38 +0200") References: <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> Message-ID: Magnus Lyck=E5 writes: > Perhaps the Python documentation needs to contain even more > suggestions to try out and experiment with features. IMHO it would benefit a lot of examples. E.g.: Perl's first page on the CGI module: ---------------------------------------------------------------------- CGI(3) User Contributed Perl Documentation C= GI(3) NAME CGI - Simple Common Gateway Interface Class SYNOPSIS # CGI script that creates a fill-out form # and echoes back its values. use CGI qw/:standard/; print header, start_html('A Simple Example'), h1('A Simple Example'), start_form, "What's your name? ",textfield('name'),p, "What's the combination?", p, checkbox_group(-name=3D>'words', -values=3D>['eenie','meenie','minie','moe']= , -defaults=3D>['eenie','minie']), p, "What's your favorite color? ", popup_menu(-name=3D>'color', -values=3D>['red','green','blue','chartreuse'])= ,p, submit, end_form, hr; if (param()) { print "Your name is",em(param('name')),p, "The keywords are: ",em(join(", ",param('words'))),p, "Your favorite color is ",em(param('color')), hr; } ABSTRACT This perl library uses perl5 objects to make it easy to create Web ---------------------------------------------------------------------- The SYNOPSIS gives you examples of how to use objects, how they work. The documentation goes on and explain the more intricated uses of such a module. Python's CGI first page: ---------------------------------------------------------------------- Python Library Documentation: module cgi NAME cgi - Support module for CGI (Common Gateway Interface) scripts. FILE /usr/lib/python2.2/cgi.py DESCRIPTION This module defines a number of utilities for use by CGI scripts written in Python. CLASSES FieldStorage MiniFieldStorage UserDict.UserDict FormContentDict FormContent SvFormContentDict InterpFormContentDict class FieldStorage | Store a sequence of fields, reading multipart/form-data. | | This class provides naming, typing, files stored on disk, and | more. At the top level, it is accessible like a dictionary, whos= e | keys are the field names. (Note: None can occur as a field name.= ) | The items are either a Python list (if there's multiple values) o= r | another FieldStorage or MiniFieldStorage object. If it's a singl= e | object, it has the following attributes: | | name: the field name, if specified; otherwise None | | filename: the filename, if specified; otherwise None; this is the | client side filename, *not* the file name on which it is ---------------------------------------------------------------------- There's no indication on, how to import the module ("import cgi"? "from cgi import *"?), on how to start a simple cgi with it, etc.=20 I try putting usage examples on my docs. They help me reminding how to use something --- it doesn't matter how good is the description, sometimes you just want to see one example using the function --- and will certainly help other people too. See you, --=20 Godoy. From magnus@thinkware.se Fri May 23 02:04:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 23 01:04:02 2003 Subject: [Tutor] Odd AttributeError In-Reply-To: <1053525387.2219.13.camel@zeus.localdomain> Message-ID: <5.2.1.1.0.20030523012723.01f0ac70@www.thinkware.se> At 06:56 2003-05-21 -0700, Neil Hodge wrote: >So, why does self.as_tuple not exist right after I defined it? Thanks. Because you didn't really define it? Is a __setattr__ method defined for the class? Does it eat your definition? See below: >>> class X: ... def __init__(self, x): ... self.x = x ... print "self.x is", self.x ... def __setattr__(self, attr, val): ... pass ... >>> x = X(42) self.x is Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __init__ AttributeError: X instance has no attribute 'x' You can try doing "self.__dict__['as_tuple'] = as_tuple" instead. Then you avoid calling __setattr__ since you don't rebind any attribute, just modify a current one. >>> class X: ... def __init__(self, x): ... self.__dict__['x'] = x ... print "self.x is", self.x ... def __setattr__(self, attr, val): ... pass ... >>> x = X(42) self.x is 42 -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From pythontutor@venix.com Fri May 23 02:11:02 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Fri May 23 01:11:02 2003 Subject: [Tutor] Read only buffer tuple ? References: Message-ID: <3ECD2248.5090008@venix.com> My best guess is that your getresult method returns a tuple of tuples like so: ( (row_0-col_0, row_0-col_1, ...) (row_1-col_0, row_1-col_1, ...) ... ) msg[0][0] may work. You can try inserting a line like: print msg to verify my guess. james dean wrote: > > Hi all, I have a file writing problem. > > I am extracting some text from a database and opening a file to write it > to and I get this error. > > f.write(msg[0]) > TypeError: read-only buffer, tuple > > Here is the code I am using: > > sql = "SELECT message FROM email WHERE emailid='%s'" % (rows[0]) > msg = con1.query(sql).getresult() > f = open('temp','w') > f.write(msg[0]) > f.close > > What am I doing wrong? > > Thanks for your help. > > _________________________________________________________________ > The new MSN 8: advanced junk mail protection and 2 months FREE* > http://join.msn.com/?page=features/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From phthenry@earthlink.net Fri May 23 02:20:19 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Fri May 23 01:20:19 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: ; from godoy@metalab.unc.edu on Fri, May 23, 2003 at 01:34:03AM -0300 References: <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> Message-ID: <20030523011811.C1316@supermac600.earthlink.net> > > Magnus Lyckå writes: > > > Perhaps the Python documentation needs to contain even more > > suggestions to try out and experiment with features. > > IMHO it would benefit a lot of examples. > > E.g.: Perl's first page on the CGI module: > > ---------------------------------------------------------------------- > CGI(3) User Contributed Perl Documentation CGI(3) > > NAME > CGI - Simple Common Gateway Interface Class > > SYNOPSIS > # CGI script that creates a fill-out form > # and echoes back its values. > > use CGI qw/:standard/; > print header, > start_html('A Simple Example'), > h1('A Simple Example'), > start_form, > "What's your name? ",textfield('name'),p, > "What's the combination?", p, > checkbox_group(-name=>'words', > -values=>['eenie','meenie','minie','moe'], > -defaults=>['eenie','minie']), p, > "What's your favorite color? ", > popup_menu(-name=>'color', > -values=>['red','green','blue','chartreuse']),p, > submit, > end_form, > hr; > > if (param()) { > print "Your name is",em(param('name')),p, > "The keywords are: ",em(join(", ",param('words'))),p, > "Your favorite color is ",em(param('color')), > hr; > } > > ABSTRACT > This perl library uses perl5 objects to make it easy to create Web > ---------------------------------------------------------------------- > > The SYNOPSIS gives you examples of how to use objects, how they > work. The documentation goes on and explain the more intricated uses > of such a module. > > > Python's CGI first page: > > ---------------------------------------------------------------------- > Python Library Documentation: module cgi > > NAME > cgi - Support module for CGI (Common Gateway Interface) scripts. > > FILE > /usr/lib/python2.2/cgi.py > > DESCRIPTION > This module defines a number of utilities for use by CGI scripts > written in Python. > > CLASSES > FieldStorage > MiniFieldStorage > UserDict.UserDict > FormContentDict > FormContent > SvFormContentDict > InterpFormContentDict > > class FieldStorage > | Store a sequence of fields, reading multipart/form-data. > | > | This class provides naming, typing, files stored on disk, and > | more. At the top level, it is accessible like a dictionary, whose > | keys are the field names. (Note: None can occur as a field name.) > | The items are either a Python list (if there's multiple values) or > | another FieldStorage or MiniFieldStorage object. If it's a single > | object, it has the following attributes: > | > | name: the field name, if specified; otherwise None > | > | filename: the filename, if specified; otherwise None; this is the > | client side filename, *not* the file name on which it is > ---------------------------------------------------------------------- > > There's no indication on, how to import the module ("import cgi"? > "from cgi import *"?), on how to start a simple cgi with it, etc. Amen! Amen! I missed some of the beginning of this thread, but I believe very strongly that good documentation would help the open source community almost more than anything. Good documentation incudes *concrete* examples, not abstractions which by themselves are confusing. Contributing documentation is perhaps a way we non-programmers (at least non-skilled programmers) can really help out. I know keeping up with documentation is difficult, given that code is always changing, and that coders usually hate to write documentation. But it is very discouraging to spend hours, or days, or even weeks struggling with a problem for simple lack of a good explanation. Poor documentation has been the major frustation for me in switching from Mac to Linux. Paul > > > I try putting usage examples on my docs. They help me reminding how to > use something --- it doesn't matter how good is the description, > sometimes you just want to see one example using the function --- and > will certainly help other people too. > > > > See you, > -- > Godoy. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From roypython@hotmail.com Fri May 23 03:42:01 2003 From: roypython@hotmail.com (roy ollis) Date: Fri May 23 02:42:01 2003 Subject: [Tutor] Documentation concerns. Message-ID: if the code keeps changing would heavily commenting the code with explainations and examples work as a form of documentation. if you wanted to see how something works just look at the source or .py files. perhaps even create a module (or full program shell) that dosn't ignore comments but displays them in a pop up with line by line explainations of what the code is doing and have a "next line" (or operation) button to slow the processing down so the running program can be examined one step at a time while running. perhaps a three pane frame, one is the program running as intended, one pane is the code, and the third pane is the comments, all three panes syncronized so that you can see the code, explaination and result all at the same time and mr gauld said there are many definitions of "advanced skill level" for programmers. to me an advanced is someone that can look at a program someone else has written and see the problems so quickly it amazes tham everyone dosn't see it. (almost like bugs were typed in a flashing neon florcent font). and thanks to many on this list. they're beyond advanced, they can explain the problem so the novice can understand the bugs too and what to do next time rather than just parroting code with no idea why or how it works. (and i'm still a novice, still parroting more than programming). thanks to all the great teachers on the list. >From: Paul Tremblay >To: tutor@python.org >Subject: Re: [Tutor] Documentation concerns. >Date: Fri, 23 May 2003 01:18:11 -0400 > > > > > Magnus Lyckå writes: > > > > > Perhaps the Python documentation needs to contain even more > > > suggestions to try out and experiment with features. > > > > IMHO it would benefit a lot of examples. > > > > E.g.: Perl's first page on the CGI module: > > > > ---------------------------------------------------------------------- > > CGI(3) User Contributed Perl Documentation >CGI(3) > > > > NAME > > CGI - Simple Common Gateway Interface Class > > > > SYNOPSIS > > # CGI script that creates a fill-out form > > # and echoes back its values. > > > > use CGI qw/:standard/; > > print header, > > start_html('A Simple Example'), > > h1('A Simple Example'), > > start_form, > > "What's your name? ",textfield('name'),p, > > "What's the combination?", p, > > checkbox_group(-name=>'words', > > -values=>['eenie','meenie','minie','moe'], > > -defaults=>['eenie','minie']), p, > > "What's your favorite color? ", > > popup_menu(-name=>'color', > > >-values=>['red','green','blue','chartreuse']),p, > > submit, > > end_form, > > hr; > > > > if (param()) { > > print "Your name is",em(param('name')),p, > > "The keywords are: ",em(join(", >",param('words'))),p, > > "Your favorite color is ",em(param('color')), > > hr; > > } > > > > ABSTRACT > > This perl library uses perl5 objects to make it easy to create >Web > > ---------------------------------------------------------------------- > > > > The SYNOPSIS gives you examples of how to use objects, how they > > work. The documentation goes on and explain the more intricated uses > > of such a module. > > > > > > Python's CGI first page: > > > > ---------------------------------------------------------------------- > > Python Library Documentation: module cgi > > > > NAME > > cgi - Support module for CGI (Common Gateway Interface) scripts. > > > > FILE > > /usr/lib/python2.2/cgi.py > > > > DESCRIPTION > > This module defines a number of utilities for use by CGI scripts > > written in Python. > > > > CLASSES > > FieldStorage > > MiniFieldStorage > > UserDict.UserDict > > FormContentDict > > FormContent > > SvFormContentDict > > InterpFormContentDict > > > > class FieldStorage > > | Store a sequence of fields, reading multipart/form-data. > > | > > | This class provides naming, typing, files stored on disk, and > > | more. At the top level, it is accessible like a dictionary, >whose > > | keys are the field names. (Note: None can occur as a field >name.) > > | The items are either a Python list (if there's multiple values) >or > > | another FieldStorage or MiniFieldStorage object. If it's a >single > > | object, it has the following attributes: > > | > > | name: the field name, if specified; otherwise None > > | > > | filename: the filename, if specified; otherwise None; this is >the > > | client side filename, *not* the file name on which it is > > ---------------------------------------------------------------------- > > > > There's no indication on, how to import the module ("import cgi"? > > "from cgi import *"?), on how to start a simple cgi with it, etc. > >Amen! Amen! > >I missed some of the beginning of this thread, but I believe very >strongly that good documentation would help the open source community >almost more than anything. Good documentation incudes *concrete* >examples, not abstractions which by themselves are confusing. > >Contributing documentation is perhaps a way we non-programmers (at >least non-skilled programmers) can really help out. > >I know keeping up with documentation is difficult, given that code is >always changing, and that coders usually hate to write documentation. >But it is very discouraging to spend hours, or days, or even weeks >struggling with a problem for simple lack of a good explanation. > >Poor documentation has been the major frustation for me in switching >from Mac to Linux. > >Paul > > > > > > > I try putting usage examples on my docs. They help me reminding how to > > use something --- it doesn't matter how good is the description, > > sometimes you just want to see one example using the function --- and > > will certainly help other people too. > > > > > > > > See you, > > -- > > Godoy. > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > >-- >************************ >*Paul Tremblay * >*phthenry@earthlink.net* >************************ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From lonetwin@yahoo.com Fri May 23 05:18:01 2003 From: lonetwin@yahoo.com (lonetwin) Date: Fri May 23 04:18:01 2003 Subject: [Tutor] Struggling with os.exec In-Reply-To: <20030522170315.635.1@wonderland.1053615256.fake> References: <20030521141218.2531.11@wonderland.1053502983.fake> <012001c31fcb$21fb10f0$6401a8c0@xp> <20030522170315.635.1@wonderland.1053615256.fake> Message-ID: <200305231405.04400.lonetwin@yahoo.com> Hi there, > That works without the 's but has seems to call the function "cd" as a > process in it's own write, ie. with it's own environment variables. What I > need to do is to be able to change the variables in the parent process, the > one from which Python is called. I thought this would be easy but it's > turning into a real challenge... ie., I'm still open for ideas! Re: Now I'm curious. Could you please describe exactly what you need to do or why you want it done this way. There might be something that can be changed about your approach to the problem itself. I remember you mentioning that you were trying to port a Unix shell script to python. Now one of the things that you need to be aware is sometimes the most natural idiom to do a certain thing in one language might not be the best way to do it in another. For example (this is a real life example I came across). If one needs to echo all the lines after a certain 'delimiter' (lets say a line containing only '#'s) in a file, using shell one might do. filename=foobar tail -n "+$(egrep -n "^#+$" $filename | cut -d":" -f1)" $filename which basically translates to a) look for the pattern of a line containing #'s b) get the line number c) echo all the lines after that line number However, in python one *might do: filename="foobar" fl = open(filename).readlines() for line in fl: if line.strip('#') == '\n': print fl[fl.index(line):] break *might == maybe not the best way to do it, but good to illustrate the point here the idiom is a) Read all the lines from the file b) Iterate through the list c) Look for the pattern, if found dump the rest of the list and break from the loop. So, maybe you could tell us what is it that you are trying to achieve and we could help you find a solution. HTH Peace Steve -- Never be afraid to tell the world who you are. - Anonymous From charlie@begeistert.org Fri May 23 06:36:00 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri May 23 05:36:00 2003 Subject: [Tutor] Struggling with os.exec In-Reply-To: <20030523031803.30440.76256.Mailman@mail.python.org> References: <20030523031803.30440.76256.Mailman@mail.python.org> Message-ID: <20030523113643.1116.2@wonderland.1053679285.fake> On 2003-05-23 at 05:18:03 [+0200], tutor-request@python.org wrote: > cd `cdmail thisuser` > > This will execute the program 'cdmail' and it'll output the correct > directory - 'cd' will take this info, and cd there. > > It's a PITA, but it works [well, mostly;kinda...] Thanx for the tip but this won't do because it won't allow you to be interactive. Oh well, learned something new. It's for security reasons that it's not possible. I can imagine things causing all kinds of havoc if modifying parent processes is allowed: I think this is possible on MS Windows, isn't it? Charlie From magnus@thinkware.se Fri May 23 09:08:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 23 08:08:02 2003 Subject: [Tutor] Handling international characters In-Reply-To: References: <5.2.1.1.0.20030523024205.01efbff0@www.thinkware.se> <5.2.1.1.0.20030523024205.01efbff0@www.thinkware.se> Message-ID: <5.2.1.1.0.20030523133525.01efd290@www.thinkware.se> At 22:10 2003-05-22 -0300, Jorge Godoy wrote: >Is there anyway I can solve/handle that? It's supposed to be like that. You aren't printing strings you know, you are printing entire data structures. These data structures might contain anything, from modules or functions to themselves. Like this: >>> import re >>> a =3D [re, 0.1, 'Hell=F6'] >>> a.append(a) >>> print a [, 0.10000000000000001,=20 'Hell\xf6', [...]] There are two builtin python functions for extracting a text string from any object. The str() function returns something which is hopefully pleasing to the eye. The repr() function extracts something which identifies the object as exactly as possible. >>> f =3D 0.1 >>> print str(f) 0.1 >>> print repr(f) 0.10000000000000001 One tenth can't be described exactly as a binary number, any more that a third can be described exactly as a decimal number. repr() shows that, str() hides it. >>> s =3D '=E5' >>> print str(s) =E5 >>> print repr(s) '\xe5' But note that '\xe5' is *not* a python unicode object. The corresponding unicode object would be u'\xe5'. It's just that they happen to be coded the same if we use Latin1. >>>s =3D '=E5' >>> l =3D [s, unicode(s, 'latin1')] >>> print l ['\xe5', u'\xe5'] >>> for x in l: print x ... =E5 =E5 In the default encoding, ISO8859-1, an a with a ring over it is stored as the numeric value which is described as e5 in hexadecimal notation. Anything that would look odd to an American computer user ;) is printed as a hexadecimal number in "repr". One good thing about that is that regardless of how clumpsy our computers or the email systems in between are, I'll be able to extract "=C9rica" from the repr() description, since it's all seven bit ASCII. If you just loop though your data structure and print each element, it will come out printed properly. If this is supposed to be read by someone, do you really want to keep the brackets and quote marks? >>> r =3D [['Jorge', 'Godoy'], ['Juliano', 'Godoy'], ['=C9rica',= 'Balaniuc']] >>> print r [['Jorge', 'Godoy'], ['Juliano', 'Godoy'], ['\xc9rica', 'Balaniuc']] >>> for row in r: ... for element in row: ... print element, ... print ... Jorge Godoy Juliano Godoy =C9rica Balaniuc (This should come out right. If might not fare well through the email=20 though...) >This is really bugging me for a while. I've tried changing some >parameters at site.py but I had no success (I tracked another problem >to what I thought was an XML problem, but then with the editing tool >that also parses the XML everything works... I don't know what's going >on). This is the wrong path to take. Don't mess with site.py. If you convert data between unicode and old fashioned 8 bit strings, you must do that conversion explicitly, and state what encoding you use. string.decode(encoding) =3D> unicode_string unicode_string.encode(encoding) =3D> string >>> s =3D "%s %s" % tuple(r[-1]) >>> s '\xc9rica Balaniuc' >>> repr(s) "'\\xc9rica Balaniuc'" >>> print s =C9rica Balaniuc >>> u =3D s.decode('latin-1') >>> print u =C9rica Balaniuc >>> print u.encode('latin1') # will print right in windows/unix etc =C9rica Balaniuc >>> print u.encode('cp850') # will print right in DOS box ?rica Balaniuc -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program=20 From hemanexp@yahoo.com Fri May 23 09:09:43 2003 From: hemanexp@yahoo.com (Python-lover) Date: Fri May 23 08:09:43 2003 Subject: [Tutor] Floating point number problem............... Message-ID: <20030523120733.73692.qmail@web41906.mail.yahoo.com> --0-1660340533-1053691653=:68665 Content-Type: text/plain; charset=us-ascii Hi, I have a problem in floating point number. I assgined a value, say 1.23456, to a variable. When i printed the variable i got 1.234560000000001 instead of 1.23456. How can i get the original value? Moreover how to have a floating point number that has only 3 numbers after decimal point even the number has got more digits after the decimal point? I tried with "round" function but it is rounding the 3rd digit instead of keeping it as it is. Thanx. --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-1660340533-1053691653=:68665 Content-Type: text/html; charset=us-ascii
Hi,
 
   I have a problem in floating point number. I assgined a value, say 1.23456, to a variable. When i printed the variable i got 1.234560000000001 instead of   1.23456. How can i get the original value? Moreover how to have a floating point number that has  only 3 numbers after decimal point even the number has got more digits after the decimal point?  I tried with "round" function but it is rounding the 3rd digit  instead of keeping it as it is.
 
 
Thanx.
 
 


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-1660340533-1053691653=:68665-- From magnus@thinkware.se Fri May 23 09:26:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 23 08:26:01 2003 Subject: [Tutor] Absolute newbie - Transliteration In-Reply-To: References: <5.2.1.1.0.20030522235615.01eff008@www.thinkware.se> Message-ID: <5.2.1.1.0.20030523142223.01f38718@www.thinkware.se> At 20:45 2003-05-22 -0700, David Rogers wrote: >Can I put some letter-combinations that include the 'soft' symbol at the >beginning of my dictionary, and have them evaluated first, thus bypassing >the single-letter entries that come later? Or does a dictionary work in >non-sequential order? As you suspected, a dictionary isn't ordered, but that doesn't matter if you loop through the original string one character at a time does it? It's there that the problem lies. A dictionary only matches an exact key, so ordering doesn't matter. The other option would be to be slightly more advanced as you pick out the characters from the original string, but the solution I gave wasn't so bat was it? I think that after-the-fact correction is simpler that to try to get the soft consonants right at once. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Fri May 23 09:47:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 23 08:47:01 2003 Subject: [Tutor] Floating point number problem............... In-Reply-To: <20030523120733.73692.qmail@web41906.mail.yahoo.com> Message-ID: <5.2.1.1.0.20030523143436.01f07cf8@www.thinkware.se> At 05:07 2003-05-23 -0700, Python-lover wrote: > I have a problem in floating point number. It's not you. :) It's the way they are represented in computers in general. Note for instance that: >>> if 0.2 + 0.4 == 0.6: ... print "same" ... else: ... print "not same" ... not same The only way to avoid this would be to use a completely different way of storing fractions in computers, but every way we might use will have disadvantages. There are discussions in the Python community do create a standard fixed point type, but it's not here yet. There is some standardization work in progress that we are waiting for... >I assgined a value, say 1.23456, to a variable. When i printed the >variable i got 1.234560000000001 instead of 1.23456. How can i get the >original value? Just as 1/3 can't be stored exactly as a decimal number, 123456/100000 can't be stored exactly as a binary number. It will be stored as the closest binary approximations. See Appendix B in the Python Tutorial: http://www.python.org/doc/current/tut/node14.html Use "print" to display fewer decimals. See also my recent mail with subject "Re: [Tutor] Handling international characters" for more about the difference between repr and string. The print statement uses str() while just typing a varable name followed by enter uses repr() >>> f = 0.1 >>> f 0.10000000000000001 >>> print f 0.1 >>> str(f) '0.1' >>> repr(f) '0.10000000000000001' >Moreover how to have a floating point number that has only 3 numbers >after decimal point even the number has got more digits after the decimal >point? I tried with "round" function but it is rounding the 3rd >digit instead of keeping it as it is. You can use format strings. >>> f = 1./3 >>> f 0.33333333333333331 >>> print f 0.333333333333 >>> print round(f, 3) 0.333 >>> round(f, 3) 0.33300000000000002 >>> print "%.3f" % f 0.333 >>> "%.3f" % f '0.333' >>> -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From godoy@metalab.unc.edu Fri May 23 12:00:02 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Fri May 23 11:00:02 2003 Subject: [Tutor] Handling international characters In-Reply-To: <5.2.1.1.0.20030523133525.01efd290@www.thinkware.se> ( =?iso-8859-1?q?Magnus_Lyck=E5's_message_of?= "Fri, 23 May 2003 14:10:08 +0200") References: <5.2.1.1.0.20030523024205.01efbff0@www.thinkware.se> <5.2.1.1.0.20030523024205.01efbff0@www.thinkware.se> <5.2.1.1.0.20030523133525.01efd290@www.thinkware.se> Message-ID: Magnus Lyck=E5 writes: > This is the wrong path to take. Don't mess with site.py. OK. > If you convert data between unicode and old fashioned 8 bit strings, > you must do that conversion explicitly, and state what encoding you > use. > > string.decode(encoding) =3D> unicode_string > > unicode_string.encode(encoding) =3D> string > > >>> s =3D "%s %s" % tuple(r[-1]) > >>> s > '\xc9rica Balaniuc' > >>> repr(s) > "'\\xc9rica Balaniuc'" > >>> print s > =C9rica Balaniuc > >>> u =3D s.decode('latin-1') > >>> print u > =C9rica Balaniuc > >>> print u.encode('latin1') # will print right in windows/unix etc > =C9rica Balaniuc > >>> print u.encode('cp850') # will print right in DOS box > ?rica Balaniuc OK. I understood your explanation. I could use that for the database output without any problems. It solves one part of my problem. But then, how can I --- if it's possible --- do that with an XRC file (it's an XML file that contains the description of the window)=20 generated with XRCed? In my code I have something like: ---------------------------------------------------------------------- from wxPython.wx import * from wxPython.xrc import * class ConvTemp(wxApp): def OnInit(self): self.res =3D wxXmlResource("convtemp.xrc") self.InitFrame() self.InitEvents() return True def InitFrame(self): self.frame =3D self.res.LoadFrame(None, "FramePrincipal") self.panelC2F =3D XRCCTRL(self.frame, "CelsiusToFahrenheit") self.panelF2C =3D XRCCTRL(self.frame, "FahrenheitToCelsius") self.panelAbout =3D XRCCTRL(self.frame, "About") sizer =3D self.frame.GetSizer() sizer.SetSizeHints(self.frame) self.frame.Show(1) (code goes on) ---------------------------------------------------------------------- Unfortunately, I can't run pydoc for such a module: $ pydoc wxPython.xrc problem in /usr/lib/python2.2/site-packages/wxPython/xrc.pyc - NameError:= name 'wxWindowPtr' is not defined And, to make things worse, there are no comments inside the xrc.py file...=20 Labels are also showing the same problem: accented letters shows up buggy.=20 (This is why I thought it was an XML parsing problem...) I'll try posting it at XRCed-user's mailing list and I'll post the answer here, if I get any (the list seems to have a VERY low traffic...).=20 Thanks again, --=20 Godoy. From charlie@begeistert.org Fri May 23 13:14:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri May 23 12:14:01 2003 Subject: [Tutor] Struggling with os.exec In-Reply-To: <20030523160007.10097.34435.Mailman@mail.python.org> References: <20030523160007.10097.34435.Mailman@mail.python.org> Message-ID: <20030523181423.6014.20@wonderland.1053679285.fake> On 2003-05-23 at 18:00:07 [+0200], tutor-request@python.org wrote: > Re: Now I'm curious. Could you please describe exactly what you need to > do or why you want it done this way. There might be something that can be > changed about your approach to the problem itself. > I remember you mentioning that you were trying to port a Unix shell > script to python. Now one of the things that you need to be aware is > sometimes the most natural idiom to do a certain thing in one language > might not be the best way to do it in another. For example (this is a > real life example I came across). If one needs to echo all the lines > after a certain 'delimiter' (lets say a line containing only '#'s) in a > file, using shell one might do. Sure, I'm trying to write the following script in Python: function goThere() { echo $1 if [ -d "$1" ] ; then cd "$1" return $? fi return 1 } function countArgs() { return $# } function j() { choices=$(query "name=\"$1\"" | tr '\n' ' ') eval "countArgs $choices" case $? in 0) return 1;; 1) eval "goThere $choices" ; return $?;; *) PS3='Choice: ' eval "\ select curChoice in ${choices};\ do\ goThere \"\$curChoice\";\ if [ \$? -eq 0 ];\ then\ break;\ fi;\ done" esac } Charlie From godoy@metalab.unc.edu Fri May 23 13:23:02 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Fri May 23 12:23:02 2003 Subject: [Tutor] Handling international characters In-Reply-To: (Jorge Godoy's message of "Fri, 23 May 2003 11:58:34 -0300") References: <5.2.1.1.0.20030523024205.01efbff0@www.thinkware.se> <5.2.1.1.0.20030523024205.01efbff0@www.thinkware.se> <5.2.1.1.0.20030523133525.01efd290@www.thinkware.se> Message-ID: Jorge Godoy writes: > self.res = wxXmlResource("convtemp.xrc") Here it was my problem. If I changed the above line to self.res = wxXmlResource("convtemp.xrc", 0) everything would have worked perfectly. The zero indicates that Python shouldn't modify anything on the XML file. I'd like to thank to the author of XRCed for his attention on that. Thanks, -- Godoy. From jeff@ccvcorp.com Fri May 23 14:32:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri May 23 13:32:02 2003 Subject: [Tutor] Struggling with os.exec References: <20030523031803.30440.76256.Mailman@mail.python.org> <20030523113643.1116.2@wonderland.1053679285.fake> Message-ID: <3ECE5BCF.8060302@ccvcorp.com> Charlie Clark wrote: >[...] I think this is possible on MS >Windows, isn't it? > I'm fairly sure that it's *not*. I use Windows all the time, and I've never noticed an instance of a child process modifying its parent's environment. While there isn't a way to directly translate this particular shell script into Python, you may want to look at what part this script plays in the larger problem that you're dealing with. There's probably some other way of approaching that larger problem, which wouldn't involve this sort of environment modifications. Jeff Shannon Technician/Programmer Credit International From charlie@begeistert.org Fri May 23 14:47:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri May 23 13:47:01 2003 Subject: [Tutor] Struggling with os.exec In-Reply-To: <3ECE5BCF.8060302@ccvcorp.com> References: <20030523031803.30440.76256.Mailman@mail.python.org> <20030523113643.1116.2@wonderland.1053679285.fake> <3ECE5BCF.8060302@ccvcorp.com> Message-ID: <20030523194718.22903.25@wonderland.1053679285.fake> On 2003-05-23 at 19:35:11 [+0200], you wrote: > > I'm fairly sure that it's *not*. I use Windows all the time, and I've > never noticed an instance of a child process modifying its parent's > environment. Maybe. The point I was making (albeit with a bit of unnecessary MS Windows bashing) was that the reason for not being able to do this is probably security. > While there isn't a way to directly translate this particular shell > script into Python, you may want to look at what part this script plays > in the larger problem that you're dealing with. There's probably some > other way of approaching that larger problem, which wouldn't involve this > sort of environment modifications. mm, the whole thing came up on the OpenBeOS list where they all love being able to change directories in the shell quickly. I saw the shell script, felt it, and piped up: wouldn't it better to do this in Python. Me and my big mouth :-D Charlie From dyoo@hkn.eecs.berkeley.edu Fri May 23 16:00:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 23 15:00:02 2003 Subject: [Tutor] Documentation concerns. [example:__builtins__.zip, __builtins__.dict] In-Reply-To: <20030523011811.C1316@supermac600.earthlink.net> Message-ID: On Fri, 23 May 2003, Paul Tremblay wrote: > > > > Magnus Lyck=E5 writes: > > > > > Perhaps the Python documentation needs to contain even more > > > suggestions to try out and experiment with features. > > > > IMHO it would benefit a lot of examples. Hmmm... I think we can attack this problem of missing examples: how about whenever we write a short example for a module function, that we add a small tag on the subject line of our emails, like [example:cgi] or [example:MySQLdb.connect]? We can then later cull these out from the rest of the Tutor archive by doing a simple regex search based on the subject line, fix them up to be more presentable, and then send them over to the doc folks. Doing this manually might be a pain, but we can write software to help us do this. For example, here's a small snippet that shows one way of playing with dict() and zip() to quickly create a set of items: ### STOP_WORDS =3D """ NOT NULL NONE AIM MIN A DID IT PERHAPS THESE ABOUT DO ITS QUITE THEY AGAIN DOES ITSELF RATHER """.split() def make_dictionary_from_words(words): return dict(zip(words, [1] * len(words))) word_dict =3D make_dictionary_from_words(STOP_WORDS) ### Actually, this is more of a cute trick that will become obsolete as soon as real Sets come through Python 2.3, but it still shows where zip() can be useful in combination with dict(). Anyway, the idea of writing some software to conveniently data mine the whole Tutor archive at: http://mail.python.org/pipermail/tutor/ sounds very seductive! *grin* We've got a lot of stored content in here; we just need to make it easier to make it more accessible. So if we find ourselves writing a small snippet of code that demonstrates the use of a function or class, perhaps tagging our subject lines with a short identifier like [example:foo] will help people out. Any thoughts on this? From alan.gauld@blueyonder.co.uk Fri May 23 16:43:15 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri May 23 15:43:15 2003 Subject: [Tutor] tutorial 5.1.3 References: Message-ID: <006101c32163$936c19c0$6401a8c0@xp> > >>>def f(x): return x % 2 != 0 and x % 3 != 0 > ... > >>>filter(f, range(2, 25)) > [5, 7, 11, 13, 17, 19, 23] > > From what I understand, the "return" statement is returning > the tested value (passed in from the range) if it passes both > tests. That is correct. It returns the value from the range() if both conditions are true. > However, it seems to me that the return statement would > return either a 1 or a 0 and nothing else As Gerrit points out Python actually returns either the value of the first expression if false or the value of the second if true. But it doesn't matter because both get passed back to filter which uses them to decide wjether to add the range value parameter to the output list. > What am I missing or misunderstanding here? You are getting the return value from the function confused with the return value from filter. They are not the same. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From magnus@thinkware.se Fri May 23 17:30:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 23 16:30:02 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <20030523011811.C1316@supermac600.earthlink.net> References: <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> Message-ID: <5.2.1.1.0.20030523143236.01f2b248@www.thinkware.se> At 01:18 2003-05-23 -0400, Paul Tremblay wrote: >Contributing documentation is perhaps a way we non-programmers (at >least non-skilled programmers) can really help out. I completely agree. In fact, it's an area where it's sometimes just a disadvantage to be a good programmer. The best documents are probably a result of cooperation between the really good and the newbies, because as a programmer with lots of routine, more or less everything is obvious (which makes documentation less than essential) but for the newbie it's not trivial to be completely correct (considering possible exceptions etc). As far as I understand, it takes some effort to learn the tools used to create python documentation, but I think those who work with documentation would be very happy if a few of us here in the tutor mailing list would start submitting clarifying patches to the docs. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Fri May 23 17:49:07 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 23 16:49:07 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> Message-ID: <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> At 01:34 2003-05-23 -0300, Jorge Godoy wrote: >There's no indication on, how to import the module ("import cgi"? >"from cgi import *"?), on how to start a simple cgi with it, etc. Perhaps you should look in the Python Library Reference? After all, that would be the logical place to read about how to use a python standard module. Go to http://www.python.org/doc/current/lib/module-cgi.html Click where it says "Using the cgi module" and read the first sentence. I quote: Begin by writing "import cgi". Do not use "from cgi import *" It certainly tells you how to import the module! In fact, if you manage to type "help(cgi)" you *have already* managed to import cgi correctly. Don't expect all of the docs to be in the source code. Maybe it would be good if an IDE could invoke the right part of the python manuals if you clicked on a word in the source code and pressed F1, but that's a separate issue than documentation contents. It's possible that we'll see more and more of the documentation being generated from the source code, but often, the ideal structure of the implementation is not the ideal structure of documentation of a module, so it's probably good to have separate documents. I'm not so sure Perl's adaption of the unix manpage format for system calls really fit whole modules like that. There are certainly examples in the python docs, but you need to look in the module reference. It's the document marked "keep this under your pillow" in the documentation index... http://www.python.org/doc/current/index.html Nothing is so good that it can't be improved though, so I really think many of you could improve things a lot be providing improved documentation. If nothing else, I'm sure you will learn a lot if you actually read the existing docs properly, which I suggest that you do before you try to improve them. ;) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Fri May 23 18:36:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 23 17:36:02 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: Message-ID: <5.2.1.1.0.20030523225356.01efd9b0@www.thinkware.se> At 06:40 2003-05-23 +0000, roy ollis wrote: >if the code keeps changing would heavily commenting the code with >explainations and examples work as a form of documentation. Shrug! I for one don't believe documentation gets better because you put it in the source code, or that the source gets better when you fill it with comments. Obviously, some documentation, such as method names are parameter lists can be extracted from the source code itself, but as I just wrote in another mail, the structure of the source might not be the best structure to explain the code. For sensible ideas on how to write comments in code, I refer to Kernighan and Pike: "The Practice of Programming". Also, I think Parnas was right in his ideas about modularity and interfaces. It might be better if you *don't* look in the source code for a module you are to use. The only thing you can rely on anyway is the documented interface. The python developers must be free to modify the implementation, and if you read that code, and made assumptions about the implementation that weren't in the documentation, your code might be depending on something that won't be there in the next version of Python... The typical consequence of putting a lot of comments in code that changes a lot is that the comments and the code gets out of sync. Where do you find the Library Reference lacking? There are shortcomings in some areas like Tkinter, but since Tkinter it fairly thin wrapper over Tcl/Tk, it's rather point- less to put the docs in the source there. Something you might find useful to learn how to use different modules is the python test code. Look in the Lib/test directory. The great thing is that the test code and the actual module code doesn't get out of sync, because that would cause the tests to fail. This is a huge advantage over any "dead" code comment. The doctest module is a way to combine the both though. Of course, there is never any guarantee that the test code is 100% complete, but that is also an area where you people could be useful. Supply more tests if you find them lacking, or write your code snippets to tutor in a format which is usable for doctest. That would also be a suitable format for email. > if you wanted to see how something works just look at the source or .py > files. I suggest that you look at test_generators.py if you want to learn about generators for instance. Really: You should take a look at that. Unfortunately, the test files are of varying quality. I think that in general, the more recent are often more useful than the older ones. I wish they were all like test_generators.py. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From mike@daboyz.org Fri May 23 19:14:02 2003 From: mike@daboyz.org (Michael Barrett) Date: Fri May 23 18:14:02 2003 Subject: [Tutor] httplib & keep-alive In-Reply-To: <20030317220418.GE65161@daboyz.org> References: <20030317220418.GE65161@daboyz.org> Message-ID: <20030523221123.GF60270@daboyz.org> Ok, I haven't looked back at this for a while, but inspiration struck me. Just in case anyone else ever has this problem, here's what I found: In order to re-use the connection, before you make the next request, you need to read the data from the last request. Not sure why that is, but thats the way it is. So make sure you do your read. Hope that helps someone else out there. On Mon, Mar 17, 2003 at 02:04:18PM -0800, Michael Barrett wrote: > Hi, can someone please post how to successfully re-use a HTTP/1.1 connection viah httplib? The code below doesn't seem to work- the exception is below the code. > > ############## > #!/usr/local/bin/python > > import httplib, sys > > httpcon = httplib.HTTPConnection('') > httpcon.debuglevel = 1 > httpcon.putrequest('GET', 'http:///ocd/') > httpcon.putheader('Connection','Keep-Alive') > httpcon.endheaders() > > reply = httpcon.getresponse() > > redirLoc = reply.getheader('Location') > > if redirLoc: > print "Found Location header, redirecting to " + redirLoc > httpcon.putrequest('GET', redirLoc) > httpcon.putheader('Connection', 'close') > httpcon.endheaders() > > newreply = httpcon.getresponse() > ############## > > ######### Exception > connect: (, 80) > send: 'GET http:///ocd/ HTTP/1.1\r\nHost: \r\nAccept-Encoding: identity\r\nConnection: Keep-Alive\r\n\r\n' > reply: 'HTTP/1.1 302 Found\r\n' > header: Date: Mon, 17 Mar 2003 22:03:00 GMT > header: Server: Apache/1.3.27 (Unix) > header: Location: http:///ocd/index.py > header: Keep-Alive: timeout=15, max=100 > header: Connection: Keep-Alive > header: Transfer-Encoding: chunked > header: Content-Type: text/html; charset=iso-8859-1 > Found Location header, redirecting to http:///ocd/index.py > send: 'GET http:///ocd/index.py HTTP/1.1\r\nHost: \r\nAccept-Encoding: identity\r\nConnection: close\r\n\r\n' > Traceback (most recent call last): > File "./redirect.py", line 21, in ? > newreply = httpcon.getresponse() > File "/usr/local/lib/python2.2/httplib.py", line 752, in getresponse > raise ResponseNotReady() > httplib.ResponseNotReady > > -- > ________________________________________________________________________ > Mike Barrett | "I used to read, now I go to raves." > mike@daboyz.org | -- Random MUNI Rider, speaking > www.daboyz.org | to my friend Allison. > ------------------------+----------------------------------------------- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ________________________________________________________________________ Mike Barrett | Calvin: "May Contain Adult Situations?" What mike@daboyz.org | does that mean? www.daboyz.org | Hobbes: Oh, you know. Paying bills. Going | to work. Taking responsibility. ------------------------+----------------------------------------------- From godoy@metalab.unc.edu Fri May 23 20:03:02 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Fri May 23 19:03:02 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> ( =?iso-8859-1?q?Magnus_Lyck=E5's_message_of?= "Fri, 23 May 2003 22:50:32 +0200") References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> Message-ID: Magnus Lyck=E5 writes: > At 01:34 2003-05-23 -0300, Jorge Godoy wrote: >>There's no indication on, how to import the module ("import cgi"? >>"from cgi import *"?), on how to start a simple cgi with it, etc. > > Perhaps you should look in the Python Library Reference? After > all, that would be the logical place to read about how to use > a python standard module. So, if there's the logical place, why some documentation is on the module itself? I think that the module is the logical place and the Python Library Reference is the *second* logical place to look at. I already have the module. > It certainly tells you how to import the module! In fact, if you I have already written some applications with the CGI module. The point is that the documentation that we have available (and searchable with pydoc -k) is not as intuitive as it should be. If I have some application, I certainly have the module but it's not guaranteed that I'll have net access or a copy of the Python Library Reference with me. > manage to type "help(cgi)" you *have already* managed to import > cgi correctly. Don't expect all of the docs to be in the source > code. Maybe it would be good if an IDE could invoke the right > part of the python manuals if you clicked on a word in the source > code and pressed F1, but that's a separate issue than documentation > contents. My IDE is Emacs + several xterms. :-) Using pydoc is really great. As is perldoc, texdoc, etc.=20 We were discussing ways to improve the documentation --- at least that's what I understood from prior messages --- and having complete docs with the module including explanations on simple use --- maybe even complex use --- of it would greatly enhance the productivity.=20 I was not --- this time ;-) --- looking for the docs (you see, even having read --- actually I just passed my eyes on everything, but I read whole parts of it --- he whole Python Library Reference I still have to look at or question for the places where docs are).=20 > It's possible that we'll see more and more of the documentation > being generated from the source code, but often, the ideal structure > of the implementation is not the ideal structure of documentation of > a module, so it's probably good to have separate documents. Standardizing places to find docs is something every project needs. Python has done that.=20 Unfortunately, putting every single modules documentation in a website is not what I think is ideal. Having the docs with the module makes them look like part of the code --- IMHO they are as important as the code itself --- and makes the author of the module update them with every change he does in the code. > I'm not so sure Perl's adaption of the unix manpage format for > system calls really fit whole modules like that. There are certainly > examples in the python docs, but you need to look in the module > reference. It's the document marked "keep this under your pillow" > in the documentation > index... http://www.python.org/doc/current/index.html I'd rather have something that is "kept with the working module". Really. Perl gives that and it is incorporated in Perlers coding style.=20 I see no reason it can't be done with Python. There's everything there, it is just needed to add some more text at the beginning and some parts of the code, no changes in standard modules are needed.=20 > Nothing is so good that it can't be improved though, so I really > think many of you could improve things a lot be providing improved > documentation. If nothing else, I'm sure you will learn a lot if you > actually read the existing docs properly, which I suggest that you > do before you try to improve them. ;) I'm reading a lot of the docs I could find. There are lots of things at Python's website but there are lots of things spread all around. And, you can bet that if I could I'd change several standard/non-standard modules documentation to add examples and make some information available with the source code. If the documentation needed is too big, adding a message like 'For complete documentation on this module look at http://somewhere.over.the.net/modules-doc'.=20 Sometimes it takes a body of new people to point out something that people are already used to see and use can be improved. I wouldn't discard any opinions even if I had to point them out the docs that say why the way it is now is better than the proposed way. All have to learn with such discussions: the ones wanting to change and the ones saying that changing is not needed. You certainly have more python experience than I do. I was just looking at it in the last two years, I haven't written much code in it and then, when I started doing such a thing, I found out that there's a HUGE difference in the documentation style used in modules. I don't know, yet, if Perl's way is much better than Python's way on that issue, but it certainly is more practical to work with, after all, as you pointed out, typing 'help(module)' is much easier than opening a browser, going to the python library reference or doing a search on the web... --=20 Godoy. From godoy@metalab.unc.edu Fri May 23 20:11:43 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Fri May 23 19:11:43 2003 Subject: [Tutor] Documentation concerns. [example:__builtins__.zip, __builtins__.dict] References: Message-ID: Danny Yoo writes: > Hmmm... > > > I think we can attack this problem of missing examples: how about whenever > we write a short example for a module function, that we add a small tag on > the subject line of our emails, like [example:cgi] or > [example:MySQLdb.connect]? > So if we find ourselves writing a small snippet of code that demonstrates > the use of a function or class, perhaps tagging our subject lines with a > short identifier like [example:foo] will help people out. > > > Any thoughts on this? I like the idea but there's a problem: changing APIs. There's also another problem: human beings. ;-) If I write something and name it '[example:something]'. You find an error and reply to it. Then we have two messages, where we could have just one. Then, someone wants to point out a third way or ask for information on your code. Then there's a third message, a fourth message and so on. I find the Wiki idea used in lots of places --- including Python --- ideal for such documents. People can submit pages and those can be updated anytime. We could put the python-tutor Wiki address on the footer of every message as an aid to newbies such as myself :-) It would show them where they have to look for information or better understanding of things. But, as I said before, the module documentation is, at least to me, the first place to search. I'm not looking at the source code (not all the time, only when I can't find anything useful on the web) but I'm using pydoc all the time. This is, IMHO, one big enhancement: a module that can be used correctly with the output of 'pydoc module'. -- Godoy. From magnus@thinkware.se Fri May 23 23:24:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 23 22:24:02 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: References: <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> Message-ID: <5.2.1.1.0.20030524014355.01f145d8@www.thinkware.se> First of all: It might be that the best Python documentation is a printed book like Beazley's Python Essential Reference or Martelli's Python in a Nutshell. I think that's fine, and not really a problem. Buying even half a dozen of Python books is cheap if you do serious development. At 20:01 2003-05-23 -0300, Jorge Godoy wrote: >So, if there's the logical place, why some documentation is on the >module itself? The standard library has always (well, for at least seven years, I don't know beyond that) been the main documentation for Python modules and packages (since they appeared). Due to the introspection facilities in python, stuff like doc-strings and tools like pydoc and happydoc etc, it's become more common to see a lot of information that can be extracted from the source code. It's quite possible that we will se a union between the library reference text and the module doc strings in the future. The Python docutils project is developing a standard for writing plain text in a format that will look pretty in HTML or PDF etc format. This is used for PEPs today, and might be used both for Python manuals and code comments in the future, thus making it possible to create the library reference manual from the source code of the modules. Several people are even writing entire books in the Docutils text format reStructuredText today. It will take yet some time before this transition can start though, and it will take years before it's completed, so please get used to the library reference. I will be the best source of information for some years. >I think that the module is the logical place and the Python Library >Reference is the *second* logical place to look at. I already have the >module. You should have the library reference as well! It's only when you sleep it should be under your pillow. In the day time it should be on your desk! ;) >If I have some application, I certainly have the module but it's not >guaranteed that I'll have net access or a copy of the Python Library >Reference with me. Only if you have a broken Python installation. >My IDE is Emacs + several xterms. :-) Using pydoc is really great. As >is perldoc, texdoc, etc. You can view your library reference in Emacs or in the xterms as well. It's probably a good habit to get used to that. >We were discussing ways to improve the documentation --- at least >that's what I understood from prior messages --- and having complete >docs with the module including explanations on simple use --- maybe >even complex use --- of it would greatly enhance the productivity. Sure. As I said, we might see this in a few years. At least for new modules, but in the cases where there are mature modules with the currently best docs only in the library ref, I'm not sure it will be converted to the source anytime soon. But perhaps someone will write a script to convert the current Latex documentation source to reStructuredText. In that case, that could just be pasted into the source code. There are problems here though: Unless you run fully optimized python (python -O -O) you will carry the bulk of this extensive documentation in your code. It will both affect startup time and memory usage. And if you do run -O -O, you will obviously lose the online help. This is of course a difference from docs in Java or C++ source code that never gets through the compiler. >I was not --- this time ;-) --- looking for the docs (you see, even >having read --- actually I just passed my eyes on everything, but I >read whole parts of it --- he whole Python Library Reference I still >have to look at or question for the places where docs are). Always have the Global Module Index available in a browser window! (Perhaps you should have it as start page in your browser? :) And as I say now and then in this mailing list: Reread chapter 2 sometimes. It's the most important part of the library ref. > > It's possible that we'll see more and more of the documentation > > being generated from the source code, but often, the ideal structure > > of the implementation is not the ideal structure of documentation of > > a module, so it's probably good to have separate documents. > >Standardizing places to find docs is something every project >needs. Python has done that. > >Unfortunately, putting every single modules documentation in a website >is not what I think is ideal. In a website? Surely you have the docs included in your Python installation? Otherwise I think it's broken. I certainly have all the docs in both Linux and Windows installations. At least in my Mandrake 9 it's in /usr/share/doc/python-docs-2.2.1/ If you *do* have web access, you might also find http://starship.python.net/crew/theller/pyhelp.cgi useful. >Having the docs with the module makes >them look like part of the code --- IMHO they are as important as the >code itself --- and makes the author of the module update them with >every change he does in the code. If that was true we would never see comments that are out of sync with the code. ;) And as I mentioned before, I'm not at all sure that the module author is always the right person to write the documentation. Besides, only a fraction of the code changes need to be reflected in the documentation needed to use the module. Actually, a problem with this kind of internal documentation is that it's important to differentiate between the external interface of a module and how that's documented, and the implementation and the documentation of that. It's important that programs that use a module only rely on it's formal interface. >I'm reading a lot of the docs I could find. There are lots of things >at Python's website but there are lots of things spread all around. Well, there are a lot of third party modules, and they are certainly documented in various ways. Obviously, there is additinal docs about all aspects of Python in web sites, books, mailing lists, etc, but I don't see that that differes from any other language. Perl has CPAN, and the Python Package Index is far from a CPAN yet. See http://www.python.org/pypi >And, you can bet that if I could I'd change several >standard/non-standard modules documentation to add examples and make >some information available with the source code. If the documentation >needed is too big, adding a message like 'For complete documentation >on this module look at http://somewhere.over.the.net/modules-doc'. Most 3rd party modules come with docs in HTML format. Not all though. I hope Docutils / reStructuredText will help make this more uniform. >Sometimes it takes a body of new people to point out something that >people are already used to see and use can be improved. I wouldn't >discard any opinions even if I had to point them out the docs that say >why the way it is now is better than the proposed way. All have to >learn with such discussions: the ones wanting to change and the ones >saying that changing is not needed. :) I know. I'm currently trying to push for some changes in both documentation and implementation of the Python DB-API, and there are many people who don't want to change the tings that they have gotten used to, even if I suggest changes that will make all the current code work as before, while new code would be more uniform and the learning curve smoother for new developers. In general I think the Python developers are open to improvements, but they are not able to put a lot of time into this. They do depend on help from the community. Right now, the Docutils project is working with the tools, and it's coming along rather fine, but I don't know how much of the work is directly focused on fixing the python code comments and manuals though. Personally I'm more interested in reStructuredText and Docutils for web site texts and article production. >You certainly have more python experience than I do. I was just >looking at it in the last two years, I haven't written much code in it >and then, when I started doing such a thing, I found out that there's >a HUGE difference in the documentation style used in modules. I don't >know, yet, if Perl's way is much better than Python's way on that >issue, but it certainly is more practical to work with, after all, as >you pointed out, typing 'help(module)' is much easier than opening a >browser, going to the python library reference or doing a search on >the web... Well, if I remember correctly, my first email correspondance with Guido, about six years ago or so, was my complaints that the docs weren't as convenient as Perls... :) I think my main complaint was with the language reference manual, and I eventually realized than you're not supposed to read that! ;) A lot has changed in both Perl and Python since then. I guess it was somewhat faster for me to get used to the Perl docs, and most of the time I just used Johan Vromans quick reference guide, but I realize that the things I needed that guide for are things that was soon completely obvious in Python, and the areas where I felt the docs could be better in Python were often in areas that I never managed to do master in Perl... The big difference for me, is that with Perl I need the docs much more... :) We also have to remember that there is a lot of important Python documentation that don't fit in a a source module. I guess the library reference content could have it's source with the respective packages and modules. The tutorial, extending and embedding and python/C api will probably be separate entities like today though. I guess the Python/C API guide could be integrated with the C source, but I don't know if that would make any practical difference. The Language Reference manual is perhaps the real problem child. I remember having problems with it initially. It's labeled as "for language lawyers" and is largely a spec, written partly in BNF, but at the same time, this *is* the reference guide for non-module things like operators and statements of various sorts. If you want something which is more reference than the tutorial, you have to look here, and end up with a very formal text. Perhaps a separate specification and users lanugage reference would be an improvement. Although, as I started, books like Beazley's or Martelli's cover these things nicely, and maybe we don't need everything for free. After all, it's good if there is a market for printed books! :) If nothing else, exposure in book stores and at places like Amazon is probably important for the growth of Python. God knows there aren't a lot of big Python advertisments in the trade rags. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dbroadwell@mindspring.com Sat May 24 00:31:43 2003 From: dbroadwell@mindspring.com (David Broadwell) Date: Fri May 23 23:31:43 2003 Subject: [Tutor] Voting for [example:__builtins__.zip, __builtins__.dict] In-Reply-To: Message-ID: > I think we can attack this problem of missing > examples: how about whenever we write a short > example for a module function, that we add a > small tag on the subject line of our emails, > like [example:cgi] or [example:MySQLdb.connect]? I think that is a small price to pay for the eventual payoff. Which I see as a (possible) long term interpretation of a html/pdf [Tutor sourcemine] that can be cross-posted to C.L.P and aid pythonistas globally. > We can then later cull these out from the rest of > the Tutor archive by doing a simple regex search > based on the subject line, fix them up to be more > presentable, and then send them over to the doc > folks. Doing this manually might be a pain, but > we can write software to help us do this. In the long run, it's like refactoring ... > So if we find ourselves writing a small snippet of > code that demonstrates the use of a function or > class, perhaps tagging our subject lines with a > short identifier like [example:foo] will help > people out. > Any thoughts on this? I do see it as a way that some could copy-paste to do homework, but then, those that do that are on the path to script-kiddie-confuzion and not pythondom. over.all = good_ly_py_thon_ic_ly.py -- David Broadwell From alan.gauld@blueyonder.co.uk Sat May 24 03:59:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat May 24 02:59:01 2003 Subject: [Tutor] Documentation concerns. References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se><013801c32040$9fb80960$6401a8c0@xp><5.2.0.9.0.20030520062251.027be6e8@66.28.54.253><5.2.0.9.0.20030521112455.0387da20@66.28.54.253><5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se><5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> Message-ID: <000301c321c2$0332f8b0$6401a8c0@xp> > So, if there's the logical place, why some documentation is on the > module itself? Because the author decided to put it there. > I think that the module is the logical place and the > Python Library Reference is the *second* logical place to look at. Depends on your background. As someone who has spent his professional life using traditional languages like Pacal, C and COBOL I would never dream of looking for documentation in the module itself - that's what manuals are for! I believe Smalltalk might have been the first to start putting main docs in the code. Perl etc have followed this trend. But I hate it! It makes the module code hard to read, it gets obscured by all the "other stuff". It also makes the module take longer to import, even if its only slightly. Big files are nearly always a bad thing in programming and that includes modules. As for the logical place. What could be more logical than that the documentation is found in the documentation? Seems to me far more logical to keep the documents with all the other documents than in the code - which is logically executable not readable!. Therefore I always go to the documents for documentation! And of course one of the good things about Python is the quality of the documentation that you get with the interpreter(on Mac and PC at least - I think Linux keeps them as separate downloads?) So if you have Python you automatically have the docs too. And both IDLE and Pythonwin have friendly help menus that launch the doc browers... Not to say the docs can't be improved, they can, and the instructions for doing so are also included, in the documents! :-) Just my 2 cents, Alan G. From magnus@thinkware.se Sat May 24 05:29:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 24 04:29:01 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <000301c321c2$0332f8b0$6401a8c0@xp> References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> Message-ID: <5.2.1.1.0.20030524102937.01f4dbd8@www.thinkware.se> At 07:59 2003-05-24 +0100, Alan Gauld wrote: >I think Linux keeps them as separate downloads Yes, I think it's a separate rpm for Mandrake for instance, but not installing that is like not installing man pages for your system. You can hardly complain that there is no good information if it's available, but you don't bother to get it. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From rmangaliag@slu.edu.ph Sat May 24 06:07:00 2003 From: rmangaliag@slu.edu.ph (ali mangaliag) Date: Sat May 24 05:07:00 2003 Subject: [Tutor] like setattr but for methods... References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se><013801c32040$9fb80960$6401a8c0@xp><5.2.0.9.0.20030520062251.027be6e8@66.28.54.253><5.2.0.9.0.20030521112455.0387da20@66.28.54.253><5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se><5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524102937.01f4dbd8@www.thinkware.se> Message-ID: <003c01c321d5$3bd26260$da19a8c0@slu.edu.ph> if i have a class, X, and an instance of X called Y... i can add attributes to Y in two ways: a.) Y.attr1 = 1 Y.attr2 = "test" Y.attr3 = [1,2,3,4,5] b.) setattr(Y,"attr1",1) setattr(Y,"attr2","test") setattr(Y,"attr3",[1,2,3,4,5]) is my understanding of this correct??? my second question is... is there a way for me to define a method like the way i did (or anything similar) with the attributes above??? From am@fx.ro Sat May 24 06:16:02 2003 From: am@fx.ro (Adrian Maier) Date: Sat May 24 05:16:02 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <5.2.1.1.0.20030524014355.01f145d8@www.thinkware.se>; from magnus@thinkware.se on Sat, May 24, 2003 at 04:25:47AM +0200 References: <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524014355.01f145d8@www.thinkware.se> Message-ID: <20030524113801.A437@coto> Magnus Lyck? (magnus@thinkware.se) a scris : > > The Language Reference manual is perhaps the real problem > child. I remember having problems with it initially. It's > labeled as "for language lawyers" and is largely a spec, > written partly in BNF, but at the same time, this *is* the > reference guide for non-module things like operators and > statements of various sorts. If you want something which > is more reference than the tutorial, you have to look here, > and end up with a very formal text. Yes... there is a big gap between the introductory elements in the "Tutorial" and the "Language Reference" (which is too advanced, and looks more like technical specifications than a manual ). Just an example, page 53 "Class definitions" (in the Reference): --- classdef ::= "class" classname [inheritance] ":" suite inheritance ::= "(" [expression_list] ")" classname ::= identifier (two descriptive paragraphs follow.) --- Compare this 20-lines subsection with the "Tutorial" which contains an entire chapter about classes... The tutorial is more clear and useful on that topic. I think that the BNF notation used to describe the syntax is not very intuitive, because the difference between this notation and the Python language is significant. It would be better if the basic statements would be described using *both* the existing notation and some kind of pseudocode, like: if : .... or some kind of schemas ( i'm thinking of the graphical notation i have seen in "Turbo Pascal Programmer's Guide" and other Pascal books to describe the language syntax. My appologies for the ones who don't know what i'm talking about. ) Best wishes, -- Adrian Maier (am@fx.ro) From alan.gauld@blueyonder.co.uk Sat May 24 06:51:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat May 24 05:51:02 2003 Subject: [Tutor] Documentation concerns. References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524102937.01f4dbd8@www.thinkware.se> Message-ID: <002101c321da$0f0922f0$6401a8c0@xp> > At 07:59 2003-05-24 +0100, Alan Gauld wrote: > >I think Linux keeps them as separate downloads > > Yes, I think it's a separate rpm for Mandrake for instance, I thought so. Thinking about this a little further, after posting my last message, it dawned on me that one reason I rarely look at module source code is because in a commercial environment you rarely have the source available. You only get the documentation and the object code. As a result it doesn't occur to you to look for the source except as a last resort. In my 5 years or so using Python I think I've only looked at standard module code maybe 3 or 4 times, the rest of the time I use the documentation and experimenting with the >>> prompt. I guess people who have cut their programming teeth using open source tools are used to having the source available and so adopt a different culture, where documentation is the last resort. That could lead to problems if they ever have to work on a project using commercial tools with no source code! Just a thought, Alan G. From magnus@thinkware.se Sat May 24 07:53:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 24 06:53:02 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <000301c321c2$0332f8b0$6401a8c0@xp> References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> Message-ID: <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> There is currently a discussion about the Python documentation in the Tutor mailing list. One issue in particular is whether the main documentation for the module should be in the module itself, rather than in a separate document. What are the attitudes about this today? In PEP 287 it says: "10. Will the docstrings in the Python standard library modules be converted to reStructuredText? No. Python's library reference documentation is maintained separately from the source. Docstrings in the Python standard library should not try to duplicate the library reference documentation. The current policy for docstrings in the Python standard library is that they should be no more than concise hints, simple and markup-free (although many do contain ad-hoc implicit markup)." Is this still gospel? Any further thoughts around this? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From op73418@mail.telepac.pt Sat May 24 08:19:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sat May 24 07:19:01 2003 Subject: [Tutor] like setattr but for methods... References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se><013801c32040$9fb80960$6401a8c0@xp><5.2.0.9.0.20030520062251.027be6e8@66.28.54.253><5.2.0.9.0.20030521112455.0387da20@66.28.54.253><5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se><5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524102937.01f4dbd8@www.thinkware.se> <003c01c321d5$3bd26260$da19a8c0@slu.edu.ph> Message-ID: <001301c321e6$50a3c290$13100dd5@violante> ----- Original Message ----- From: "ali mangaliag" To: Sent: Saturday, May 24, 2003 10:16 AM Subject: [Tutor] like setattr but for methods... > if i have a class, X, and an instance of X called Y... > i can add attributes to Y in two ways: > > a.) > Y.attr1 = 1 > Y.attr2 = "test" > Y.attr3 = [1,2,3,4,5] > > b.) > setattr(Y,"attr1",1) > setattr(Y,"attr2","test") > setattr(Y,"attr3",[1,2,3,4,5]) > > is my understanding of this correct??? > Yes > my second question is... is there a way for me to define a method like the > way i did (or anything similar) with the attributes above??? > I'm not sure I understand your question, but i'll try to answer anyway :-) functions, methods, etc. are first-class objects in Python. This means you can do things like >>> class X(object): ... pass ... >>> Y = X() >>> def ridiculous(): ... return "I am a ridiculous function." ... >>> Y.ridiculous = ridiculous >>> Y.ridiculous() 'I am a ridiculous function.' >>> Notice though that only the Y instance is ridiculous. >>> another_Y = X() >>> another_Y.ridiculous() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'X' object has no attribute 'ridiculous' >>> To make *all* X instances ridiculous you have to attach the ridiculous function to the class itself, that is, something like >>> X.ridiculous = ridiculous And now you do >>> another_Y.ridiculous() Traceback (most recent call last): File "", line 1, in ? TypeError: ridiculous() takes no arguments (1 given) Oi, trouble!! The "problem" is that when Python adds a function attribute to a class it does some magic in the background. I'm not going to explain the details, but suffices to say that in practical terms you have to add the self argument to the ridiculous function - as you do to all the usual methods!! >>> def ridiculous(self): ... return "We are all ridiculous!" ... >>> X.ridiculous = ridiculous >>> another_Y.ridiculous() 'We are all ridiculous!' HTH, with my best regards, G. Rodrigues From godoy@metalab.unc.edu Sat May 24 09:06:42 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Sat May 24 08:06:42 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <5.2.1.1.0.20030524014355.01f145d8@www.thinkware.se> ( =?iso-8859-1?q?Magnus_Lyck=E5's_message_of?= "Sat, 24 May 2003 04:25:47 +0200") References: <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524014355.01f145d8@www.thinkware.se> Message-ID: Magnus Lyck=E5 writes: > First of all: It might be that the best Python documentation is a > printed book like Beazley's Python Essential Reference or Martelli's > Python in a Nutshell. I think that's fine, and not really a > problem. Buying even half a dozen of Python books is cheap if you do > serious development. I agree with you on how good it is to have books to do serious development. We in the southe hemisphere, with rare exceptions, have a 'small' problem: our money is a lot devalued when compared to yours. Spending US$70,00 on a book is like spending a worker full month paying. And books I'd like to have --- such as Python Bible --- are more expensive than that...=20 I first must have some results --- small ones, of course, since I don't have the 'library' yet --- then I can spend money to have bigger results. We're a small company, yet. :-) > At 20:01 2003-05-23 -0300, Jorge Godoy wrote: >>So, if there's the logical place, why some documentation is on the >>module itself? > > The standard library has always (well, for at least seven years, I > don't know beyond that) been the main documentation for Python > modules and packages (since they appeared). It's been there since I first saw python, about three years ago --- my first installation of it was two years ago. So, knowing where the standard modules' docs are is not a real problem.=20 > Due to the introspection facilities in python, stuff like > doc-strings and tools like pydoc and happydoc etc, it's become more > common to see a lot of information that can be extracted from the > source code. And this is a big improvement in the documentation area. You can share everything with your code and it is enough to have working implementations. People can grab the source code, run 'pydoc source-code' and see how to use it for their work. (And without ads as in free websites ;-)). > It's quite possible that we will se a union between the library > reference text and the module doc strings in the future. The Python > docutils project is developing a standard for writing plain text in > a format that will look pretty in HTML or PDF etc format. This is > used for PEPs today, and might be used both for Python manuals and > code comments in the future, thus making it possible to create the > library reference manual from the source code of the modules. It would be great. And would allow us to have the documentation whenever the source is available. Please, note that I'm not willing to change the standard modules documentation. I'm just willing to improve documentation by adding aditional hints in the source code. It isn't needed to do that now.=20 Instead of having to do 'pydoc cgi' to look at some method declaration/syntax and having to open a web browser to see how to use it, we could just use 'pydoc' to have both. The thing is: "there's always a Python interpreter running on your machine". There isn't always a web browser and an Internet connection. > Several people are even writing entire books in the Docutils text > format reStructuredText today. I've read a big argument about using ReST for the standard modules documentation... :-) Coincidently it was started with a PEP suggesting its use. > It will take yet some time before this transition can start though, > and it will take years before it's completed, so please get used to > the library reference. I will be the best source of information for ^ > some years. I be you will :-) Just kidding. Yes, it wil be the best source of information. But it can't prevent us from enhancing it. As I said, if we had access and authorization to change standard libraries documentation, I'd volunteer to add some things to the output I get when I run 'pydoc'.=20 >>I think that the module is the logical place and the Python Library >>Reference is the *second* logical place to look at. I already have the >>module. > > You should have the library reference as well! It's only when you > sleep it should be under your pillow. In the day time it should be > on your desk! ;) Hmmm... This might be the reason why it wasn't helping more! :-))) >>If I have some application, I certainly have the module but it's not >>guaranteed that I'll have net access or a copy of the Python Library >>Reference with me. > > Only if you have a broken Python installation. Some Linux distributions out there split their packages a lot and allow the installation of packages without their docs. This is also true on small systems with a limited amount of disk (where this issue becomes critical in both ways: too much docs =3D too much disk used, too little docs =3D too hard to have the docs when needed).=20 >>My IDE is Emacs + several xterms. :-) Using pydoc is really great. As >>is perldoc, texdoc, etc. > > You can view your library reference in Emacs or in the xterms > as well. It's probably a good habit to get used to that. Yep. 'info python', 'info python-lib' and 'info python-api' are very good and well known friends. I can access them with C-h i on Emacs. Unfortunately, third part modules don't insert themselves on info's index or at the standard library. They are spreaded on the system (there's a logic on their installation, though).=20 > Sure. As I said, we might see this in a few years. At least for new > modules, but in the cases where there are mature modules with the > currently best docs only in the library ref, I'm not sure it will be > converted to the source anytime soon. I hope they are... But, for standard modules, I can live with that.=20 > But perhaps someone will write a script to convert the current Latex > documentation source to reStructuredText. In that case, that could > just be pasted into the source code. LaTeX is, as pointed out by Guido on the thread I've spoken above, much less verbose than XML and gives a much better output when generating printed or screen reading documents. For screen reading, HTML is enough, though. LaTeX -> HTML converters make a good job on the Python documentation.=20 > There are problems here though: > > Unless you run fully optimized python (python -O -O) you will carry > the bulk of this extensive documentation in your code. It will both > affect startup time and memory usage. And if you do run -O -O, you > will obviously lose the online help. When developing an application it isn't a problem. When in production, you can run fully optimized... This won't, them, affect production systems except that they'll have '#!/usr/bin/python -O -O -tt' as the first line of their code ('-tt' is an addition of mine it is already present in the development stage ;-)). > This is of course a difference from docs in Java or C++ source code > that never gets through the compiler. Maybe it's something we should inherit from their experience... I think that Perl's docs have the same behaviour: they don't get through the compiler. > Always have the Global Module Index available in a browser window! > (Perhaps you should have it as start page in your browser? :) I have the info system open with them. > And as I say now and then in this mailing list: Reread chapter 2 > sometimes. It's the most important part of the library ref. OK. Except that 'chapter 2' isn't meaningful in info, where chapters aren't numbered... Oh, yes! "2. Built-in Functions, Types, and Exceptions". This is the one I thought when I looked at info...=20 > In a website? Surely you have the docs included in your Python > installation? Otherwise I think it's broken. I certainly have all > the docs in both Linux and Windows installations. At least in my > Mandrake 9 it's in /usr/share/doc/python-docs-2.2.1/ I do have it here, but I can choose not to have them on machines with a low capacity -- such as handhelds -- or on machines that are in production. It saves --- at least my python-doc package do --- almost 2.6 MB of disk... Exactly 2612985 bytes. > If you *do* have web access, you might also find > http://starship.python.net/crew/theller/pyhelp.cgi useful. I also like http://www.pythonware.com/library/ > If that was true we would never see comments that are out of sync > with the code. ;) And as I mentioned before, I'm not at all sure > that the module author is always the right person to write the > documentation. Besides, only a fraction of the code changes need to > be reflected in the documentation needed to use the module. Comments out of sync with code reflect either a development stage or a lack of attention from the coder himself.=20 I don't think the author would be the best writer, but he surely can document the module and give one simple working example. And, if the theory or documentation is too dense, he can put a note pointing somewhere else.=20 > Actually, a problem with this kind of internal documentation is that > it's important to differentiate between the external interface of a > module and how that's documented, and the implementation and the > documentation of that. It's important that programs that use a > module only rely on it's formal interface. And I'm not suggesting to have the module's documentation as comments in the source. I'm suggesting having them as part of the code. Something that can be extracted and printed on screen with happydoc or pydoc.=20 > Well, there are a lot of third party modules, and they are certainly > documented in various ways. Obviously, there is additinal docs about > all aspects of Python in web sites, books, mailing lists, etc, but I > don't see that that differes from any other language. Neither do I. (see below) > Perl has CPAN, and the Python Package Index is far from a CPAN yet. > See http://www.python.org/pypi I've already seen that. CPAN is a great thing.=20 But, one additional thing here is that Perl include the doc with the module. And it is also documented at CPAN: http://search.cpan.org/ --- using the same example (the CGI module), take a look at http://search.cpan.org/author/JHI/perl-5.8.0/lib/CGI.pm (this is extracted from the module). > Most 3rd party modules come with docs in HTML format. Not all > though. I hope Docutils / reStructuredText will help make this more > uniform. Me too. I'd rather have text documentation since I can use it virtually anywhere without installing a browser or stripping the HTML output (what isn't really hard...).=20 > :) I know. I'm currently trying to push for some changes in both > documentation and implementation of the Python DB-API, and there are > many people who don't want to change the tings that they have gotten > used to, even if I suggest changes that will make all the current > code work as before, while new code would be more uniform and the > learning curve smoother for new developers. God bless you. :-) I hope you can get changes --- if they are for better --- approved.=20 > In general I think the Python developers are open to improvements, > but they are not able to put a lot of time into this. They do depend > on help from the community. :-) And then they should offer the community more resources.=20 I am proud of code I write, but I know other developers will make improvements and/or additions to my code if they think it will help. I just have to decide if I will accept them or not. This is why my email is at each and every source file I write. > Right now, the Docutils project is working with the tools, and it's > coming along rather fine, but I don't know how much of the work is > directly focused on fixing the python code comments and manuals > though. Personally I'm more interested in reStructuredText and > Docutils for web site texts and article production. :-) You're not a newbie, this is why. For website and articles I'd take a look at HTMLgen(http://starship.python.net/crew/friedrich/HTMLgen/html/main.html). It's like Perl's Template Toolkit (http://www.tt2.org) and allow an easy way to standardize your website look'n'feel without too much trouble. I bet that getting PDFs with it is also easy and can be done on the fly without much trouble (of course caching would make things better, but files can be generated on demand and stored for some time in the cache). > Well, if I remember correctly, my first email correspondance with > Guido, about six years ago or so, was my complaints that the docs > weren't as convenient as Perls... :) Heh...=20 > I think my main complaint was with the language reference manual, > and I eventually realized than you're not supposed to read that! ;) I use that as a reference, as the name says... I just looked at it and read some parts from top to bottom. But, I haven't read it all. > A lot has changed in both Perl and Python since then. I guess it was > somewhat faster for me to get used to the Perl docs, and most of the > time I just used Johan Vromans quick reference guide, but I realize > that the things I needed that guide for are things that was soon > completely obvious in Python, and the areas where I felt the docs > could be better in Python were often in areas that I never managed > to do master in Perl... The big difference for me, is that with Perl > I need the docs much more... :) I solved my problems very fast with it... And with maintenable and readable code :-)=20 Python is easier, though, to have something working right from the design table.=20 > We also have to remember that there is a lot of important Python > documentation that don't fit in a a source module. Of course! As I said, I'm not willing to put everything inside some module. Just some examples and a more verbose explanation on how to use the module.=20 > I guess the library reference content could have it's source with > the respective packages and modules. Hmmm... Dunno. It might be hard to make searches on specific parts of it that way. The '-k' option should be enhanced too... maybe an index of keywords, dunno. > The tutorial, extending and embedding and python/C api will probably > be separate entities like today though. I guess the Python/C API > guide could be integrated with the C source, but I don't know if > that would make any practical difference. I think it would cause more trouble since you'd have to have a tool for extracting Python documentation from Python's source and Python documentation from C source...=20 > Perhaps a separate specification and users lanugage reference would > be an improvement. Although, as I started, books like Beazley's or > Martelli's cover these things nicely, and maybe we don't need > everything for free. After all, it's good if there is a market for > printed books! :) Indeed. > If nothing else, exposure in book stores and at places like Amazon > is probably important for the growth of Python. God knows there > aren't a lot of big Python advertisments in the trade rags. Maybe this is documentations fault or the lack of a centralized place (such as CPAN) to search things... (There is a module list at python's website, but I couldn't find it fast on the hyperlinks... maybe because I'm not used to go there since the list is very small.) --=20 Godoy. From godoy@metalab.unc.edu Sat May 24 09:14:01 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Sat May 24 08:14:01 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <000301c321c2$0332f8b0$6401a8c0@xp> (Alan Gauld's message of "Sat, 24 May 2003 07:59:25 +0100") References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <000301c321c2$0332f8b0$6401a8c0@xp> Message-ID: "Alan Gauld" writes: > Depends on your background. As someone who has spent his > professional life using traditional languages like Pacal, C and > COBOL I would never dream of looking for documentation in the module > itself - that's what manuals are for! That's fine. Using, again, the perl example, when I type 'man module' I get exactly the same output as when I type 'perldoc module'. And I'm using the manual ;-) > I believe Smalltalk might have been the first to start putting main > docs in the code. Perl etc have followed this trend. But I hate it! > It makes the module code hard to read, it gets obscured by all the > "other stuff". It also makes the module take longer to import, even > if its only slightly. Big files are nearly always a bad thing in > programming and that includes modules. I think that if this speed difference on importing the module is relevant, than your application would benefit a lot from C code. Maybe Python compile should also discard/ignore the code to reduce the memory use. > As for the logical place. What could be more logical than that the > documentation is found in the documentation? Seems to me far more > logical to keep the documents with all the other documents than in > the code - which is logically executable not readable!. Therefore I > always go to the documents for documentation! This is also obvious to me. Where are my system's docs? Available in man pages. Where do I think other things docs should be? In man pages as well. Or info, which can have hyperlinks and consult both info and man pages. One interface, all the docs. It was true with C, it was true with Perl and I think that it could be true with Python. Why not? More documentation is better than fewer documentation. > And of course one of the good things about Python is the quality of > the documentation that you get with the interpreter(on Mac and PC at > least - I think Linux keeps them as separate downloads?) So if you Well, I run Linux on a PC, so I suppose you were talking about Windows. But, with regards to your question, it is true that some Linux distributions have separate packages for the docs but if you get Python's source from www.python.org, than everything is packaged together and in any other operating system. > have Python you automatically have the docs too. And both IDLE and > Pythonwin have friendly help menus that launch the doc browers... I use my system's standard tools a lot (info and man). It's something like having a way to make python documentation searchable with Windows Help. (I'm not guilty if Unix tools are easier to use in that case...) > Not to say the docs can't be improved, they can, and the > instructions for doing so are also included, in the documents! :-) :-) We just have to find those instructions. They change from module to module (except for the standard ones). -- Godoy. From godoy@metalab.unc.edu Sat May 24 09:19:02 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Sat May 24 08:19:02 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <002101c321da$0f0922f0$6401a8c0@xp> (Alan Gauld's message of "Sat, 24 May 2003 10:51:33 +0100") References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524102937.01f4dbd8@www.thinkware.se> <002101c321da$0f0922f0$6401a8c0@xp> Message-ID: "Alan Gauld" writes: > In my 5 years or so using Python I think I've only looked at > standard module code maybe 3 or 4 times, the rest of the time I use > the documentation and experimenting with the >>> prompt. I do that too, but I think it's more productive when I get the docs easily. As I said in another message, looking at the source code is the last approach I take: usually it takes longer than searching something on Internet and maybe it isn't as helpful, specially for big packages such as wxPython. > I guess people who have cut their programming teeth using open > source tools are used to having the source available and so adopt a > different culture, where documentation is the last resort. That Documentation should be the first resort. This is why it is important to have it as easily accessible as with standard system's documentation. > could lead to problems if they ever have to work on a project using > commercial tools with no source code! If they have good programming background they will be used to read the docs. They won't have the source and that can only be a problem if they rely solely on it for writing their code... I don't know anybody that relies only in the source code (except when the documentation is embedded in the source code and not extractable with something) to write their programs. And I worked some years side by side with very good Linux hackers... See you, -- Godoy. From magnus@thinkware.se Sat May 24 10:03:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 24 09:03:01 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: References: <000301c321c2$0332f8b0$6401a8c0@xp> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <000301c321c2$0332f8b0$6401a8c0@xp> Message-ID: <5.2.1.1.0.20030524141933.01efddf8@www.thinkware.se> At 09:12 2003-05-24 -0300, Jorge Godoy wrote: >I think that if this speed difference on importing the module is >relevant, than your application would benefit a lot from C code. Hm... Have you worked a lot with Python? Startup time is very often the only factor where Python programs have performance problems. This is certainly true for most CGI scripts, it's is the main problem with Python CGI scripts compared to Perl for instance, it's often important for GUI applications, and in many development situations, such as during unit tests. In case of other performance problems, it's typically possible to improve agorithms, write a part of the system in C etc, but startup time is an eternal problem. I haven't made any precise calculations, but I think putting all the library reference text in the Python code would add maybe 30% to the size of the modules, and about the the same to startup time in many situations. Working with both Python and C in a combination is often a good way to get both development speed and execution speed, but the Python startup time is the factor you can't fix with a C extension module... (BTW, with recent additions such as Pyrex, the need for C is shrinking.) >Maybe >Python compile should also discard/ignore the code to reduce the >memory use. Python -O -O will do that, but how many use that? For many people, putting all docs in the code would hamper performance, and the only option is to loose most of the use for tools such as help. You also loose assertions and other debug code when you use -O -O, so you don't want that during development. And startup time is the one timing problem you want the least of development. You often use smaller data sets and so on, so slow data processing is often not a problem, but you typically run the program many more times per day that normal users. (If it's not small apps like CGI scripts.) >One interface, all the docs. It was true with C, Really? Do you have K & R on line? Surely that's the only C documentation worth having. :) Besides, you don't have *one* interface to all these. You have man, info etc etc. What's the problem with adding lynx /usr/share/doc/python-docs-2.2.1/lib/modindex.html to the mix? >it was true with Perl >and I think that it could be true with Python. Why not? More >documentation is better than fewer documentation. Noone is arguing against that! We're just trying help you realize where to look. >We just have to find those instructions. They change from module to >module (except for the standard ones). I certainly agree that a more uniform handling of documentation for third party applications would be great. Maybe docutils can help there. Besides -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From pythontutor@venix.com Sat May 24 10:43:02 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Sat May 24 09:43:02 2003 Subject: [Tutor] like setattr but for methods... References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se><013801c32040$9fb80960$6401a8c0@xp><5.2.0.9.0.20030520062251.027be6e8@66.28.54.253><5.2.0.9.0.20030521112455.0387da20@66.28.54.253><5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se><5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524102937.01f4dbd8@www.thinkware.se> <003c01c321d5$3bd26260$da19a8c0@slu.edu.ph> Message-ID: <3ECF76A2.5030005@venix.com> You have one reply. I am going to guess that you were looking for a different kind of answer. class X: def __init__(self): self.attr1 = 1 self.attr2 = "test" self.attr3 = [1,2,3,4,5] Y = X() print Y.attr1 >>> 1 __init__ can provide initial values for an instance. You can also provide more arguments after self if necessary. Typically people use Upper Case for Classes and lower case for an instance. Hopefully one of these replies answers your question. (When starting a new thread, it's better not to reply to an existing message. Even when you change the subject, the mail headers will place the message into the thread you replied to. I think that's what happened here.) ali mangaliag wrote: > if i have a class, X, and an instance of X called Y... > i can add attributes to Y in two ways: > > a.) > Y.attr1 = 1 > Y.attr2 = "test" > Y.attr3 = [1,2,3,4,5] > > b.) > setattr(Y,"attr1",1) > setattr(Y,"attr2","test") > setattr(Y,"attr3",[1,2,3,4,5]) > > is my understanding of this correct??? > > my second question is... is there a way for me to define a method like the > way i did (or anything similar) with the attributes above??? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From magnus@thinkware.se Sat May 24 11:27:05 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 24 10:27:05 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: References: <5.2.1.1.0.20030524014355.01f145d8@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524014355.01f145d8@www.thinkware.se> Message-ID: <5.2.1.1.0.20030524152319.01eefed0@www.thinkware.se> At 09:04 2003-05-24 -0300, Jorge Godoy wrote: >I agree with you on how good it is to have books to do serious >development. We in the southe hemisphere, Oh, I though UNC was in North Carolina. :) >with rare exceptions, have a >'small' problem: our money is a lot devalued when compared to >yours. Spending US$70,00 on a book is like spending a worker full >month paying. And books I'd like to have --- such as Python Bible --- >are more expensive than that... So you have to trade time for money... $70 seems very much though. Python is a Nutshell, which I haven't read, but have heard very good things about, is $21.50 + shipping at bookpool. If you buy a number of books, shipping costs will not be such a big part of the cost. Try to get together with some other people so that you can buy ten books or so at the same time, and you will get a much lower price than through most other channels. >It's been there since I first saw python, about three years ago --- my >first installation of it was two years ago. So, knowing where the >standard modules' docs are is not a real problem. That makes your complaints about lacking information a bit surprising. >And this is a big improvement in the documentation area. You can share >everything with your code and it is enough to have working >implementations. People can grab the source code, run 'pydoc >source-code' and see how to use it for their work. (And without ads as >in free websites ;-)). There aren't any ads in the python documents either... As both Alan and I pointed out, there are several disadvantages with this. For documentation like the wxPython docs that mainly consist of showing the method calls, it would probably be better to use something generated from code, particualrly considering the problem that project has in keeping the docs updated. Also, consider all the questions Robin Dunn has to answer every day, it's clear that wxPython need documentaion which is on a completely differnt level than to describe the details on what parameters to provide for each method call etc. As I've said, the source code structure might not match the best structure for describing the code. >It would be great. And would allow us to have the documentation >whenever the source is available. I think we should make certain that we always get docs with our code, but I can't see that the exact organisation of docs and source code is an important issue. >Please, note that I'm not willing to change the standard modules >documentation. I'm just willing to improve documentation by adding >aditional hints in the source code. It isn't needed to do that now. It seems that the current approach is still to have the bulk of docs in separate files and just small hints in the soure code. >Instead of having to do 'pydoc cgi' to look at some method >declaration/syntax and having to open a web browser to see how to use >it, we could just use 'pydoc' to have both. I'm sure you can write a nice utility that will get the right information quickly without too many key-presses. >The thing is: "there's >always a Python interpreter running on your machine". There isn't >always a web browser and an Internet connection. That's up to you. I think adapting to the standards in the community is your most productive way ahead. You don't need an internet connection to access local docs in a browser. > > the library reference. I will be the best source of information for > ^ > > some years. > >I be you will :-) Freudian slip? ;) >Unfortunately, third part modules don't insert themselves on info's >index or at the standard library. They are spreaded on the system >(there's a logic on their installation, though). I think it would be great to have some way of integrating the docs for site-packages in some common structure. Both for indexing and for searching. >LaTeX is, as pointed out by Guido on the thread I've spoken above, >much less verbose than XML and gives a much better output when >generating printed or screen reading documents. For screen reading, >HTML is enough, though. LaTeX -> HTML converters make a good job on >the Python documentation. But reStructuredText is not XML. It's less verbose and more readable than Latex in my opinion. Have you used it? >When developing an application it isn't a problem. Startup delays are annoying. If you run several hundred small tests and every test has a startup cost, you won't want to run the tests as often as you should. >Maybe it's something we should inherit from their experience... I >think that Perl's docs have the same behaviour: they don't get through >the compiler. No we should not. The introspection facilities and dynamic nature of Python is a big advantage. Stripping the code will give us much less to introspect. > > In general I think the Python developers are open to improvements, > > but they are not able to put a lot of time into this. They do depend > > on help from the community. > >:-) >And then they should offer the community more resources. I'm not sure what you mean. What is it that you need and don't have? >I am proud of code I write, but I know other developers will make >improvements and/or additions to my code if they think it will help. I >just have to decide if I will accept them or not. This is why my email >is at each and every source file I write. Python is obviously more of a collective effort, and it has a fairly clear structure and reasonable information about how to contribute. See for instance http://www.python.org/dev/ >:-) You're not a newbie, this is why. For website and articles I'd >take a look at >HTMLgen(http://starship.python.net/crew/friedrich/HTMLgen/html/main.html). Really? It's not been in development for years. I used it to build a web site a number of years ago, and I ended up building something reStructuredText-like on top of it. reStructuredText is a much easier tool, and you don't need to worry about programming to get decent looking documents in both XHTML and PDF from the same simple source. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From a_abdi406@yahoo.com Sat May 24 11:59:01 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Sat May 24 10:59:01 2003 Subject: [Tutor] about NLTK parser Message-ID: <20030524145841.61376.qmail@web14508.mail.yahoo.com> --0-192669929-1053788321=:60980 Content-Type: text/plain; charset=us-ascii Hi I was trying to run a program to build a sentence tree, but the interpreter is giving me an error such as the follows: raceback (most recent call last): File "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "C:\Grammar\grammar_pp_02.py", line 41, in ? AttributeError: 'NoneType' object has no attribute 'draw' This is what I was trying to achieve in order to build a parse tree of the sentence in the code: >>> import nltk.parser >>> import nltk.token >>> parser = nltk.parser.ShiftReduceParser(G) >>> tokenizer = nltk.token.WSTokenizer() >>> tokens = tokenizer.tokenize('the man saw a woman in the garden') >>> parse = parser.parse(tokens) >>> parse.draw() <----------------even if parser module loaded it is giving me an error Does any body know NLTK problems associated with win32 ? thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-192669929-1053788321=:60980 Content-Type: text/html; charset=us-ascii
Hi
I was trying to run a program to build a sentence tree, but the interpreter
is giving me an error such as the follows:
 
raceback (most recent call last):
  File "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript
    exec codeObject in __main__.__dict__
  File "C:\Grammar\grammar_pp_02.py", line 41, in ?
AttributeError: 'NoneType' object has no attribute 'draw'
 
This is what I was trying to achieve in order to build a parse tree
of the sentence in the code:
 
>>> import nltk.parser
>>> import nltk.token
>>> parser = nltk.parser.ShiftReduceParser(G)
>>> tokenizer = nltk.token.WSTokenizer()
>>> tokens = tokenizer.tokenize('the man saw a woman in the garden')
>>> parse = parser.parse(tokens)
>>> parse.draw()  <----------------even if parser module loaded
                                            it is giving me an error

Does any body know NLTK problems associated with win32 ?

thanks in advance

 



Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-192669929-1053788321=:60980-- From magnus@thinkware.se Sat May 24 12:24:06 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 24 11:24:06 2003 Subject: [Tutor] about NLTK parser In-Reply-To: <20030524145841.61376.qmail@web14508.mail.yahoo.com> Message-ID: <5.2.1.1.0.20030524171318.01ee83f8@www.thinkware.se> At 07:58 2003-05-24 -0700, Abdirizak abdi wrote: > >>> import nltk.parser > >>> import nltk.token > >>> parser = nltk.parser.ShiftReduceParser(G) > >>> tokenizer = nltk.token.WSTokenizer() > >>> tokens = tokenizer.tokenize('the man saw a woman in the garden') > >>> parse = parser.parse(tokens) The docs say: Return the best parse for the given text, or None if no parses are available. I know nothing about NLTK, but is your grammer right? Is it able to parse that sentence? You have left that part out. parse() obviously returned None here. It seems to me that you just wasn't able to parse the tokens, and that it behaves as it should then. You might need something like parse = parser.parse(tokens) if parse: parse.draw() else: print "Can't parse", tokens > >>> parse.draw() <----------------even if parser module loaded > it is giving me an error > -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From hemanexp@yahoo.com Sat May 24 14:03:43 2003 From: hemanexp@yahoo.com (Python-lover) Date: Sat May 24 13:03:43 2003 Subject: [Tutor] Keypress event in canvas.......... Message-ID: <20030524170134.30951.qmail@web41901.mail.yahoo.com> --0-1924752861-1053795694=:29590 Content-Type: text/plain; charset=us-ascii Hi, iam using python and Tkinter. Is it possible to bind a keyboard event, say "Up" arrow press, to a canvas item (like rectangle)? i have created a canvas and drawn a set of rectangles one above another.Now when i press "Up" arrow key first time i expect first rectangle to get focus and second one for next keypress and so on utill you reach the last rectangle. how can i do it? My sample code is given below:***************************************from Tkinter import * class App: def __init__(self,parent): self.myparent = parent self.canvas = Canvas(self.myparent,width=600,height=500) self.canvas.pack() x1 = 100 y1 = 100 x2 = 200 y2 = 200 i = 1 while i<4: self.canvas.create_rectangle(x1,y1,x2,y2,tag='RECT',fill='red') y1 = y2 y2 = y1 + 100 i = i+1 self.canvas.tag_bind('RECT','', self.get_rect_points) def get_rect_points(): #....................... # Here i want to get rectangle points #........................ root = Tk() myapp = App(root) root.mainloop() Thanx. --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-1924752861-1053795694=:29590 Content-Type: text/html; charset=us-ascii
Hi,
  iam using python and Tkinter. Is it possible to bind a keyboard event, say "Up" arrow press, to a canvas item (like rectangle)? i have created a canvas and drawn a set of rectangles one above another.Now when i press "Up" arrow key first time i expect first rectangle to get focus and second one for  next keypress and so on utill you reach the last rectangle. how can i do it?
 
  My sample code is given below:
***************************************
from Tkinter import *
class App:
  def __init__(self,parent):
  self.myparent = parent
  self.canvas = Canvas(self.myparent,width=600,height=500)
  self.canvas.pack()
  x1 = 100
  y1 = 100
  x2 = 200
  y2 = 200
  i = 1
  while i<4:
          self.canvas.create_rectangle(x1,y1,x2,y2,tag='RECT',fill='red')
          y1 = y2
          y2 = y1 + 100
          i = i+1
  self.canvas.tag_bind('RECT','<Up>', self.get_rect_points)
 
 def get_rect_points():
   #.......................
  # Here i want to get rectangle points
  #........................
        
root = Tk()
myapp =  App(root)
root.mainloop()
 
 
Thanx.
 


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-1924752861-1053795694=:29590-- From magnus@thinkware.se Sat May 24 18:04:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 24 17:04:01 2003 Subject: [Doc-SIG] Re: [Tutor] Documentation concerns. In-Reply-To: <1053804978.1167.49.camel@lothlorien> References: <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> Message-ID: <5.2.1.1.0.20030524225458.01ec9430@www.thinkware.se> At 14:36 2003-05-24 -0500, Ian Bicking wrote: >One issue I see with moving the documentation into the code, is that we >don't have any system that can represent the kind of documentation from >the standard library as docstrings. Typically documentation created >from docstrings is highly (overly) structured, and does not allow items >to be introduced in an order different from the code, or presented with >a different structure than the code, plus there is no place for >narrative that is not connected with a function or class. You can always put a big blurb in the beginning of the module, but I agree, and I argued the same in python-tutor. You can't expect that the best structure for the implementation would be the best structure to explain how to work with the software. On the other hand, even if it takes some restructuring of the extracted data, it seems that the docstrings for methods and functions should typically contain the same information as we would have in the corresponding part of the documentation. It seems very redundant to write that twice. Another issue is that it's great if documention examples are written as doctest strings and run as part of a test suite. In that way, we can at least verify that that part of the documentation is synchronized with the implementation. Maybe the best solution is some kind of mix. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From GREENDAY31087@aol.com Sun May 25 03:28:02 2003 From: GREENDAY31087@aol.com (GREENDAY31087@aol.com) Date: Sun May 25 02:28:02 2003 Subject: [Tutor] I need ideas please Message-ID: <191.1a28ed39.2c01bc11@aol.com> --part1_191.1a28ed39.2c01bc11_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit I'm going to make a little program that tells the user his or her sign-Pisces, libra, gemini, etc. This isn't a program I want people to take seriously but I'm making it to test what I've been learning. This is my first language and im not experienced at all. Anyway, my first problem is the months. Determining what your sign is depends on the month but it's not like every sign starts on the first day of the month. (march 1st-31st: you are a Pisces) the different signs start in the middle of the month. So you cant just take the input (month) and determine what sign corresponds with it. I was thinking about making each month a certain value and then asking the user the day of the month they were born. After that, the program could add the day to the month value to make a new value. I could assign a different sign to each range of numbers and if, say, the value was in the range that 'Pisces' covers, they would be Pisces. Follow me so far? My next problem is not as complicated as the first one but I don't know what should be made into a function to be called. Should I make the whole month thing into a function or should I not define any functions? I'm sort of confused. Also, I wanted to know ... will this program probably need to use a list? pisces(february19-march20) aries(march21-april19) taurus(april20-may20) gemini(may21-june20) cancer(june21-july22) leo(july23-august22) virgo(august23-september22) libra(september23-october22) scorpio(october23-november22) sagiattius(november23-december21) capricorn(december22-january19) aquarius(january20-february18) If you understood my explanation clearly, could someone help? THANKS -Wayne --part1_191.1a28ed39.2c01bc11_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable I'm going to make a little program that tells the user= his or her sign-Pisces, libra, gemini, etc. This isn't a program I want peo= ple to take seriously but I'm making it to test what I've been learning. Thi= s is my first language and im not experienced at all.

Anyway, my first problem is the months. Determining what your sign is depend= s on the month but it's not like every sign starts on the first day of the m= onth. (march 1st-31st: you are a Pisces) the different signs start in the mi= ddle of the month. So you cant just take the input (month) and determine wha= t sign corresponds with it. I was thinking about making each month a certain= value and then asking the user the day of the month they were born. After t= hat, the program could add the day to the month value to make a new value. I= could assign a different sign to each range of numbers and if, say, the val= ue was in the range that 'Pisces' covers, they would be Pisces. Follow me so= far?

My next problem is not as complicated as the first one but I don't know what= should be made into a function to be called. Should I make the whole month=20= thing into a function or should I not define any functions? I'm sort of conf= used. Also, I wanted to know ... will this program probably need to use a li= st?

pisces(february19-march20)
aries(march21-april19)
taurus(april20-may20)
gemini(may21-june20)
cancer(june21-july22)
leo(july23-august22)
virgo(august23-september22)
libra(september23-october22)
scorpio(october23-november22)
sagiattius(november23-december21)
capricorn(december22-january19)
aquarius(january20-february18)

If you understood my explanation clearly, could someone help?
THANKS
-Wayne
--part1_191.1a28ed39.2c01bc11_boundary-- From am@fx.ro Sun May 25 08:05:02 2003 From: am@fx.ro (Adrian Maier) Date: Sun May 25 07:05:02 2003 Subject: [Tutor] I need ideas please In-Reply-To: <191.1a28ed39.2c01bc11@aol.com>; from GREENDAY31087@aol.com on Sun, May 25, 2003 at 02:26:25AM -0400 References: <191.1a28ed39.2c01bc11@aol.com> Message-ID: <20030525132642.A273@coto> GREENDAY31087@aol.com (GREENDAY31087@aol.com) a scris : > Also, I wanted to know ... will this program probably need to use a list? > > pisces(february19-march20) > aries(march21-april19) > taurus(april20-may20) > gemini(may21-june20) > cancer(june21-july22) > leo(july23-august22) > virgo(august23-september22) > libra(september23-october22) > scorpio(october23-november22) > sagiattius(november23-december21) > capricorn(december22-january19) > aquarius(january20-february18) I would divide the period of each sign in two distinct periods: Month Start End Sign ---- ----- ---- ----- FEB 19 29 PISCES MAR 1 20 PISCES MAR 21 31 ARIES APR 1 19 ARIES APR 20 30 TAURUS MAY 1 20 TAURUS ... and so on ... (this way, searching for the period corresponding to a particular date becomes easier: you don't have to worry about the fact that an astral sign spans over 2 months) You could store the above data in a list of lists: signs = [] signs.append(['FEB',19,29,'PISCES']) signs.append(['MAR', 1,20,'PISCES']) signs.append(['MAR',21,31,'ARIES']) signs.append(['APR', 1,19,'ARIES']) ... and so on ... Now, suppose that you are looking for the Sign of a person born on 15 MAY: month='MAY' day=15 You have to iterate over the list of lists and check whether the month equals 'MAY' and the day is between the corresponding limits. I won't go into further details because maybe you want to experiment yourself. If you have difficulties with implementing this idea in Python, feel free to ask for more help. I hope this helps. > If you understood my explanation clearly, could someone help? > THANKS > -Wayne -- Adrian Maier (am@fx.ro) From hemanexp@yahoo.com Sun May 25 11:30:43 2003 From: hemanexp@yahoo.com (Python-lover) Date: Sun May 25 10:30:43 2003 Subject: [Tutor] KeyPress event on canvas itms........................ Message-ID: <20030525041259.25216.qmail@web41902.mail.yahoo.com> --0-912497880-1053835979=:23604 Content-Type: text/plain; charset=us-ascii Hi, iam using python and Tkinter. Is it possible to bind a keyboard event, say "Up" arrow press, to a canvas item (like rectangle)? i have created a canvas and drawn a set of rectangles one above another.Now when i press "Up" arrow key first time i expect first rectangle to get focus and second one for next keypress and so on utill you reach the last rectangle. how can i do it? My sample code is given below:***************************************from Tkinter import * class App: def __init__(self,parent): self.myparent = parent self.canvas = Canvas(self.myparent,width=600,height=500) self.canvas.pack() x1 = 100 y1 = 100 x2 = 200 y2 = 200 i = 1 while i<4: self.canvas.create_rectangle(x1,y1,x2,y2,tag='RECT',fill='red') y1 = y2 y2 = y1 + 100 i = i+1 self.canvas.tag_bind('RECT','', self.get_rect_points) def get_rect_points(): #....................... # Here i want to get rectangle points #........................ root = Tk() myapp = App(root) root.mainloop() Thanx. --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-912497880-1053835979=:23604 Content-Type: text/html; charset=us-ascii
Hi,
  iam using python and Tkinter. Is it possible to bind a keyboard event, say "Up" arrow press, to a canvas item (like rectangle)? i have created a canvas and drawn a set of rectangles one above another.Now when i press "Up" arrow key first time i expect first rectangle to get focus and second one for  next keypress and so on utill you reach the last rectangle. how can i do it?
 
  My sample code is given below:
***************************************
from Tkinter import *
class App:
  def __init__(self,parent):
  self.myparent = parent
  self.canvas = Canvas(self.myparent,width=600,height=500)
  self.canvas.pack()
  x1 = 100
  y1 = 100
  x2 = 200
  y2 = 200
  i = 1
  while i<4:
          self.canvas.create_rectangle(x1,y1,x2,y2,tag='RECT',fill='red')
          y1 = y2
          y2 = y1 + 100
          i = i+1
  self.canvas.tag_bind('RECT','<Up>', self.get_rect_points)
 
 def get_rect_points():
   #.......................
  # Here i want to get rectangle points
  #........................
        
root = Tk()
myapp =  App(root)
root.mainloop()
 
 
Thanx.
 


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-912497880-1053835979=:23604-- From Vernon Miller" This is a multi-part message in MIME format. ------=_NextPart_000_0007_01C322B6.947391A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Thanks to everyone for the help, I guess that my problem was that I = tried to type and run the program into the interpreter instead of = opening a new window and typing it in and then saving it.=20 And the problem with " the elif" was indeed caused by improper = indentation. Thanks to each and everyone who sent a response. Vernon Miller vvernon@earthlink.net ------=_NextPart_000_0007_01C322B6.947391A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Thanks to everyone for the help, I = guess that my=20 problem was that I tried to type and run the program into the = interpreter=20 instead of opening a new window and typing it in and then saving it.=20
 
And the problem with " the elif" was = indeed caused=20 by improper indentation.
 
Thanks to each and everyone who sent a=20 response.
Vernon Miller
------=_NextPart_000_0007_01C322B6.947391A0-- From lennart_middel@hotmail.com Sun May 25 14:15:02 2003 From: lennart_middel@hotmail.com (Lennart Middel) Date: Sun May 25 13:15:02 2003 Subject: [Tutor] documentation Message-ID:
Hi, I had some trouble finding some documentation about how learn to run two things at a time in a programm. i thought it was called threads. Does anyone have an idea where to find this? You can send your reply to : Lennart_middel@hotmail.com.
 
A satishfied python user.


Tired of spam? Get advanced junk mail protection with MSN 8. From godoy@metalab.unc.edu Sun May 25 16:56:01 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Sun May 25 15:56:01 2003 Subject: [Doc-SIG] Re: [Tutor] Documentation concerns. In-Reply-To: <200305241803.h4OI31w27894@pcp02138704pcs.reston01.va.comcast.net> (Guido van Rossum's message of "Sat, 24 May 2003 14:03:01 -0400") References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> <200305241803.h4OI31w27894@pcp02138704pcs.reston01.va.comcast.net> Message-ID: Guido van Rossum writes: > But every project has its own constraints, and I can certainly > understand why some projects prefer to have the full user > documentation as docstrings. I expect that such projects will still > require some external documentation, e.g. a separate tutorial. I was one of the people who suggested the documentation within the module. Let me try, again, to explain :-) What I think is a good thing to have is a concise document available with the code so that if we have the code, we can just run something like 'pydoc module' and see how to use the referred module. It could (and IMO should) contain some example. The idea is not put all the documentation that exists inside the module. The idea is to put enough documentation to have a working prototype or testing code. It may be a taboo here, but I made the comparison with the first page of two modules: Perl's CGI and Python's CGI. I won't include the cited text again, it can be read from python-tutor's archives or from your own systems. The thing was that Perl's module included enough documentation to have a start. There are more documents on the subject available in books, on websites, etc. Python's module, on the other hand, gave me a description of the class and its methods. Some of them had a nice description, other didn't. I'm not saying that consulting Python's standard docs (in this case http://www.python.org/doc/current/lib/module-cgi.html) was too hard, but it surely could be simpler. I use 'man' or 'info' to do read system docs, C docs, Perl docs. It would be very interesting if something like 'pydoc' was integrated with the system docs as is 'perldoc' and it would be even better if the output of the documentation shown was enough to write a prototype (even for a newbie as myself). >> Is this still gospel? Any further thoughts around this? > > This is still gospel for the Python standard library. Let me make clear, here too, that this is not my intention to change the existing docs. My intention was to add new stuff to modules so that they can be easily understood with no additional material (specially when people can install python in a 'defective' way without its docs on embedded systems or production machines --- it saves 2.6 MiB here, what can be very significative in a 12 MiB flash card :-)). -- Godoy. From pythontutor@venix.com Sun May 25 17:03:01 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Sun May 25 16:03:01 2003 Subject: [Tutor] documentation References: Message-ID: <3ED12128.2070309@venix.com> You are looking for the threading module. There is an older thread module that is used by threading. threading provides a higher-level interface. module-threading.html gives a good description of what it does and how to use it. Lennart Middel wrote: > Hi, I had some trouble finding some documentation about how learn to run > two things at a time in a programm. i thought it was called threads. > Does anyone have an idea where to find this? You can send your reply to > : Lennart_middel@hotmail.com . > > A satishfied python user. > > ------------------------------------------------------------------------ > Tired of spam? Get advanced junk mail protection > with MSN > 8._______________________________________________ Tutor maillist - > Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From python@dhumketu.cjb.net Sun May 25 17:04:03 2003 From: python@dhumketu.cjb.net (Shantanu Mahajan) Date: Sun May 25 16:04:03 2003 Subject: [Tutor] using rdflib Message-ID: <20030525194553.GA1542@dhumketu.homeunix.net> Hi! Can anyone point me to the tutorial for using rdflib? Regards, Shantanu (newbie) -- Madness has no purpose. Or reason. But it may have a goal. From idiot1@netzero.net Sun May 25 17:14:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun May 25 16:14:02 2003 Subject: [Tutor] footer update to appear(?) in version 1.7.0 Message-ID: <3ED123DE.6090106@netzero.net> With assorted laws pending regarding insuring effective self removal from lists, I wanted to insure that TinyList ALWAYS offered a link to the management page for a list. Heretofore, this was in the intelligent footer, but one could have NO footer or a custom footer, and might forget to not offer such a link, or structure it incorrectly. so I am in 1.7.0 moving the link to a section of the footer which is ALWAYS inserted at the end of the message. This should insure compliance with any such bill, if it ever comes to a vote (hope hope hope). You can still not have any footers at all, OTHER THAN THIS LINK. Also, people offering random footers are usually rotating a stack of links for affiliate programs in the hope of making money. To help insure reading, the random footer is not placed BEFORE the static per list footer, so at least they skim past it when looking for instructions about the list. These changes are under testing on the working install of TL at http://www.tinylist.org/ and one can subscribe to testlist3 to play with it and see what I mean. http://www.tinylist.org/cgi-bin/TLwebform2.py?testlist3 Any comments on these proposed alterations? -- end Cheers! Kirk D Bailey http://www.howlermonkey.net/ http://www.tinylist.org/ http://www.listville.net/ http://www.sacredelectron.org/ "Thou art free"-ERIS From godoy@metalab.unc.edu Sun May 25 17:33:01 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Sun May 25 16:33:01 2003 Subject: [Doc-SIG] Re: [Tutor] Documentation concerns. (LONG POST) References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> <1053804978.1167.49.camel@lothlorien> Message-ID: Ian Bicking writes: > One issue I see with moving the documentation into the code, is that > we don't have any system that can represent the kind of > documentation from the standard library as docstrings. Typically > documentation created from docstrings is highly (overly) structured, > and does not allow items to be introduced in an order different from > the code, or presented with a different structure than the code, > plus there is no place for narrative that is not connected with a > function or class. On the other hand, putting an introductory text is possible. I'm sorry for the long post, but I wished giving a simple example. ,----[ example.py ]---------------------------------------------------- #!/usr/bin/python -tt # # Demonstration file for everybody at python-tutor and crossposted # people. # # $Author: $ (somebody@somewhere.overthe.net) # $Date: $ # # This is a demonstration on how introductory texts can be used to # give better documentation, specially for newbies, including # examples and an introductory text. # # All other docstrings can be maintained as they are. # # Note that I've included CVS keywords and an email for further # contact on improving this module (or its documentation). # # Usage: # # import DemoClass # checktemp = DemoClass(100, 'Celsius') # # # Here be functions to read the temperature from somewhere. # # Lets suppose it was 89 Celsius degrees (water boils at 100 # # Celsius degrees) # temperature = 89 # # if checktemp.IsBoiling(temperature): # print "Turn it off. It's boiling." # else: # print "Not ready yet." # # # The rest of this document describes DemoClass' implementation. You # should read it carefully to understand the above example and some # other details. # $Log: $ # Just an example of imported modules... import os import sys class DemoClass: """ This is a demonstration class. It does nothing useful. This demonstration class was written to show as an example of what I had in my mind about a more complete documentation inside of modules. My main concern is with having usage example and a more complete document than one with only the methods syntax and classes available with (or inherited by) the module. """ def __init__(self, var = 'default', othervar = 'other default'): """ Initializes DemoClass and set values for 'var' and 'othervar' DemoClass has 'default' as a default value for 'var', which describes something in the system. It could be the default temperature where the water boils. 'othervar', with a default value of 'other default' represent something else. It could be the unit used to measure the temperature (after all, we must know if we're working with Celsius or Fahrenheit). """ self.var = var self.othervar = othervar def IsBoiling(self, temp_read): """ Checks if the water is boiling. Returns None if it isn't. IsBoiling receives the read temperature. If it is the same temperature that is available from self.var, it returns '1', otherwise it returns None. """ if (temp_read == self.var): return 1 else: return None def main(): """ Main function for the program. Calls all other functions. """ checktemp = DemoClass(100, 'Celsius') # Here be functions to read the temperature from somewhere. # Lets suppose it was 89 Celsius degrees (water boils at 100 # Celsius degrees) temperature = 89 if checktemp.IsBoiling(temperature): print "Turn it off. It's boiling." else: print "Not ready yet." if __name__ == '__main__': main() ---------------------------------------------------------------------- The resulting output is: ,----[ pydoc ./example.py ]------------------------------------------- Python Library Documentation: module example NAME example FILE /home/godoy/tempo/example.py DESCRIPTION # Demonstration file for everybody at python-tutor and crossposted # people. # # $Author: $ (somebody@somewhere.overthe.net) # $Date: $ # # This is a demonstration on how introductory texts can be used to # give better documentation, specially for newbies, including # examples and an introductory text. # # All other docstrings can be maintained as they are. # # Note that I've included CVS keywords and an email for further # contact on improving this module (or its documentation). # # Usage: # # import DemoClass # checktemp = DemoClass(100, 'Celsius') # # # Here be functions to read the temperature from somewhere. # # Lets suppose it was 89 Celsius degrees (water boils at 100 # # Celsius degrees) # temperature = 89 # # if checktemp.IsBoiling(temperature): # print "Turn it off. It's boiling." # else: # print "Not ready yet." # # # The rest of this document describes DemoClass' implementation. You # should read it carefully to understand the above example and some # other details. CLASSES DemoClass class DemoClass | This is a demonstration class. It does nothing useful. | | This demonstration class was written to show as an example of what | I had in my mind about a more complete documentation inside of | modules. | | My main concern is with having usage example and a more complete | document than one with only the methods syntax and classes | available with (or inherited by) the module. | | Methods defined here: | | IsBoiling(self, temp_read) | Checks if the water is boiling. Returns None if it isn't. | | IsBoiling receives the read temperature. If it is the same | temperature that is available from self.var, it returns '1', | otherwise it returns None. | | __init__(self, var='default', othervar='other default') | Initializes DemoClass and set values for 'var' and 'othervar' | | DemoClass has 'default' as a default value for 'var', which | describes something in the system. It could be the default | temperature where the water boils. | | 'othervar', with a default value of 'other default' represent | something else. It could be the unit used to measure the | temperature (after all, we must know if we're working with | Celsius or Fahrenheit). | | ---------------------------------------------------------------------- | Data and non-method functions defined here: | | __doc__ = '\n This is a demonstration class. It does noth...availab... | | __module__ = 'example' FUNCTIONS main() Main function for the program. Calls all other functions. DATA __file__ = './example.pyc' __name__ = 'example' ---------------------------------------------------------------------- It seems to be too much documentation for such a small module, but it helps a lot with big ones. There are some modules that doesn't even generate an output when we do 'pydoc' on it (i.e., it has no docstrings at all), making it even harder to use it (you have to go after its documentation on the web). Of course, these aren't (up to now) included with Python in its standard modules. TIA, -- Godoy. From godoy@metalab.unc.edu Sun May 25 18:00:02 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Sun May 25 17:00:02 2003 Subject: [Tutor] Documentation concerns. In-Reply-To: <5.2.1.1.0.20030524152319.01eefed0@www.thinkware.se> ( =?iso-8859-1?q?Magnus_Lyck=E5's_message_of?= "Sat, 24 May 2003 16:29:06 +0200") References: <5.2.1.1.0.20030524014355.01f145d8@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524014355.01f145d8@www.thinkware.se> <5.2.1.1.0.20030524152319.01eefed0@www.thinkware.se> Message-ID: Magnus Lyck=E5 writes: > At 09:04 2003-05-24 -0300, Jorge Godoy wrote: >>I agree with you on how good it is to have books to do serious >>development. We in the southe hemisphere, > > Oh, I though UNC was in North Carolina. :) I'm sorry. I have some projects there (I'm on the LDP staff) and their email system is VERY reliable. I use it, saving IEEE's address for engineering related stuff and my company's address for commercial or commercially interesting communication. :-) > So you have to trade time for money... $70 seems very much though. > Python is a Nutshell, which I haven't read, but have heard very good > things about, is $21.50 + shipping at bookpool. Good to know that.=20 > If you buy a number of books, shipping costs will not be such a big > part of the cost. Try to get together with some other people so that > you can buy ten books or so at the same time, and you will get a > much lower price than through most other channels. I want to do that, but then I have to find those people :-) > That makes your complaints about lacking information a bit > surprising. I'm not arguing about the lack of existing documentation. I'm arguing about the lack of existing documentation *within* the module.=20 I've sent an example on the message you crossposted. I hope it makes my point clearer. If not, I can keep on trying to explain until you people say that I should stop trying it. :-) > There aren't any ads in the python documents either... As both Alan > and I pointed out, there are several disadvantages with this. For > documentation like the wxPython docs that mainly consist of showing > the method calls, it would probably be better to use something > generated from code, particualrly considering the problem that > project has in keeping the docs updated. Also, consider all the > questions Robin Dunn has to answer every day, it's clear that > wxPython need documentaion which is on a completely differnt level > than to describe the details on what parameters to provide for each > method call etc. > > As I've said, the source code structure might not match the > best structure for describing the code. It shouldn't describe everything but it should be enough to get a working example or a better undertanding on how to use the available stuff.=20 It shouldn't be a tutorial. > I think we should make certain that we always get docs with our > code, but I can't see that the exact organisation of docs and source > code is an important issue. This lead us back to the new point of view with new people, I think.=20 > It seems that the current approach is still to have the bulk of docs > in separate files and just small hints in the soure code. If it's possible to make something that read the documentation from this other place and make it standard, it would be enough. Actually, it would make things even better since people would be allowed to exclude the docs if they want (the embedded case I talked about) but they can't talk about the lack of docs if they do that.=20 > I'm sure you can write a nice utility that will get the right > information quickly without too many key-presses. Not for each and every module... Unfortunately. I'm looking for a more generic solution. I'm a lazy guy and this is why I write programs: they can do my job while I keep reading emails :-) >>I be you will :-) > > Freudian slip? ;) Heh... Got me on my own joke. > I think it would be great to have some way of integrating the docs > for site-packages in some common structure. Both for indexing and > for searching. Me too. Maybe we can come up with some kind of proposal for that.=20 > But reStructuredText is not XML. It's less verbose and more readable > than Latex in my opinion. Have you used it? I've just used docstrings... For more verbose docs I usually use LaTeX myself or some kind of XML (I'm used to use DocBook).=20 > Startup delays are annoying. If you run several hundred small tests > and every test has a startup cost, you won't want to run the tests > as often as you should. On the other hand, with better docs I should develop faster and with less mistakes on my understanding of the docs.=20 > No we should not. The introspection facilities and dynamic nature of > Python is a big advantage. Stripping the code will give us much less > to introspect. I can't, yet, comment on that. I take your word on it. >> > In general I think the Python developers are open to improvements, >> > but they are not able to put a lot of time into this. They do depend >> > on help from the community. >> >>:-) >>And then they should offer the community more resources. > > I'm not sure what you mean. What is it that you need and don't have? Means to reach them and propose changes.=20 But, with all this discussion, I think I had that too. So this problem is solved. > Python is obviously more of a collective effort, and it > has a fairly clear structure and reasonable information > about how to contribute. See for instance > http://www.python.org/dev/ > >>:-) You're not a newbie, this is why. For website and articles I'd >>take a look at >>HTMLgen(http://starship.python.net/crew/friedrich/HTMLgen/html/main.htm= l). > > Really? It's not been in development for years. I used it to build a Yep. I saw that too... But it seemed to be the simplest thing out there. I was anxious to have something that solved this fast. I am studying which module I'm using to replace TT2... (And it accepted what I had out of the box.) > web site a number of years ago, and I ended up building something > reStructuredText-like on top of it. reStructuredText is a much > easier tool, and you don't need to worry about programming to get > decent looking documents in both XHTML and PDF from the same simple > source. I'll look at it. If I can plug my existing documents only with minor changes it will be very good. I'm trying to see what tasks I can switch from Perl to Python and which of these are easier to me and my team. --=20 Godoy. From magnus@thinkware.se Sun May 25 18:13:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun May 25 17:13:02 2003 Subject: [Tutor] documentation In-Reply-To: Message-ID: <5.2.1.1.0.20030525222313.01e799e0@www.thinkware.se> At 19:13 2003-05-25 +0200, Lennart Middel wrote: >Hi, I had some trouble finding some documentation about how learn to run >two things at a time in a programm. i thought it was called threads. Does >anyone have an idea where to find this? You can send your reply to : >Lennart_middel@hotmail.com. > >A satishfied python user. Look here for a start: http://starship.python.net/crew/aahz/OSCON2001/index.html It's naturally described in the library reference guide as well. It's far from always that threads are the ideal way to do things though. I think many pythonistas feel that threads are overused in the Microsoft environment. Threads mean that you have several things going on at once in the same memory areas, without the kind of protection you get when you run your tasks in separate processes. It makes it both easier to cause bugs, and to find the bugs when they happen. Other options are to use several processes, or to serialize things as far as possible, and try to do things sequentially instead. Feel free to tell us what you are really trying to achieve. After all, "run two things at a time" is hardly a goal in its own right, but rather something you perceive that you need to do to reach your real goal. Maybe some other approach is much smarter? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From pijus@virketis.com Sun May 25 20:10:01 2003 From: pijus@virketis.com (Pijus Virketis) Date: Sun May 25 19:10:01 2003 Subject: [Tutor] python cgi debugging 101 Message-ID: <64546C72-8F1F-11D7-9FC6-000A9575F08A@virketis.com> Dear all, I am trying to install pyblosxom (roughingit.subtlehints.net/pyblosxom), an all-Python blogging engine. So far, I am not having much luck. ;) But fear not, I am not asking for any program-specific advice. Rather, I would appreciate a few basic Python cgi debugging tips and tricks (or a link to a tutorial on the subject). Basically, my Apache error log only has this (to me cryptic) line: [Sun May 25 15:39:03 2003] [error] [client xx.xxx.xxx.xxx] Premature end of script headers: /usr/local/www/virtual/xx.xxx.xxx.xxx/html//cgi-bin/pyblosxom.cgi I would at least like to figure out at which point the program fails, or if it even starts up. And anything else informative that can be gleaned ... N.B.: A Python test.cgi does successfully execute. I have set the permissions on the file correctly (I think). I am trying to execute it on Python 2.1.1, for which pyblosxom is cleared. Thank you! Pijus From shalehperry@attbi.com Sun May 25 20:39:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun May 25 19:39:02 2003 Subject: [Tutor] python cgi debugging 101 In-Reply-To: <64546C72-8F1F-11D7-9FC6-000A9575F08A@virketis.com> References: <64546C72-8F1F-11D7-9FC6-000A9575F08A@virketis.com> Message-ID: <200305251637.42972.shalehperry@attbi.com> On Sunday 25 May 2003 19:11, Pijus Virketis wrote: > Dear all, > > I am trying to install pyblosxom > (roughingit.subtlehints.net/pyblosxom), an all-Python blogging engine. > So far, I am not having much luck. ;) But fear not, I am not asking for > any program-specific advice. Rather, I would appreciate a few basic > Python cgi debugging tips and tricks (or a link to a tutorial on the > subject). Basically, my Apache error log only has this (to me cryptic) > line: > How about some generic CGI wisdom? A CGI is simply a script which reads from standard input and writes to standard output. It may also get some variables from the environment. So a simple way to start debugging is to simply run the CGI by hand from the command line. A lot of time you end up with things like: * wrong location for the interpreter. it uses /usr/local and yours is in /usr for instance * missing file or directory. Maybe it wants logs in /var/log/myscript or a helper program in /usr/share/myscript/helper. * permissions. Maybe it needs something from the last item and even though it exists this CGI does not have the rights to look/use/edit it. * an actual code bug This applies to any CGI in any language. From R. Alan Monroe" Subject says it all... example class dummy: stuff = 0 def task(): pass >>> dir(dummy) ['__doc__', '__module__', 'stuff', 'task'] How do I find out, when working with a new class I'm not familiar with, how many attributes it has, and how many methods? dir() is a bit too generic because both look identical in the list... Alan From op73418@mail.telepac.pt Sun May 25 21:59:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun May 25 20:59:01 2003 Subject: [Tutor] dir() question: how do you know which are attributes and which are methods? References: <721216893810.20030525203228@columbus.rr.com> Message-ID: <001b01c32322$017dd5b0$07160dd5@violante> From: "R. Alan Monroe" > Subject says it all... > > example > > > class dummy: > stuff = 0 > def task(): > pass > > >>> dir(dummy) > ['__doc__', '__module__', 'stuff', 'task'] > > How do I find out, when working with a new class I'm not familiar > with, how many attributes it has, and how many methods? dir() is a bit > too generic because both look identical in the list... > What exactly do you want to know? If you want to know which are data attributes and which are callables you can use the builtin callable function. >>> print callable.__doc__ callable(object) -> Boolean Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances with a __call__() method. >>> For other type of info, there are various answers. The most basic one starts by reading the docstring of dir: >>> print dir.__doc__ dir([object]) -> list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: [rest snipped] Since it returns a list of strings you can just iterate over it. What questions do you want to ask? A simple list comprehension can give you a list of special names that dummy recognizes [attrib for attrib in dir(dummy) if attrib.startswith('__') and attrib.endswith('__')] How many attributes? len(dir(dummy)) Callable attributes? [attrib for attrib in dir(dummy) if callable(getattr(dummy, attrib))] etc. > Alan > HTH, with my best regards, G. Rodrigues From pythontutor@venix.com Sun May 25 22:10:02 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Sun May 25 21:10:02 2003 Subject: [Tutor] python cgi debugging 101 References: <64546C72-8F1F-11D7-9FC6-000A9575F08A@virketis.com> Message-ID: <3ED1691D.6060901@venix.com> import cgi #import cgitb; cgitb.enable() The traceback is VERY helpfull once you get past the header error. If you are using something like HTMLgen it will produce a content header if you tell it to doc = HTMLgen.SimpleDocument(cgi=1) otherwise your first line of output needs to be: html_header = "Content-Type: text/html\n\n" print html_header (assumes you are sending html back through apache) #! /usr/local/bin/python cgi is running under the httpd server's environment. It's best to point directly to python (not /usr/bin/env python) Finally you can run the cgi script directly specifying HTML Form input on the command line: ./pyblosxom.cgi field1=value&field2=morevalues& (watch out for url encoding issues) My guess is that you are simply missing the Content-Type header. Pijus Virketis wrote: > Dear all, > > I am trying to install pyblosxom (roughingit.subtlehints.net/pyblosxom), > an all-Python blogging engine. So far, I am not having much luck. ;) But > fear not, I am not asking for any program-specific advice. Rather, I > would appreciate a few basic Python cgi debugging tips and tricks (or a > link to a tutorial on the subject). Basically, my Apache error log only > has this (to me cryptic) line: > > [Sun May 25 15:39:03 2003] [error] [client xx.xxx.xxx.xxx] > Premature end of script headers: > /usr/local/www/virtual/xx.xxx.xxx.xxx/html//cgi-bin/pyblosxom.cgi > > I would at least like to figure out at which point the program fails, or > if it even starts up. And anything else informative that can be gleaned ... > > N.B.: A Python test.cgi does successfully execute. I have set the > permissions on the file correctly (I think). I am trying to execute it > on Python 2.1.1, for which pyblosxom is cleared. > > Thank you! > > Pijus > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From jciancio@indiana.edu Sun May 25 22:25:02 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Sun May 25 21:25:02 2003 Subject: [Tutor] new and freezing problem Message-ID: <200305260124.UAA14482@indiana.edu> Hi! I'm new to this list. I have no programming experience, but I'm trying to teach myself some with python. I've written a short program that keeps making my computer freeze. Actually it's not the whole computer, just python. This is the program: def freqChange(p, N, w11, w12, w22): q=1-p pnew=(N*(p**2*w11+q*p*w12))/(N*(p**2*w11+2*p*q*w12+q**2*w22)) while 0<=pnew<=1.0: p=pnew q=1-pnew print pnew any ideas what might be wrong?? thanks in advance Jen From kalle@lysator.liu.se Sun May 25 22:37:02 2003 From: kalle@lysator.liu.se (Kalle Svensson) Date: Sun May 25 21:37:02 2003 Subject: [Tutor] new and freezing problem In-Reply-To: <200305260124.UAA14482@indiana.edu> References: <200305260124.UAA14482@indiana.edu> Message-ID: <20030526013607.GW513@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Jennifer Cianciolo] > Hi! > > I'm new to this list. I have no programming experience, but I'm > trying to teach myself some with python. Welcome! Good choise, programming can be a lot of fun! > I've written a short program that keeps making my computer freeze. > Actually it's not the whole computer, just python. This is the > program: When this happens, there's probably an infinite loop (a loop where the loop condition is always true) somewhere. > def freqChange(p, N, w11, w12, w22): > q=1-p > pnew=(N*(p**2*w11+q*p*w12))/(N*(p**2*w11+2*p*q*w12+q**2*w22)) > while 0<=pnew<=1.0: > p=pnew > q=1-pnew The loop condition here is 0<=pnew<=1.0, which depends on the value of pnew. The problem here is that you don't assign a new, changed value to pnew in the loop body. pnew keeps it's initial value through each repetition, and if the condition was true in the beginning, it will be forever. Try running the function with values that result in a pnew smaller than 0 or larger than 1.0. It should return immediately. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE+0W+BdNeA1787sd0RAtYxAJ9HpOoanUzfDLH1RIcE6Dxiv4qkNQCffmJU F0TvSytd/YR7qS1uJWi+fqU= =3knu -----END PGP SIGNATURE----- From mico@intermatik.co.id Mon May 26 02:04:02 2003 From: mico@intermatik.co.id (Mico Siahaan) Date: Mon May 26 01:04:02 2003 Subject: [Tutor] Making python extension in Windows Message-ID: <3ED19FB8.000003.03852@siahaan> Dear All, =0D =0D can anybody give me a hint aor HOWTO to make python extension in Windows?= I=0D know there is a chapter about it in Python Programming on Win 32, but I d= on=0D t have Visual C++. The only C++ compiler I have is Dev C++. I did this: =0D 1. Add C:\Python21\include in Compiler Options/C Include Files =0D 2. Add C:\Python21\libs in Compiler Options/Libraries directory =0D 3. Open a new empty project =0D 4. Add spammodule.c (the example in Python Programming) into project =0D 5. In project options I checked 'Create a DLL' in project options =0D 6. Compile the project =0D =0D I got this warning from linker: =0D c:\documents and settings\mico\my documents\spammodule.o(=0D text+0x1d):spammodule.c: undefined reference to `_imp__PyArg_ParseTuple' = =0D c:\documents and settings\mico\my documents\spammodule.o(=0D text+0x52):spammodule.c: undefined reference to `_imp__Py_BuildValue' =0D c:\documents and settings\mico\my documents\spammodule.o(=0D text+0xa3):spammodule.c: undefined reference to `_imp__Py_InitModule4' =0D c:\documents and settings\mico\my documents\spammodule.o(=0D text+0xba):spammodule.c: undefined reference to `_imp__PyModule_GetDict' = =0D c:\documents and settings\mico\my documents\spammodule.o(=0D text+0xd6):spammodule.c: undefined reference to `_imp__PyErr_NewException= ' =0D c:\documents and settings\mico\my documents\spammodule.o(=0D text+0xfa):spammodule.c: undefined reference to `_imp__PyDict_SetItemStri= ng' =0D Warning: no export definition file provided =0D dllwrap will create one, but may not be what you want =0D C:\PROGRA~1\DEVC__~1\Bin\dllwrap: gcc exited with status 1 =0D =0D Then there is spammodule.o in my directory. I copied it to python lib=0D directory, renamed it to spam.pyd, then tried to import in, but I failed.= =0D =0D Can anybody tell me how to make python extension in WIndows using Dev C++= ? =0D =0D Thanks. And sorry for this long email. :) =0D =0D -mico-=20 From lennart_middel@hotmail.com Mon May 26 07:47:01 2003 From: lennart_middel@hotmail.com (Lennart Middel) Date: Mon May 26 06:47:01 2003 Subject: [Tutor] livewires--> working with the mouse Message-ID:
Hi,
I had a question about working with the mouse with python. I use the livewire module and in a sheet i downloaded they use a command: mouse_begin()
only when i do this, python gives an error. It does not reconnice the command. How come? and what is the right command to start using the mouse with the use of livewires?
 


Tired of spam? Get advanced junk mail protection with MSN 8. From Janssen@rz.uni-frankfurt.de Mon May 26 08:01:45 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Mon May 26 07:01:45 2003 Subject: [Tutor] new and freezing problem In-Reply-To: <200305260124.UAA14482@indiana.edu> Message-ID: On Sun, 25 May 2003, Jennifer Cianciolo wrote: > Hi! > > I'm new to this list. I have no programming experience, but I'm > trying to teach myself some with python. > > I've written a short program that keeps making my computer freeze. > Actually it's not the whole computer, just python. This is the > program: > > def freqChange(p, N, w11, w12, w22): > q=1-p > pnew=(N*(p**2*w11+q*p*w12))/(N*(p**2*w11+2*p*q*w12+q**2*w22)) > while 0<=pnew<=1.0: > p=pnew > q=1-pnew > print pnew adding a "print" statement is your friend: def freqChange(p, N, w11, w12, w22): q=1-p pnew=(N*(p**2*w11+q*p*w12))/(N*(p**2*w11+2*p*q*w12+q**2*w22)) while 0<=pnew<=1.0: print pnew # <-- here p=pnew q=1-pnew print pnew freqChange(1, 1, 1, 1, 1) ---> prints lost of "1" ----> pnew never gets change inside the "while" loop. Even putting pnew's formular inside the loop: def freqChange(p, N, w11, w12, w22): q=1-p pnew = 0.5 # enter the loop at least one time while 0<=pnew<=1.0: pnew=(N*(p**2*w11+q*p*w12))/(N*(p**2*w11+2*p*q*w12+q**2*w22)) print pnew p=pnew q=1-pnew print pnew dosn't change this behaviour (but: my startup values 1, 1, 1, 1, 1 possibly arn't sensibly. It's a pity that you havn't provide some real cases). But it's left to you to use better startup values or debug the formular, so that it change pnew's value to something outside of [0.0-1.0] (and break the while loop condition). The print statement is all you need as debug-information. Michael > > > any ideas what might be wrong?? > > thanks in advance > Jen > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From magnus@thinkware.se Mon May 26 10:12:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 26 09:12:02 2003 Subject: [Tutor] Making python extension in Windows In-Reply-To: <3ED19FB8.000003.03852@siahaan> Message-ID: <5.2.1.1.0.20030526142529.00b61628@www.thinkware.se> At 12:01 2003-05-26 +0700, Mico Siahaan wrote: >can anybody give me a hint aor HOWTO to make python extension in Windows? I >know there is a chapter about it in Python Programming on Win 32, but I don't >have Visual C++. The only C++ compiler I have is Dev C++. You can't compile Python extensions with Dev C++ that will work with the normal Windows binary version of Python. In contrast to for instance Java, there is no standard for the binary files generated by C or C++ compilers. Microsofts compiled files are not compatible with files compiled with the GNU Compiler Collection, on which Dev C++ is based. They can't be linked together. At least this is my understanding. Please someone correct me if I'm wrong. Cygwin is free and includes Python. It's based on the same compiler as Dev C++, i.e. GCC, so I think they will be able to play with each other. If nothing else, extension modules built with the compiler included i Cygwin will work as they should with Cygwin's Python. But the consequence of using another compiler is that you won't be able to use other extension modules built with MS Visual C++, such as the win32all extension ot wxPython. I think the only really good way of using Python together with other programming languages such as C and C++ without using any commercial software is to run on free operating systems such as Linux or FreeBSD. If you want to work on Windows, I'm afraid you are stuck with using Microsoft's tools. Not only their OS... If you are a computer company, you might well be able to get some partner pack from Microsoft to a reasonable price though. I think the current pack here in Sweden, called "Microsoft Action Pack" doesn't include Visual Studio though. I bought a kit containing a license of Visual Studio 6.0, five licenses of Office 2000 and the client OS's and a whole bunch of other software that I don't use for maybe 400-500 USD a few years ago. I hope that will last until Linux is really ready for the desktop! :) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Mon May 26 10:24:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 26 09:24:02 2003 Subject: [Tutor] livewires--> working with the mouse In-Reply-To: Message-ID: <5.2.1.1.0.20030526151739.01ff1e58@www.thinkware.se> At 12:45 2003-05-26 +0200, Lennart Middel wrote: >Hi, >I had a question about working with the mouse with python. I use the >livewire module and in a sheet i downloaded they use a command: mouse_begin() >only when i do this, python gives an error. It does not reconnice the >command. How come? and what is the right command to start using the mouse >with the use of livewires? You have to be much more specific about your problems if we are going to be able to help you. Forget all your literature teacher ever told you about describing things in your own words! ;) It's much easier to respond to a clear Python traceback message then to "python gives an error. It does not reconnice the command". Show the piece of code that caused the error and show us what the error looked like. Exactly. I don't expect that anyone here has used the livewires stuff. I dodn't even know there was more than text there. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Mon May 26 13:24:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 26 12:24:02 2003 Subject: [Tutor] dir() question: how do you know which are attributes and which are methods? In-Reply-To: <721216893810.20030525203228@columbus.rr.com> Message-ID: <5.2.1.1.0.20030526141840.01f73988@www.thinkware.se> At 20:32 2003-05-25 -0400, R. Alan Monroe wrote: >How do I find out, when working with a new class I'm not familiar >with, how many attributes it has, and how many methods? dir() is a bit >too generic because both look identical in the list... Why don't you use help() instead of dir()? >>> class Dummy: ... stuff = 0 ... def task(self): ... pass ... You did: >>> dir(Dummy) ['__doc__', '__module__', 'stuff', 'task'] You could do... >>> for name in dir(Dummy): ... print name, eval('type(Dummy.%s)' % name) ... __doc__ __module__ stuff task ...to get some more help, but most of the time you are better off doing: >>> help(Dummy) Help on class Dummy in module __main__: class Dummy | Methods defined here: | | task(self) | | ---------------------------------------------------------------------- | Data and non-method functions defined here: | | __doc__ = None | | __module__ = '__main__' | | stuff = 0 >>> -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From jim_938@hotmail.com Mon May 26 14:36:46 2003 From: jim_938@hotmail.com (Jimmy verma) Date: Mon May 26 13:36:46 2003 Subject: [Tutor] c to python Message-ID: Hi ! I have a structure in c like this struct ab { int a; int b; int *c; struct d *d; } AB; And i am using it in my program like void XYZ(int a , AB *b) How can this kind of structure be translated in python code? Your suggestions are welcomed. Regards _________________________________________________________________ Race along with NK. The fastest Indian http://server1.msn.co.in/sp03/tataracing/index.asp Feel the thrill! From magnus@thinkware.se Mon May 26 15:58:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 26 14:58:02 2003 Subject: [Tutor] c to python In-Reply-To: Message-ID: <5.2.1.1.0.20030526195603.01fd1098@www.thinkware.se> At 23:04 2003-05-26 +0530, Jimmy verma wrote: >I have a structure in c like this > >struct ab >{ > int a; > int b; > int *c; > struct d *d; >} AB; > > >And i am using it in my program like > >void XYZ(int a , AB *b) > > >How can this kind of structure be translated in python code? It's common to use a tuple in situations where a struct would be used in C. B1 =3D (a, b, c, d) XYZ(A, B1) The main difference is that you the access stuff in the data structure by position, not by name. def XYZ(A, B): a, b, c, d =3D B or def XYZ(A, B): a =3D B[0] b =3D B[1] c =3D B[2] d =3D B[3] If you want to be able to change your "struct" after you create it, but feel ok with positional access instead of access by name, you use a list instead of a tuple. B2 =3D [0, 0, [], None] B2[0] =3D 4 B2[1] =3D 2 B2[2].extend([1,2,3,4,5]) B2[3] =3D B1 A simple way to get access by name instead is to use a dctionary instead. B3 =3D {'a': 0, 'b': 0, 'c': [], 'd': None} Fourth, and most similar to C/C++ is to use a class. After all, a struct in C++ is simply a class where attributes are public by default. (As in Python.) Due to the dynamic nature of Python, a class that is just for data storage can be made extremely simple. class N: pass B4 =3D N() B4.a =3D 42 B4.b =3D 6 * 8 B4.c =3D [1,2,3] B4.d =3D B3 If you want a little bit more convenience, you might do something like: class AB: def __init__(self, a=3D0, b=3D0, c=3D[], d=3DNone): self.a =3D a self.b =3D b self.c =3D c self.d =3D d None of the solutions above have any kind of typechecking whatsoever. This is fairly typical in Python programs. Don't make any restrictions that you don't really need. The main reason is that a variable in Python is just a name for an object--any object. In C, a variable is a named location in memory, and it only fits particular data types. Very often, a piece of code can be written so that it works equally well for many different kinds of data, and this is a great strength. For instance: >>> def topTen(seq): ... l =3D list(seq) ... l.sort() ... return l[:10] ... >>> topTen('asldkfjeorij=C3=B6lkf=C3=B6alksj=C3=B6alkf') ['a', 'a', 'a', 'd', 'e', 'f', 'f', 'f', 'i', 'j'] >>> topTen([1,2,4,32,5,8,8,5,3,3,5,6,7,56,4,3,8]) [1, 2, 3, 3, 3, 4, 4, 5, 5, 5] >>> topTen([4,3,8]) [3, 4, 8] >>> topTen((1,2,5,87,9,5,4,3,4.23,3.14159)) [1, 2, 3, 3.1415899999999999, 4, 4.2300000000000004, 5, 5, 9, 87] If you do want type checking, you can add that. There are no such things as int* or structs in Python though, so let's imagine that a and b should be integers, c should be a list and d should be an instance of the same class as the one we implement. As you see below, the type checking in Python is much more verbose than in C, but on the other hand, the mechanisms involved are much, much more powerful. >>> class AB(object): ... def __init__(self, a=3D0, b=3D0, c=3D[], d=3DNone): ... self.a =3D a ... self.b =3D b ... self.c =3D c ... self.d =3D d ... def get_a(self): ... return self.__a ... def set_a(self, a): ... assert isinstance(a, int) ... self.__a =3D a ... a =3D property(get_a, set_a, None, '') ... def get_b(self): ... return self.__b ... def set_b(self, b): ... assert isinstance(b, int) ... self.__b =3D b ... b =3D property(get_b, set_b, None, '') ... def get_c(self): ... return self.__c ... def set_c(self, c): ... assert isinstance(c, list) ... self.__c =3D c ... c =3D property(get_c, set_c, None, '') ... def get_d(self): ... return self.__d ... def set_d(self, d): ... assert d is None or isinstance(d, self.__class__) ... self.__d =3D d ... d =3D property(get_d, set_d, None, '') ... >>> ab =3D AB() >>> ab.a 0 >>> ab.b 0 >>> ab.c [] >>> ab.d >>> print ab.d None >>> ab2 =3D AB(42, 1984, [1,2,3],ab) >>> ab2.d.d >>> print ab2.d.d None >>> print ab2.d <__main__.AB object at 0x0127AF40> >>> print ab2.a, ab2.b, ab2.c 42 1984 [1, 2, 3] >>> ab3=3DAB('1', 2, [1,1,], ab2) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __init__ File "", line 10, in set_a AssertionError >>> -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program=20 From jciancio@indiana.edu Mon May 26 18:22:02 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Mon May 26 17:22:02 2003 Subject: [Tutor] new and freezing problem In-Reply-To: Message-ID: <200305262121.QAA11440@iupui.edu> this print statement took care of it I think - thanks! it stopped the freezing and made it do what I wanted it to do. This was just a simple genetics problem. p and q are alternative forms of the same gene (like blue eyes and brown eyes); p and q add to 1. Then the 'W's weight these gene forms according to how well they perform in their environment; 1 is great, 0 is terrible. So 'pnew' (usually written as p subscript(t+1)) is the frequency of the gene form (called an allele) in the next generation according to how well it did in its environment and it's initial frequency. It's nothing earth shattering - I just wanted to see if I could make it go in python. I'm sure I'll have more questions soon thanks again ------------------- > On Sun, 25 May 2003, Jennifer Cianciolo wrote: > > > Hi! > > > > I'm new to this list. I have no programming experience, but I'm > > trying to teach myself some with python. > > > > I've written a short program that keeps making my computer freeze. > > Actually it's not the whole computer, just python. This is the > > program: > > > > def freqChange(p, N, w11, w12, w22): > > q=1-p > > pnew=(N*(p**2*w11+q*p*w12))/(N*(p**2*w11+2*p*q*w12+q**2*w22)) > > while 0<=pnew<=1.0: > > p=pnew > > q=1-pnew > > print pnew > > adding a "print" statement is your friend: > > def freqChange(p, N, w11, w12, w22): > q=1-p > pnew=(N*(p**2*w11+q*p*w12))/(N*(p**2*w11+2*p*q*w12+q**2*w22)) > while 0<=pnew<=1.0: > print pnew # <-- here > p=pnew > q=1-pnew > print pnew > > freqChange(1, 1, 1, 1, 1) > > ---> prints lost of "1" ----> pnew never gets change inside the "while" > loop. > > Even putting pnew's formular inside the loop: > > def freqChange(p, N, w11, w12, w22): > q=1-p > pnew = 0.5 # enter the loop at least one time > while 0<=pnew<=1.0: > pnew=(N*(p**2*w11+q*p*w12))/(N*(p**2*w11+2*p*q*w12+q**2*w22)) > print pnew > p=pnew > q=1-pnew > print pnew > > dosn't change this behaviour (but: my startup values 1, 1, 1, 1, 1 > possibly arn't sensibly. It's a pity that you havn't provide some real > cases). But it's left to you to use better startup values or debug the > formular, so that it change pnew's value to something outside of [0.0-1.0] > (and break the while loop condition). > > The print statement is all you need as debug-information. > > Michael > > > > > > > any ideas what might be wrong?? > > > > thanks in advance > > Jen > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From lonetwin@yahoo.com Tue May 27 05:03:04 2003 From: lonetwin@yahoo.com (lonetwin) Date: Tue May 27 04:03:04 2003 Subject: [Tutor] Struggling with os.exec In-Reply-To: <20030523181423.6014.20@wonderland.1053679285.fake> References: <20030523160007.10097.34435.Mailman@mail.python.org> <20030523181423.6014.20@wonderland.1053679285.fake> Message-ID: <200305271350.26489.lonetwin@yahoo.com> Hi there, On Friday 23 May 2003 09:44 pm, Charlie Clark wrote: > Sure, I'm trying to write the following script in Python: > > function goThere() { > echo $1 > if [ -d "$1" ] ; then > cd "$1" > return $? > fi > return 1 > } def goThere(dir_name): print 'Changing to %s from %s' % (dir_name, os.getcwd()) if os.path.isdir(dir_name): return os.chdir(dir_name) return 1 > function countArgs() { > return $# > } def countArgs(some_args): return len(some_args) > function j() { > choices=$(query "name=\"$1\"" | tr '\n' ' ') > eval "countArgs $choices" > case $? in > 0) return 1;; > 1) eval "goThere $choices" ; return $?;; > *) PS3='Choice: ' > eval "\ > select curChoice in ${choices};\ > do\ > goThere \"\$curChoice\";\ > if [ \$? -eq 0 ];\ > then\ > break;\ > fi;\ > done" > esac > } Now here I don't really understand what 'query' is in the line: > choices=$(query "name=\"$1\"" | tr '\n' ' ') but I'm assuming that $choices would be a string that has names of directories within a directory hierarchary. eg: if the dir. structure is top |- first | |- second | |- third choices would be ['first', 'second', 'third' ] so the above function j becomes: def j(): choices = ['first', 'second', 'third' ] # or ['first'] or [] if not choices: return 1 elif countArgs(choices) == 1: goThere(choices[0]) else: for curChoice in choices: print os.getcwd() if goThere(curChoice) == 1: # Sorry this part may be wrong bcos I break # don't really know what $choices is Now, does this work as expected ?? If it doesn't what is expected ?? Regards Steve -- Never be afraid to tell the world who you are. - Anonymous From hemanexp@yahoo.com Tue May 27 06:46:03 2003 From: hemanexp@yahoo.com (Python-lover) Date: Tue May 27 05:46:03 2003 Subject: [Tutor] Passing user defined variables to mouseclick/enter/leave events Message-ID: <20030527094519.35019.qmail@web41905.mail.yahoo.com> --0-2029238476-1054028719=:33916 Content-Type: text/plain; charset=us-ascii hi, I am using python and tkinter. Is it possible to pass user defined variables to and event that bind to mouse enter ("Enter" ) event. I want to pass some data to the event which is bound to "Enter" event. The coding is given below: ********************************************************self.canvas.tag_bind('movex1',"", lambda type=1, xy=1: self.ChangeCursor(type,xy)) self.canvas.tag_bind('movey1',"", lambda event,type=1, xy=2: self.ChangeCursor(type,xy)) def ChangeCursor(self,event,type,xy): if type == 1: #Mouse enter event if xy == 1: #X1/X2 position self.canvas.config(cursor="sb_v_double_arrow") if xy == 2: #Y1/Y2 position self.canvas.config(cursor="sb_h_double_arrow") ************************************************************************ When i ran my program i got the following error: TypeError: ChangeCursor() takes exactly 4 arguments (3 given). Where the problem exist and how can i pass user define variables to ChangeCursor routine? Thanx. --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-2029238476-1054028719=:33916 Content-Type: text/html; charset=us-ascii
hi,
  I am using python and tkinter. Is it possible to pass user defined variables to and event that bind to mouse enter ("Enter" ) event. I want to pass some data to the event which is bound to "Enter" event. The coding is given below:
 
********************************************************
self.canvas.tag_bind('movex1',"<Enter>",
         lambda type=1, xy=1:
         self.ChangeCursor(type,xy))

  self.canvas.tag_bind('movey1',"<Enter>",
         lambda  event,type=1, xy=2:
         self.ChangeCursor(type,xy))
 
 def ChangeCursor(self,event,type,xy):
          if type == 1:    #Mouse enter event
               if xy == 1:  #X1/X2 position
                  self.canvas.config(cursor="sb_v_double_arrow")
             if xy == 2: #Y1/Y2 position
                  self.canvas.config(cursor="sb_h_double_arrow")
      
************************************************************************
  When i ran my program i got the following error:
 
TypeError: ChangeCursor() takes exactly 4 arguments (3 given).
 
  Where the problem exist and how can i pass user define variables to ChangeCursor routine?
 
Thanx.
 


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-2029238476-1054028719=:33916-- From jim_938@hotmail.com Tue May 27 09:10:06 2003 From: jim_938@hotmail.com (Jimmy verma) Date: Tue May 27 08:10:06 2003 Subject: [Tutor] Re: c to python Message-ID: Thanks everyone for responding to my query. The explainations are really very much helpful for me in converting my program to python. I hope to have a much shorter program with python as compared to the one i have. I am going to look at all the cases mentioned in the responses. Thanks again. Regards. Jim _________________________________________________________________ Got a wish? Make it come true. http://server1.msn.co.in/msnleads/citibankpersonalloan/index.asp Best personal loans! From nixonron@yahoo.com Tue May 27 13:10:02 2003 From: nixonron@yahoo.com (Ron Nixon) Date: Tue May 27 12:10:02 2003 Subject: [Tutor] kodos Message-ID: <20030527160919.82948.qmail@web20306.mail.yahoo.com> --0-1104561969-1054051759=:81176 Content-Type: text/plain; charset=us-ascii Can someone give me a hand it setting up kodos--the python regex GUI. I downloaded the file and a pyqt file as well per the documentation. It also calls for something called SIP, which seems to be included in the pyqt file. Still when I run the set-up file, it tells me that the SIP code generator is lacking. I also tried setting up kodos using the command line, but get a error saying files can't be found. Can anyone help on this. Thanks in advance. Ron --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-1104561969-1054051759=:81176 Content-Type: text/html; charset=us-ascii
Can someone give me a hand it setting up kodos--the python regex GUI. I downloaded the file and a pyqt file as well per the documentation. It also calls for something called SIP, which seems to be included in the pyqt file. Still when I run the set-up file, it tells me that the SIP code generator is lacking. I also tried setting up kodos using the command line, but get a error saying files can't be found. Can anyone help on this. Thanks in advance.
 
Ron


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-1104561969-1054051759=:81176-- From jeff@ccvcorp.com Tue May 27 14:49:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue May 27 13:49:01 2003 Subject: [Tutor] I need ideas please References: <191.1a28ed39.2c01bc11@aol.com> Message-ID: <3ED3A5C4.6040504@ccvcorp.com> GREENDAY31087@aol.com wrote: > Anyway, my first problem is the months. Determining what your sign is > depends on the month but it's not like every sign starts on the first > day of the month. (march 1st-31st: you are a Pisces) the different > signs start in the middle of the month. So you cant just take the > input (month) and determine what sign corresponds with it. I was > thinking about making each month a certain value and then asking the > user the day of the month they were born. After that, the program > could add the day to the month value to make a new value. I could > assign a different sign to each range of numbers and if, say, the > value was in the range that 'Pisces' covers, they would be Pisces. > Follow me so far? You should look into the time module. There's two standard methods of representing time (which includes dates): Unix standard, expressed as number of seconds since Jan 1st, 1970, and a 9-tuple format with fields representing year, month, day, hours, minutes, seconds, etc. One of the fields of that tuple format is the so-called "Julian date", or the day of the year (1-366). You can use these Julian dates to assign an unambiguous start date for each astrological sign -- Pisces, for example, starts on Feb 19th, which is Julian day 40. You'll need to get your user's birthday, presumably in month/day form, and convert that into a Julian date. The trick here is in using the functions that convert a time tuple into a Unix date (mktime()) and a Unix date back into a time tuple (localtime()). mktime() doesn't necessarily require a completely-filled-out 9-member tuple; you can specify just year, month, and day, use 0 for the other 6 members, and mktime() will react appropriately (this will give you Unix time for midnight at the start of that particular day). Now you can take the Unix time that that has given you and convert that back into a time tuple, and those previously empty fields will be filled in with the proper values. You can then extract the Julian date, and you're set. def MakeJulianDate(year, month, day): timetuple = (year, month, day) + ( (0,) * 6 ) #pad 9-tuple with 0's unixtime = time.mktime(timetuple) timetuple = time.localtime(unixtime) return timetuple[7] # number of julian-date field I've used a bit of trickery to build my time tuple without counting out six 0's -- I use multiplication to create a tuple with six 0's, and then add that to a tuple of the known date fields to create a new, 9-member tuple. It's up to you whether you want to use the current year or to ask the user their birth year (or just use an arbitrary year, like 2000). > My next problem is not as complicated as the first one but I don't > know what should be made into a function to be called. Should I make > the whole month thing into a function or should I not define any > functions? I'm sort of confused. Also, I wanted to know ... will this > program probably need to use a list? You definitely should define functions. I've already shown one example -- a function that converts a "regular" month/day date into a Julian date. You'll probably also want a function that asks the user for their birthday, and returns the year, month, and day. Finding the correct sign based off of the Julian date should probably be a third function. One way to decide what to put into separate functions, is to describe what you're trying to do as a series of steps. "First, I get the birthdate. Then, I convert that into a format I can use more easily. Next, I figure out what sign that date belongs to. Finally, I print out the sign and maybe some extra information about it." Each of those steps is a likely candidate to become a separate function. If a given step seems to be complicated, you might break that down into substeps, each of which is done by another function. As for needing to use a list... probably, but it depends on how you want to do things. You could set this up as a nested list -- each sign is represented by a list of its start date, the name of the sign, and maybe a descriptive paragraph. You then create a list of these sub-lists. By using the start date as the first element of each sub-list, they'll easily sort into the proper order. Note that Capricorn's sub-list may need to appear twice -- once starting at Day 1, and a second time starting at Day 356 -- since it applies both at the beginning and the end of the year. You can start at the beginning of the list, and for each following element, see if the birthdate is greater than the sign's start date. Hope that this gives you some ideas. If you have further questions, don't be afraid to ask further on the list. Jeff Shannon Technician/Programmer Credit International From tpc@csua.berkeley.edu Tue May 27 15:09:01 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Tue May 27 14:09:01 2003 Subject: [Tutor] I need ideas please In-Reply-To: <3ED3A5C4.6040504@ccvcorp.com> Message-ID: <20030527110716.N17636-100000@localhost.name> > fields of that tuple format is the so-called "Julian date", or the day > of the year (1-366). You can use these Julian dates to assign an > unambiguous start date for each astrological sign -- Pisces, for > example, starts on Feb 19th, which is Julian day 40. shouldn't that be: 31 + 19 = 50 ? From jeff@ccvcorp.com Tue May 27 15:23:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue May 27 14:23:02 2003 Subject: [Tutor] I need ideas please References: <20030527110716.N17636-100000@localhost.name> Message-ID: <3ED3ACDA.40708@ccvcorp.com> tpc@csua.berkeley.edu wrote: >>fields of that tuple format is the so-called "Julian date", or the day >>of the year (1-366). You can use these Julian dates to assign an >>unambiguous start date for each astrological sign -- Pisces, for >>example, starts on Feb 19th, which is Julian day 40. >> >> > >shouldn't that be: 31 + 19 = 50 ? > Erm. Yes, it should. I plead morning fuzzy-headedness. :) Maybe I *should* get that coffee after all... Jeff Shannon Technician/Programmer Credit International From nixonron@yahoo.com Tue May 27 15:23:23 2003 From: nixonron@yahoo.com (Ron Nixon) Date: Tue May 27 14:23:23 2003 Subject: [Tutor] redemo file error Message-ID: <20030527182232.93952.qmail@web20310.mail.yahoo.com> --0-207666994-1054059752=:92623 Content-Type: text/plain; charset=us-ascii Can anyone tell me why I get a "unscriptable object" error when running the redemo script listed in the tools folder in Python 2.2? --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-207666994-1054059752=:92623 Content-Type: text/html; charset=us-ascii
Can anyone tell me why I get a "unscriptable object" error when running the redemo script listed in the tools folder in Python 2.2?


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-207666994-1054059752=:92623-- From dyoo@hkn.eecs.berkeley.edu Tue May 27 15:47:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 27 14:47:02 2003 Subject: [Tutor] dir() question: how do you know which are attributes and which are methods? In-Reply-To: <721216893810.20030525203228@columbus.rr.com> Message-ID: On Sun, 25 May 2003, R. Alan Monroe wrote: > Subject says it all... > > example > > > class dummy: > stuff = 0 > def task(): > pass > > >>> dir(dummy) > ['__doc__', '__module__', 'stuff', 'task'] > > How do I find out, when working with a new class I'm not familiar with, > how many attributes it has, and how many methods? dir() is a bit too > generic because both look identical in the list... Hi Alan, (Well, technically, a method in Python is an attribute. *grin*) You may find the 'inspect' module useful to do digging through the class definitions: http://www.python.org/doc/lib/inspect-types.html ### >>> class dummy: ... stuff = 0 ... def task(self): ... pass ... >>> import inspect >>> inspect.getmembers(dummy, inspect.ismethod) [('task', )] >>> >>> >>> class dummy2(dummy): ... def task2(self): pass ... >>> inspect.getmembers(dummy2, inspect.ismethod) [('task', ), ('task2', )] ### Hope this helps. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Tue May 27 15:52:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 27 14:52:02 2003 Subject: [Tutor] Passing user defined variables to mouseclick/enter/leave events In-Reply-To: <20030527094519.35019.qmail@web41905.mail.yahoo.com> Message-ID: On Tue, 27 May 2003, Python-lover wrote: > hi, I am using python and tkinter. Is it possible to pass user defined > variables to and event that bind to mouse enter ("Enter" ) event. Hello! Sure; it should work ok. > I want to pass some data to the event which is bound to "Enter" event. Ok, let's take a look. ### self.canvas.tag_bind('movex1',"", lambda type=1, xy=1: self.ChangeCursor(type,xy)) ### This would look ok, except that I'm not too familiar with tag_bind. Doesn't the function need to account for the even object that's passed over? The second call to tag_bind looks better: ### self.canvas.tag_bind('movey1',"", lambda event,type=1, xy=2: self.ChangeCursor(type,xy)) ### but it still needs to send that event over to ChangeCursor as a parameter. Try: ### self.canvas.tag_bind('movex1',"", lambda event, type=1, xy=1: self.ChangeCursor(event, type, xy)) self.canvas.tag_bind('movey1',"", lambda event, type=1, xy=2: self.ChangeCursor(event, type, xy)) ### Hope this helps! From magnus@thinkware.se Tue May 27 17:13:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue May 27 16:13:01 2003 Subject: [Tutor] Making python extension in Windows In-Reply-To: <3ED19FB8.000003.03852@siahaan> Message-ID: <5.2.1.1.0.20030527220514.01ff6008@www.thinkware.se> At 12:01 2003-05-26 +0700, Mico Siahaan wrote: >I don't have Visual C++. The only C++ compiler I have is Dev C++. You might be interested in this: http://mail.python.org/pipermail/python-dev/2003-May/035375.html It seems the Visual C++ compiler (at least version 7) is freely downloadable from MS. (Not the GUI though.) As you see, it's not even possible for things built with that compiler to coexist with the current VC 6 built stuff... As you see in the thread, it seems that Mingw is compatible with MS VC 6. See also http://www.msdn.microsoft.com/netframework/downloads/howtoget.aspx etc. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dyoo@hkn.eecs.berkeley.edu Tue May 27 17:27:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 27 16:27:03 2003 Subject: [Tutor] using rdflib In-Reply-To: <20030525194553.GA1542@dhumketu.homeunix.net> Message-ID: On Mon, 26 May 2003, Shantanu Mahajan wrote: > Can anyone point me to the tutorial for using rdflib? Hi Shantanu, By rdflib, I'll assume that you mean a library to work with the 'Resource Description Framework': http://rdflib.net/ Isn't this the Semantic Web stuff that Tim Bernes-Lee is working on? Very cool! But I haven't had a chance to dive into this yet. The documentation on rdflib, http://rdflib.net/stable/doc/index.html seems slightly... well, not quite complete yet. *grin* There are examples that you can experiment with: http://rdflib.net/stable/example.py http://rdflib.net/stable/example_btree.py which try to show common use of the rdflib.TripleStore module to work with those RDF triples. Unfortunately, I can't find an introduction tutorial to rdflib itself. If we use Google, we should be able to find introductory material for 'rdf'. For example, http://www.xml.com/pub/a/2001/01/24/rdf.html http://www.zvon.org/xxl/RDFTutorial/General/book.html but I haven't yet found anything that introduces rdflib itself. You may want to ask your question on the newsgroup 'comp.lang.python' instead: RDF is actually really specialized, and many of us may not be experienced enough with it to help you find good resources. Good luck to you. From willblake@wanadoo.fr Wed May 28 06:27:02 2003 From: willblake@wanadoo.fr (Guillaume RAIMONDEAU) Date: Wed May 28 05:27:02 2003 Subject: [Tutor] Games written in Py Message-ID: <7659262.1054113944043.JavaMail.www@wwinf0503> Hi Does anybody know some games written in Py. I would like to write some progs like that but I need some models :) Thanks From a_abdi406@yahoo.com Wed May 28 12:10:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed May 28 11:10:02 2003 Subject: [Tutor] about nltk Message-ID: <20030528002351.53840.qmail@web14508.mail.yahoo.com> --0-293102233-1054081431=:53804 Content-Type: text/plain; charset=us-ascii Hi, I was trying to play with python NLTK text classification tutorial , I can not run the following code even if the way I installed NLTK is correct, I cann't run the followingcode: >>> import nltk.classifier >>> test = nltk.classifier.LabeledText('test','q') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'LabeledText' the result I am expecting after runing this code is: ' test ' / ' q ' the above class is from: http://nltk.sourceforge.net/ref/nltk.classifier.LabeledText.html Can anyonbe help me understand why it is giving me this error ? Another quesstion is how do we use interface classes in python ? thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-293102233-1054081431=:53804 Content-Type: text/html; charset=us-ascii
Hi,
 
I was trying to play with python NLTK  text classification tutorial , I can not run the following code even if the way I installed NLTK is correct, I cann't run the followingcode:
 
>>> import nltk.classifier
>>> test = nltk.classifier.LabeledText('test','q')
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: 'module' object has no attribute 'LabeledText'
 
the result I am expecting after runing this code is:
' test ' / ' q '
the above class is from:
 
 
Can anyonbe help me understand why it is giving me this error ?
 
Another quesstion is how do we use interface classes in python ?
 
thanks in advance


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-293102233-1054081431=:53804-- From roypython@hotmail.com Wed May 28 12:30:02 2003 From: roypython@hotmail.com (roy ollis) Date: Wed May 28 11:30:02 2003 Subject: [Tutor] Games written in Py Message-ID: lookat at http://pygame.org/ . there is aslo a game section at http://www.vex.net/parnassus/ . both of these sites are linked to on the pain python.org page so they should be pretty good. happy programming. >From: Guillaume RAIMONDEAU >Reply-To: willblake@wanadoo.fr >To: tutor@python.org >Subject: [Tutor] Games written in Py >Date: Wed, 28 May 2003 11:25:44 +0200 (CEST) > >Hi >Does anybody know some games written in Py. >I would like to write some progs like that but I need some models :) >Thanks > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From jciancio@indiana.edu Wed May 28 13:41:47 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Wed May 28 12:41:47 2003 Subject: [Tutor] random numbers In-Reply-To: <200305281619.LAA02282@indiana.edu> Message-ID: <200305281639.LAA13785@iupui.edu> Hi, I'm having trouble generating random numbers. if I do import random random.random() I get TypeError: 'module' object is not callable and what I would really like to do is get random integers, but I can't do that either. if I put in randrange(1, 10) I get NameError: name 'randrange' is not defined but I found that in FAQ http://www.python.org/cgi-bin/faqw.py?querytype=anykeywords&casefold=y es&req=search&query=random one more thing - what does it mean that random numbers generated by python are 'psuedo' random? any way to make them not psuedorandom? thanks in advance Jen From tpc@csua.berkeley.edu Wed May 28 13:58:01 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed May 28 12:58:01 2003 Subject: [Tutor] random numbers In-Reply-To: <200305281639.LAA13785@iupui.edu> Message-ID: <20030528094554.P24312-100000@localhost.name> I don't know yet how to generate random numbers in Python, but I think pseudorandom means generated by a computational process defined to generate random numbers, as opposed to natural processes, although the term may be archaic. You may wish to read: http://mathworld.wolfram.com/RandomNumber.html On Wed, 28 May 2003, Jennifer Cianciolo wrote: > Hi, > > I'm having trouble generating random numbers. > > if I do > > import random > random.random() > > I get > > TypeError: 'module' object is not callable > > and what I would really like to do is get random integers, but I can't > do that either. > > if I put in > > randrange(1, 10) > > I get > > NameError: name 'randrange' is not defined > > but I found that in FAQ > http://www.python.org/cgi-bin/faqw.py?querytype=anykeywords&casefold=y > es&req=search&query=random > > one more thing - what does it mean that random numbers generated by > python are 'psuedo' random? any way to make them not psuedorandom? > > thanks in advance > Jen > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dana@pixelenvy.ca Wed May 28 13:58:13 2003 From: dana@pixelenvy.ca (Dana Larose) Date: Wed May 28 12:58:13 2003 Subject: [Tutor] random numbers In-Reply-To: <200305281639.LAA13785@iupui.edu> Message-ID: On Wed, 28 May 2003, Jennifer Cianciolo wrote: > > import random > random.random() > > I get > > TypeError: 'module' object is not callable > Which platform/version of python are you using? On mine (W2K, Python 2.2.2) it seems to work: >>> import random >>> random.random() 0.3523578254734825 > and what I would really like to do is get random integers, but I can't > do that either. > > if I put in > > randrange(1, 10) > > I get > > NameError: name 'randrange' is not defined > If you have imported the module like this: import random Then you'll want to use: random.randrange(1,10) You can also do: from random import randrange then call randrange without prefixing random to it. > but I found that in FAQ > http://www.python.org/cgi-bin/faqw.py?querytype=anykeywords&casefold=y > es&req=search&query=random > > one more thing - what does it mean that random numbers generated by > python are 'psuedo' random? any way to make them not psuedorandom? > Any random number generated by a computer is pseudo-random, because it uses an algorithm to generate a sequence of numbers which appear as random. As I understand things, the random numbers are statistically indistinguishable from true random numbers. They are a sequence however, and will eventually repeat, but the period is extremely large. This isn't a python thing, keep in mind, any random number generator for any computer currently in existence is a pseudo-random number generator. But I wouldn't really worry about it. For anything that you are doing, the difference between the pseudo-random numbers are true random numbers is theoretical and won't matter. (Once they get quantum computers up and running, they'll be able to generate true random numbers (as I understand it), but don't hold your breath for those!) dana. From python@jaydorsey.com Wed May 28 14:00:03 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Wed May 28 13:00:03 2003 Subject: [Tutor] random numbers In-Reply-To: <200305281639.LAA13785@iupui.edu> References: <200305281639.LAA13785@iupui.edu> Message-ID: <200305281259.30768.python@jaydorsey.com> On Wednesday 28 May 2003 12:39, Jennifer Cianciolo wrote: > I'm having trouble generating random numbers. > > if I do > > import random > random.random() > > I get > > TypeError: 'module' object is not callable What version of Python are you using? The above code seems to work fine for me. If you want a random integer within a set of numbers, try the following: >>> import whrandom >>> whrandom.randrange(1, 10) 4 -- Jay Dorsey python at jay dorsey dot com From dyoo@hkn.eecs.berkeley.edu Wed May 28 14:11:49 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed May 28 13:11:49 2003 Subject: [Tutor] about nltk In-Reply-To: <20030528002351.53840.qmail@web14508.mail.yahoo.com> Message-ID: On Tue, 27 May 2003, Abdirizak abdi wrote: > Hi, > I was trying to play with python NLTK text classification tutorial , I > can not run the following code even if the way I installed NLTK is > correct, I cann't run the followingcode: > > >>> import nltk.classifier > >>> test = nltk.classifier.LabeledText('test','q') > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'LabeledText' Hi Abdirizak, This is odd! This works for me: ### >>> import nltk.classifier >>> dir(nltk.classifier) ['ClassifierI', 'ClassifierTrainerI', 'ConfusionMatrix', 'LabeledText', 'Numeric', 'Token', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'accuracy', 'find_labels', 'label_tokens', 'log_likelihood', 'math'] >>> nltk.classifier.LabeledText >>> nltk.classifier.LabeledText('text', 'q') 'text'/'q' ### Just to check: what directory are you in when you tried to test your example? What happens if you try: ### import nltk print nltk.__file__ ### Show us what the above prints out; it may clue us into why the import isn't working. If your current directory is the nltk installation directory, that can cause a problem, because the files in the current directory may confuse Python's module system. From dyoo@hkn.eecs.berkeley.edu Wed May 28 14:17:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed May 28 13:17:01 2003 Subject: [Tutor] random numbers In-Reply-To: <200305281639.LAA13785@iupui.edu> Message-ID: On Wed, 28 May 2003, Jennifer Cianciolo wrote: > I'm having trouble generating random numbers. > > if I do > > import random > random.random() > > I get > > TypeError: 'module' object is not callable Hello! Hmmm... we seem to be getting a whole slew of module importing questions today... *grin* I think we need more information; it sounds like the 'random' that you're importing isn't the one from the Standard Library. Let's probe this: what's the name of your current source file? Is it called 'random.py', or is there a 'random.py' in your current directory? If so, that's most likely the source of our problem. If not, then we'll have to think of something else. By the way, I've actually cooked up a small pseudomodule that tries to alleviate a common module importing problem: http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ Good luck to you! From kalle@lysator.liu.se Wed May 28 14:23:01 2003 From: kalle@lysator.liu.se (Kalle Svensson) Date: Wed May 28 13:23:01 2003 Subject: [Tutor] random numbers In-Reply-To: <200305281259.30768.python@jaydorsey.com> References: <200305281639.LAA13785@iupui.edu> <200305281259.30768.python@jaydorsey.com> Message-ID: <20030528172020.GC513@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Jay Dorsey] > >>> import whrandom > >>> whrandom.randrange(1, 10) > 4 whrandom is an old module and shouldn't be used (if you're not specifically interested in the Wichmann-Hill PRNG, I guess). Use the random module instead. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE+1O/MdNeA1787sd0RAsDxAJ0TWNx1Ef9YBudL/94l71zzm/vHnQCcC95m X4IdsPiSrRwGHMqY8nml9fs= =lP6/ -----END PGP SIGNATURE----- From tpc@csua.berkeley.edu Wed May 28 14:40:02 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed May 28 13:40:02 2003 Subject: [Tutor] random numbers In-Reply-To: Message-ID: <20030528103732.Y24567-100000@localhost.name> hi Danny, I just downloaded your module and tried to install it and I get this: [tpc@nike __std__-1.0]# python setup.py usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: no commands supplied Am I doing something wrong ? On Wed, 28 May 2003, Danny Yoo wrote: > > > On Wed, 28 May 2003, Jennifer Cianciolo wrote: > > > I'm having trouble generating random numbers. > > > > if I do > > > > import random > > random.random() > > > > I get > > > > TypeError: 'module' object is not callable > > > Hello! > > > Hmmm... we seem to be getting a whole slew of module importing questions > today... *grin* I think we need more information; it sounds like the > 'random' that you're importing isn't the one from the Standard Library. > > > > Let's probe this: what's the name of your current source file? Is it > called 'random.py', or is there a 'random.py' in your current directory? > If so, that's most likely the source of our problem. If not, then we'll > have to think of something else. > > > By the way, I've actually cooked up a small pseudomodule that tries to > alleviate a common module importing problem: > > http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ > > > > > Good luck to you! > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From python@jaydorsey.com Wed May 28 14:51:03 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Wed May 28 13:51:03 2003 Subject: [Tutor] random numbers In-Reply-To: <20030528172020.GC513@i92.ryd.student.liu.se> References: <200305281639.LAA13785@iupui.edu> <200305281259.30768.python@jaydorsey.com> <20030528172020.GC513@i92.ryd.student.liu.se> Message-ID: <200305281350.32661.python@jaydorsey.com> On Wednesday 28 May 2003 13:20, Kalle Svensson wrote: > > whrandom is an old module and shouldn't be used (if you're not > specifically interested in the Wichmann-Hill PRNG, I guess). > Use the random module instead. > > Peace, > Kalle I was not aware of that. Thank you very much :) Jay -- Jay Dorsey python at jay dorsey dot com From gerrit@nl.linux.org Wed May 28 14:53:02 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Wed May 28 13:53:02 2003 Subject: [Tutor] random numbers In-Reply-To: <20030528103732.Y24567-100000@localhost.name> References: <20030528103732.Y24567-100000@localhost.name> Message-ID: <20030528175225.GA4149@nl.linux.org> tpc@csua.berkeley.edu schreef op woensdag 28 mei om 19:48:07 +0000: > [tpc@nike __std__-1.0]# python setup.py > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > > error: no commands supplied You probably need to do: # python setup.py install or, if it's binary, first: # python setup.py build Read a distributed README file or something similar for details. # python setup.py help ...may also provide useful information. If all else fails, you can always read the source! yours, Gerrit. -- 280. If while in a foreign country a man buy a male or female slave belonging to another of his own country; if when he return home the owner of the male or female slave recognize it: if the male or female slave be a native of the country, he shall give them back without any money. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From dyoo@hkn.eecs.berkeley.edu Wed May 28 15:00:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed May 28 14:00:03 2003 Subject: [Tutor] random numbers [installing 3rd party modules] In-Reply-To: <20030528175225.GA4149@nl.linux.org> Message-ID: On Wed, 28 May 2003, Gerrit Holl wrote: > tpc@csua.berkeley.edu schreef op woensdag 28 mei om 19:48:07 +0000: > > [tpc@nike __std__-1.0]# python setup.py > > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > > or: setup.py --help [cmd1 cmd2 ...] > > or: setup.py --help-commands > > or: setup.py cmd --help > > > > error: no commands supplied > > You probably need to do: > > # python setup.py install > > or, if it's binary, first: > > # python setup.py build > > Read a distributed README file or something similar for details. By the way, there's a fairly detailed installation guide to 3rd party Python modules here: http://www.python.org/doc/current/inst/inst.html But the __std__ module should be fairly trivial to install; the command 'python setup.py install' should be enough. *grin* Good luck! From jciancio@indiana.edu Wed May 28 15:03:01 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Wed May 28 14:03:01 2003 Subject: [Tutor] random numbers In-Reply-To: Message-ID: <200305281802.NAA23297@iupui.edu> Ok, I did have a file named random.py. I guess that's not a good idea!! I deleted it, but the random.random() is still not working. import whrandom whrandom.randrange(1, 10) does work!! but then someone said not to use that :( so I'm still confused. also thanks to all on clarifying pseudorandom! ------------------- > > > On Wed, 28 May 2003, Jennifer Cianciolo wrote: > > > I'm having trouble generating random numbers. > > > > if I do > > > > import random > > random.random() > > > > I get > > > > TypeError: 'module' object is not callable > > > Hello! > > > Hmmm... we seem to be getting a whole slew of module importing questions > today... *grin* I think we need more information; it sounds like the > 'random' that you're importing isn't the one from the Standard Library. > > > > Let's probe this: what's the name of your current source file? Is it > called 'random.py', or is there a 'random.py' in your current directory? > If so, that's most likely the source of our problem. If not, then we'll > have to think of something else. > > > By the way, I've actually cooked up a small pseudomodule that tries to > alleviate a common module importing problem: > > http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ > > > > > Good luck to you! > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From jciancio@indiana.edu Wed May 28 15:04:19 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Wed May 28 14:04:19 2003 Subject: [Tutor] random numbers In-Reply-To: Message-ID: <200305281803.NAA23404@iupui.edu> oh yeah, I'm using python 2.2.2 ------------------- > > > On Wed, 28 May 2003, Jennifer Cianciolo wrote: > > > I'm having trouble generating random numbers. > > > > if I do > > > > import random > > random.random() > > > > I get > > > > TypeError: 'module' object is not callable > > > Hello! > > > Hmmm... we seem to be getting a whole slew of module importing questions > today... *grin* I think we need more information; it sounds like the > 'random' that you're importing isn't the one from the Standard Library. > > > > Let's probe this: what's the name of your current source file? Is it > called 'random.py', or is there a 'random.py' in your current directory? > If so, that's most likely the source of our problem. If not, then we'll > have to think of something else. > > > By the way, I've actually cooked up a small pseudomodule that tries to > alleviate a common module importing problem: > > http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ > > > > > Good luck to you! > > > > From dyoo@hkn.eecs.berkeley.edu Wed May 28 15:09:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed May 28 14:09:01 2003 Subject: [Tutor] random numbers In-Reply-To: <200305281802.NAA23297@iupui.edu> Message-ID: On Wed, 28 May 2003, Jennifer Cianciolo wrote: > Ok, I did have a file named random.py. I guess that's not a good idea!! Hi Jennifer, Yes, I'm glad we sorted that out. > I deleted it, but the random.random() is still not working. You may want to check if there's a 'random.pyc' in your current directory. What's probably happening is that Python has "cached" what it thinks is the real 'random.py' module. If you delete that 'random.pyc' from your current directory, try importing 'random' again then and see if things work. For some wacky reason, this sort of problem always seems to happen with the random module: people have this undeniable compulsion to name their test file 'random' when they want to test out the random number generator... *grin* Good luck! From jciancio@indiana.edu Wed May 28 15:19:12 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Wed May 28 14:19:12 2003 Subject: [Tutor] random numbers In-Reply-To: Message-ID: <200305281815.NAA24844@iupui.edu> I did have a random.pyc, so I've deleted that - still no luck. (and thanks for the help!) > > On Wed, 28 May 2003, Jennifer Cianciolo wrote: > > > Ok, I did have a file named random.py. I guess that's not a good > You may want to check if there's a 'random.pyc' in your current directory. > What's probably happening is that Python has "cached" what it thinks is > the real 'random.py' module. If you delete that 'random.pyc' from your > current directory, try importing 'random' again then and see if things > work. > From jciancio@indiana.edu Wed May 28 15:20:05 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Wed May 28 14:20:05 2003 Subject: [Tutor] random SUCCESS In-Reply-To: Message-ID: <200305281819.NAA25272@iupui.edu> ok, I deleted random.pyc, shut down the program (nothing like rushing to write back with 'it didn't work!') opened it back up, and viola - perfect. thanks a million From magnus@thinkware.se Wed May 28 16:21:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 28 15:21:02 2003 Subject: [Tutor] about nltk In-Reply-To: <20030528002351.53840.qmail@web14508.mail.yahoo.com> Message-ID: <5.2.1.1.0.20030528191231.01e66c28@www.thinkware.se> At 17:23 2003-05-27 -0700, Abdirizak abdi wrote: >Hi, > >I was trying to play with python NLTK text classification tutorial , I >can not run the following code even if the way I installed NLTK is >correct, I cann't run the followingcode: > > >>> import nltk.classifier > >>> test = nltk.classifier.LabeledText('test','q') >Traceback (most recent call last): > File "", line 1, in ? >AttributeError: 'module' object has no attribute 'LabeledText' Works for me. >>> import nltk.classifier >>> dir(nltk.classifier) ['ClassifierI', 'ClassifierTrainerI', 'ConfusionMatrix', 'LabeledText', 'Numeric', 'Token', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'accuracy', 'find_labels', 'label_tokens', 'log_likelihood', 'math'] >>> nltk.classifier.LabeledText >>> nltk.classifier.LabeledText('test', 'q') 'test'/'q' I downloaded nltk to a windows box after your previous question. It's version 1.0 >>> nltk.__version__ '1.0' Perhaps you can try >>> help(nltk) or >>> help(nltk.classifier) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From tpc@csua.berkeley.edu Wed May 28 16:58:03 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed May 28 15:58:03 2003 Subject: [Tutor] Danny's __std__ module In-Reply-To: <20030528103732.Y24567-100000@localhost.name> Message-ID: <20030528124652.P25313-100000@localhost.name> hi Danny, I was curious: when you made this module did you intend for it to be called only when you name a file after a standard module, or for general everyday use ? I ask because I am writing a script and when I called your module in my script and then tried to run it I got: [tpc@nike htdocs]# ./text2decimalascii.py hello world Traceback (most recent call last): File "./text2decimalascii.py", line 2, in ? from __std__ import sys ImportError: cannot import name sys I then called your module on a program called random.py and it works fine. I guess I am trying to figure out when to use your module and when not to. On Wed, 28 May 2003 tpc@CSUA.Berkeley.EDU wrote: > > > hi Danny, I just downloaded your module and tried to install it and I get > this: > > [tpc@nike __std__-1.0]# python setup.py > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > > error: no commands supplied > > Am I doing something wrong ? > > On Wed, 28 May 2003, Danny Yoo wrote: > > > > > > > On Wed, 28 May 2003, Jennifer Cianciolo wrote: > > > > > I'm having trouble generating random numbers. > > > > > > if I do > > > > > > import random > > > random.random() > > > > > > I get > > > > > > TypeError: 'module' object is not callable > > > > > > Hello! > > > > > > Hmmm... we seem to be getting a whole slew of module importing questions > > today... *grin* I think we need more information; it sounds like the > > 'random' that you're importing isn't the one from the Standard Library. > > > > > > > > Let's probe this: what's the name of your current source file? Is it > > called 'random.py', or is there a 'random.py' in your current directory? > > If so, that's most likely the source of our problem. If not, then we'll > > have to think of something else. > > > > > > By the way, I've actually cooked up a small pseudomodule that tries to > > alleviate a common module importing problem: > > > > http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ > > > > > > > > > > Good luck to you! > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jmricker@nc.rr.com Wed May 28 17:14:02 2003 From: jmricker@nc.rr.com (Jody) Date: Wed May 28 16:14:02 2003 Subject: [Tutor] Games written in Py In-Reply-To: Message-ID: <009f01c32555$87649670$ade33942@joelom35kpq2rs> > -----Original Message----- > From: tutor-admin@python.org [mailto:tutor-admin@python.org]=20 > On Behalf Of roy ollis >=20 > lookat at http://pygame.org/ . there is aslo a game section at=20 > http://www.vex.net/parnassus/ . both of these sites are=20 > linked to on the=20 > pain python.org page so they should be pretty good. happy=20 > programming. Also for inspiration you may want to check out Activision's Star Trek = Bridge Commander. They use an embedded python engine to script all of the = game's missions. You even can access the interpreter from within the game = itself though if I remember correctly you have to use hotkeys to get to it. The = SDK they provide has imformation scripting more missions in Python for use within the game. Jody From njensen@utahfirst.com Wed May 28 17:52:02 2003 From: njensen@utahfirst.com (Nick Jensen) Date: Wed May 28 16:52:02 2003 Subject: [Tutor] help on newbie program Message-ID: <544BE8EBDBEE344F96B32750CA5753E9793D85@ufcu_ntes.utahfirst.com> Hello, I'm just starting to learn programming and python is my first language. = I've been using Josh Cogliati's guide: "Non-Programmers Tutorial For = Python" with a url of = http://www.honors.montana.edu/~jjc/easytut/easytut/node10.html which is = linked off from www.python.org under beginners guide. I have read every = example and line of code up to and including the section on lists, but I = just cannot understand the last example in that section named test.py.=20 I understand parts of it, but not all of it as a whole. I'm not able to = follow the flow of the program and whats happening at each step. Maybe = I'm asking too much, but was wondering if anyone could walk me through = the code and whats happening. By the way, I did send an email to Josh = asking this same question, but not sure if I'll hear back or not and = thought I'd ask here just in case. Here it is... Thanks! test.py=20 ## This program runs a test of knowledge true =3D 1 false =3D 0 # First get the test questions # Later this will be modified to use file io. def get_questions(): # notice how the data is stored as a list of lists return [["What color is the daytime sky on a clear day?","blue"],\ ["What is the answer to life, the universe and = everything?","42"],\ ["What is a three letter word for mouse trap?","cat"]] # This will test a single question # it takes a single question in # it returns true if the user typed the correct answer, otherwise false def check_question(question_and_answer): #extract the question and the answer from the list question =3D question_and_answer[0] answer =3D question_and_answer[1] # give the question to the user given_answer =3D raw_input(question) # compare the user's answer to the testers answer if answer =3D=3D given_answer: print "Correct" return true else: print "Incorrect, correct was:",answer return false # This will run through all the questions def run_test(questions): if len(questions) =3D=3D 0: print "No questions were given." # the return exits the function return index =3D 0 right =3D 0 while index < len(questions): #Check the question if check_question(questions[index]): right =3D right + 1 #go to the next question index =3D index + 1 #notice the order of the computation, first multiply, then divide print "You got ",right*100/len(questions),"% right out = of",len(questions) #now lets run the questions run_test(get_questions()) From dyoo@hkn.eecs.berkeley.edu Wed May 28 18:15:57 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed May 28 17:15:57 2003 Subject: [Tutor] Danny's __std__ module In-Reply-To: <20030528124652.P25313-100000@localhost.name> Message-ID: On Wed, 28 May 2003 tpc@csua.berkeley.edu wrote: > hi Danny, I was curious: when you made this module did you intend for it > to be called only when you name a file after a standard module, or for > general everyday use? Hello! The first case: when someone is forced to name a program with the same name as something from the Standard Library, __std__ is a way to do it. In almost all cases, __std__ is completely unnecessary, so I don't expect to see it in widespread use. *grin* > I ask because I am writing a script and when I called your module in my > script and then tried to run it I got: > > [tpc@nike htdocs]# ./text2decimalascii.py hello world > Traceback (most recent call last): > File "./text2decimalascii.py", line 2, in ? > from __std__ import sys > ImportError: cannot import name sys ??! Yikes! I did expect that to work. That's a bug on the part of the __std__ module. ... ah. The 'sys' module seems to be one of the core modules in Python, and doesn't live in the same place as the rest of the Standard Library. In fact, it appears to be statically compiled into Python itself. So you hit on one of the few special cases. *grin* I wonder if there are others... We can see that 'sys' is hardcoded by doing a 'help(sys)'; unlike the other standard Python modules, 'sys' doesn't have a __file__ attribute. Ok, I think I can fix __std__ to make it handle 'sys' as a special case. Ok, done. Can you try it out? If you can replace the file __std__/__init__.py with: ### import distutils.sysconfig """Note: it is important to do an 'import sys' here! 'sys' doesn't really live in distutils.sysconfig.get_python_lib()--- it's statically compiled into Python. If we want: from __std__ import sys to work, we need to have 'sys' here in our namespace. Thanks to tpc@csua.berkeley.edu for pointing this out. """ import sys __path__ = [distutils.sysconfig.get_python_lib(standard_lib=1)] __all__ = [] ### and reinstall __std__, the 'from __std__ import sys' should then work. If it looks good with you, I'll update the package with the fix. Thanks again! From magnus@thinkware.se Wed May 28 18:33:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 28 17:33:02 2003 Subject: [Tutor] random SUCCESS In-Reply-To: <200305281819.NAA25272@iupui.edu> References: Message-ID: <5.2.1.1.0.20030528231848.01e715a8@www.thinkware.se> At 13:19 2003-05-28 -0500, Jennifer Cianciolo wrote: >ok, I deleted random.pyc, shut down the program Yes, if you already *did* "import random" and the wrong random module got loaded into memory, it won't go away from memory because you remove the file. A new "import random" will do nothing if random is loaded already. This is to avoid the same code existing in multiple copies in memory. If you build a large program, you might import the same module in perhaps ten different places. It will still be loaded just once. This is a Good Thing. A new "import random" will only make the name "random" in the part of the program where you made this "import" refer to the already loaded module. Even if you do "del random; import random" it will find the old module which is already loaded in memory. Still, you don't need to quit Python now. You can type "reload(random)" after you deleted the bad files, to make python try to load from a file again. Hopefully, Python will now find the *right* file. If not, you can see that at the Python prompt: >>> reload(random) This was the file I wanted! -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From tpc@csua.berkeley.edu Wed May 28 18:46:01 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed May 28 17:46:01 2003 Subject: [Tutor] Danny's __std__ module In-Reply-To: Message-ID: <20030528144352.Y25854-100000@localhost.name> hi Danny, yes it works now. On Wed, 28 May 2003, Danny Yoo wrote: > > > On Wed, 28 May 2003 tpc@csua.berkeley.edu wrote: > > > > hi Danny, I was curious: when you made this module did you intend for it > > to be called only when you name a file after a standard module, or for > > general everyday use? > > Hello! > > The first case: when someone is forced to name a program with the same > name as something from the Standard Library, __std__ is a way to do it. > In almost all cases, __std__ is completely unnecessary, so I don't expect > to see it in widespread use. *grin* > > > > > I ask because I am writing a script and when I called your module in my > > script and then tried to run it I got: > > > > [tpc@nike htdocs]# ./text2decimalascii.py hello world > > Traceback (most recent call last): > > File "./text2decimalascii.py", line 2, in ? > > from __std__ import sys > > ImportError: cannot import name sys > > > ??! Yikes! I did expect that to work. That's a bug on the part of the > __std__ module. ... ah. The 'sys' module seems to be one of the core > modules in Python, and doesn't live in the same place as the rest of the > Standard Library. In fact, it appears to be statically compiled into > Python itself. So you hit on one of the few special cases. *grin* I > wonder if there are others... > > We can see that 'sys' is hardcoded by doing a 'help(sys)'; unlike the > other standard Python modules, 'sys' doesn't have a __file__ attribute. > > > > Ok, I think I can fix __std__ to make it handle 'sys' as a special case. > Ok, done. Can you try it out? If you can replace the file > __std__/__init__.py with: > > > > ### > import distutils.sysconfig > > > """Note: it is important to do an 'import sys' here! 'sys' doesn't > really live in distutils.sysconfig.get_python_lib()--- it's statically > compiled into Python. If we want: > > from __std__ import sys > > to work, we need to have 'sys' here in our namespace. > > Thanks to tpc@csua.berkeley.edu for pointing this out. > """ > import sys > > > > __path__ = [distutils.sysconfig.get_python_lib(standard_lib=1)] > > __all__ = [] > ### > > > > and reinstall __std__, the 'from __std__ import sys' should then work. > If it looks good with you, I'll update the package with the fix. > > > > Thanks again! > > From kthet_02@yahoo.com Wed May 28 19:13:08 2003 From: kthet_02@yahoo.com (matt dittsworth) Date: Wed May 28 18:13:08 2003 Subject: [Tutor] Please UNSUBSCRIBE me Message-ID: <20030528221249.70274.qmail@web21507.mail.yahoo.com> --0-1039138237-1054159969=:69840 Content-Type: text/plain; charset=us-ascii I need to be unsubscribed fromt the Tutor, Please. I don't remember my password and have been able to get the computer to send me it. I emailed the admin at tutor and never received a response. I like the information just to much and I don't have time to sit and read it all. Thank you. Matt Matt Dittsworth Semper Fi New Website --------------------------------- Do you Yahoo!? Free online calendar with sync to Outlook(TM). --0-1039138237-1054159969=:69840 Content-Type: text/html; charset=us-ascii
I need to be unsubscribed fromt the Tutor, Please.  I don't remember my password and have been able to get the computer to send me it.  I emailed the admin at tutor and never received a response.  I like the information just to much and I don't have time to sit and read it all.  Thank you.
 
Matt


Matt Dittsworth
Semper Fi


Do you Yahoo!?
Free online calendar with sync to Outlook(TM). --0-1039138237-1054159969=:69840-- From magnus@thinkware.se Wed May 28 19:42:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 28 18:42:02 2003 Subject: [Tutor] help on newbie program In-Reply-To: <544BE8EBDBEE344F96B32750CA5753E9793D85@ufcu_ntes.utahfirst .com> Message-ID: <5.2.1.1.0.20030528233859.01ec7820@www.thinkware.se> Hi Nick, and welcome to Python. I hope you will enjoy it. It's really a rather amazing tool to make thoughts turn into action. :) A wise man called Fred Brooks wrote about "the joys of the craft" in his book "The Mythical Man-Month" almost 30 years ago. See http://www.davar.net/PROGRAM/EXTRACTS/CRAFTJOY.HTM for his view of why we like programming. At 14:49 2003-05-28 -0600, Nick Jensen wrote: >I have read every example and line of code up to and including the section >on lists, but I just cannot understand the last example in that section >named test.py. Are you just reading this, or are you playing interactively with the interpreter as you go along? Reading is good, but I don't think there is a better way than to try to improvise at the python interpreter based on what you read. Few other languages makes it so simple to do that as Python. The problem with *only* reading is that there is no way you can really know how much you learnt. Does it work the way you think, or do you only think you know how it works? You can never know that, unless you try to modify the code to do something different, based on the principles you think you understood, and...fail. You need to push the limits...and get reality checks... Learning programming without really practicing, is like learning electromagnetic fields and waves without doing the exercises properly. I tried that, and the exam result was really humiliating. :) Reading and thinking that you understand just won't cut it. >I understand parts of it, but not all of it as a whole. I'm not able to >follow the flow of the program and whats happening at each step. Maybe I'm >asking too much, but was wondering if anyone could walk me through the >code and whats happening. By the way, I did send an email to Josh asking >this same question, but not sure if I'll hear back or not and thought I'd >ask here just in case. Here it is... Have you tried single-stepping it in a debugger? In IDLE for instance. Start IDLE and load the file in question, Select Debug -> Debugger in the Python shell window to open the "Debug Control", tick the "Source" checkbox, activate the editor window with your source code, and press Ctrl+F5 to start the program. Then use the "Step" button in the Debug Control to advance one code line a at time. This will let you follow the way the code is executed. You will also be able to see the current values of the objects that are in the current local and global (it you choose so) scopes. You might get into other pieces of code during the debugging, at least when the program asks you for a question. At that point you can just press the "Out" button in Debug Control to run until you leave that code. You might also need to manually switch to the Python shell window to be able to answer the question when it's time for that. (If the "Step" button is grey and you don't know understand why you can't continue, it's probably because you have to answer a question. Activate the Python shell window, type your answer followed by pressing the [Enter]-key. (Actually, now that I tried, I eventually got stuck in the debugger. Maybe the debugger needs debugging? Anyway, I had already answered the third question by that time, so I had followed most of the code.) Returning to your woes: What is it you don't understand? We don't want to spend our own and your time explaining things you already know! ;) Do you understand what a function is, and how defining a function is different from calling a function? Do you understand how functions return values? Do you understand the concept of scopes and namespaces? Do you understand the distinction between objects and the names that refer to ojects? Do you understand these questions? ;) >run_test(get_questions()) Do you understand that the above is eqivalent to the code below? questions = get_questions() run_test(questions) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From godoy@ieee.org Wed May 28 19:57:01 2003 From: godoy@ieee.org (Jorge Godoy) Date: Wed May 28 18:57:01 2003 Subject: [Tutor] Handling international characters In-Reply-To: <5.2.1.1.0.20030523024205.01efbff0@www.thinkware.se> ( =?iso-8859-1?q?Magnus_Lyck=E5's_message_of?= "Fri, 23 May 2003 02:44:54 +0200") References: <5.2.1.1.0.20030523024205.01efbff0@www.thinkware.se> Message-ID: Magnus Lyck=E5 writes: > At 10:36 2003-05-21 -0300, Jorge Godoy wrote: >>[['Jorge', 'Godoy'], ['Juliano', 'Godoy'], ['\xc9rica', 'Balaniuc']] > > It allways looks like that in a list. The content of the list is > displayed using the __repr__ method, not the __str__ method. > > Test for yourself if you do something like: > > >>> a =3D 'Ol=E9' > >>> a > 'Ol\xe9' > >>> print a > Ol=E9 > >>> print [a] > ['Ol\xe9'] Is there anyway I can solve/handle that?=20 This is really bugging me for a while. I've tried changing some parameters at site.py but I had no success (I tracked another problem to what I thought was an XML problem, but then with the editing tool that also parses the XML everything works... I don't know what's going on).=20 I would be very grateful if there were some points I could look at or some docs to go after... There's very little related to I18N configuration at Python's website (and googling for 'charset' or 'encoding' is useless since it gets each and every mail message posted to any python list :-)). I think this happens because everything should work properly out of the box... :-) If I were writing software in English it wouldn't bother me :-( [godoy@wintermute ~]$ python Python 2.2.2 (#1, Mar 6 2003, 13:36:19) [GCC 3.2.2] on linux-i386 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.getdefaultencoding() 'ISO8859-1' >>> TIA, --=20 Godoy. From pdg@lucent.com Wed May 28 19:57:16 2003 From: pdg@lucent.com (Dasgupta, Pallavi (Pallavi)) Date: Wed May 28 18:57:16 2003 Subject: [Tutor] Query Message-ID: <6733C768256DEC42A72BAFEFA9CF06D2021DE485@II0015EXCH002U> Hello, How do I get the timestamp using time() in python script? Please give an example. Regards, Pallavi From guido@python.org Wed May 28 19:57:34 2003 From: guido@python.org (Guido van Rossum) Date: Wed May 28 18:57:34 2003 Subject: [Doc-SIG] Re: [Tutor] Documentation concerns. In-Reply-To: "Your message of Sat, 24 May 2003 12:53:54 +0200." <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> Message-ID: <200305241803.h4OI31w27894@pcp02138704pcs.reston01.va.comcast.net> > There is currently a discussion about the Python documentation in > the Tutor mailing list. > > One issue in particular is whether the main documentation for > the module should be in the module itself, rather than in a > separate document. This is a contentious issue that every project has to decide for itself. I personally think that documentation external to the code, while it takes more time to create and maintain, can also be of better quality than documentation maintained as part of the code. I like to see docstrings that serve as comments to the code and at the same time serve as concise reference docs. But every project has its own constraints, and I can certainly understand why some projects prefer to have the full user documentation as docstrings. I expect that such projects will still require some external documentation, e.g. a separate tutorial. > What are the attitudes about this today? In PEP 287 it says: > > "10. Will the docstrings in the Python standard library modules > be converted to reStructuredText? > > No. Python's library reference documentation is maintained separately > from the source. Docstrings in the Python standard library should not > try to duplicate the library reference documentation. The current > policy for docstrings in the Python standard library is that they > should be no more than concise hints, simple and markup-free (although > many do contain ad-hoc implicit markup)." > > Is this still gospel? Any further thoughts around this? This is still gospel for the Python standard library. --Guido van Rossum (home page: http://www.python.org/~guido/) From ianb@colorstudy.com Wed May 28 19:57:52 2003 From: ianb@colorstudy.com (Ian Bicking) Date: Wed May 28 18:57:52 2003 Subject: [Doc-SIG] Re: [Tutor] Documentation concerns. In-Reply-To: <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> Message-ID: <1053804978.1167.49.camel@lothlorien> On Sat, 2003-05-24 at 05:53, Magnus Lyck=E5 wrote: > One issue in particular is whether the main documentation for > the module should be in the module itself, rather than in a > separate document. One issue I see with moving the documentation into the code, is that we don't have any system that can represent the kind of documentation from the standard library as docstrings. Typically documentation created from docstrings is highly (overly) structured, and does not allow items to be introduced in an order different from the code, or presented with a different structure than the code, plus there is no place for narrative that is not connected with a function or class. Ian From lkvam@venix.com Wed May 28 19:58:13 2003 From: lkvam@venix.com (Lloyd Kvam) Date: Wed May 28 18:58:13 2003 Subject: [Tutor] documentation References: Message-ID: <3ED120B4.1090608@venix.com> You are looking for the threading module. There is an older thread module that is used by threading. threading provides a higher-level interface. module-threading.html gives a good description of what it does and how to use it. Lennart Middel wrote: > Hi, I had some trouble finding some documentation about how learn to run > two things at a time in a programm. i thought it was called threads. > Does anyone have an idea where to find this? You can send your reply to > : Lennart_middel@hotmail.com . > > A satishfied python user. > > ------------------------------------------------------------------------ > Tired of spam? Get advanced junk mail protection > with MSN > 8._______________________________________________ Tutor maillist - > Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From guido@python.org Wed May 28 19:58:34 2003 From: guido@python.org (Guido van Rossum) Date: Wed May 28 18:58:34 2003 Subject: [Doc-SIG] Re: [Tutor] Documentation concerns. In-Reply-To: "Your message of Sun, 25 May 2003 16:53:35 -0300." References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> <200305241803.h4OI31w27894@pcp02138704pcs.reston01.va.comcast.net> Message-ID: <200305252037.h4PKbp505168@pcp02138704pcs.reston01.va.comcast.net> Jorge, I think it would be great if every important module's doc string contained a short introduction to its use with an example. Perhaps you can get us started by posting a patch for your favorite module to SF? --Guido van Rossum (home page: http://www.python.org/~guido/) From grubert@users.sourceforge.net Wed May 28 19:58:55 2003 From: grubert@users.sourceforge.net (grubert@users.sourceforge.net) Date: Wed May 28 18:58:55 2003 Subject: [Doc-SIG] Re: [Tutor] Documentation concerns. In-Reply-To: References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> <1053804978.1167.49.camel@lothlorien> Message-ID: a possible split would be: * the module reference is in docstrings * there might be a user manaual for bigger ones * and even a (maybe two) tutorials for large ones. too trivial ? already done ? -- BINGO: pure play b to b in the real world --- Engelbert Gruber -------+ SSG Fintl,Gruber,Lassnig / A6170 Zirl Innweg 5b / Tel. ++43-5238-93535 ---+ From ianb@colorstudy.com Wed May 28 19:59:22 2003 From: ianb@colorstudy.com (Ian Bicking) Date: Wed May 28 18:59:22 2003 Subject: [Doc-SIG] Re: [Tutor] Documentation concerns. In-Reply-To: References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> <1053804978.1167.49.camel@lothlorien> Message-ID: <1053935935.738.15.camel@lothlorien> On Mon, 2003-05-26 at 01:03, grubert@users.sourceforge.net wrote: > a possible split would be: > > * the module reference is in docstrings > * there might be a user manaual for bigger ones > * and even a (maybe two) tutorials for large ones. In a similar One thing I've played with is being able to reference the docstrings, so you can put some reference information in the docstrings, and then inline those into the documentation. I played around with a reST hack that did something like: # module docstring: """ The foo module provides X, Y, and Z, but all functionality is provided through the `Foo` class: .. inline: Foo """ class Foo: """ yada yada. Pay particular attention to the `bar` method. .. inline: bar """ def bar(self): """and so on...""" Another option might be to use such inlining in the external document. Then you can interject narrative, reorder and exclude things, but you avoide duplicate documentation. For another document, I've been using something that strips examples from a script (marked with special comments), and turns them into highlighted source snippets that can be included. Kind of a similar idea. Ian From cben@techunix.technion.ac.il Wed May 28 19:59:43 2003 From: cben@techunix.technion.ac.il (Beni Cherniavsky) Date: Wed May 28 18:59:43 2003 Subject: [Doc-SIG] Re: [Tutor] Documentation concerns. In-Reply-To: <1053935935.738.15.camel@lothlorien> References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> <1053804978.1167.49.camel@lothlorien> <1053935935.738.15.camel@lothlorien> Message-ID: Ian Bicking wrote on 2003-05-26: > On Mon, 2003-05-26 at 01:03, grubert@users.sourceforge.net wrote: > > a possible split would be: > > > > * the module reference is in docstrings > > * there might be a user manaual for bigger ones > > * and even a (maybe two) tutorials for large ones. > > In a similar One thing I've played with is being able to reference the > docstrings, so you can put some reference information in the docstrings, > and then inline those into the documentation. I played around with a > reST hack that did something like: > > # module docstring: > """ > The foo module provides X, Y, and Z, but all functionality is provided > through the `Foo` class: > > .. inline: Foo > """ > > class Foo: > #snipped... > > Another option might be to use such inlining in the external document. > Then you can interject narrative, reorder and exclude things, but you > avoide duplicate documentation. > > For another document, I've been using something that strips examples > from a script (marked with special comments), and turns them into > highlighted source snippets that can be included. Kind of a similar > idea. > Having all info inside the document itself is better because when editing you can see it all. If the docstrings are included later, you might not notice when they change and the documentation can get out of sync. Even if the docstrings and the exrnal doc don't conradict each other, it's harder to ensure that they cover all material without gaps or too much overlap. Of course, it's good practice to render the final documentation and read it from time to time but you woulnd't do it every 2 minutes, right? I think the best solution is to have a tool that includes the docstrings into your source while leaving some markers around it, so that it is idempotent when run upon its own output. Then you can directly edit this output like it would appear at the end but you can sync it to the docstrings at any moment by re-running the tool. Supporting evidence: I'm now working on a reST document that includes examples of logical-order strings and the result of applying the unicode bidi algorithm on them. Doing it manually would be error-prone. So I wrote a python script that leaves all unrecognized text as-is but recomputes the visual-order results from the logical order inputs and bound a key in emacs to filtering the region with it. Now it's extremely convenient because I can see when writing what precisely will the example teach my reader and things can't get out of sync... -- Beni Cherniavsky From ianb@colorstudy.com Wed May 28 20:00:09 2003 From: ianb@colorstudy.com (Ian Bicking) Date: Wed May 28 19:00:09 2003 Subject: [Doc-SIG] Re: [Tutor] Documentation concerns. In-Reply-To: References: <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <013801c32040$9fb80960$6401a8c0@xp> <5.2.0.9.0.20030520062251.027be6e8@66.28.54.253> <5.2.0.9.0.20030521112455.0387da20@66.28.54.253> <5.2.1.1.0.20030523022201.01f05c00@www.thinkware.se> <5.2.1.1.0.20030523223300.01efca58@www.thinkware.se> <5.2.1.1.0.20030524103225.01edd0a8@www.thinkware.se> <1053804978.1167.49.camel@lothlorien> <1053935935.738.15.camel@lothlorien> Message-ID: <1053978376.731.26.camel@lothlorien> On Mon, 2003-05-26 at 04:44, Beni Cherniavsky wrote: > Having all info inside the document itself is better because when > editing you can see it all. If the docstrings are included later, you > might not notice when they change and the documentation can get out of > sync. Even if the docstrings and the exrnal doc don't conradict each > other, it's harder to ensure that they cover all material without gaps > or too much overlap. Of course, it's good practice to render the > final documentation and read it from time to time but you woulnd't do > it every 2 minutes, right? > > I think the best solution is to have a tool that includes the > docstrings into your source while leaving some markers around it, so > that it is idempotent when run upon its own output. Then you can > directly edit this output like it would appear at the end but you can > sync it to the docstrings at any moment by re-running the tool. Like maybe, say: .. inline Foo (stuff taken from Foo's docstring) .. end inline And instead of making this a directive, it is a pre-compiler, where everything between ".. inline Foo" and ".. end inline" is derivative (and so shouldn't be edited, but can be read). Of course, it should support more than just inlining docstrings, as there's already two other examples of inlining that we want to use, and no doubt more are likely. But it is a little crude to use a preprocessor. That seems integral, though, without some sort of powerful IDE that dynamically inlined such documentation. Ian From njensen@utahfirst.com Wed May 28 20:30:02 2003 From: njensen@utahfirst.com (Nick Jensen) Date: Wed May 28 19:30:02 2003 Subject: [Tutor] help on newbie program Message-ID: <544BE8EBDBEE344F96B32750CA5753E9793E22@ufcu_ntes.utahfirst.com> Hello Magnus and thank you for taking time to answer. I should have been more clear on a few things in my email. Sorry about = that. Not only have I read the code and example programs, but I did type = it all out and run the programs on my Linux box. I know I may understand = the code from just reading it, but won't be able to create anything = unless I spend time typing it out fiddling with it. >>Have you tried single-stepping it in a debugger? Actually, I was wondering if there was a way to follow the program line = by line as it executed. I didn't know you could do that and I will = definitely try that now. Thank you for showing me that. I also apologize for not being more specific about what I don't = understand. I think my problem was that I really wasn't sure where to = start explaining what I didn't understand if that makes any sense hehe = =3D). Lets see if I can take a stab at it... I've looked over the program in question time and time again, but I = guess my problem starts with the first line that is executed which is: run_test(get_questions()) I know run_test function is run, but not sure what (get_questions()) is = doing for that. I think it is accessing the lists from the get_questions = function at the beginning, but that is really where I lose track of it.=20 I'm going to try using the debugger right now and see if that helps. I = just simply lose track of what's goin on right off the bat. Its funny = too because I had no problem with the other examples in the tutorial for = lists or functions. Maybe its just a lot more complicated than what I've = seen up till now.=20 At any rate, I'm going to try single-stepping in the debugger and see if = that helps me understand more. Btw, any suggestion for a good book to go through for a python newbie? I = wanted to try some of the online guides first before I spend money, but = will eventually need more material. Thanks for your time... -Nick -----Original Message----- From: Magnus Lyck=E5 [mailto:magnus@thinkware.se] Sent: Wednesday, May 28, 2003 4:45 PM To: Nick Jensen; tutor@python.org Subject: Re: [Tutor] help on newbie program Hi Nick, and welcome to Python. I hope you will enjoy it. It's really a rather amazing tool to make thoughts turn into action. :) A wise man called Fred Brooks wrote about "the joys of the craft" in his book "The Mythical Man-Month" almost 30 years ago. See http://www.davar.net/PROGRAM/EXTRACTS/CRAFTJOY.HTM for his view of why we like programming. At 14:49 2003-05-28 -0600, Nick Jensen wrote: >I have read every example and line of code up to and including the = section=20 >on lists, but I just cannot understand the last example in that section = >named test.py. Are you just reading this, or are you playing interactively with the interpreter as you go along? Reading is good, but I don't think there is a better way than to try to improvise at the python interpreter based on what you read. Few other languages makes it so simple to do that as Python. The problem with *only* reading is that there is no way you can really know how much you learnt. Does it work the way you think, or do you only think you know how it works? You can never know that, unless you try to modify the code to do something different, based on the principles you think you understood, and...fail. You need to push the limits...and get reality checks... Learning programming without really practicing, is like learning electromagnetic fields and waves without doing the exercises properly. I tried that, and the exam result was really humiliating. :) Reading and thinking that you understand just won't cut it. >I understand parts of it, but not all of it as a whole. I'm not able to = >follow the flow of the program and whats happening at each step. Maybe = I'm=20 >asking too much, but was wondering if anyone could walk me through the=20 >code and whats happening. By the way, I did send an email to Josh = asking=20 >this same question, but not sure if I'll hear back or not and thought = I'd=20 >ask here just in case. Here it is... Have you tried single-stepping it in a debugger? In IDLE for instance. Start IDLE and load the file in question, Select Debug -> Debugger in the Python shell window to open the "Debug Control", tick the "Source" checkbox, activate the editor window with your source code, and press Ctrl+F5 to start the program. Then use the "Step" button in the Debug Control to advance one code line a at time. This will let you follow the way the code is executed. You will also be able to see the current values of the objects that are in the current local and global (it you choose so) scopes. You might get into other pieces of code during the debugging, at least when the program asks you for a question. At that point you can just press the "Out" button in Debug Control to run until you leave that code. You might also need to manually switch to the Python shell window to be able to answer the question when it's time for that. (If the "Step" button is grey and you don't know understand why you can't continue, it's probably because you have to answer a question. Activate the Python shell window, type your answer followed by pressing the [Enter]-key. (Actually, now that I tried, I eventually got stuck in the debugger. Maybe the debugger needs debugging? Anyway, I had already answered the third question by that time, so I had followed most of the code.) Returning to your woes: What is it you don't understand? We don't want to spend our own and your time explaining things you already know! ;) Do you understand what a function is, and how defining a function is different from calling a function? Do you understand how functions return values? Do you understand the concept of scopes and namespaces? Do you understand the distinction between objects and the names that refer to ojects? Do you understand these questions? ;) >run_test(get_questions()) Do you understand that the above is eqivalent to the code below? questions =3D get_questions() run_test(questions) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program=20 From magnus@thinkware.se Wed May 28 23:17:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 28 22:17:03 2003 Subject: [Tutor] help on newbie program In-Reply-To: <544BE8EBDBEE344F96B32750CA5753E9793E22@ufcu_ntes.utahfirst .com> Message-ID: <5.2.1.1.0.20030529035621.01ef5018@www.thinkware.se> At 17:26 2003-05-28 -0600, Nick Jensen wrote: >I've looked over the program in question time and time again, but I guess >my problem starts with the first line that is executed which is: > >run_test(get_questions()) > >I know run_test function is run, but not sure what (get_questions()) is >doing for that. I think it is accessing the lists from the get_questions >function at the beginning, but that is really where I lose track of it. I guessed so, and I gave you the answer in my previous reply, but I might take this in some more detail. Just as in mathematical expressions, where a = (5 * (3 + 4)) needs to be worked out from the inside and out, and can be split up like this: temp = 3 + 4 a = 5 * temp If you have a = tan x and b = sin a you can write this as b = sin tan x The same applies for function calls in programs. a = fa() b = fb(a) c = fc(b) can be written like c = fc(fb(fa())) It's not so strange is it? Since a = fa(), fb(a) must be fb(fa()), and since c = fc(b) and b = fb(a) = fb(fa()) c = fc(fb(fa())). Right? Note the diffence between fa and fa(). fa is a function object, and fa() is a call to a function object that will return some kind of object. In other words, you don't feed run_test with the get_question-function, you feed run_test with the *output* from get_question, i.e. the list of questions and answers. The three line version above is probably clearer for the newbie, but if we don't need to use the variables a and b any more, it might save a little memory and possibly time (very little though) to avoid those locals, and just pass the function resules directly to the next function. It also makes the code more compact, and if this means that your program fits in one page of paper instead of two, it might make is easier to grasp the code. In languages like C++, it's often not advisable to write like this even if all readers of the code are experienced and understand it, since it makes it more difficult to see exactly where compilation errors really happen. It might also be useful to be able to see the values of a and b in a debugger. In Python, this is less of an issue. The tracebacks that occur on exceptions, are usually so clear that we can see if the problem is in fa, fb or fc, even if they are on the same row. Also note that python treats all sorts of objects in a very unform way: >>> def myPrint(x): ... print x ... >>> def double(i): ... return i * 2 ... >>> myPrint(double) >>> myPrint(double(4)) 8 >>> myPrint(double('Hello ')) Hello Hello >>> import math >>> myPrint(math) >>> import random >>> myPrint(random) >>> myPrint(myPrint) >>> myPrint(myPrint('Hello')) Hello None -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Wed May 28 23:27:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 28 22:27:03 2003 Subject: [Tutor] Query In-Reply-To: <6733C768256DEC42A72BAFEFA9CF06D2021DE485@II0015EXCH002U> Message-ID: <5.2.1.1.0.20030529042651.01efc9f0@www.thinkware.se> At 14:07 2003-05-23 +0530, Dasgupta, Pallavi (Pallavi) wrote: >Hello, > >How do I get the timestamp using time() in python script? >Please give an example. >>> import time >>> time.time() 1054175047.052 >>> # That's seconds since 1970-01-01 00:00:00 >>> time.asctime() 'Thu May 29 04:24:37 2003' >>> time.localtime() (2003, 5, 29, 4, 24, 43, 3, 149, 1) >>> # Or with mxBase >>> from mx.DateTime import now >>> now() >>> print now() 2003-05-29 04:25:34.76 >>> print now().Format('%m/%d/%Y %H:%M') 05/29/2003 04:26 -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From tompol@hotmail.com Wed May 28 23:38:01 2003 From: tompol@hotmail.com (Tom Brownlee) Date: Wed May 28 22:38:01 2003 Subject: [Tutor] txt document to xml using dom (or sax) Message-ID: hi there, thankyou in advanced for viewing my email and hopefully returning an answer. im looking for code to convert a txt file to an xml document using dom (or minidom) or sax. im a beginner and therefore not familiar with this procedure. ive attempted this but to no avail. i like python, and like other languages, ive learnt more from seeing code and the structure of that code (rather than a blarzay attempt at a blank python script). can you help? thankyou very much. _________________________________________________________________ Need more speed? Get Xtra Jetstream @ http://www.xtra.co.nz/products/0,,5803,00.html ! From magnus@thinkware.se Wed May 28 23:55:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed May 28 22:55:02 2003 Subject: [Tutor] help on newbie program In-Reply-To: <544BE8EBDBEE344F96B32750CA5753E9793E22@ufcu_ntes.utahfirst .com> Message-ID: <5.2.1.1.0.20030529043155.01ef6e50@www.thinkware.se> At 17:26 2003-05-28 -0600, Nick Jensen wrote: >Btw, any suggestion for a good book to go through for a python newbie? I >wanted to try some of the online guides first before I spend money, but >will eventually need more material. It's a long time since I was a newbie... There are certainly some books aiming at beginners. I'd like to hear comments from others. There is Alan Gauld's "Learn to Program using Python" which is aimed at complete beginners. Alan also have a web site at http://www.freenetpages.co.uk/hp/alan.gauld/ So is "How to Think Like a Computer Scientist: Learning with Python" which is also on line at http://www.ibiblio.org/obp/thinkCSpy/ That is a bit more academic than Alans book. For more about Python books, see http://www.thinkware.se/cgi-bin/thinki.cgi/PythonDocs http://www.python.org/cgi-bin/moinmoin/IntroductoryBooks http://gnosis.cx/publish/programming/charming_python_b8.txt http://gnosis.cx/publish/programming/charming_python_b3.txt http://gnosis.cx/publish/programming/charming_python_12.txt and of course http://www.amazon.com/exec/obidos/search-handle-form/ref=s_b_rs/103-1150007-9287854 Anyway, this is becoming a FAQ I think. Maybe we should have a FAQ page somewhere on the web? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From schalla@vasoftware.com Thu May 29 02:02:01 2003 From: schalla@vasoftware.com (shobhan) Date: Thu May 29 01:02:01 2003 Subject: [Tutor] Query In-Reply-To: <6733C768256DEC42A72BAFEFA9CF06D2021DE485@II0015EXCH002U> References: <6733C768256DEC42A72BAFEFA9CF06D2021DE485@II0015EXCH002U> Message-ID: <3ED59544.4010007@vasoftware.com> Dasgupta, Pallavi (Pallavi) wrote:
Hello,

How do I get the timestamp using time() in python script?
Please give an example.
Regards,
Pallavi



  
You can use the standard "time" module included with Python.

#!/usr/bin/python
from time import gmtime, strftime
strftime("%a, %d, %b, %Y %H:%M:%S ", gmtime())

Output -> 'Thu, 29 May 2003 10:16:13"

For more info check the webpage: http://www.python.org/doc/current/lib/module-time.html

Hope this helps
Best Regards,
Schalla

From rmangaliag@slu.edu.ph Thu May 29 04:16:02 2003 From: rmangaliag@slu.edu.ph (ali mangaliag) Date: Thu May 29 03:16:02 2003 Subject: [Tutor] calling the constructor of an inherited class Message-ID: <000801c325b3$c44d9ba0$da19a8c0@slu.edu.ph> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C325F6.CFA0A4A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable class x: def __init__(self, a): self.a =3D a class x(y): def __init__(self): # how can i call the constructor of class x??? thanks... ali ------=_NextPart_000_0005_01C325F6.CFA0A4A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
class x:
    def __init__(self,=20 a):
        = self.a =3D=20 a
 
class x(y):
    def = __init__(self):
        # = how can i=20 call the constructor of class x???
 
thanks...
 
ali
------=_NextPart_000_0005_01C325F6.CFA0A4A0-- From willblake@wanadoo.fr Thu May 29 05:19:02 2003 From: willblake@wanadoo.fr (guillaume) Date: Thu May 29 04:19:02 2003 Subject: [Tutor] help on newbie program In-Reply-To: <5.2.1.1.0.20030529043155.01ef6e50@www.thinkware.se> Message-ID: I'm a newbie and to learn the basis of python I'm reading the Introduction to Python written by Mark Lutz and David Asher. It's a clear book well written -----Message d'origine----- De : tutor-admin@python.org [mailto:tutor-admin@python.org]De la part de Magnus Lycka Envoye : jeudi 29 mai 2003 04:57 A : Nick Jensen; tutor@python.org Objet : RE: [Tutor] help on newbie program At 17:26 2003-05-28 -0600, Nick Jensen wrote: >Btw, any suggestion for a good book to go through for a python newbie? I >wanted to try some of the online guides first before I spend money, but >will eventually need more material. It's a long time since I was a newbie... There are certainly some books aiming at beginners. I'd like to hear comments from others. There is Alan Gauld's "Learn to Program using Python" which is aimed at complete beginners. Alan also have a web site at http://www.freenetpages.co.uk/hp/alan.gauld/ So is "How to Think Like a Computer Scientist: Learning with Python" which is also on line at http://www.ibiblio.org/obp/thinkCSpy/ That is a bit more academic than Alans book. For more about Python books, see http://www.thinkware.se/cgi-bin/thinki.cgi/PythonDocs http://www.python.org/cgi-bin/moinmoin/IntroductoryBooks http://gnosis.cx/publish/programming/charming_python_b8.txt http://gnosis.cx/publish/programming/charming_python_b3.txt http://gnosis.cx/publish/programming/charming_python_12.txt and of course http://www.amazon.com/exec/obidos/search-handle-form/ref=s_b_rs/103-1150007- 9287854 Anyway, this is becoming a FAQ I think. Maybe we should have a FAQ page somewhere on the web? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jim_938@hotmail.com Thu May 29 05:34:02 2003 From: jim_938@hotmail.com (Jimmy verma) Date: Thu May 29 04:34:02 2003 Subject: [Tutor] Re: c to python Message-ID: What if we have a statement like #define ABC 0x0001 in my c struct. I m following like this in python. class AB: def __init__(self): self.a = None self.b = None #statement here ? Thanks a lot. Regards. At 23:04 2003-05-26 +0530, Jimmy verma wrote: I have a structure in c like this struct ab { int a; int b; int *c; struct d *d; } AB; And i am using it in my program like void XYZ(int a , AB *b) How can this kind of structure be translated in python code? It's common to use a tuple in situations where a struct would be used in C. B1 = (a, b, c, d) XYZ(A, B1) The main difference is that you the access stuff in the data structure by position, not by name. def XYZ(A, B): a, b, c, d = B or def XYZ(A, B): a = B[0] b = B[1] c = B[2] d = B[3] If you want to be able to change your "struct" after you create it, but feel ok with positional access instead of access by name, you use a list instead of a tuple. B2 = [0, 0, [], None] B2[0] = 4 B2[1] = 2 B2[2].extend([1,2,3,4,5]) B2[3] = B1 A simple way to get access by name instead is to use a dctionary instead. B3 = {'a': 0, 'b': 0, 'c': [], 'd': None} Fourth, and most similar to C/C++ is to use a class. After all, a struct in C++ is simply a class where attributes are public by default. (As in Python.) Due to the dynamic nature of Python, a class that is just for data storage can be made extremely simple. class N: pass B4 = N() B4.a = 42 B4.b = 6 * 8 B4.c = [1,2,3] B4.d = B3 If you want a little bit more convenience, you might do something like: class AB: def __init__(self, a=0, b=0, c=[], d=None): self.a = a self.b = b self.c = c self.d = d None of the solutions above have any kind of typechecking whatsoever. This is fairly typical in Python programs. Don't make any restrictions that you don't really need. The main reason is that a variable in Python is just a name for an object--any object. In C, a variable is a named location in memory, and it only fits particular data types. Very often, a piece of code can be written so that it works equally well for many different kinds of data, and this is a great strength. For instance: >>>def topTen(seq): ... l = list(seq) ... l.sort() ... return l[:10] ... >>>topTen('asldkfjeorijölkföalksjöalkf') ['a', 'a', 'a', 'd', 'e', 'f', 'f', 'f', 'i', 'j'] >>>topTen([1,2,4,32,5,8,8,5,3,3,5,6,7,56,4,3,8]) [1, 2, 3, 3, 3, 4, 4, 5, 5, 5] >>>topTen([4,3,8]) [3, 4, 8] >>>topTen((1,2,5,87,9,5,4,3,4.23,3.14159)) [1, 2, 3, 3.1415899999999999, 4, 4.2300000000000004, 5, 5, 9, 87] If you do want type checking, you can add that. There are no such things as int* or structs in Python though, so let's imagine that a and b should be integers, c should be a list and d should be an instance of the same class as the one we implement. As you see below, the type checking in Python is much more verbose than in C, but on the other hand, the mechanisms involved are much, much more powerful. >>>class AB(object): ... def __init__(self, a=0, b=0, c=[], d=None): ... self.a = a ... self.b = b ... self.c = c ... self.d = d ... def get_a(self): ... return self.__a ... def set_a(self, a): ... assert isinstance(a, int) ... self.__a = a ... a = property(get_a, set_a, None, '') ... def get_b(self): ... return self.__b ... def set_b(self, b): ... assert isinstance(b, int) ... self.__b = b ... b = property(get_b, set_b, None, '') ... def get_c(self): ... return self.__c ... def set_c(self, c): ... assert isinstance(c, list) ... self.__c = c ... c = property(get_c, set_c, None, '') ... def get_d(self): ... return self.__d ... def set_d(self, d): ... assert d is None or isinstance(d, self.__class__) ... self.__d = d ... d = property(get_d, set_d, None, '') ... >>>ab = AB() >>>ab.a 0 >>>ab.b 0 >>>ab.c [] >>>ab.d >>>print ab.d None >>>ab2 = AB(42, 1984, [1,2,3],ab) >>>ab2.d.d >>>print ab2.d.d None >>>print ab2.d <__main__.AB object at 0x0127AF40> >>>print ab2.a, ab2.b, ab2.c 42 1984 [1, 2, 3] >>>ab3=AB('1', 2, [1,1,], ab2) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __init__ File "", line 10, in set_a AssertionError >>> -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Reconnect with old pals. Relive the happy times. http://www.batchmates.com/msn.asp With just one click. From Don Arnold" Message-ID: <0a7c01c325d0$96639600$9011ba3f@defaultcomp> ----- Original Message ----- From: "ali mangaliag" To: Sent: Thursday, May 29, 2003 2:27 AM Subject: [Tutor] calling the constructor of an inherited class class x: def __init__(self, a): self.a = a class x(y): def __init__(self): # how can i call the constructor of class x??? thanks... ali I believe you meant 'class y(x):' above. Anyway, you call the parent's __init__ just like any other function: class A: def __init__(self,name): self.name=name class B(A): def __init__(self, name, address): ## added address parameter A.__init__(self,name) self.address=address me = B('Don','12345 Main St') print me.name print me.address >>> Don >>> 12345 Main St HTH, Don From jason@museunlimited.com Thu May 29 08:12:41 2003 From: jason@museunlimited.com (Jason Thompson) Date: Thu May 29 07:12:41 2003 Subject: [Tutor] help on newbie program In-Reply-To: References: <5.2.1.1.0.20030529043155.01ef6e50@www.thinkware.se> Message-ID: <20030529071003.2171b9a4.jason@museunlimited.com> Although I spent a little time learning Perl before moving over to Python, I still consider myself to be a newbie. So far I've used most of the books already mentioned by others. For me it has helped to read several books, even moving back and forth between them on particular topics. Each author approaches the information in a unique way and sometimes when I'm stuck on one author's explanation, reading a different author on the topic is really helpful. I've had most of my "light bulb" moments that way. One book that I haven't seen mentioned is Dive Into Python (http://www.diveintopython.org). It's billed as an introduction to Python for experienced programmers but I found it to be the best book I've read on Python so far. Jason From sean@odonnell.nu Thu May 29 12:27:10 2003 From: sean@odonnell.nu (sean@odonnell.nu) Date: Thu May 29 11:27:10 2003 Subject: [Tutor] reading from redirected standard input on windows In-Reply-To: <20030529071003.2171b9a4.jason@museunlimited.com> References: <5.2.1.1.0.20030529043155.01ef6e50@www.thinkware.se> <20030529071003.2171b9a4.jason@museunlimited.com> Message-ID: <1054222405.3ed62845db924@webmail.odonnell.nu> Hi Guys, I'm attempting to write a script than can read redirected input. e.g. if you run echo xxxxxx | testread.py it should be able to read the string xxxxxx. I've tried using stdin , with no sucess , the script still waits for keystrokes. Anyone have any ideas? or know if this is even possible in windows??? Thanks Sean ------------------------------------------------- This mail sent through IMP: http://horde.org/imp/ From magnus@thinkware.se Thu May 29 14:12:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 29 13:12:01 2003 Subject: [Tutor] calling the constructor of an inherited class In-Reply-To: <000801c325b3$c44d9ba0$da19a8c0@slu.edu.ph> Message-ID: <5.2.1.1.0.20030529190907.01f11f48@www.thinkware.se> At 15:27 2003-05-29 +0800, ali mangaliag wrote: >class x: > def __init__(self, a): > self.a = a > >class x(y): > def __init__(self): > # how can i call the constructor of class x??? Don already gave you the answer for old style classes, but for new classes, i.e. classes that inherit from object, or from a built in type such as file or float etc, there is a new function called super. It will determine from what base class to choose the (in this case) __init__ method. This is more important if you use multiple inheritance. See http://www.python.org/doc/2.2.2/whatsnew/whatsnew22.html >>> class A(object): ... def __init__(self): ... print "A constructor" ... >>> class B(A): ... def __init__(self): ... print "B constructor" ... super(B, self).__init__() ... >>> a = A() A constructor >>> b=B() B constructor A constructor -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From njensen@utahfirst.com Thu May 29 14:18:03 2003 From: njensen@utahfirst.com (Nick Jensen) Date: Thu May 29 13:18:03 2003 Subject: [Tutor] help on newbie program Message-ID: <544BE8EBDBEE344F96B32750CA5753E9793E8B@ufcu_ntes.utahfirst.com> >It's a long time since I was a newbie... There are >certainly some books aiming at beginners. I'd like >to hear comments from others. >There is Alan Gauld's "Learn to Program using Python" which >is aimed at complete beginners. Alan also have a web site at >http://www.freenetpages.co.uk/hp/alan.gauld/ >So is "How to Think Like a Computer Scientist: Learning with Python" >which is also on line at http://www.ibiblio.org/obp/thinkCSpy/ >That is a bit more academic than Alans book. >For more about Python books, see >http://www.thinkware.se/cgi-bin/thinki.cgi/PythonDocs >http://www.python.org/cgi-bin/moinmoin/IntroductoryBooks >http://gnosis.cx/publish/programming/charming_python_b8.txt >http://gnosis.cx/publish/programming/charming_python_b3.txt >http://gnosis.cx/publish/programming/charming_python_12.txt >and of course >http://www.amazon.com/exec/obidos/search-handle-form/ref=3Ds_b_rs/103-11= 50007-9287854 >Anyway, this is becoming a FAQ I think. Maybe we should have a >FAQ page somewhere on the web? Sounds like a good idea. ----------------- >I'm a newbie and to learn the basis of python >I'm reading the Introduction to Python written by >Mark Lutz and David Asher. >It's a clear book well written ----------------- >Although I spent a little time learning Perl before moving over to >Python, I still consider myself to be a newbie. So far I've used most = of >the books already mentioned by others.=20 >For me it has helped to read several books, even moving back and forth >between them on particular topics. Each author approaches the >information in a unique way and sometimes when I'm stuck on one = author's >explanation, reading a different author on the topic is really helpful. >I've had most of my "light bulb" moments that way. One book that I >haven't seen mentioned is Dive Into Python >(http://www.diveintopython.org). It's billed as an introduction to >Python for experienced programmers but I found it to be the best book >I've read on Python so far. Guys thanks so much for the feedback about the books. I think I'll read = some reviews about those suggestions on the net and pick up a book this = weekend. It helps to get other people's views... Magnus, I appreciate your explanation about functions. After going over your = examples and then going back over the program again I think I've finally = seen the light =3D). I think two things were hanging me up on this program. One was how the = functions passed info around which you helped me understand. The other = one is that I did not understand how a list within a list works and how = to access information inside of it. I didn't understand indexing for a = list of lists. But I think I finally see the pattern in the program. Let = me explain how I believe it works and see if that is correct. We have faction get_questions. def get_questions(): # notice how the data is stored as a list of lists return [["What color is the daytime sky on a clear day?","blue"],\ ["What is the answer to life, the universe and = everything?","42"],\ ["What is a three letter word for mouse trap?","cat"]] When run_test(get_questions()) is run, the entire list of lists that is = returned from get_questions() is passed back into run_test. So then run_test function is run and the first if statement is false so = it is skipped. Then the while loop is run because it is true. Then we = have >>>if check_question(questions[index]): This is part of what I did not understand, but now I think I do. Index = at this point is 0. So what we have is index 0 of the list which would = be ["What color is the daytime sky on a clear day?","blue"].=20 Then that is put into the check_questions function as = question_and_answer. From there the question is extracted from that = single list and then the answer is extracted as well. That was not = making sense to me at first. I didn't know if index 0 was the first list = or just the first question in the get_questions function. That was = really fowling me up. It seems that you need to extract a list from the = list first and then extract the info inside of that list.=20 Then run_test is run two more times for the other two lists passing them = into check_question each time. Finally the results are computed and printed out in >>>print "You got ",right*100/len(questions),"% right out = of",len(questions) I think my mind just needs conditioning to be able to think like a = programmer. I've been working with computer networks, but never = programming and my brain wants to resist it, but I won't let it win. = =3D) Thanks again for your assistance... -Nick =20 From magnus@thinkware.se Thu May 29 15:08:19 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 29 14:08:19 2003 Subject: [Tutor] help on newbie program In-Reply-To: References: <5.2.1.1.0.20030529043155.01ef6e50@www.thinkware.se> Message-ID: <5.2.1.1.0.20030529191815.01edf548@www.thinkware.se> At 10:21 2003-05-29 +0200, guillaume wrote: >I'm a newbie and to learn the basis of python >I'm reading the Introduction to Python written by >Mark Lutz and David Asher. >It's a clear book well written You mean "Learning Python" I guess. That is a bit old, covering Python 1.5, and for instance it tells you to write stuff like: import string s = "Hello" print string.upper(s) For years now, you have been able to write... s = "Hello" s.upper() ...and the string module might disappear soon. There is a lot that has changed with python since November 1998, when the book was finished. Things like distutils, unicode support, new style classes, generators, the new division scheme, __future__, list comprehension, iterators, nested scopes, augmented assingment, integer and long unification etc etc. See http://www.python.org/doc/2.3b1/whatsnew/ http://www.python.org/doc/2.2.2/whatsnew/ http://www.amk.ca/python/2.1/ http://www.amk.ca/python/2.0/ and http://www.python.org/peps/ "Finished PEPs (done, implemented in CVS)" It might also be useful to look at: http://www.python.org/doc/essays/ppt/regrets/PythonRegrets.pdf Of course, almost everything in Learning Python is still good and true, but some things are deprecated, and a lot of good new stuff is missing. A paper book can never keep up to date with something like Python, but Learning Python needs a 2nd edition that covers 2.3 to stay useful. It's a bit sad to learn stuff, just to unlearn them as we turn to the next book. I think a good newbie book today should ... * Mainly use new style classes, and encourage their use. Old classes should be described since you are likely to run into them, but they should be treated a bit like the old regex module... As legacy code... * Suggest using list comprehension rather than map, filter and lambda. * Encourage use of new features such as nested scopes, new division, etc, even if it means using "from __future__ import". * Forget about the string module and only use string methods. * Explain how to use distutils to install 3rd party modules. * Encourage use of unicode and locale etc. * Skip apply and explain *args and **kwargs instead. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From nixonron@yahoo.com Thu May 29 15:39:02 2003 From: nixonron@yahoo.com (Ron Nixon) Date: Thu May 29 14:39:02 2003 Subject: [Tutor] PDF program Message-ID: <20030529183828.98312.qmail@web20310.mail.yahoo.com> --0-618176499-1054233508=:96620 Content-Type: text/plain; charset=us-ascii I thought I say a Python program that would read and extract text from PDF files. Anyone recall anything on this? Ron --------------------------------- Do you Yahoo!? Free online calendar with sync to Outlook(TM). --0-618176499-1054233508=:96620 Content-Type: text/html; charset=us-ascii
I thought I say a  Python program that would read and extract text from PDF files. Anyone recall anything on this?
 
Ron


Do you Yahoo!?
Free online calendar with sync to Outlook(TM). --0-618176499-1054233508=:96620-- From jciancio@indiana.edu Thu May 29 16:56:53 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Thu May 29 15:56:53 2003 Subject: [Tutor] recursion sort of Message-ID: <200305291955.OAA18672@indiana.edu> Hi all, I'm trying to write a little program on population growth (of anything, say plants). The key is that it's frequency dependent. When the size is large, individuals don't do as well, and then when it's smaller, they do better. also there are 2 'types' of individuals (here called n1 and n2; 'w' is how well they do) Here it is so far: def run(n1, n2): while n1>=501: w=1 n1=n1*w while n1<=500: w=0.2 n1=n1*W while n2>=501: w=0.8 n2=n2*w while n2<=500: w=0.4 n2=n2*W nt=n2+n1 print nt now 2 problems, it is making python freeze again, and I'm sure if I could run it like this it would say n2 is called before it is defined (or something like that) but I don't think I want to put it in the loop, do I? I would also want it to keep measuring nt over time, but I think I can work on that more myself, if I can get around getting it to calculate nt once in the first place. Any suggustions? I hope this isn't too vague. thanks in advance Jen From magnus@thinkware.se Thu May 29 17:09:04 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 29 16:09:04 2003 Subject: [Tutor] Re: c to python In-Reply-To: Message-ID: <5.2.1.1.0.20030529211957.01f60e78@www.thinkware.se> Hi Jimmy, Plese remove all stuff you don't need in your future emails to mailing lists like this one. The mail I'm replying to contained my previous reply for no appearent reason. I don't need to read that once more. (I read it through after I wrote it. ;) At 14:03 2003-05-29 +0530, Jimmy verma wrote: >What if we have a statement like > >#define ABC 0x0001 in my c struct. ABC = 1 ABC = 0x0001 works too, but why? It's just a longwinded way of writing 1. If you prefer 0xA0A0 to 41120, by all means, write that. Note that there are no constants in Python, ABC will be a normal name, that can be reassigned to other objects. It's common that people use the convention that upper case names are for constants though. For attributes in a class, you can use properties as I suggested in my previous mail, and not define any set method. >>> class RO(object): ... def __init__(self, x): ... self.__x = x ... self.__y = 1 ... def get_x(self): ... return self.__x ... def get_y(self): ... return self.__y ... x = property(get_x, None, None, '') ... y = property(get_y, None, None, '') ... >>> a = RO('Magnus') >>> a.x 'Magnus' >>> a.y 1 >>> a.x = 'Mike' Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute >>> a.y = 42 Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute You *can* actually cheat here (which might be good for testing and debugging). >>> a._RO__y = 42 >>> a.y 42 Attributes for class instances with names that begin (but don't end) with __, i.e. double underscores, will get their names mangled so that you need to put an _ followed by the name of the class in front of the attribute do access it externally. So, inside the code of the class, you write for instance self.__y, and outside it might be a._RO__y. This is as close to "private" attributes that you get in Python. It's like locking the door and putting the key on a clearly visible hook next to the door. Noone will enter the locked door by mistake. It's clear that you *shouldn't* enter. If you must, you can though. As I said, this is useful for debugging and testing, but should only be used in production code in exceptional cases. One key idea in Python is to trust the programmers judgement. Make it easy to do things right, and make it clear what is discouraged practice, but don't try to stop a programmer that is convinced that he has to bend the rules. Instead, try to make it possible for all programmers to do what they need to do without jumping through too many loops. A lot of C++ and Java code out in real life is very contrieved because it tries to get around the language designers idea about how things ought to be done. If we compare programming languages with cars, Java is like a car that has its speed electronically blocked so that it can't exceed the current speed limit. Python is like a car with electronics that will turn on the warning blinkers and honk the horn if you exceed the speed limit. Which car would you rather drive in an emergency? Sometimes it's useful to be able to break the rules, but by all means, let is be clear that we're cheating... It's bad if we start to cheat without being aware of it. But noone will write a._RO__y by accident... I honestly find it strange that other programming languages have the police state view on this, rather than the trusting but clarifying view of Python. After all, if we can't trust that the programmer will do what he can to avoid bad practice if it's clearly pointed out to him, how can we trust him to implement important algorithms, and write any code at all? After all, it's much harder to write a program that actually does what it's supposed to do, than to write one that simply compiles and runs without errors. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dana@pixelenvy.ca Thu May 29 17:12:01 2003 From: dana@pixelenvy.ca (Dana Larose) Date: Thu May 29 16:12:01 2003 Subject: [Tutor] recursion sort of In-Reply-To: <200305291955.OAA18672@indiana.edu> Message-ID: On Thu, 29 May 2003, Jennifer Cianciolo wrote: > Hi all, > > I'm trying to write a little program on population growth (of > anything, say plants). The key is that it's frequency dependent. > When the size is large, individuals don't do as well, and then when > it's smaller, they do better. also there are 2 'types' of individuals > (here called n1 and n2; 'w' is how well they do) > > Here it is so far: > > def run(n1, n2): > while n1>=501: > w=1 > n1=n1*w Hmmm. This will cause an infinite loop everytime n1 greater than 500. You see, you aren't changing the value of n1. If n1 = 600, your code will set n1 = n1 * w. You're setting w = 1 everytime through the loop, you are effectively doing this: n1 = n1 > while n1<=500: > w=0.2 > n1=n1*W Is the capital W a type? > while n2>=501: > w=0.8 > n2=n2*w > while n2<=500: > w=0.4 > n2=n2*W > nt=n2+n1 > print nt > > now 2 problems, it is making python freeze again, and I'm sure if I > could run it like this it would say n2 is called before it is defined > (or something like that) but I don't think I want to put it in the > loop, do I? It shouldn't, you're passing n2 as one of the function paraeters. > I would also want it to keep measuring nt over time, but I think I can > work on that more myself, if I can get around getting it to calculate > nt once in the first place. > dana. From magnus@thinkware.se Thu May 29 17:39:10 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 29 16:39:10 2003 Subject: [Tutor] reading from redirected standard input on windows In-Reply-To: <1054222405.3ed62845db924@webmail.odonnell.nu> References: <20030529071003.2171b9a4.jason@museunlimited.com> <5.2.1.1.0.20030529043155.01ef6e50@www.thinkware.se> <20030529071003.2171b9a4.jason@museunlimited.com> Message-ID: <5.2.1.1.0.20030529223204.01f0e2d8@www.thinkware.se> At 16:33 2003-05-29 +0100, sean@odonnell.nu wrote: >I'm attempting to write a script than can read redirected input. > >e.g. if you run > >echo xxxxxx | testread.py > >it should be able to read the string xxxxxx. > >I've tried using stdin , with no sucess , the script still waits >for keystrokes. Anyone have any ideas? or know if this is even possible in >windows??? In MS Windows this won't work, since the default mechanism for connecting extensions to programs doesn't handle pipes. You have to write: echo xxxxxx | python.exe testread.py If you desperately want it to work as it *should* in Windows, use bash instead of cmd.exe/command.com. If you have echo on your computer you might have a real shell as well... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From mfarnham@acm.org Thu May 29 17:49:26 2003 From: mfarnham@acm.org (Michael Farnham) Date: Thu May 29 16:49:26 2003 Subject: [Tutor] recursion sort of In-Reply-To: <200305291955.OAA18672@indiana.edu> References: <200305291955.OAA18672@indiana.edu> Message-ID: <200305291548.59957.mfarnham@acm.org> On Thursday 29 May 2003 14:55, Jennifer Cianciolo wrote: > Hi all, > > def run(n1, n2): > while n1>=501: > w=1 > n1=n1*w As Dana stated this is an infinite loop because n1 does not change. If n1 starts out >= 501 then this loop is entered and it never exits. > while n1<=500: > w=0.2 > n1=n1*W Assuming that the capital W is a typo as suggested by Dana, this is also an infinite loop. If n1 is <= 500 then this loop is entered and n1 is multiplied by 0.2. Therefore n1 becomes smaller each time through the loop and the loop is never exited. > while n2>=501: > w=0.8 > n2=n2*w This loop is OK. If n2 is >= 501 this loop is entered. n2 is multiplied by 0.8, which makes n2 smaller. So at some point n2 will be > 501 and the loop will be exited. > while n2<=500: > w=0.4 > n2=n2*W Again assuming that the capital W is a typo this is another infinite loop. This loop is entered when n2 <= 500. It is then multiplied by 0.4 which makes it smaller. Therefore n2 will never be > 500 and the loop will never exit. > nt=n2+n1 > print nt > I do not know what this algorithm is supposed to do but this does not look right. For example suppose that n2 = 600. The while n2 >= 501 loop is entered and n2 is assigned 480 (0.8 * 600). Since n2 is now <= 500 the second loop is also entered. I would think that these two loops should be mutually exclusive. Maybe they should not even be loops but if then else constructs. However it is your algorithm and you know it better than I do HTH Mike Farnham -- You've got to be honest; if you can fake that, you've got it made. -- George Burns From magnus@thinkware.se Thu May 29 17:55:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 29 16:55:02 2003 Subject: [Tutor] PDF program In-Reply-To: <20030529183828.98312.qmail@web20310.mail.yahoo.com> Message-ID: <5.2.1.1.0.20030529224337.01f50aa0@www.thinkware.se> At 11:38 2003-05-29 -0700, Ron Nixon wrote: >I thought I say a Python program that would read and extract text from >PDF files. Anyone recall anything on this? You don't know what you say? ;) The best tools for working with PDF from Python are probably ReportLab's, www.reportlab.com. The free ReportLab Toolkit is great at creating PDF file, but I don't think it can read them. Their PageCatcher product can certainly add stuff to existing PDF files (like fill in forms) and I think it can extract info as well. PageCatcher isn't cheap though, but have a look at their site. You can download all their stuff for evaluation at least. PreScript http://www.nzdl.org/html/prescript.html can get text from PostScript files, and I suppose you can convert PDF to PS. It uses GhostScript, which can read PDF these days, so maybe it's worth taking a look at that. Adobe has a rather poor online tool at http://www.adobe.com/products/acrobat/access_onlinetools.html and I assume you could make a Python wrapper for that if you have online access and can live with the quality. (Fails on non-ascii characters it seems.) The file I tried was *not* created with Adobes tools though, but with pdflatex. Maybe it handles their own files better... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dyoo@hkn.eecs.berkeley.edu Thu May 29 18:02:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 29 17:02:02 2003 Subject: [Tutor] PDF program [pdftotext] In-Reply-To: <20030529183828.98312.qmail@web20310.mail.yahoo.com> Message-ID: On Thu, 29 May 2003, Ron Nixon wrote: > I thought I say a Python program that would read and extract text from > PDF files. Anyone recall anything on this? Hi Ron, (If anyone finds an alternative to the solution below, I'd be very very interested in this, as my work depends on doing this sort of stuff too! *grin*) The 'pdfsearch' project, http://pdfsearch.sourceforge.net/ uses the Unix utility 'pdftotext' as its backend to pull text out of these files. pdftotext is part of the 'xpdf' package: http://www.foolabs.com/xpdf/download.html It wouldn't be too hard to write a Python wrapper around pdftotext. Here's a sketch of a kind of wrapper: ### def extractPdfText(filename): return os.popen("pdftotext '%s' -" % filename).read() ### This isn't complete or foolproof, but it should be a good start. Good luck to you! From magnus@thinkware.se Thu May 29 18:07:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 29 17:07:02 2003 Subject: [Tutor] recursion sort of In-Reply-To: <200305291955.OAA18672@indiana.edu> Message-ID: <5.2.1.1.0.20030529230211.01f50490@www.thinkware.se> At 14:55 2003-05-29 -0500, Jennifer Cianciolo wrote: >def run(n1, n2): > while n1>=501: > w=1 > n1=n1*w > while n1<=500: > w=0.2 > n1=n1*W > while n2>=501: > w=0.8 > n2=n2*w > while n2<=500: > w=0.4 > n2=n2*W > nt=n2+n1 > print nt Is this a school assignment? It would be helpful if you would be clear in stating such things so that we know how to respond. We're not supposed to do your assignments for you... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Thu May 29 18:20:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 29 17:20:02 2003 Subject: [Tutor] txt document to xml using dom (or sax) In-Reply-To: Message-ID: <5.2.1.1.0.20030529231642.01f2f260@www.thinkware.se> At 14:36 2003-05-29 +1200, Tom Brownlee wrote: >im looking for code to convert a txt file to an xml document using dom (or >minidom) or sax. Look here: http://xml.coverpages.org/xmlPython.html -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dyoo@hkn.eecs.berkeley.edu Thu May 29 18:43:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 29 17:43:02 2003 Subject: [Tutor] recursion sort of [use math when you need it!] In-Reply-To: Message-ID: On Thu, 29 May 2003, Dana Larose wrote: > On Thu, 29 May 2003, Jennifer Cianciolo wrote: > > > Hi all, > > > > I'm trying to write a little program on population growth (of > > anything, say plants). The key is that it's frequency dependent. When > > the size is large, individuals don't do as well, and then when it's > > smaller, they do better. also there are 2 'types' of individuals > > (here called n1 and n2; 'w' is how well they do) Hi Jennifer, When we run into infinite loops, our suspicious should point immediately to any while loops and their conditions. In the program, there appear to be a few while loops, so each one needs to be checked and guaranteed to terminate: > > while n1>=501: > > w=1 > > n1=n1*w The key expression here that needs to be looked at is: n1 >= 501 Is there anything in the body of this loops that guarantees that n1 will ever get larger than 501? If we have 501 sterile and immortal bunnies, will we ever have fewer than 501 bunnies in the future? By thew way: it's relatively easy to code up a population-prediction program by using while loops, but they're not always the most appropriate way of doing things. Have you considered using a math equation here? You should be able to define a set of equations that should tell you, at any given point, what the population of the system is. Let P(n) stand for the size of our population at time 'n'. Let P(0), then, stand for the initial population. It sounds like every subsequent growth in the population is proportional to the previous population. In formal math language, we'd say: P(n + 1) = P(n) * some constant of growth And if we want to be more terse and mysterious, we can use the letter C to stand for "some constant of growth". P(n + 1) = P(n) * C If we have these relationships stated, we can play around with them to see what they mean. If we're trying to find the population at time 1, P(1) we can see that: P(1) = P(0) * C from the relationship that we defined above about the population being proportional to the previous population. That's immediate enough. How about P(2)? P(2) = P(1) * C = (P(0) * C) * C = P(0) * (C**2) How about P(3)? What about P(4)? What about P(100)? If you do this by hand, you should see some sort of pattern here. And once you see the pattern, you should be able calculate P(n) for any n, without any loops. The reason why this is nice is because if we can define a function that relates population size to n, we can rearrange the equation so that, given a desired population size, we can calculate what 'n' needs to be to make that happen. I guess I'm trying to say: try to do the problem without computers first. I think you're looking too closely at the while loop syntax, and not really seeing what you're actually computing. Doing a few computations on scratch paper will help you get a better handle on what the problem is really about. I hope this helps! From dyoo@hkn.eecs.berkeley.edu Thu May 29 18:49:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 29 17:49:02 2003 Subject: [Tutor] import (fwd) Message-ID: Hi Vernon, tutor-admin@python.org is an address for administrative questions only, and it only reaches maybe two or three grumpy people... *grin* I'm forwarding this to tutor@python.org, which is where the main discussion lives. Please use 'tutor@python.org' next time. ---------- Forwarded message ---------- Date: Wed, 28 May 2003 18:44:40 -0700 From: Vernon Miller To: tutor-admin@python.org Subject: import Last night as I went through the easytut written by Alan Gauld I had to go back and import the three classes BankAccount, InterestAccount, and Charging Account after each part of the exercise. Is it normal to import a class or Module and after running a couple of lines to have to go back and re- import the classes. What happened is this; "I imported the BankAccount class and added two accounts" a = BankAccount(500) b = BankAccount(200 a.withdraw(100) b.transfer(100) " then I went to the command line and imported InterestAccount, but when I type c = InterestAccount(1000) at the command line I got the error message "BankAccount' is not defined" It did the same thing when I went on down to the next class ChargingAccount. Yet both worked fine if at the beginning of each transaction I went back to the command line and first imported the classes as follows: from BankAccount import * from InterestAccount import * from ChargingAccount import * ; is it normal to have to stop each time you import a new module or class to have to go back and re-import(if there is any such word) each class or module that you had previously used in the program. Help Please Vernon vvernon@earthlink.net From jpollack@socrates.Berkeley.EDU Thu May 29 19:21:37 2003 From: jpollack@socrates.Berkeley.EDU (Joshua Pollack) Date: Thu May 29 18:21:37 2003 Subject: [Tutor] random variable generation Message-ID: <3ED686F6.1AF83FE8@socrates.berkeley.edu> This is a multi-part message in MIME format. --------------93ED7717CE21FDC28B1CEB78 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Some time ago I was working on a migration simulation and am picking it up again, but I'm having some trouble with the use of RandomArray.binomial. I've written a function to choose a random variable based on the length of a list and an explicitly specified probability of success. I run the function and then do the exact same thing outside of the function call. Problem is, I keep getting the exact same Random Variable from the function call everytime I run it. [jpollack@mws5 Arctic]$ python migrator.py [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] 2 10 0.1 <-- function calll 1 10 0.1 <-- non function call [jpollack@mws5 Arctic]$ python migrator.py [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] 2 10 0.1 <-- function call 1 10 0.1 <-- nonfunction call [jpollack@mws5 Arctic]$ python migrator.py [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] 2 10 0.1 2 10 0.1 [jpollack@mws5 Arctic]$ python migrator.py [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] 2 10 0.1 0 10 0.1 [jpollack@mws5 Arctic]$ python migrator.py [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] 2 10 0.1 0 10 0.1 etc... I've attached the code. I think the problem maybe with the seeding. I've looked at the RandomArray seed specifications and played around a bit, but can't find anything that solves the problem. I admit, I don't understand the process of seeding all that well though. If anyone has any ideas on how to fix this, let me know. Thanks, Josh -- Joshua Pollack Graduate Student, Slatkin Lab 4151 VLSB Department of Integrative Biology University of California-Berkeley jpollack@socrates.berkeley.edu --------------93ED7717CE21FDC28B1CEB78 Content-Type: text/plain; charset=us-ascii; name="migrator.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="migrator.py" import random,RandomArray x=[[1]*10] print x migrationrate=.1 ## define a function to generate a binomial random variable with parameters = list length and migration rate def migration(list): nummigrants = RandomArray.binomial(len(list[0]) , migrationrate) print nummigrants , len(list[0]) , migrationrate migration(x) ## Do the same thing as my function, outside of a function call nummig2 = RandomArray.binomial(len(x[0]) , migrationrate) print nummig2 , len(x[0]) , migrationrate --------------93ED7717CE21FDC28B1CEB78-- From dyoo@hkn.eecs.berkeley.edu Thu May 29 19:48:09 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 29 18:48:09 2003 Subject: [Tutor] recursion sort of [and use functions when you need them! *grin*] In-Reply-To: Message-ID: > You should be able to define a set of equations that should tell you, at > any given point, what the population of the system is. > > Let P(n) stand for the size of our population at time 'n'. > > Let P(0), then, stand for the initial population. > > > It sounds like every subsequent growth in the population is proportional > to the previous population. In formal math language, we'd say: > > P(n + 1) = P(n) * some constant of growth > > > And if we want to be more terse and mysterious, we can use the letter C > to stand for "some constant of growth". > > P(n + 1) = P(n) * C Just to mention, though: in your problem, C itself actually constant, because it too depends on population size. If the population size is too large, then C changes to penalize overpopulation, and rewards underpopulation. That seems slightly simplistic, but oh well... maybe an extended version of the problem will use a predator-prey model, where the two populations effect each other. One can hope. *grin* Anyway, in that case, the relationship above needs to account for changes in the condition of our population. In math, we'd say: P(0) = Initial population P(n + 1) = --- | [fill me in] if P(n) is not overpopulated, | [fill me in] otherwise. --- (Jennifer has to do SOME work here... *grin*) It's essential to capture this as an equation --- a function --- and not just as a set of disconnected statements. Once we've defined P clearly, it's not too difficult to write an equivalent P(n) in Python. And once we have two functions that tell us what the first and second populations look like, at any given time, then we're able to do more interesting things, like calculating the sum of the two populations. The key is not to try to write everything in terms of a bunch of while loops, but to define the problem in terms of simple functions. Functions are essential here: they insulate us from what might otherwise be a complicated process. Hope this helps! From alan.gauld@blueyonder.co.uk Thu May 29 20:10:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Thu May 29 19:10:01 2003 Subject: [Tutor] Re: c to python References: Message-ID: <005101c32637$124e8b60$6401a8c0@xp> > What if we have a statement like > > #define ABC 0x0001 in my c struct. First thing to remember is that #define is really an instruction to the C preprocessor to textually substitute 0x0001 everytime you type ABC in a source file. Its not really a language issue. In particular since ANSI C introduced the const statement these kind of #defines should be considered deprecated. So looking at the issue of how we would represent const int ABC=0x0001; in Python, the most common technique is simply to define a variable: ABC = 0x0001 or just ABC = 1 Then use it as usual (The uppercase name is just a convention originating in C's similar convention for #defines) In a bigger program you might like to put all such constants in a module, in which case you can then do: import consts print consts.ABC > I m following like this in python. > > class AB: > def __init__(self): > self.a = None > self.b = None > #statement here ? Or yes, you could put the constants in a class. Inwhich case you just add a line self.ABC = 1 And access it as: ab = AB() print ab.ABC HTH, Alan G. From alan.gauld@blueyonder.co.uk Thu May 29 20:14:20 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Thu May 29 19:14:20 2003 Subject: [Tutor] reading from redirected standard input on windows References: <5.2.1.1.0.20030529043155.01ef6e50@www.thinkware.se> <20030529071003.2171b9a4.jason@museunlimited.com> <1054222405.3ed62845db924@webmail.odonnell.nu> Message-ID: <005a01c32637$e65b5d70$6401a8c0@xp> > echo xxxxxx | testread.py you need to explicitly call python, thus: Alan Gauld@XP ~ $ cat > testread.py text = raw_input('?') print 'I read ', text Alan Gauld@XP ~ $ echo fooey|python testread.py ?I read fooey works OK. (Note the above is using the cygwin Bash shell so really is on Windows despite appearances!) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@blueyonder.co.uk Thu May 29 20:31:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Thu May 29 19:31:02 2003 Subject: [Tutor] help on newbie program References: <5.2.1.1.0.20030529043155.01ef6e50@www.thinkware.se> <5.2.1.1.0.20030529191815.01edf548@www.thinkware.se> Message-ID: <000301c3263a$66371370$6401a8c0@xp> I'm hoping to do a second edition of my book sometime. Interestingly my wishlist is similar to Magnus': > I think a good newbie book today should ... > * Mainly use new style classes, and encourage their use. Old classes > should be described since you are likely to run into them, but they > should be treated a bit like the old regex module... As legacy code... > * Suggest using list comprehension rather than map, filter and lambda. I'd cerainly do comprehensions, but I still prefer map and especially filter for many things - I think the names and syntax are more readable. As for lambda, my book teaches general programming principles and lambdas are so important that I couldn'yt possibly miss them out(even tho in Python they are purely cosmetic). The principle appears in lots ofllanguages, you need to know about the concept of anonymous functions and executable code blocks... > * Encourage use of new features such as nested scopes, new division, > etc, even if it means using "from __future__ import". Agree the first bit but I'm always wary of the __future__ stuff. > * Forget about the string module and only use string methods. > * Explain how to use distutils to install 3rd party modules. Just as soon as I figure out how to use distutils myself! :-) > * Encourage use of unicode and locale etc. I really should... being an native English speaker I get lazy... :-) > * Skip apply and explain *args and **kwargs instead. Agreed. The changes will appear on the Web site towards the end of this year I hope... Part of an update to 2.3 and along with a few more topics (eg. using OS facilities and basic web programming...) There you go, I've made it public so I'm committed now! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From magnus@thinkware.se Thu May 29 20:42:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu May 29 19:42:02 2003 Subject: [Tutor] recursion sort of In-Reply-To: <200305291955.OAA18672@indiana.edu> Message-ID: <5.2.1.1.0.20030530005234.00ba5c38@www.thinkware.se> Sorry about my previous comment. Jennifer is obviously one of the many clever researchers who discover what a useful tool Python is. For more about Python and science, I have some links at http://www.thinkware.se/cgi-bin/thinki.cgi/PythonInScience At 14:55 2003-05-29 -0500, Jennifer Cianciolo wrote: >I'm trying to write a little program on population growth (of >anything, say plants). The key is that it's frequency dependent. >When the size is large, individuals don't do as well, and then when >it's smaller, they do better. also there are 2 'types' of individuals >(here called n1 and n2; 'w' is how well they do) The code below is obviously not not doing what you intended, and since the code it what you showed us, we don't know what you *did* intend! :) What did you expect to happen? Can you describe in words what you are trying to achieve? By the way, a useful (but rather primitive) way to get more grips on what is happening in the code is to put print statements at good points in the code. >>> def x(n): ... while n > 0.1: ... n = n / 2. ... print n ... >>> x(3) 1.5 0.75 0.375 0.1875 0.09375 It's obviously much easier to understand what's happening here than if you don't have the print... Another option, which is more powerful, but perhaps a little more complicated is to use a debugger as I described some time ago: http://mail.python.org/pipermail/tutor/2003-May/022724.html >Here it is so far: > >def run(n1, n2): > while n1>=501: > w=1 > n1=n1*w > while n1<=500: > w=0.2 > n1=n1*W > while n2>=501: > w=0.8 > n2=n2*w > while n2<=500: > w=0.4 > n2=n2*W > nt=n2+n1 > print nt > >now 2 problems, it is making python freeze again, It's not freezing, it's running like---well somewhere hot... Unfortunately the same three lines are running over and over and over. It seems you have described a population that has no hope... Maybe you had something like this in mind? >>> def run(n1, n2, x): ... for i in range(x): ... print "Round", i, ... if n1 > 500: ... pass # Might as well do nothing as multiply with 1 ... else: ... n1 *= 0.2 ... print 'n1:', n1, ... if n2 > 500: ... n2 *= 0.8 ... else: ... n2 *= 0.4 ... print 'n2:', n2, ... print 'nt:', n1 + n2 ... >>> run(600, 600, 5) Round 0 n1: 600 n2: 480.0 nt: 1080.0 Round 1 n1: 600 n2: 192.0 nt: 792.0 Round 2 n1: 600 n2: 76.8 nt: 676.8 Round 3 n1: 600 n2: 30.72 nt: 630.72 Round 4 n1: 600 n2: 12.288 nt: 612.288 >>> run(400, 400, 5) Round 0 n1: 80.0 n2: 160.0 nt: 240.0 Round 1 n1: 16.0 n2: 64.0 nt: 80.0 Round 2 n1: 3.2 n2: 25.6 nt: 28.8 Round 3 n1: 0.64 n2: 10.24 nt: 10.88 Round 4 n1: 0.128 n2: 4.096 nt: 4.224 >>> run(400, 600, 5) Round 0 n1: 80.0 n2: 480.0 nt: 560.0 Round 1 n1: 16.0 n2: 192.0 nt: 208.0 Round 2 n1: 3.2 n2: 76.8 nt: 80.0 Round 3 n1: 0.64 n2: 30.72 nt: 31.36 Round 4 n1: 0.128 n2: 12.288 nt: 12.416 >>> run(600, 400, 5) Round 0 n1: 600 n2: 160.0 nt: 760.0 Round 1 n1: 600 n2: 64.0 nt: 664.0 Round 2 n1: 600 n2: 25.6 nt: 625.6 Round 3 n1: 600 n2: 10.24 nt: 610.24 Round 4 n1: 600 n2: 4.096 nt: 604.096 >>> "x *= y" is a shorthand for "x = x * y". (Actually, I have recently learnt that this isn't always exactly true, but it's at least true from all practical aspects if x and y are numbers.) When you use a while-loop, the indented lines following the while statement will be repeatedly executed until the condition between "while" and ":" is not true. Nothing else will happen in the program during this time. A Python program is only in one place at a time. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From nixonron@yahoo.com Thu May 29 21:47:02 2003 From: nixonron@yahoo.com (Ron Nixon) Date: Thu May 29 20:47:02 2003 Subject: [Tutor] PDF program [pdftotext] In-Reply-To: Message-ID: <20030530004626.98968.qmail@web20309.mail.yahoo.com> --0-492612706-1054255586=:98904 Content-Type: text/plain; charset=us-ascii Thanks to all who responded on my question about Python and PDF files. Once again the list has proved its value. Ron Danny Yoo wrote: On Thu, 29 May 2003, Ron Nixon wrote: > I thought I say a Python program that would read and extract text from > PDF files. Anyone recall anything on this? Hi Ron, (If anyone finds an alternative to the solution below, I'd be very very interested in this, as my work depends on doing this sort of stuff too! *grin*) The 'pdfsearch' project, http://pdfsearch.sourceforge.net/ uses the Unix utility 'pdftotext' as its backend to pull text out of these files. pdftotext is part of the 'xpdf' package: http://www.foolabs.com/xpdf/download.html It wouldn't be too hard to write a Python wrapper around pdftotext. Here's a sketch of a kind of wrapper: ### def extractPdfText(filename): return os.popen("pdftotext '%s' -" % filename).read() ### This isn't complete or foolproof, but it should be a good start. Good luck to you! --------------------------------- Do you Yahoo!? Free online calendar with sync to Outlook(TM). --0-492612706-1054255586=:98904 Content-Type: text/html; charset=us-ascii
Thanks to all who responded on my question about Python and PDF files. Once again the list has proved its value.
 
Ron

Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:


On Thu, 29 May 2003, Ron Nixon wrote:

> I thought I say a Python program that would read and extract text from
> PDF files. Anyone recall anything on this?


Hi Ron,


(If anyone finds an alternative to the solution below, I'd be very very
interested in this, as my work depends on doing this sort of stuff too!
*grin*)


The 'pdfsearch' project,

http://pdfsearch.sourceforge.net/


uses the Unix utility 'pdftotext' as its backend to pull text out of these
files. pdftotext is part of the 'xpdf' package:

http://www.foolabs.com/xpdf/download.html


It wouldn't be too hard to write a Python wrapper around pdftotext.
Here's a sketch of a kind of wrapper:


###
def extractPdfText(filename):
return os.popen("pdftotext '%s' -" % filename).read()
###

This isn't complete or foolproof, but it should be a good start.



Good luck to you!


Do you Yahoo!?
Free online calendar with sync to Outlook(TM). --0-492612706-1054255586=:98904-- From rmangaliag@slu.edu.ph Fri May 30 04:44:02 2003 From: rmangaliag@slu.edu.ph (ali mangaliag) Date: Fri May 30 03:44:02 2003 Subject: [Tutor] calling the constructor of an inherited class References: <000801c325b3$c44d9ba0$da19a8c0@slu.edu.ph> <0a7c01c325d0$96639600$9011ba3f@defaultcomp> Message-ID: <00e001c32680$e3f72480$da19a8c0@slu.edu.ph> > I believe you meant 'class y(x):' above. Anyway, you call the parent's > __init__ just like any other function: thanks for the correction... got it... thanks again.. > class A: > def __init__(self,name): > self.name=name > > class B(A): > def __init__(self, name, address): ## added address parameter > A.__init__(self,name) > self.address=address > > me = B('Don','12345 Main St') > > print me.name > print me.address > > >>> Don > >>> 12345 Main St > > HTH, > Don > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From jciancio@indiana.edu Fri May 30 09:06:01 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Fri May 30 08:06:01 2003 Subject: [Tutor] recursion sort of In-Reply-To: <5.2.1.1.0.20030530005234.00ba5c38@www.thinkware.se> Message-ID: <200305301205.HAA15233@indiana.edu> ------------------- > Sorry about my previous comment. Jennifer is obviously one > of the many clever researchers who discover what a useful > tool Python is. :) no problem! (I just wrote this email and I think it didn't go, so sorry if it's coming twice). It had been a while since I'd eaten, and for me, low blood sugar = over-react to silly things like email. I see how it could have looked like homework. I worked on the problem and changed it a lot yesterday before I got the responses (then went home), so I just printed them all out and will see where I get today... thanks a million to for the help! it's really something Jen From jciancio@indiana.edu Fri May 30 13:32:03 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Fri May 30 12:32:03 2003 Subject: [Tutor] Jen's not recursion and a long explaination In-Reply-To: <5.2.1.1.0.20030530005234.00ba5c38@www.thinkware.se> Message-ID: <200305301631.LAA06738@iupui.edu> Hi again all, I've looked through all the suggestions people sent, and I think my main question is whether I should keep stuggling with this, or go back to trying to learn more about programming in first place! I gave up because (I'm pretty impatient) (hence my hastily trying to write this program that didn't make any sense; although I did try for about four hours yesterday) the tutorial I was using (How do think like a computer scientist) got into all kinds of things I imagine I'll never use. all kinds of string things mostly. I'm only interested in using this for mathematical modeling. So I stopped, but I'm sure I don't know enough (I didn't know 'pass' for example!). Here's more on what I was doing before and trying to do; this is pretty long, so don't read it if you're not interested! The equation P(2) = P(1) * C (etc) is the basic discrete exponential growth model in ecology (C is lamda)! But that's not really what I'm after. here's some hand waving... It's a quick and dirty, simplistic intro to evolution. I'm interested in the evolutionary mantenance of biparental reproduction (otherwise known as sex, but by that I don't mean copulation, although it's certainly a related issue!). When we look at a trait in evolution we evaluate it's costs and benifits. Costs are things that make genes (basically) less likely to get passed on. Benifits... more likely. If an organim gets thirsty when it's cells are running out of water and another doesn't, our first organsim will (presumably, this is a probablity) produce more offspring than the second, and those babies will get thirsy when they need to, and before we know it, everybody's thirsy when they need to be (oversimplification, yes). Take bacterial resistance to antibiotics. If you remove the antibiotic, the bacteria WITHOUT the resistance gene should do better, because the resistance gene exacts some energetic cost. So for natural selection to work, we need variation in the population (otherwise how can there be change), that variation must be heritable, and there must be differential reproductive success based on the abilty of that variation to affect the differential reproduction in the present environment. If this change happens by accident (say all the organisms with 'p' type genes disappear in an earthquake) this is still evolution, just not evolution by natural selection (it's basically sampling error; we call it genetic drift). ANYWAY, the big problem with sex is that is SO costly. If an asexual female arises in a population due to mutation (a very possible and regular thing) that female has a TWO-FOLD reproductive advantage - for every female (or reproducing individual) produced by a sexual female, this asexual produces two females! (this is known as the cost of males ;) there's also a cost of meiosis...). So since sex is so prevalent, it must have a two-fold advantage to outweigh this two-fold cost. What's that? well, lots of controversy, but one idea (with lots of empirical support) is that parasites maintain sex. I'll try to make this long story shorter... when individuals with certain genotypes (that's gene combinations basically) become common, parasites adapt to them - for a host, it's better to be rare! so you produce offspring that are different from you. Then those rare genotypes are 'parasite free' (sort of), they do well, increase in number and then become parasitized when they're common. Hence we get time-lagged frequency dependent selection... Of course all of this depends on the life cycle of the parasites (i.e. they often have multiple hosts), transmission rates, virulence and resistance levels, and the genetics of infectivity. This has been modeled a lot. I don't want to reinvent the wheel, but to get beyound it, I have go get TO it! and I'm just starting at trying to get two 'genotypes' which were my n1 and n2 to oscillate. Obviously I was way off! Sorry this was so long. If anyone has suggestions on how to learn more just about the math in python, that would be great. thanks Jen From aicolburn@yahoo.com Fri May 30 14:03:01 2003 From: aicolburn@yahoo.com (Alan Colburn) Date: Fri May 30 13:03:01 2003 Subject: [Tutor] Reordering a list Message-ID: <20030530170054.41179.qmail@web41610.mail.yahoo.com> Hi all -- I'm working on a program that includes a list, displayed in order (the list is displayed in a PythonCard list box but, for purposes of this post, that's relatively unimportant ... just think of a standard list). What I'm trying to figure out is how to be able to rearrange the list at will -- specifically, at the push of a button marked "Up" the currently highlighted list element will be moved up one place, and the previous list element will be moved down one place. In other words, if list=["one","two","three"] and the user selects "two" from the list box (i.e., list[1]), and clicks the "Up" button, then the list will become list=["two","one","three"]. I've figured out a successful way to do this, but my procedure is cumbersome -- I know there must be an easier way ... but I don't know what it is. Any suggestions? Thanks, as always -- Al C. __________________________________ Do you Yahoo!? Yahoo! Calendar - Free online calendar with sync to Outlook(TM). http://calendar.yahoo.com From willblake@wanadoo.fr Fri May 30 14:30:02 2003 From: willblake@wanadoo.fr (guillaume) Date: Fri May 30 13:30:02 2003 Subject: [Tutor] The meaning of "raw_input" Message-ID: C'est un message de format MIME en plusieurs parties. ------=_NextPart_000_0000_01C326E2.42CE8140 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hello, All is in the subject:) I tried to run a prog I found in Cogliati's tutorial print "Halt!" s = raw_input("Who Goes there? ") print "You may pass,", s The output is: Halt! Who Goes there? Josh You may pass,Josh If I let raw_input like that, no Josh or anything else. It's a variable,I think,but I don't understand her roll :-( Contrarly at what he said, I didn't notice that "I had to type in my name and then press Enter" Unfortunately I'm not using IDLE (I'm downloading it), I'm working on W$ (at home!) Could u help me to understand clearly what is an input. Thanks in advance :) ------=_NextPart_000_0000_01C326E2.42CE8140 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hello,
All=20 is in the subject:)
I=20 tried to run a prog I found in Cogliati's tutorial
 
print "Halt!"
s =3D=20 raw_input("Who Goes there? ")
print "You may pass,", s
 
The=20 output is:
Halt!
Who=20 Goes there? Josh
You=20 may pass,Josh
 
If I=20 let raw_input like that, no Josh or anything else.
It's=20 a variable,I think,but I don't understand her roll = :-(
Contrarly at what he said, I didn't = notice that "I=20 had to type in 
my=20 name and then press Enter"
Unfortunately I'm not using IDLE (I'm = downloading it),=20 I'm working on W$ (at home!)
Could u help me to understand clearly what is = an=20 input.
Thanks in advance=20 :)
------=_NextPart_000_0000_01C326E2.42CE8140-- From jeff@ccvcorp.com Fri May 30 14:51:59 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri May 30 13:51:59 2003 Subject: [Tutor] Reordering a list References: <20030530170054.41179.qmail@web41610.mail.yahoo.com> Message-ID: <3ED799BD.5060000@ccvcorp.com> Alan Colburn wrote: >[...] What I'm trying to figure out is how >to be able to rearrange the list at will -- >specifically, at the push of a button marked "Up" the >currently highlighted list element will be moved up >one place, and the previous list element will be moved >down one place. > >[...] >I've figured out a successful way to do this, but my >procedure is cumbersome -- I know there must be an >easier way ... but I don't know what it is. Any >suggestions? > Well, I'm not sure what your "cumbersome" method might be, but the obvious way to switch two list elements (at indices a and b) is this: mylist[a], mylist[b] = mylist[b], mylist[a] This in essence constructs a temporary tuple containing the values of the two list elements, and then unpacks that tuple back into the same locations but in reversed order. You may need some care to properly specify the correct indices to use -- you'd move "up" the list by swapping the selected element with the previous one (i.e., b = a - 1), but what happens when the selected element is already at the top? If you don't special-case this, then "up" from the top (mylist[0]) will wrap around to the bottom (mylist[-1]), which may or may not be desired behavior... but using a similar naive method to move down from the bottom (b = a + 1) won't wrap around to the top, and will in fact cause IndexError exceptions. You can solve these issues by putting safeguards in your swapping code, or by simply disabling the "up" button when the topmost item is selected and the "down" button when the bottommost item is selected, or you can do both -- which is probably the best alternative. Jeff Shannon Technician/Programmer Credit International From rick@niof.net Fri May 30 15:10:03 2003 From: rick@niof.net (Rick Pasotto) Date: Fri May 30 14:10:03 2003 Subject: [Tutor] Reordering a list In-Reply-To: <20030530170054.41179.qmail@web41610.mail.yahoo.com> References: <20030530170054.41179.qmail@web41610.mail.yahoo.com> Message-ID: <20030530180913.GA23381@tc.telocity.com> On Fri, May 30, 2003 at 10:00:54AM -0700, Alan Colburn wrote: > Hi all -- > > I'm working on a program that includes a list, displayed in order (the > list is displayed in a PythonCard list box but, for purposes of this > post, that's relatively unimportant ... just think of a standard > list). What I'm trying to figure out is how to be able to rearrange > the list at will -- specifically, at the push of a button marked "Up" > the currently highlighted list element will be moved up one place, and > the previous list element will be moved down one place. > > In other words, if list=["one","two","three"] and the user selects > "two" from the list box (i.e., list[1]), and clicks the "Up" button, > then the list will become list=["two","one","three"]. > > I've figured out a successful way to do this, but my procedure is > cumbersome -- I know there must be an easier way ... but I don't know > what it is. Any suggestions? If you want to move the item at index 'x': one slot closer to the front of the list: l.insert(x-1, l.pop(x)) one slot closer to the end of the list: l.insert(x+1, l.pop(x)) -- "Exhilaration is that feeling you get just after a great idea hits you, and just before you realize what's wrong with it." -- Anonymous Rick Pasotto rick@niof.net http://www.niof.net From zak@harlekin-maus.com Fri May 30 15:31:02 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri May 30 14:31:02 2003 Subject: [Tutor] Jen's not recursion and a long explaination In-Reply-To: <200305301631.LAA06738@iupui.edu> References: <5.2.1.1.0.20030530005234.00ba5c38@www.thinkware.se> <200305301631.LAA06738@iupui.edu> Message-ID: <2402.192.206.201.185.1054319450.squirrel@mail.harlekin-maus.com> > Hi again all, > > I've looked through all the suggestions people sent, and I think my main > question is whether I should keep stuggling with this, or go back to > trying to learn more about programming in first place! My suggestion would be to follow through the learning process, including the strings. At the very least, you'll eventually want to print strings to the screen or a file! In addition, learning strings will provide you with the mental building blocks that can be applied to programming problems outside (or including) strings. For example, if I have an artificial organism with a genome (I'm probably using biology terms wrong, so bear with me) represented by a sequence of letters, say "AABBCDDDEEAABCDDEAAA", and I want to breed new organisms via sexual reproduction, I cross with a genome "AABABDECEEAABCDBBCDA", I can use string manipulations to produce a series of new genomes with random cross-overs and mutation and so on. Though that's straying from mathematical formula, which it sounds like you're focusing on :) -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From magnus@thinkware.se Fri May 30 15:41:05 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 30 14:41:05 2003 Subject: [Tutor] Reordering a list In-Reply-To: <20030530170054.41179.qmail@web41610.mail.yahoo.com> Message-ID: <5.2.1.1.0.20030530203522.01f6b3e0@www.thinkware.se> At 10:00 2003-05-30 -0700, Alan Colburn wrote: >In other words, if list=["one","two","three"] and the >user selects "two" from the list box (i.e., list[1]), >and clicks the "Up" button, then the list will become >list=["two","one","three"]. First of all, don't use builtin names such as 'list' as variable names. I assume you use some better name in your program, I just thought I'd mention this once more... :) Suddenly you need to do l2 = list(t2), and that won't work as expected if you redefined the name 'list'. Over to the code: >>> l=["two","one","three"] >>> l[1],l[2] = l[2],l[1] >>> l ['two', 'three', 'one'] >>> So, you could write functions like... >>> def swapInList(l, x, y): ... l[x], l[y] = l[y], l[x] ... >>> def moveUpInList(l, x): ... swapInList(l, x, x-1) ... >>> l = range(5) >>> l [0, 1, 2, 3, 4] >>> moveUpInList(l, 3) >>> l [0, 1, 3, 2, 4] >>> moveUpInList(l, 2) >>> l [0, 3, 1, 2, 4] moveDownInList is left as an exercise for the reader... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Fri May 30 15:56:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 30 14:56:01 2003 Subject: [Tutor] The meaning of "raw_input" In-Reply-To: Message-ID: <5.2.1.1.0.20030530205529.00bb1ab0@www.thinkware.se> At 19:32 2003-05-30 +0200, guillaume wrote: >If I let raw_input like that, no Josh or anything else. >It's a variable,I think,but I don't understand her roll :-( The raw_input function prompts you for input and returns that as a string. This certainly worked for me. You don't need idle. Just open a "DOS prompt" and run the program. This is what it looked like for me: C:\temp>type test.py print "Halt!" s = raw_input("Who Goes there? ") print "You may pass,", s C:\temp>python test.py Halt! Who Goes there? Magnus You may pass, Magnus I types my name and pressed [Enter] after the program had printed "Who Goes there?" -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From missive@hotmail.com Fri May 30 16:01:01 2003 From: missive@hotmail.com (Lee Harr) Date: Fri May 30 15:01:01 2003 Subject: [Tutor] Re: recursion sort of Message-ID: import time def run(n1, n2): cycle = 1 while 1: nt = n1 + n2 print 'Cycle: %4d n1: %3d n2: %3d nt: %3d' % (cycle, n1, n2, nt) if nt > 500: w1 = 1 w2 = 0.8 else: w1 = 1.2 w2 = 1.4 n1 = int(n1 * w1) n2 = int(n2 * w2) cycle += 1 time.sleep(0.2) if __name__ == '__main__': run(10, 250) _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From aicolburn@yahoo.com Fri May 30 16:05:01 2003 From: aicolburn@yahoo.com (Alan Colburn) Date: Fri May 30 15:05:01 2003 Subject: [Tutor] Re: Reordering a list Message-ID: <20030530190331.36075.qmail@web41603.mail.yahoo.com> Thank you all for your quick responses! Your solutions are much better than mine -- I'm so glad I posted! I didn't know such a simple solution was possible. Part of the application I'm writing, which will be most useful to students and people writing research papers, includes a frame where users see displayed the headings they're using for their paper (or outline). They can move the headings around -- hence today's question -- and also rename them. Each of these headings will have notes associated with them -- kind of like those note cards you filled out when doing library research, once upon a time. Moving or renaming headings won't affect the notes associated with the headings. In any case, thanks again! -- Al C. __________________________________ Do you Yahoo!? Yahoo! Calendar - Free online calendar with sync to Outlook(TM). http://calendar.yahoo.com From jciancio@indiana.edu Fri May 30 17:05:02 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Fri May 30 16:05:02 2003 Subject: [Tutor] Re: recursion sort of In-Reply-To: Message-ID: <200305302004.PAA08001@iupui.edu> wow, this is more complicated than stuff I've seen, but I stole some of it and wrote the following, which works only because n1 and n2 actually oscillate def run(n1, n2): cycle = 1 while 1: nt=n1+n2 print nt if n1>=800: w1=0.1 nnew1=n1*2*w1 elif n1<=799: w1=1.5 nnew1=n1*2*w1 if n2>=800: w2=0.3 nnew2=n2*2*w2 elif n2<=799: w2=1.1 nnew2=n2*2*w2 n1=int(n1*2*w1) #what is this 'int' thing? n2=int(n2*2*w2) cycle +=1 #and what is this? / is this why it's recursive? I'm glad I've got this oscillating, but I'm going to go back to basics for a bit, both on the math and the computer stuff. thanks a lot Jen ------------------- > import time > > def run(n1, n2): > cycle = 1 > > while 1: > nt = n1 + n2 > > print 'Cycle: %4d n1: %3d n2: %3d nt: %3d' % (cycle, n1, n2, > nt) > > if nt > 500: > w1 = 1 > w2 = 0.8 > else: > w1 = 1.2 > w2 = 1.4 > > n1 = int(n1 * w1) > n2 = int(n2 * w2) > > cycle += 1 > > time.sleep(0.2) > > if __name__ == '__main__': > run(10, 250) > > _________________________________________________________________ > The new MSN 8: advanced junk mail protection and 2 months FREE* > http://join.msn.com/?page=features/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From dbroadwell@mindspring.com Fri May 30 17:12:02 2003 From: dbroadwell@mindspring.com (David Broadwell) Date: Fri May 30 16:12:02 2003 Subject: [Tutor] Re: recursion sort of In-Reply-To: <200305302004.PAA08001@iupui.edu> Message-ID: > wow, this is more complicated than stuff I've seen, but I stole some > of it and wrote the following, which works only because n1 and n2 > actually oscillate And once you understand it, write it again ... > n1=int(n1*2*w1) #what is this 'int' thing? int() = integer() > cycle +=1 #and what is this? / is this why it's recursive? that equates to cycle = cycle + 1 And it's not recursive. -- David Broadwell From dyoo@hkn.eecs.berkeley.edu Fri May 30 17:34:13 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 30 16:34:13 2003 Subject: [Tutor] recursion sort of In-Reply-To: <5.2.1.1.0.20030530005234.00ba5c38@www.thinkware.se> Message-ID: > >I'm trying to write a little program on population growth (of anything, > >say plants). The key is that it's frequency dependent. When the size > >is large, individuals don't do as well, and then when it's smaller, > >they do better. also there are 2 'types' of individuals (here called > >n1 and n2; 'w' is how well they do) > > The code below is obviously not not doing what you intended, and since > the code it what you showed us, we don't know what you *did* intend! :) Hi again, [My apologies for posting so much on this; it's an interesting problem!] I think the problem is one of assignment; the program is trying to simulate the advance of time in the simulation by doing reassignments to the n1 and n2 variables. The problem, though, is that this doesn't make it clean to simulate both populations at the same time. Nor is it trivially to go "back in time" without saving previous results in some kind of list. What the program ends up doing is something very serial --- it's simulating the first population up to a certain point in time, and then simulating the second population up to another certain point in time, and the main problem is that we simply don't know how much time has passed. >def run(n1, n2): > while n1>=501: > w=1 > n1=n1*w > while n1<=500: > w=0.2 > n1=n1*W At this point, how do we know how many iterations of life our population has gone through? > while n2>=501: > w=0.8 > n2=n2*w > while n2<=500: > w=0.4 > n2=n2*W And the same question applies here. There's no guarantee that the simulation of n2 goes through the same number of time steps as the simulation of the n1. And that's what makes the next calculation meaningless: > nt=n2+n1 > print nt Conceptually, I'm guessing that we'd like 'nt' to sum up those two populations, but without guaranteeing that n2 and n1 have run for equal amounts of time, this won't give a useful answer. If we really want to do this simulation with loops and reassignment, the iterating variable should probably be time, not population size: ### def simulate(number_of_steps, p1_initial, p2_initial): """Simulates 'number_of_steps' steps of two populations.""" p1, p2 = p1_inital, p2_initial for time in range(number_of_steps): print "Time", time print "Population 1:", p1 print "Population 2:", p2 p1 = calculate_new_p1(p1) ## This needs to be defined somewhere. p2 = calculate_new_p2(p2) ## So does this. ### The structure of this pseudocode is equivalent to Magnus's example. (It's also designed in a way that will make it difficult to make it loop infinitely. *grin*) But an alternative approach is to model our population growth by using functions. For example: ### def f(time): if time == 0: return 0 return f(time-1) + 1 ### is a function that's represents a linear growth, sorta like: / / / / / ---------------------> time 0 1 2 3 4 Another one we can do is: ### def g(time): return 2 * math.sin(time / 3.0) ### which looks a little bit more bouncy: .. .. . . . . . . . . .. What's nice about modeling populations with functions is that we can compose them together: we can make a new function that is a combination of the two others: ### >>> import math >>> def f(time): ... if time == 0: ... return 0 ... return f(time-1) + 1 ... >>> def g(time): ... return 2 * math.sin(time / 3.0) ... >>> def compose_add(function1, function2): ... def new_function(time): ... return function1(time) + function2(time) ... return new_function ... >>> fg = compose_add(f, g) ### 'fg' is a function that represents the sum of the functions 'f' and 'g'. If we graph these together, we'll see that the behavior of fg is sort of a blend between f and g, exhibiting both linear growth but with a slight oscillating component. ### >>> for i in range(20): ... print i, fg(i) ... 0 0.0 1 1.65438939359 2 3.23673960614 3 4.68294196962 4 5.94387580273 5 6.9908159155 6 7.81859485365 7 8.44617176348 8 8.91454525327 9 9.28224001612 10 9.61886407425 11 9.99744590282 12 10.4863950094 13 11.1419709975 14 12.0020901658 15 13.0821514507 16 14.3733412169 17 15.8436035165 18 17.4411690036 19 19.1002540198 ### And this is sorta neat, for 10 lines of code. *grin* And it becomes easy to use this to start adding other functions together: ### >>> ff = compose_add(f, f) >>> ff(0) 0 >>> ff(1) 2 >>> ff(2) 4 >>> ff(3) 6 >>> ff(4) 8 ### If you have any questions on this, please feel free to ask! From jciancio@indiana.edu Fri May 30 18:21:01 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Fri May 30 17:21:01 2003 Subject: [Tutor] recursion sort of In-Reply-To: Message-ID: <200305302120.QAA16053@iupui.edu> > [My apologies for posting so much on this; it's an interesting problem!] that's ok with me!! :) it's going to take me a while to decipher your suggestions, but I do understand the problem you pointed out with time. If you don't mind my sticking with what I had before for another moment, this is what I did before I got your message, because I realized (duh) that I am not interested in nt (the TOTAL of n1 + n2) I'm interested in the dynamics of n1 and n2 (we can imagine they're two different clones), specifially what will make them oscillate WITHIN the population (nt can stay constant all the time for all I care) this is the little change def run(n1, n2): cycle = 1 while 1: print n1 #change here print n2 #change here if n1>=800: w1=0.1 nnew1=n1*2*w1 elif n1<=799: w1=1.5 nnew1=n1*2*w1 if n2>=800: w2=0.3 nnew2=n2*2*w2 elif n2<=799: w2=1.1 nnew2=n2*2*w2 n1=int(n1*2*w1) n2=int(n2*2*w2) n1=n1+nnew1 #added (I think) n2=n2+nnew2 #added cycle +=1 if there are typos... believe it or not I'm manually copying these in. One computer with internet... one with python... don't ask. but what this does is make n1 wave up and down and n2 wave up and down (like a sin curve, but I don't want to make it happen by asking to make a sin curve!) It's terribly hard to copy and paste the output of this though to graph in excel... I'll see what I can figure out about your suggustions thanks again! Jen > > I think the problem is one of assignment; the program is trying to > simulate the advance of time in the simulation by doing reassignments to > the n1 and n2 variables. > > The problem, though, is that this doesn't make it clean to simulate both > populations at the same time. Nor is it trivially to go "back in time" > without saving previous results in some kind of list. > > > > What the program ends up doing is something very serial --- it's > simulating the first population up to a certain point in time, and then > simulating the second population up to another certain point in time, and > the main problem is that we simply don't know how much time has passed. > > > >def run(n1, n2): > > while n1>=501: > > w=1 > > n1=n1*w > > while n1<=500: > > w=0.2 > > n1=n1*W > > > At this point, how do we know how many iterations of life our population > has gone through? > > > > while n2>=501: > > w=0.8 > > n2=n2*w > > while n2<=500: > > w=0.4 > > n2=n2*W > > And the same question applies here. There's no guarantee that the > simulation of n2 goes through the same number of time steps as the > simulation of the n1. > > > > And that's what makes the next calculation meaningless: > > > nt=n2+n1 > > print nt > > Conceptually, I'm guessing that we'd like 'nt' to sum up those two > populations, but without guaranteeing that n2 and n1 have run for equal > amounts of time, this won't give a useful answer. > > > > > If we really want to do this simulation with loops and reassignment, the > iterating variable should probably be time, not population size: > > ### > def simulate(number_of_steps, p1_initial, p2_initial): > """Simulates 'number_of_steps' steps of two populations.""" > p1, p2 = p1_inital, p2_initial > > for time in range(number_of_steps): > print "Time", time > print "Population 1:", p1 > print "Population 2:", p2 > > p1 = calculate_new_p1(p1) ## This needs to be defined somewhere. > p2 = calculate_new_p2(p2) ## So does this. > ### > > The structure of this pseudocode is equivalent to Magnus's example. > (It's also designed in a way that will make it difficult to make it loop > infinitely. *grin*) > > > > > > But an alternative approach is to model our population growth by using > functions. For example: > > > ### > def f(time): > if time == 0: > return 0 > return f(time-1) + 1 > ### > > > is a function that's represents a linear growth, sorta like: > > / > / > / > / > / > ---------------------> time > 0 1 2 3 4 > > > > > Another one we can do is: > > ### > def g(time): > return 2 * math.sin(time / 3.0) > ### > > > which looks a little bit more bouncy: > > > .. .. > . . . > . . . > . . > .. > > > What's nice about modeling populations with functions is that we can > compose them together: we can make a new function that is a combination of > the two others: > > > ### > >>> import math > >>> def f(time): > ... if time == 0: > ... return 0 > ... return f(time-1) + 1 > ... > >>> def g(time): > ... return 2 * math.sin(time / 3.0) > ... > >>> def compose_add(function1, function2): > ... def new_function(time): > ... return function1(time) + function2(time) > ... return new_function > ... > >>> fg = compose_add(f, g) > ### > > > > 'fg' is a function that represents the sum of the functions 'f' and 'g'. > If we graph these together, we'll see that the behavior of fg is sort of a > blend between f and g, exhibiting both linear growth but with a slight > oscillating component. > > > ### > >>> for i in range(20): > ... print i, fg(i) > ... > 0 0.0 > 1 1.65438939359 > 2 3.23673960614 > 3 4.68294196962 > 4 5.94387580273 > 5 6.9908159155 > 6 7.81859485365 > 7 8.44617176348 > 8 8.91454525327 > 9 9.28224001612 > 10 9.61886407425 > 11 9.99744590282 > 12 10.4863950094 > 13 11.1419709975 > 14 12.0020901658 > 15 13.0821514507 > 16 14.3733412169 > 17 15.8436035165 > 18 17.4411690036 > 19 19.1002540198 > ### > > > > And this is sorta neat, for 10 lines of code. *grin* And it becomes easy > to use this to start adding other functions together: > > ### > >>> ff = compose_add(f, f) > >>> ff(0) > 0 > >>> ff(1) > 2 > >>> ff(2) > 4 > >>> ff(3) > 6 > >>> ff(4) > 8 > ### > > > If you have any questions on this, please feel free to ask! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From jciancio@indiana.edu Fri May 30 18:46:07 2003 From: jciancio@indiana.edu (Jennifer Cianciolo) Date: Fri May 30 17:46:07 2003 Subject: [Tutor] 'return' In-Reply-To: Message-ID: <200305302145.QAA19256@iupui.edu> ok, 'return' I looked around a bit, but I haven't found the FAQ to be all that helpful yet. what is the difference between 'return' and 'print'? Other than that print is happy to be written anywhere, return is picky and return can stop a program if it's sitting there all by itself. right? thanks ### > >>> import math > >>> def f(time): > ... if time == 0: > ... return 0 > ... return f(time-1) + 1 > ... > >>> def g(time): > ... return 2 * math.sin(time / 3.0) > ... > >>> def compose_add(function1, function2): > ... def new_function(time): > ... return function1(time) + function2(time) > ... return new_function > ... > >>> fg = compose_add(f, g) > ### From hall@ouhep1.nhn.ou.edu Fri May 30 18:46:22 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Fri May 30 17:46:22 2003 Subject: [Tutor] recursion sort of In-Reply-To: <200305302120.QAA16053@iupui.edu> Message-ID: One suggestion I might make...If I were doing this, instead of copying the results into an excel spreadsheet/graph, I would use one of pythons graphical interfaces to create the plot. it id possible to do this with Tkinter, which ships with python, and there are also some other packages which are available on the net that make plotting even easier.... Just a thought... Ike On Fri, 30 May 2003, Jennifer Cianciolo wrote: > > [My apologies for posting so much on this; it's an interesting > problem!] > > > that's ok with me!! :) > > it's going to take me a while to decipher your suggestions, but I do > understand the problem you pointed out with time. > > If you don't mind my sticking with what I had before for another > moment, this is what I did before I got your message, because I > realized (duh) that I am not interested in nt (the TOTAL of n1 + n2) > I'm interested in the dynamics of n1 and n2 (we can imagine they're > two different clones), specifially what will make them oscillate > WITHIN the population (nt can stay constant all the time for all I > care) > > this is the little change > > def run(n1, n2): > cycle = 1 > while 1: > print n1 #change here > print n2 #change here > if n1>=800: > w1=0.1 > nnew1=n1*2*w1 > elif n1<=799: > w1=1.5 > nnew1=n1*2*w1 > if n2>=800: > w2=0.3 > nnew2=n2*2*w2 > elif n2<=799: > w2=1.1 > nnew2=n2*2*w2 > n1=int(n1*2*w1) > n2=int(n2*2*w2) > n1=n1+nnew1 #added (I think) > n2=n2+nnew2 #added > cycle +=1 > > if there are typos... believe it or not I'm manually copying these in. > One computer with internet... one with python... > don't ask. > > but what this does is make n1 wave up and down and n2 wave up and down > (like a sin curve, but I don't want to make it happen by asking to > make a sin curve!) > It's terribly hard to copy and paste the output of this though to > graph in excel... > > > I'll see what I can figure out about your suggustions > thanks again! > > Jen > From ATrautman@perryjudds.com Fri May 30 18:58:02 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Fri May 30 17:58:02 2003 Subject: [Tutor] recursion sort of Message-ID: <06738462136C054B8F8872D69DA140DB0107B8@corp-exch-1.pjinet.com> >One suggestion I might make...If I were doing this, instead of copying the >results into an excel spreadsheet/graph, I would use one of pythons >graphical interfaces to create the plot. it id possible to do >this with Tkinter, which ships with python, and there are also some other >packages which are available on the net that make plotting even easier.... >Just a thought... >Ike Adding to that thought, there are several great graphing utilities already available at http://py.vaults.ca/parnassus/apyllo.py/302299380. I have used several and most can be fed from a simple text file containing ordered pairs of data. I would concentrated on out putting a standardized file with your results and then using these graphing tools to display them. If you look at the samples provided most includes a sample file to read in and that will give you your format for output. Good Luck, Alan From hall@ouhep1.nhn.ou.edu Fri May 30 19:19:01 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Fri May 30 18:19:01 2003 Subject: [Tutor] 'return' In-Reply-To: <200305302145.QAA19256@iupui.edu> Message-ID: On Fri, 30 May 2003, Jennifer Cianciolo wrote: > ok, 'return' > > I looked around a bit, but I haven't found the FAQ to be all that > helpful yet. > what is the difference between 'return' and 'print'? Other than that > print is happy to be written anywhere, return is picky and return can > stop a program if it's sitting there all by itself. right? > > thanks > Return is actually much different than print. commonly, return is used to stop a function and send back some result to whatever called the function for instance: def foo(spam) return str(spam)+' spam spam spam eggs and spam' order=foo('bacon') print order gives us 'bacon spam spam spam eggs and spam' and this is stored in the variable order. using print instead of return makes the program forget what the result of the function is once it has run Ike From py-tutor@fancy.org Fri May 30 19:34:02 2003 From: py-tutor@fancy.org (Tom Plunket) Date: Fri May 30 18:34:02 2003 Subject: [Tutor] unit testing Message-ID: I have just been getting into Python, but one of the most infuriating things that I've come across is that I cannot for the life of me figure out how to easily write unit test code that automatically gets loaded and imported at runtime. As a C++ pro, CppUnit did exactly what I wanted it to do, and there was never any question. PyUnit, however... My test.py is pretty much ripped off from the regrtest.py found in Py22's test unit (although I also don't understand why I can't import test.regrtest): #!/usr/bin/python, but I'm on Windows. :) import unittest import os if __name__ =3D=3D "__main__": names =3D os.listdir('.') tests =3D [] for name in names: if name[:5] =3D=3D "test_" \ and name[-3:] =3D=3D os.extsep+"py": modname =3D name[:-3] tests.append(modname) tests.sort() for test in tests: module =3D __import__(test, globals(), locals(), []) unittest.main() Now if I get rid of all of this hooplah and manually=20 import unittest from test_something import * from test_somethingelse import * if __name__ =3D=3D "__main__": unittest.main() then everything works. Why isn't my code pulling my tests into my local namespace? I really don't want to have to maintain this (with CppUnit I could have test files that had no external dependencies, I just had to link them into the project and everything would start getting tests run. I want to just have all tests in every test_* file run automatically.) Additionally- why is it that unittest throws an exception when it ends properly? Why on earth can't it be nice and procedural and just allow execution to return normally? (Mind you, I am probably not "getting" Python yet, but that will come!) thanks. -tom! From py-tutor@fancy.org Fri May 30 19:48:01 2003 From: py-tutor@fancy.org (Tom Plunket) Date: Fri May 30 18:48:01 2003 Subject: [Tutor] Re: recursion sort of In-Reply-To: <200305302004.PAA08001@iupui.edu> References: <200305302004.PAA08001@iupui.edu> Message-ID: Jennifer Cianciolo wrote: > cycle +=3D1 # and what is this? / is this why it's recursive? A recursive function is one that calls itself, so this function is not recursive. Recursion is a cool solution to a number of problems that are not conveniently solved with looping, but a simple one is the factorial function, where factorial(N) means the product of each number between 1 and N, so if N is 4, the result is 1 * 2 * 3 * 4. (Many of you probably know that already, but it's for anyone who doesn't. ) >>> def factorial(number): ... if number > 1: ... return number * factorial(number - 1) ... elif number =3D=3D 1: ... return 1 ... else: ... return 0 ... =09 >>> factorial(4) 24 >>> factorial(6) 720 -tom! From alan.gauld@blueyonder.co.uk Fri May 30 20:35:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri May 30 19:35:01 2003 Subject: [Tutor] Re: recursion sort of References: Message-ID: <007201c32704$258017d0$6401a8c0@xp> From: "David Broadwell" > > n1=int(n1*2*w1) #what is this 'int' thing? > int() = integer() Which is to say that it converts the floating point (or Real Number) result into an Integer result. If you want more control you can 'import math' and use math.floor() and math.ceil() to round up or down in the direction you prefer. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@blueyonder.co.uk Fri May 30 20:45:03 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri May 30 19:45:03 2003 Subject: [Tutor] The meaning of "raw_input" References: Message-ID: <007a01c32705$9e3b1de0$6401a8c0@xp> > It's a variable,I think,but I don't understand her roll :-( It's called a function, you'll learn about them later in Josh's tutor I suspect. > Unfortunately I'm not using IDLE (I'm downloading it), > I'm working on W$ If you have Python you already have IDLE (or Pythonwin if you got the Activestate version - they are effectively the same) Look for the python GUI in your Python menu list(Start->Programs->Python) > Could u help me to understand clearly what is an input. An input in this case is where the program stops and waits for you to type something followed by ENTER. If you haven't used MS DOS before then it will probably seem strange. Bascally Python will run in a Command Prompt or MS DOS window. It will print things into the window and when it requests input you can type responses - just like using the >>> prompt in Python itself - I hope you have somehow gotten to the >>> prompt by now?! Technically Python writes to "Standard Output" or stdout and reads from "Standard Input" or stdin. raw_input() is so called because it just reads the raw keystrokes you type whereas input() tries to interpret the keystrokes and return either a number or some other Python value. Thus when you run your Python program you need to watch the window in which it runs and read the prompts. When asked just make sure the window has focus (click its title bar with the mouse) and type your reply at the keyboard. You should see it echoed in the window and when you hit ENTER Python will process the data you entered. Sorry if that seems unnecessarily patronising but I have discovered from readers of my tutor that many Windows users have never seen a command prompt system before and the whole concept is new to them. Alan g. From R. Alan Monroe" References: <200305302120.QAA16053@iupui.edu> Message-ID: <1171649931796.20030530204846@columbus.rr.com> >> [My apologies for posting so much on this; it's an interesting > problem!] > that's ok with me!! :) > it's going to take me a while to decipher your suggestions, but I do > understand the problem you pointed out with time. > If you don't mind my sticking with what I had before for another > moment, this is what I did before I got your message, because I > realized (duh) that I am not interested in nt (the TOTAL of n1 + n2) > I'm interested in the dynamics of n1 and n2 (we can imagine they're > two different clones), specifially what will make them oscillate > WITHIN the population (nt can stay constant all the time for all I > care) > this is the little change > It's terribly hard to copy and paste the output of this though to > graph in excel... Print the numbers with commas between. Then redirect the output of the program to a file, and open it in Excel as a .csv file :^) Alan From magnus@thinkware.se Sat May 31 07:29:08 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 31 06:29:08 2003 Subject: [Tutor] 'return' In-Reply-To: <200305302145.QAA19256@iupui.edu> References: Message-ID: <5.2.1.1.0.20030531120122.01f8c7d8@www.thinkware.se> At 16:45 2003-05-30 -0500, Jennifer Cianciolo wrote: >what is the difference between 'return' and 'print'? With the print statement the expression after "print" is sent to the screen (or a file). Print can occur anywhere. The return statement ends a function, and returns the expression after "return" to the caller of the function. If you call a function in an interactive session and don't assign the return value to anything, the interpreter will display that value on th screen. Example: >>> def add(a,b): ... return a + b ... >>> add(1,2) 3 In this case, the practical result was the same as if we had used "print" in the function, but only in an interactive session. In a program you would need "print add(1,2)" >>> x = add(1,2) >>> print x 3 Here, we assign the return value to a new variable "x". It's not printed until we explicitly print x. Another examples follow below. >>> a = b = 1 >>> while a < 20: ... old_b = b ... b = add(a, b) ... a = old_b ... print a, ... 1 2 3 5 8 13 21 As you see, return and print have entirely different intentions. The issue of print vs return pops up as beginners often write functions that prints a value and then end (and return None, which is the default value to return if no return statement is present). Such a function is a "dead end". It can only be used to show a value. If the function returns the value instead of printing it, the caller can decide whether to print it, use it in further calculations or both. It gives much more options to the caller, i.e. the function is more widely useful. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From mwagman@charter.net Sat May 31 08:15:02 2003 From: mwagman@charter.net (Mike Wagman) Date: Sat May 31 07:15:02 2003 Subject: [Tutor] Sending a file via email Message-ID: <1054379858.3106.1.camel@c24.241.239.54.jvl.wi.charter.com> I need to send a file via email using python. Possibly on the Linux, Windows, and Mac, Can anyone please give me a piece of sample code that will do that. Thanks -- Mike Wagman From magnus@thinkware.se Sat May 31 08:16:04 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 31 07:16:04 2003 Subject: [Tutor] recursion sort of In-Reply-To: References: <200305302120.QAA16053@iupui.edu> Message-ID: <5.2.1.1.0.20030531123026.01f77700@www.thinkware.se> At 16:45 2003-05-30 -0500, Isaac Hall wrote: >One suggestion I might make...If I were doing this, instead of copying the >results into an excel spreadsheet/graph, I would use one of pythons >graphical interfaces to create the plot. This is a lot more to learn though...and if Excel files are used commonly at a location, why not use them. Using the Windows extensions for Python, it's possible to make the python script start Excel, move the data and make a graph. A simpler version is to simply make the data formatted so that copy/paste is easier. Example: >>> import math >>> result = [] >>> for x in range(1, 11): ... l = math.log(x) ... s = math.sin(x) ... result.append((x, l, s)) ... Now we have a set of data as a list of ten tuples, where each tuple contains (x, log(x), sin(x)) for x = 1 to 10. >>> for x, l, s in result: ... print x, ',', l, ',', s ... 1 , 0.0 , 0.841470984808 2 , 0.69314718056 , 0.909297426826 3 , 1.09861228867 , 0.14112000806 4 , 1.38629436112 , -0.756802495308 5 , 1.60943791243 , -0.958924274663 6 , 1.79175946923 , -0.279415498199 7 , 1.94591014906 , 0.656986598719 8 , 2.07944154168 , 0.989358246623 9 , 2.19722457734 , 0.412118485242 10 , 2.30258509299 , -0.544021110889 You can also use the string formatting features in Python and write: >>> for row in result: ... print "%i, %f, %f" % row ... 1, 0.000000, 0.841471 2, 0.693147, 0.909297 3, 1.098612, 0.141120 4, 1.386294, -0.756802 5, 1.609438, -0.958924 6, 1.791759, -0.279415 7, 1.945910, 0.656987 8, 2.079442, 0.989358 9, 2.197225, 0.412118 10, 2.302585, -0.544021 This is all in the Python Tutorial. (Right?) This you can easily paste into Excel. It will end up in one column, but if you open the "Data" menu, and select "Text to Columns", you just need to follow the wizard to get it into three columns. From there, I'm sure you can make a graph. But if you do this more than twice, it's boring to use that Wizard. And you don't have to... Avoiding copy/paste/wizard means that you need the win32all package (it's linked from the Python for Windows web page) or ActiveState's ActivePython. (I'd suggest that you save any currently open Excel files before you try this.) >>> import win32com.client >>> xl = win32com.client.Dispatch("Excel.Application") >>> xl.Visible = 1 >>> xl.Workbooks.Add() >>> for x, l, s in result: ... xl.Cells(x, 1).Value = x ... xl.Cells(x, 2).Value = l ... xl.Cells(x, 3).Value = s ... >>> Your data should now be copied from your Python script to the Excel cells you indicated with "xl.Cells(, )". Note that "x" doubles as excel row variable and x-value in the maths in this particular example. If you use data transfer to Excel often you will want to put the lines above in a function that you can use again and again. That function might have some convenient features. It should be able to place your data in any location in a spread sheet, and in that case it should be able to use a currently open spreadsheet as well as an new one like here. It could also be able to open (and save?) an existing file, given a path. It could also make the chart, or call an Excel macro which does that. But that's too much for now... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From alan.gauld@blueyonder.co.uk Sat May 31 08:43:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat May 31 07:43:02 2003 Subject: [Tutor] 'return' References: <200305302145.QAA19256@iupui.edu> Message-ID: <009201c32769$b839f040$6401a8c0@xp> > ok, 'return' You're coming from a math background so I'll use a math analogy. return is the value returned from a function. Thus if we define a function in math: f(x) = x*x you can assign that to a variable by: y = f(x) or even y = f(2) so that y now equals 4. THis translates in Python to def f(x): return x*x and y = f(2) y now stores 4 But if we had used print instead of return y would store 'None' (the default return value from a python function) and the function would have printed 4. So using return allows your functions to produce a value that can be stored by a variable. Try reading the modules and functions topic in my tutor for a slightly different explanation. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From magnus@thinkware.se Sat May 31 09:06:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 31 08:06:01 2003 Subject: [Tutor] unit testing In-Reply-To: Message-ID: <5.2.1.1.0.20030531132233.01f79e30@www.thinkware.se> At 15:32 2003-05-30 -0700, Tom Plunket wrote: >I have just been getting into Python, but one of the most >infuriating things that I've come across is that I cannot for the >life of me figure out how to easily write unit test code that >automatically gets loaded and imported at runtime. As a C++ pro, >CppUnit did exactly what I wanted it to do, and there was never >any question. PyUnit, however... It'll come to you. It's proably just too simple! ;) I guess you realize the difference between Python's "import" and "#include" in C++. Import always makes it's own namespace, which is a very good thing. I'm sure you know what problems #include can cause, with redefining names etc. I use a script like this: --------------- import glob, os, time start = time.time() tests = glob.glob('*_ut.py') # You'd change this to 'test_*.py' tests.sort() for test in tests: print "Running", test os.system('python ' + test) stop = time.time() print "Ran %i test modules in %.3f seconds real time" % (len(tests), stop-start) ----------------- Each of my test files contain: if __name__ == "__main__": unittest.main() I'm sure this can be handled differently, so that I don't have to call os.system, but I wrote this and it worked well enough. By doing it like this, I also know that each test module is run independently, that there are no inadvertant dependencies between test modules, since each module runs in a new process. >My test.py is pretty much ripped off from the regrtest.py found >in Py22's test unit Note that only a fraction of the Python regression tests use unittest. Most are older than unittest, and Python has two unit testing modules: unittest and doctest. Don't expect regrtest.py to be a good example of how to use the unittest module. It must handle all sorts of test scripts. >(although I also don't understand why I can't >import test.regrtest): Neither do I. In Active Python 2.2.2 I can do: >>> import test.regrtest >>> help(test.regrtest) Help on module test.regrtest in test: NAME test.regrtest - Regression test. FILE g:\python22\lib\test\regrtest.py [snip] Is there some problem after that, or don't you even get here? >Why isn't my code pulling my tests into my local namespace? Because you are explicitly pulling it into a variable called 'module' instead? You tell me, you wrote it! ;) I would *not* try to pull all my modules into the same namespace. If each test has it's own namespace, there will be no name collisions as long as you don't have collisions in a single file. Also, with "from x import *" it's possible that your entire test suite will run, but some test suites can't run on their own since it lacks an import that's defined in a test which is imported earlier when you run the whole suite. So, when you remove the dependency on module X in tes_a, test_b will suddenly fail... Hm... >Additionally- why is it that unittest throws an exception when it >ends properly? Never happened to me. Show a minimal but complete example. I can understand your frustration. Sometimes it's easier to be a complete newbie than to be used to something working in a particular way, and then come to a place where things work slightly differently. As Yoda said: "You have to unlearn what you have learnt." :) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Sat May 31 09:21:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 31 08:21:02 2003 Subject: [Tutor] Sending a file via email In-Reply-To: <1054379858.3106.1.camel@c24.241.239.54.jvl.wi.charter.com> Message-ID: <5.2.1.1.0.20030531141124.01fbaac8@www.thinkware.se> At 06:17 2003-05-31 -0500, Mike Wagman wrote: >I need to send a file via email using python. Possibly on the Linux, >Windows, and Mac, Can anyone please give me a piece of sample code that >will do that. Read The Fabulous Manual! http://www.python.org/doc/current/lib/node397.html -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From charlie@begeistert.org Sat May 31 09:28:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sat May 31 08:28:02 2003 Subject: Charting with Python was [Tutor] recursion sort of In-Reply-To: <20030531111604.26416.26057.Mailman@mail.python.org> References: <20030531111604.26416.26057.Mailman@mail.python.org> Message-ID: <20030531142909.2591.5@wonderland.1054368754.fake> On 2003-05-31 at 13:16:04 [+0200], tutor-request@python.org wrote: > Adding to that thought, there are several great graphing utilities > already available at http://py.vaults.ca/parnassus/apyllo.py/302299380. I > have used several and most can be fed from a simple text file containing > ordered pairs of data. I would concentrated on out putting a standardized > file with your results and then using these graphing tools to display > them. If you look at the samples provided most includes a sample file to > read in and that will give you your format for output. Keep out of Excel! I really hate the charts produced by office packets and, to be honest, it's often easier to program the stuff yourself if you've got a good library. Plus this will be a nice introduction into Python. Unfortunately most programmers have little or no aesthetics and are happy with system palettes, etc. See the junk Webalizer produces. PyChart looks pretty nice and the source looks usable, GDChart is better than the most but note that the user manual is still in the to-do's. I've recently tried Chart Director from http://www.advsofteng.com/ and I think it is head and shoulders above the rest (great defaults including TrueType support and anti-aliasing in default); documentation is great as is the support. It's completely usable in the free version and the little banner is easily removed. Charlie From Don Arnold" Message-ID: <103301c32774$1e0c5480$9011ba3f@defaultcomp> ----- Original Message ----- From: "Magnus Lyckå" To: "Mike Wagman" ; Sent: Saturday, May 31, 2003 7:23 AM Subject: Re: [Tutor] Sending a file via email > At 06:17 2003-05-31 -0500, Mike Wagman wrote: > >I need to send a file via email using python. Possibly on the Linux, > >Windows, and Mac, Can anyone please give me a piece of sample code that > >will do that. > > Read The Fabulous Manual! > > http://www.python.org/doc/current/lib/node397.html > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The shortest path from thought to working program > I think that 'RTFM' often comes off as a rather terse reply. In this case, however, the Manual undeniably _is_ Fabulous, giving 4 examples of sending email. I never knew it could be that easy! Thanks, Magnus. Don From randytalbot@comcast.net Sat May 31 13:05:02 2003 From: randytalbot@comcast.net (Randy Talbot) Date: Sat May 31 12:05:02 2003 Subject: [Tutor] help on newbie program In-Reply-To: <5.2.1.1.0.20030529191815.01edf548@www.thinkware.se> Message-ID: <000201c3278e$07fa7680$5b582144@aberdn01.md.comcast.net> > A paper book can never keep up to date with something like Python, but > Learning Python needs a 2nd edition that covers 2.3 to stay useful. > It's a bit sad to learn stuff, just to unlearn them as we turn to the > next book. Learning Python is coming out with a 2nd edition. Amazon.com has a possible release date of July 2003 with the book's ISBN # as 0596002815. Randy From absmythe@ucdavis.edu Sat May 31 13:23:02 2003 From: absmythe@ucdavis.edu (ashleigh smythe) Date: Sat May 31 12:23:02 2003 Subject: [Tutor] Installing gnome-python/conflicts with old python versions trouble Message-ID: <1054372761.28257.178.camel@nate.ucdavis.edu> Hello! I'm trying to install gnome-python-1.99.16. My Linux came with python1.5 (in /usr/lib) but I installed python2.2 in /usr/local/lib. I'm using 2.2 for all my python learning. I read somewhere (Red Hat info?) that I should leave the python1.5 on my system as Red Hat might need to use it. Of course that was _after_ I deleted some of the 1.5 files! Nevertheless, now when I try to install gnome-python, it seems like it finds 2.2 but also 1.5 and gives me error messages indicating that my python libraries are too old. I have had similar problems installing additional python modules as I'm just not clear on where they (or frankly anything else I install!) should go - I put biopython into /usr/local/lib/python2.2/site-packages but python2.2 can't find my input files in my home directory, only if they are also in /site-packages. I tried some of the options offered in ./config -- help but they didn't seem to help (but I could just be misunderstanding them as I am still pretty lame with general Linux/bash stuff!). Long configure message after my ./config is below. Thanks for any ideas/explanations! Ashleigh [ashleigh@nate gnome-python-1.99.16]$ ./configure checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for gawk... gawk checking whether make sets $(MAKE)... yes checking build system type... i686-pc-linux-gnu checking host system type... i686-pc-linux-gnu checking for style of include used by make... GNU checking for gcc... gcc checking for C compiler default output... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ANSI C... none needed checking dependency style of gcc... gcc3 checking for ld used by GCC... /usr/bin/ld checking if the linker (/usr/bin/ld) is GNU ld... yes checking for /usr/bin/ld option to reload object files... -r checking for BSD-compatible nm... /usr/bin/nm -B checking for a sed that does not truncate output... /bin/sed checking whether ln -s works... yes checking how to recognise dependent libraries... pass_all checking command to parse /usr/bin/nm -B output... ok checking how to run the C preprocessor... gcc -E checking for egrep... grep -E checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking dlfcn.h usability... yes checking dlfcn.h presence... yes checking for dlfcn.h... yes checking for ranlib... ranlib checking for strip... strip checking for objdir... .libs checking for gcc option to produce PIC... -fPIC checking if gcc PIC flag -fPIC works... yes checking if gcc static flag -static works... yes checking if gcc supports -c -o file.o... yes checking if gcc supports -c -o file.lo... yes checking if gcc supports -fno-rtti -fno-exceptions... yes checking whether the linker (/usr/bin/ld) supports shared libraries... ./configure: =$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib: command not found yes checking how to hardcode library paths into programs... immediate checking whether stripping libraries is possible... yes checking dynamic linker characteristics... GNU/Linux ld.so checking if libtool supports shared libraries... yes checking whether to build shared libraries... yes checking whether to build static libraries... no checking whether -lc should be explicitly linked in... no creating libtool checking for python... /usr/bin/python checking for python version... 1.5 checking for python platform... linux-i386 checking for python script directory... ${prefix}/lib/python1.5/site-packages checking for python extension module directory... ${exec_prefix}/lib/python1.5/site-packages checking for python >= 2.2... configure: error: too old From Anish.Mehta@enst-bretagne.fr Sat May 31 13:34:02 2003 From: Anish.Mehta@enst-bretagne.fr (Mehta, Anish) Date: Sat May 31 12:34:02 2003 Subject: [Tutor] c struct with python Message-ID: <3ED8DC8E.10508@antares.enst-bretagne.fr> Hello ! I have a c structure which i am representing with a class in python. The structure is of the form: typedef struct abc { void (*XY)(int a, int b); }ABC; void XY(int a, int b) { # code here } Can someone tell me how this can be handled in python. Thanks in advance. Regards, Anish MEHTA. From py-tutor@fancy.org Sat May 31 15:04:01 2003 From: py-tutor@fancy.org (Tom Plunket) Date: Sat May 31 14:04:01 2003 Subject: [Tutor] help on newbie program In-Reply-To: <544BE8EBDBEE344F96B32750CA5753E9793D85@ufcu_ntes.utahfirst.com> References: <544BE8EBDBEE344F96B32750CA5753E9793D85@ufcu_ntes.utahfirst.com> Message-ID: Nick Jensen wrote: > I understand parts of it, but not all of it as a whole. Ok- I'll walk through it with you. :) I'll jam through it as the parser is going to see it. > ## This program runs a test of knowledge comment. :) > true = 1 > false = 0 this defines two global variables. > # First get the test questions > # Later this will be modified to use file io. > def get_questions(): > # notice how the data is stored as a list of lists > return [["What color is the daytime sky on a clear day?","blue"],\ > ["What is the answer to life, the universe and everything?","42"],\ > ["What is a three letter word for mouse trap?","cat"]] This defines a function called "get_questions" that takes no arguments. > # This will test a single question > # it takes a single question in > # it returns true if the user typed the correct answer, otherwise false > def check_question(question_and_answer): > #extract the question and the answer from the list > question = question_and_answer[0] > answer = question_and_answer[1] > # give the question to the user > given_answer = raw_input(question) > # compare the user's answer to the testers answer > if answer == given_answer: > print "Correct" > return true > else: > print "Incorrect, correct was:",answer > return false This defines a function called "check_question" which takes one argument. Looking at the way the argument is used, it needs to be something that is subscriptable with two entries, either a two-element list, or a two-element tuple. Probably other things could work too, but I'm a Python newbie (but have been a professional programmer for 7+ years) myself. > # This will run through all the questions > def run_test(questions): > if len(questions) == 0: > print "No questions were given." > # the return exits the function > return > index = 0 > right = 0 > while index < len(questions): > #Check the question > if check_question(questions[index]): > right = right + 1 > #go to the next question > index = index + 1 > #notice the order of the computation, first multiply, then divide > print "You got ",right*100/len(questions),"% right out of",len(questions) This defines a function called "run_test" which takes one argument. Again, looking at how the argument is used, it needs to be subscriptable, but in this case it can have any length (notice the use of 'len(questions)' makes the function loop as many times as there are questions). Note that this loop is not really "the Python way," though, but I'll discuss that later. > #now lets run the questions > run_test(get_questions()) Finally we get a line that asks the interpreter to actually do something with all of the functions that I've defined. What this does is call the function "run_test" with the result of the function "get_questions". Due to this dependency, "get_questions" certainly must execute first. Then, whatever comes back from that as the return value gets passed as the argument to "run_test". When "run_test" finishes, program flow returns to the next line in the script, and since there are no more lines to execute, the program terminates. Now- how does the code actually work? Well- "get_questions" is called. That function returns a list of lists, in this case, the list is three elements long, and the lists within it are each two strings. So this function returns this list of lists, and that return value then goes to... "run_test" is called with the return value from "get_questions", so that list-of-lists is passed in. If the length of that list is zero, an informative message is printed, and program flow returns to the point where "run_test" was called. If there are questions to ask, two variables are created. One is "index", which is used to index into the list of "questions", and the other is "right", which is used to count the number of correct answers. Each of these variables are initialized to zero (remember, in the case of "index", lists and so forth's first elements are index zero). Now, we enter a loop- while index is less than the number of questions, we have an if statement that checks the return value of "check_question". So, Python now calls "check_question" with the "index"'th entry in the "questions" list-of-lists. Jumping to "check_question", we see that the argument that we get is one of those sub-lists in the list-of-lists returned by "get_questions". So, the "question" is the first entry and "answer" is the second; the first time into this function, "question" is "What color is the daytime sky on a clear day?" and "answer" is "blue". Python then prints the "question" to the console, and awaits input from the user. The users types an answer, and Python sticks that answer into the variable "given_answer". If "given_answer" is equivalent to the actual "answer", the user is rewarded with the text "Correct", and the function returns 1, which indicates success. If the "given_answer" does not match the correct "answer", the user is told that the answer is not correct, and the function returns zero to indicate failure. This use of zero and one in this way is historical to some extent, but basically boils down to zero meaning "off" and one meaning "on." We'll see how that works when program flow returns... To "run_test", we're now back in the if statement where we left for "check_question". Since the return value to "check_question" isn't explicitly compared to any value, 'if' just checks to see if the value is "on" or "off". In the case where the return value is "on" (i.e. the user answered the question correctly), then the value of the "right" local variable is incremented. If the return value is "off", then nothing happens. If you wanted to, though, you could put in: else: wrong = wrong + 1 after that 'right = right + 1' and then be counting up the number of wrong answers also, but that is a decision that you can make for yourself. :) The next thing that happens, regardless of the user's answer to the question, is that index is incremented. The while loop then continues- if index is still less than the length of the "questions" list, do the loop again. Once "index" is equal to or greater than the length of the "questions" list (remember that for a list of 4 elements, and since lists' first element is index zero, that the list's last element is index 3. Four elements are indexed 0, 1, 2, 3), the while loop terminates and program flow continues to the print call. That last line of print just prints the user's results to the console, and then program flow returns to the place where "run_tests" was called. (Since there is no explicit 'return' statement, Python implicitly adds one after the last line of the function. Additionally, 'return' by itself with no arguments is equivalent to 'return None', so the return value isn't really intended to be checked.) As mentioned above, once program flow returns from "run_tests", there are no more lines in the program, so the script terminates. Notes: 1) I mentioned that this code isn't exactly "the Python way" above: index = 0 right = 0 while index < len(questions): #Check the question if check_question(questions[index]): right = right + 1 #go to the next question index = index + 1 What I mean by that is that "the Python way" would probably be more along the lines of: right = 0 for question in questions: #Check the question if check_question(question): right = right + 1 As you can see, far fewer lines in this code. Basically, the 'for' loop just peels off the next element of the "questions" list each time through the loop, assigning that element to the "question" variable. 2) "check_question" isn't really a good name for that function, because it actually doesn't check the question at all. The function *asks* the question and then checks the *answer*. While some may argue that this is a decent "abbreviation", let me just point out that when you read code that you've written like this a year down the road, or when others read your code for the first time (like newbies reading a tutorial ), the reader starts to wonder why descriptive names weren't used in the first place. That's it. :) Any questions? -tom! From py-tutor@fancy.org Sat May 31 15:06:01 2003 From: py-tutor@fancy.org (Tom Plunket) Date: Sat May 31 14:06:01 2003 Subject: [Tutor] unit testing In-Reply-To: <5.2.1.1.0.20030531132233.01f79e30@www.thinkware.se> References: <5.2.1.1.0.20030531132233.01f79e30@www.thinkware.se> Message-ID: Magnus Lyckå wrote: > It'll come to you. It's proably just too simple! ;) That's what I fear. > I guess you realize the difference between Python's "import" > and "#include" in C++. Import always makes it's own namespace... Sure- is there a way that I can call __import__ to look like "from x import *" though? > I use a script like this: > --------------- > import glob, os, time > > start = time.time() > tests = glob.glob('*_ut.py') # You'd change this to 'test_*.py' > tests.sort() > for test in tests: > print "Running", test > os.system('python ' + test) > stop = time.time() > > print "Ran %i test modules in %.3f seconds real time" % (len(tests), > stop-start) Interesting. My only fear is that, for a program with a lot of modules, that this spits a lot of trash on the screen. > Each of my test files contain: > > if __name__ == "__main__": > unittest.main() Try adding the line "print 'done!'" after that. You'll find that, since unittest.main() calls sys.exit(), you never hit your print statement. At least, that's how it is coded in my 2.2.2 install. (like this: : def runTests(self): : if self.testRunner is None: : self.testRunner = TextTestRunner(verbosity=self.verbosity) : result = self.testRunner.run(self.test) : sys.exit(not result.wasSuccessful()) ) I don't recall off the top of my head what exception is thrown in this case, but normally it's supressed by the environment (or so it seems). > I'm sure this can be handled differently, so that I don't have to > call os.system, but I wrote this and it worked well enough. And with testing, that's all it needs to do! :) > By doing it like this, I also know that each test module is run > independently, that there are no inadvertant dependencies between > test modules, since each module runs in a new process. That's a good point, although I do try to make sure there are no dependencies anyway by limiting my use of global variables to none and trying to always create new class instances. :) > Note that only a fraction of the Python regression tests use unittest. Sure- I was just inspired by the way they were loading up test modules. > >(although I also don't understand why I can't > >import test.regrtest): > > Neither do I. In Active Python 2.2.2 I can do: > > >>> import test.regrtest > >>> help(test.regrtest) > Help on module test.regrtest in test: Hmm... In IDLE I can do that too. Unfortunately: C:\Documents and Settings\tom\My Documents>type test.py import test.regrtest C:\Documents and Settings\tom\My Documents>test.py Traceback (most recent call last): File "C:\Documents and Settings\tom\My Documents\test.py", line 1, in ? import test.regrtest File "C:\Documents and Settings\tom\My Documents\test.py", line 1, in ? import test.regrtest ImportError: No module named regrtest > >Why isn't my code pulling my tests into my local namespace? > > Because you are explicitly pulling it into a variable > called 'module' instead? You tell me, you wrote it! ;) Heh- ok, then as above, how do I pull into the local namespace using __import__ ? > I would *not* try to pull all my modules into the same > namespace. I will probably have an epiphany one day that this is not what I want, but for the sake of learning... ;) > If each test has it's own namespace, there will be no name > collisions as long as you don't have collisions in a single file. Hmm- there's something interesting. Maybe I could hack unittest so that it takes a list of modules to run. ...or maybe that's what that 'argv' parameter is for. Hmm, maybe I can do it just by passing my 'tests' list in as argv. > I can understand your frustration. Sometimes it's easier to > be a complete newbie than to be used to something working in > a particular way, and then come to a place where things work > slightly differently. As Yoda said: "You have to unlearn what > you have learnt." :) Yes indeed- I actually had similar frustrations when moving between C++ compilers, even. The way to do things optimally often depended entirely on the compiler. :( Thanks for your help- -tom! From njensen@utahfirst.com Sat May 31 15:25:02 2003 From: njensen@utahfirst.com (Nick Jensen) Date: Sat May 31 14:25:02 2003 Subject: [Tutor] help on newbie program Message-ID: <544BE8EBDBEE344F96B32750CA5753E923C884@ufcu_ntes.utahfirst.com> IA0KLS0tLS1PcmlnaW5hbCBNZXNzYWdlLS0tLS0gDQpGcm9tOiBSYW5keSBUYWxib3QgW21haWx0 bzpyYW5keXRhbGJvdEBjb21jYXN0Lm5ldF0gDQpTZW50OiBTYXQgNS8zMS8yMDAzIDEwOjAyIEFN IA0KVG86IFB5dGhvbiANCkNjOiANClN1YmplY3Q6IFJFOiBbVHV0b3JdIGhlbHAgb24gbmV3Ymll IHByb2dyYW0NCg0KDQoNCgk+IEEgcGFwZXIgYm9vayBjYW4gbmV2ZXIga2VlcCB1cCB0byBkYXRl IHdpdGggc29tZXRoaW5nIGxpa2UgUHl0aG9uLCBidXQNCgkNCgk+IExlYXJuaW5nIFB5dGhvbiBu ZWVkcyBhIDJuZCBlZGl0aW9uIHRoYXQgY292ZXJzIDIuMyB0byBzdGF5IHVzZWZ1bC4NCgk+IEl0 J3MgYSBiaXQgc2FkIHRvIGxlYXJuIHN0dWZmLCBqdXN0IHRvIHVubGVhcm4gdGhlbSBhcyB3ZSB0 dXJuIHRvIHRoZQ0KCT4gbmV4dCBib29rLg0KCQ0KCT4+TGVhcm5pbmcgUHl0aG9uIGlzIGNvbWlu ZyBvdXQgd2l0aCBhIDJuZCBlZGl0aW9uLiBBbWF6b24uY29tIGhhcyBhPj4NCgk+PnBvc3NpYmxl IHJlbGVhc2UgZGF0ZSBvZiBKdWx5IDIwMDMgd2l0aCB0aGUgYm9vaydzIElTQk4gIyBhcyAwNTk2 MDAyODE1Lg0KDQoJDQoJPj5SYW5keQ0KCQ0KDQoJWWVwLCBJIHNhdyB0aGlzIGFuZCB0aGluayBJ J2xsIHdhaXQgZm9yIGl0IHRvIGNvbWUgb3V0LiBUaGUgZmlyc3QgZWRpdGlvbiBnb3QgcmVhbGx5 IGhpZ2ggcmF0aW5ncyBhbmQgc2luY2UgaXQgZm9jdXNlcyBqdXN0IG9uIHB5dGhvbiBhbmQgaXMg Zm9yIG5ld2JpZXMgaXQgc2VlbXMgdG8gYmUgZXhhY3RseSB3aGF0IEkgd2FudC4gVGhhbmtzDQoN CgkgDQoNCgktTmljaw0KCQ0KCQ0KCV9fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19f X19fX19fX19fX19fDQoJVHV0b3IgbWFpbGxpc3QgIC0gIFR1dG9yQHB5dGhvbi5vcmcNCglodHRw Oi8vbWFpbC5weXRob24ub3JnL21haWxtYW4vbGlzdGluZm8vdHV0b3INCgkNCg0K From loizie@hotmail.com Sat May 31 15:39:02 2003 From: loizie@hotmail.com (evros loizides) Date: Sat May 31 14:39:02 2003 Subject: [Tutor] recursive function Message-ID: <000001c327a3$b2e96aa0$69d6c518@6z5lw01> This is a multi-part message in MIME format. ------=_NextPart_000_0001_01C32779.CA15D3A0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit i need to use recursive fuction insted of while loop in the following program . does anybody have any good ideas how to do that? #def isString() import string myString = raw_input("enter string:") num=len(myString) print myString print len(myString) n=1 sum=0 while n<=num: if myString[n-1].isdigit(): #print "is digit" sum=sum+int(myString[n-1]) #print sum #else: #print "is not digit" n=n+1 print sum ------=_NextPart_000_0001_01C32779.CA15D3A0 Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Message
i need = to use=20 recursive fuction insted of while loop in the following program=20 .
 does=20 anybody  have any good ideas how to do that?
 
 
 
#def=20 isString()
 
import = string
myString =3D raw_input("enter = string:")
num=3Dlen(myString)
print=20 myString
print len(myString)
n=3D1
sum=3D0
while=20 n<=3Dnum:
    if=20 myString[n-1].isdigit():
        = #print=20 "is digit"
       =20 sum=3Dsum+int(myString[n-1])
       = ; #print=20 sum
    = #else:
       =20 #print "is not digit"
       =20
    n=3Dn+1   
print=20 sum
------=_NextPart_000_0001_01C32779.CA15D3A0-- From loizie@hotmail.com Sat May 31 16:52:59 2003 From: loizie@hotmail.com (evros loizides) Date: Sat May 31 15:52:59 2003 Subject: [Tutor] Recursive function(posting the output of teh code) Message-ID: <000001c327ad$c1542ad0$69d6c518@6z5lw01> This is a multi-part message in MIME format. ------=_NextPart_000_0001_01C32783.D87E22D0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable enter string:erfe7er6e9eve09 erfe7er6e9eve09 15 31 what this program does gets the digits form a string add them and print teh sum evrything okey until i have to use recursive function taht i am not = familiar with how does it work . Any good reference on recursive functions taht will be helpfull too. thanks=20 ------=_NextPart_000_0001_01C32783.D87E22D0 Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Message
enter=20 string:erfe7er6e9eve09
erfe7er6e9eve09
15
31
what this program = does
gets the=20 digits form a string add them and print teh = sum
evrything okey=20 until i have to use recursive function taht i am not familiar with how = does it=20 work .
Any good=20 reference on recursive functions taht will be helpfull=20 too.
thanks 
= ------=_NextPart_000_0001_01C32783.D87E22D0-- From py-tutor@fancy.org Sat May 31 17:14:01 2003 From: py-tutor@fancy.org (Tom Plunket) Date: Sat May 31 16:14:01 2003 Subject: [Tutor] Recursive function(posting the output of teh code) In-Reply-To: <000001c327ad$c1542ad0$69d6c518@6z5lw01> References: <000001c327ad$c1542ad0$69d6c518@6z5lw01> Message-ID: evros loizides wrote: > evrything okey until i have to use recursive function taht i am not familiar > with how does it work . > Any good reference on recursive functions taht will be helpfull too. A recursive function is a function that calls itself. For instance: >>> def silly_print_string(s): ... if len(s) > 0: ... print s[0] ... silly_print_string(s[1:]) ... >>> silly_print_string("test") t e s t >>> silly_print_string("another test") a n o t h e r t e s t this recursive function prints the first letter of the string and then calls itself with the remainder of the string. This function definition may also give you a hint. -tom! From alan.gauld@blueyonder.co.uk Sat May 31 18:28:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat May 31 17:28:01 2003 Subject: [Tutor] c struct with python References: <3ED8DC8E.10508@antares.enst-bretagne.fr> Message-ID: <00e901c327bb$8a3c2170$6401a8c0@xp> > I have a c structure which i am representing with a class in python. The > structure is of the form: > > typedef struct abc > { > void (*XY)(int a, int b); > }ABC; > > void XY(int a, int b) > {...} > Can someone tell me how this can be handled in python. You have a structure containing a pointer to a function that takes two (integer) arguments and no return value. A similar function in python is easy: def XY(a,b): pass And you can put that in any Python structure you want, including a class: class ABC: def __init__(self, func): self.XY = func NOw you can instantiate ABC: abc = ABC(XY) and call the function like: abc.XY(3,4) Or you could store it in a tuple, or a list or a dictionary. funcList = [XY] funcTuple = (XY) funcDict = {'XY':XY} And call them like so: funcList[0](3,4) funcTuple[0](3,4) funcDict['XY'](3,4) Does that help? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@blueyonder.co.uk Sat May 31 18:34:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat May 31 17:34:02 2003 Subject: [Tutor] unit testing References: <5.2.1.1.0.20030531132233.01f79e30@www.thinkware.se> Message-ID: <00f001c327bc$6e2095b0$6401a8c0@xp> > > >(although I also don't understand why I can't > > >import test.regrtest): > > Hmm... In IDLE I can do that too. Unfortunately: > > C:\Documents and Settings\tom\My Documents>type test.py > import test.regrtest > > C:\Documents and Settings\tom\My Documents>test.py > Traceback (most recent call last): ... > ImportError: No module named regrtest What about from the python prompt in a DOS window? My guess is that you don't have the PYTHONPATH environment variable set properly or somesuch? Try starting python in DOS then importing sys and checking the sys.path value to see if the right directories are included. Just a guess, Alan G. From alan.gauld@blueyonder.co.uk Sat May 31 18:38:03 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat May 31 17:38:03 2003 Subject: [Tutor] help on newbie program References: <544BE8EBDBEE344F96B32750CA5753E923C884@ufcu_ntes.utahfirst.com> Message-ID: <00f501c327bc$f7d54530$6401a8c0@xp> > >>Learning Python is coming out with a 2nd edition. Amazon.com has a>> > >>possible release date of July 2003 with the book's ISBN # as 0596002815. > > Yep, I saw this and think I'll wait for it to come out. The first edition got really > high ratings and since it focuses just on python and is for newbies It focuses on Python and is for newbies to Python. If you have some programming experience thats fine and Learning Python is a fine choice. If you are a complete newbie to programming you might find it quite tough going. It's easier to read than the official tutor but not much. If you are a complete beginner you might be better off with going through one of the Newbie web site tutors first. But then I'm biased! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@blueyonder.co.uk Sat May 31 18:51:08 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat May 31 17:51:08 2003 Subject: [Tutor] recursive function References: <000001c327a3$b2e96aa0$69d6c518@6z5lw01> Message-ID: <00fd01c327be$bbd3b830$6401a8c0@xp> > i need to use recursive fuction insted of while loop in the following > program . Since the code should work this looks suspiciously like a homework assignment! However I'll give you the benefit of some doubt and suggest an approach. You want a function that takes a string argument and if the string is empty returns zero else it reads the first character and if it is a number adds it to the value from the rest of the string else it adds zero to the value from the rest of the string > does anybody have any good ideas how to do that? FWIW my version took 5 lines of code, so the end result should be a lot shorter than your current version! Now you try building that. If you don't get it to work show us what you've done and we might be able to help further. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@blueyonder.co.uk Sat May 31 18:52:59 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat May 31 17:52:59 2003 Subject: [Tutor] Recursive function(posting the output of teh code) References: <000001c327ad$c1542ad0$69d6c518@6z5lw01> Message-ID: <010501c327be$e5eed550$6401a8c0@xp> > Any good reference on recursive functions taht will be helpfull too. Try the chapter on recursion in my tutor Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From loizie@hotmail.com Sat May 31 18:55:56 2003 From: loizie@hotmail.com (evros loizides) Date: Sat May 31 17:55:56 2003 Subject: [Tutor] -Recursive Functions Message-ID: <000e01c3274b$514fa370$69d6c518@6z5lw01> This is a multi-part message in MIME format. ------=_NextPart_000_000F_01C32721.68799B70 Content-Type: multipart/alternative; boundary="----=_NextPart_001_0010_01C32721.68799B70" ------=_NextPart_001_0010_01C32721.68799B70 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit * Your program should accept a string using the raw_input function. It should define a RECURSIVE function stringToNum(aString) than accepts a string parameter and returns the sum of the digit characters that occur in the string. Thus, e.g., if the input is 'he5llo7 9world', the return value would be 21 this the part i cannot amke it work with recursive fuction my program work using while loop. anybody ahs any ideas how to use recursive fuction? can email me any suggestions at loizie@hotmail.com ------=_NextPart_001_0010_01C32721.68799B70 Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Message
  • Your program should = accept a string=20 using the raw_input = function.  It should define a RECURSIVE function stringToNum(aString) than = accepts a=20 string parameter and returns the sum of the digit characters that = occur in the=20 string.  Thus, e.g., if = the input=20 is ‘he5llo7 9world’, the return value would be 21
this the part i cannot amke it work with = recursive fuction=20
my program work using while = loop.
anybody ahs any ideas how to use recursive=20 fuction?
can email me any suggestions at loizie@hotmail.com
------=_NextPart_001_0010_01C32721.68799B70-- ------=_NextPart_000_000F_01C32721.68799B70 Content-Type: application/octet-stream; name="pro02.py" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="pro02.py" #def isString() import string myString = raw_input("enter string:") num=len(myString) print myString print len(myString) n=1 sum=0 while n<=num: if myString[n-1].isdigit(): #print "is digit" sum=sum+int(myString[n-1]) #print sum #else: #print "is not digit" n=n+1 print sum ------=_NextPart_000_000F_01C32721.68799B70-- From py-tutor@fancy.org Sat May 31 19:18:02 2003 From: py-tutor@fancy.org (Tom Plunket) Date: Sat May 31 18:18:02 2003 Subject: [Tutor] -Recursive Functions In-Reply-To: <000e01c3274b$514fa370$69d6c518@6z5lw01> References: <000e01c3274b$514fa370$69d6c518@6z5lw01> Message-ID: <5eaidvsi9494djnaeqs5237orlrkncp86s@4ax.com> evros loizides wrote: > * Your program should accept a string using the raw_input function. Show us what you have so far and what steps you've taken to solve the problem. -tom! From magnus@thinkware.se Sat May 31 20:42:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 31 19:42:01 2003 Subject: [Tutor] unit testing In-Reply-To: References: <5.2.1.1.0.20030531132233.01f79e30@www.thinkware.se> <5.2.1.1.0.20030531132233.01f79e30@www.thinkware.se> Message-ID: <5.2.1.1.0.20030601010722.01fa9e50@www.thinkware.se> Warning: I just got home from testing three fine malts (well, two fine and one reasonable). Don't trust what I write below. :) At 11:05 2003-05-31 -0700, Tom Plunket wrote: >Sure- is there a way that I can call __import__ to look like >"from x import *" though? The simplest solution I can think of is to do for filename in glob.glob('test_*.py): exec "from %s import *" % filename[:-3] As I said, I advise against this. >Interesting. My only fear is that, for a program with a lot of >modules, that this spits a lot of trash on the screen. Real sample session: P:\XXX>utsts.py Running ccc_ut.py . ---------------------------------------------------------------------- Ran 1 tests in 0.321s OK Running container_ut.py ............ ---------------------------------------------------------------------- Ran 12 tests in 0.300s OK Running entities_ut.py ............................................................................. ---------------------------------------------------------------------- Ran 77 tests in 4.576s OK Running h2util_ut.py ..... ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK Running kbase_ut.py .... ---------------------------------------------------------------------- Ran 4 tests in 0.641s OK Running matrix_ut.py ................ ---------------------------------------------------------------------- Ran 16 tests in 0.010s OK Running session_ut.py ..... ---------------------------------------------------------------------- Ran 5 tests in 0.161s OK Running settings_ut.py ........ ---------------------------------------------------------------------- Ran 8 tests in 0.260s OK Ran 8 test modules in 25.326 seconds real time Make sure that you have a big screen buffer in your cmd.exe so that you can scroll back if needed... > > By doing it like this, I also know that each test module is run > > independently, that there are no inadvertant dependencies between > > test modules, since each module runs in a new process. > >That's a good point, although I do try to make sure there are no >dependencies anyway by limiting my use of global variables to >none and trying to always create new class instances. :) But this means that you might have problems with functions defined in a test module. A quick check reveals that I have a global function called 'init' in four of my test suites. Running all the test suites in one big namespace means that I have to avoid things like that. I prefer not to create such restrictions for myself. It's also quite possible to have the same class name in two modules. Why not have an activities.Rest that handles relaxation for the staff as well as a fractions.Rest that handles the recycling fractions that don't go into categories like Glass, metal etc. That will mean that if you first import class RestTest from activities, and then RestTest from fractions, you will only run the RestTest cases for fractions. activities.RestTest will be hidden. >C:\Documents and Settings\tom\My Documents>type test.py >import test.regrtest test.py is importing itself! :) Rename it to something else. I guess the tutorial should have something about this in large flaming letters where it discusses imports. Jen had almost the same problem a few days ago. But it was funny that it was a self reference this time! :) >Hmm- there's something interesting. Maybe I could hack unittest >so that it takes a list of modules to run. ...or maybe that's >what that 'argv' parameter is for. Hmm, maybe I can do it just >by passing my 'tests' list in as argv. Please tell us what you found. Separate namespaces are probably enough protection, even if separate processes feel *very* safe... As you see above, my total testing time is a lot longer than the sum of times for each test. I'm sure module loading takes some time, but maybe a better approach could save me ten seconds or so... >Yes indeed- I actually had similar frustrations when moving >between C++ compilers, even. The way to do things optimally >often depended entirely on the compiler. :( You mean like when you build something with Visual C++ and get no warnings, and in Unix you get hundreds, and realize that you have done things that are obviously not correct C++, but the "forgiving" Visual C++ compiler guessed what you meant, and didn't even bother to tell you that you were wrong. It's just the same as with HTML code for MS IE and other browsers. Old MS tactics. Make it easy for programmers to get all their code to run with our compiler, and make it difficult to get what they develop with our tools to compile with other tools. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program