From gus.tabares@verizon.net Sat Sep 6 05:17:27 2003 From: gus.tabares@verizon.net (Gus Tabares) Date: Sat, 6 Sep 2003 00:17:27 -0400 (EDT) Subject: [Tutor] Is there a file creator? In-Reply-To: <200209070304.g87342W13581@mail21.bigmailbox.com> Message-ID: SA, I think when you open a file in write mode, if the file doesn't already exists, it will be created, hence, it will start empty. Hope this helps... Gus On Fri, 6 Sep 2002, S A wrote: > Is there a function or module that creates an empty file like the unix command "touch" does? > > > Thanks. > SA > > > > "I can do everything on my Mac that I used to do on my PC, plus alot more ..." > > -Me > > ------------------------------------------------------------ > Free, BeOS-friendly email accounts: http://BeMail.org/ > BeOS News and Community: http://www.BeGroovy.com/ > > > --------------------------------------------------------------------- > Express yourself with a super cool email address from BigMailBox.com. > Hundreds of choices. It's free! > http://www.bigmailbox.com > --------------------------------------------------------------------- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From learning.python at dbmail.dk Mon Sep 1 05:27:04 2003 From: learning.python at dbmail.dk (Ole Jensen) Date: Sun Aug 31 22:28:39 2003 Subject: [Tutor] WAIDW - copying list within a recursive function Message-ID: <007001c37030$883cc150$a64c73d5@BAERBAR> WAIDW == (W)hat (A)m (I) (D)oing (W)rong (Question put short: Why does this function return; None? ### def shuffle(i=24, deck=[]): a = [ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king] deck.append(a[:]) print deck if i > 0: print "if i > 0" shuffle(i-1, deck) elif i == 0: print "elif i == 0" print deck return deck else: print "failsafe" ### Read below for more detailed describtion of my wrong doings ;) ) I'm trying to create a list representing a stack of cards containing six card decks, I do not really care much of the about colour so my stack would come to look like this: ### stack = [[ace, 2, 3,....., king], [ace, 2, 3,....., king],........,[ace, 2, 3,...., king] ### The above should symbolise a list (stack) with 24 lists of different colours (allthough the colours e.g. clubs or hearts, are not shown as such). Now call me lazy but I would prefer not to type all those those identical lists manually (both easthatically and labour wise), so I saw this as a good time to try to play around with recursive functions (easily done in a forloop with two lines, but now I'm stubborn). The best bit of code I have come up with untill now is this: ### def shuffle(i=24, deck=[]): a = [ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king] deck.append(a[:]) print deck if i > 0: print "if i > 0" shuffle(i-1, deck) elif i == 0: print "elif i == 0" print deck return deck else: print "failsafe" ### (The print statements are for testing) Which of course doesn't work (Otherwise I wouldn't be writing this mail)! The the output ends up like this: [[11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]] if i > 0 [[11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10], [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]] if i > 0 etc. etc. These few lines above shows me that everything shaping about nicely, the list is looking the way it's supposed to. In the end of the output i finally equals 0, and the list is printed a final time looking complete (len(deck) == 24). When the next command in the sourcecode reads: return deck. ### elif i == 0: print "elif i == 0" print deck return deck ### My question is this: If the list "deck" is as it is supposed to (and it looks to be), then why does the function return; None? In advance thanks for any enlightment. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030901/590eb7f9/attachment.htm From pythontutor at venix.com Mon Sep 1 00:21:47 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sun Aug 31 23:22:19 2003 Subject: [Tutor] WAIDW - copying list within a recursive function In-Reply-To: <007001c37030$883cc150$a64c73d5@BAERBAR> References: <007001c37030$883cc150$a64c73d5@BAERBAR> Message-ID: <3F52BB4B.2030806@venix.com> This function will return a None if it ends though your failsafe else OR if it ends through a non-zero i. It is not ending through the failsafe branch since we do not see the printing of failsafe. When the i==0 path returns the deck, it is returning it to the i==1 invocation of shuffle. That invocation does NOT have an explicit return, so it returns None to the i == 2 invocation and so on. The fix is: .... if i > 0: print "if i > 0" shuffle(i-1, deck) return deck .... Ole Jensen wrote: > WAIDW == (W)hat (A)m (I) (D)oing (W)rong > > (Question put short: > Why does this function return; None? > ### > def shuffle(i=24, deck=[]): > a = [ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king] > deck.append(a[:]) > print deck > if i > 0: > print "if i > 0" > shuffle(i-1, deck) > elif i == 0: > print "elif i == 0" > print deck > return deck > else: print "failsafe" > ### > > Read below for more detailed describtion of my wrong doings ;) > ) > > I'm trying to create a list representing a stack of cards containing six > card decks, I do not really care much of the about colour so my stack > would come to look like this: > > ### > stack = [[ace, 2, 3,....., king], [ace, 2, 3,....., king],........,[ace, > 2, 3,...., king] > ### > > The above should symbolise a list (stack) with 24 lists of different > colours (allthough the colours e.g. clubs or hearts, are not shown as such). > > Now call me lazy but I would prefer not to type all those those > identical lists manually (both easthatically and labour wise), so I saw > this as a good time to try to play around with recursive functions > (easily done in a forloop with two lines, but now I'm stubborn). > The best bit of code I have come up with untill now is this: > > ### > def shuffle(i=24, deck=[]): > a = [ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king] > deck.append(a[:]) > print deck > if i > 0: > print "if i > 0" > shuffle(i-1, deck) > elif i == 0: > print "elif i == 0" > print deck > return deck > else: print "failsafe" > ### > (The print statements are for testing) > > Which of course doesn't work (Otherwise I wouldn't be writing this mail)! > The the output ends up like this: > [[11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]] > if i > 0 > [[11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10], [11, 2, 3, 4, 5, 6, 7, 8, > 9, 10, 10, 10, 10]] > if i > 0 > etc. etc. > These few lines above shows me that everything shaping about nicely, the > list is looking the way it's supposed to. > > In the end of the output i finally equals 0, and the list is printed a > final time looking complete (len(deck) == 24). When the next command in > the sourcecode reads: return deck. > > ### > elif i == 0: > print "elif i == 0" > print deck > return deck > ### > > My question is this: > If the list "deck" is as it is supposed to (and it looks to be), then > why does the function return; None? > > In advance thanks for any enlightment. > > > > ------------------------------------------------------------------------ > > _______________________________________________ > 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 lobow at brturbo.com Mon Sep 1 17:01:24 2003 From: lobow at brturbo.com (Diego Galho Prestes) Date: Mon Sep 1 15:00:11 2003 Subject: [Tutor] WxArt2d Message-ID: <3F539784.9090800@brturbo.com> Hi! Someone know if I can use wxart2d in Python? Diego From alan.gauld at blueyonder.co.uk Mon Sep 1 22:23:31 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Sep 1 16:24:53 2003 Subject: [Tutor] using the modules and command prompt References: Message-ID: <004601c370c6$e970dfb0$6401a8c0@xp> > use the winsound module - but i dont know how. Neither do I sorry... > I would also like to know/if how you can python to open > up cmd.exe or similar and run commands such as ping. First, ping is not in cmd.exe it's a separate exe file. (C:\WINDOWS\System32\ping.exe on my system) You can execute ping from python using os.system('ping www.python.org') or to capture the output for later processing use os.popen() There is also a recent addition to Python that makes this easier but I've forgotten its name, maybe someone else can advise... But CD,MD etc for example are builtin commands of cmd.exe and to execute those you may need to use the command flags of CMD.EXE Try typing HELP CMD at the DOS prompt. Usually /C suffices: os.system(r"CMD.EXE /C CD C:\TEMP") HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Mon Sep 1 20:29:31 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Sep 1 21:31:27 2003 Subject: [Tutor] regular expression question In-Reply-To: <1062323186.8cd28ba0exnihilo@myrealbox.com> Message-ID: <5.2.1.1.0.20030901192658.02e8a118@66.28.54.253> At 09:46 AM 8/31/2003 +0000, nihilo wrote: >hi, > >I'm stuck on a regular expression. I want to match everything starting >from a word up to and including the next occurence of the word. > >If the word were a single character (say 'a'), then I could do the following: > >pat = re.compile('a[^a]*a') > >The problem is that I haven't been able to find out how to exclude the >word if it is more than one character. [^word] excludes the individual >letters, not the word as a whole, and I tried grouping with braces and >parentheses [^(word)], but these don't work. I've checked many re >tutorials, and they all say how to exclude a single character from the set >of characters inside the brackets, but not how to exclude more than 1 >character. Instead of asking it to exclude the word just match from word to word: re.findall(r'.*?(word.*?word).*', 'A word to the wise is word enough') gives: ['word to the wise is word'] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From bgailer at alum.rpi.edu Mon Sep 1 21:02:33 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Sep 1 22:04:29 2003 Subject: [Tutor] problems with win32com.client and excel. In-Reply-To: <200308312101.23309.thomi@imail.net.nz> Message-ID: <5.2.1.1.0.20030901194039.02ea2db0@66.28.54.253> At 09:01 PM 8/31/2003 +1200, Thomi Richards wrote: >For the last month or so I've been trying to develop a piece of a program >which enters numbers into an excel spreadsheet. I've managed to get it to go >from the interactive interpreter, but as soon as I put those same commands >into a file, I get errors: > >---- >Traceback (most recent call last): > File "wedderburn.py", line 467, in idle > self.xlapp.adddata((command,args)) > File "C:\Documents and >Settings\Administrator\Desktop\wedderburn\excelspread.py", line 58, in >adddata > self.app.ActiveSheet.Cells(self.x,self.y).Value = d #insert the data > into >the sheet. > File "C:\PYTHON23\lib\site-packages\win32com\client\dynamic.py", line 154, >in __call__ > return >self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None) >pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, >None, 0, -2146827284), None) >---- > >This is the file "excelspread.py": > >-- >#!/usr/bin/python > >import os,sys > >if os.name != 'nt': > print "we're not in a win32 environment, so excel logging will > not be >available." > sys.exit(1) > >try: > import win32com.client >except: > print "you don't seem to have the python windows/COM > extensions >installed!\n\nget them from: http://www.python.org/windows/" > sys.exit(1) > > >'''This file contains functions and classes to append information to an excel >spreadsheet.''' > >class app: > def __init__(self,title="Weight SpreadSheet:"): > > #we have to start excel with a spreadsheet, and put up > the title. > > self.x = self.y = self.width = 0 > > self.app = win32com.client.Dispatch("Excel.Application") > self.app.Visible = 1 > self.app.Workbooks.Add() > > #set the title: > self.app.ActiveSheet.Cells(1,1).Value = title > self.y += 1 > > self.initial = 1 > self.cols = {} > > > #that's it as far as initialisation goes... > > def adddata(self,values): > # values will be a two part list. he first part will > always contain the > # text string 'DATA'. THe second part will be a list of > lists. these > # inner lists will contain two values. the first will be > a header code, > # the second item will be the actual data. this from the > dummy driver: > # > # return >['DATA',[['CODENO','0125846'],['NETWEIGHT',netw],['GROSSWEIGHT',grossw],['TARE',tare]]] > # > code,data = values #unpack the values. > > self.x = 0 > self.y += 1 > > if self.initial: > #this is the first time we have added data to the > spreadsheet. we need to >set up > #the column headers. > for chunk in data: > c,d = > chunk #unpack the code chunk > self.cols[c] = > self.x #add entry to cols dictionary. > >self.app.ActiveSheet.Cells(self.x,self.y).Value = d #insert the data into >the sheet. > self.x += > 1 #incriment the x column > self.initial = 0 > else: > for chunk in data: > c,d = chunk #unpack the code chunk. > self.x = self.cols.get(c,10) #put > error messages in col 10 > >self.app.ActiveSheet.Cells(self.x,self.y).Value = d > > >if __name__ == '__main__': > xl = app() > # this is the format that data is sent to the class: > >xl.adddata(['DATA'[['HEADER1','VALUE1'],['HEADER2','VALUE2'],['HEADER3','VALUE3'],['HEADER4','VALUE','4']]]) This is as far as I got running the program in PythonWin. Traceback (most recent call last): File "J:\samis\python\xl.py", line 53, in ? xl.adddata(['DATA'[['HEADER1','VALUE1'],['HEADER2','VALUE2'],['HEADER3','VALUE3'],['HEADER4','VALUE','4']]]) TypeError: sequence index must be integer To get past that error I had t add a comma after data: xl.adddata(['DATA',[['HEADER1','VALUE1'],['HEADER2','VALUE2'],['HEADER3','VALUE3'],['HEADER4','VALUE','4']]]) [snip] Also I wonder why this line is not indented the same as xl = app(). This will not stop the program from working as long as its name is __main__, but if you import it, you'll get NameError: name 'xl' is not defined Even in PythonWin the program then gets the error you posted. The reason is that you are indexing Cells(0,1) and Excel Cell indexing starts at 1. I changed self.x = 0 to self.x = 1. Then I got yet another error that required me to change ['HEADER4','VALUE','4'] ot ['HEADER4','VALUE4']. Then it works fine as a module. I wonder how you got it to run at all! Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From brian at dungeoncrawl.org Tue Sep 2 01:50:33 2003 From: brian at dungeoncrawl.org (Brian Christopher Robinson) Date: Tue Sep 2 00:51:03 2003 Subject: [Tutor] for x in myClass Message-ID: <5.2.0.9.0.20030902004429.025724c0@localhost> A friend of mine had an assignment to write a program that would take an array and create another array containing indexes into the first array, then sort the second array according to the values in the first array. So, if you have the array: [1, 50, 0, 42] Your second array, called the tag array, would start out unsorted as: [0, 1, 2, 3] Then sorted it would be: [2, 0, 3, 1] I wanted to create a TagArray (really TagList, but he's working in VB and I'm working in Python, oh well) class. So I wrote this: class TagArray(list): def __init__(self, array): self.array = array for i in range(len(array)): self.append(i) def __getitem__(self, k): return self.array[list.__getitem__(self, k)] def __contains__(self, k): return k in self.array This correctly refers to the original array when you use the bracket notation to get an element. However, if you loop through it, you get the indexes instead of the values they're pointing to in the original array. I overrode __contains__ which is the "in" statement, but apparently that's not the same one used when you do a for loop. How can I override the elements returned when you have a statement like: tag = TagArray([20, 30, 10, 0]) for x in tag: print x this should print 20, 30, etc., not 0, 1, etc. Also, will this cause the sort() method to work? -- reaching out to embrace whatever may come From thomi at imail.net.nz Tue Sep 2 20:21:16 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Tue Sep 2 03:21:20 2003 Subject: [Tutor] problems with win32com.client and excel. In-Reply-To: <5.2.1.1.0.20030901194039.02ea2db0@66.28.54.253> References: <5.2.1.1.0.20030901194039.02ea2db0@66.28.54.253> Message-ID: <200309021921.16361.thomi@imail.net.nz> > > To get past that error I had t add a comma after data: > > xl.adddata(['DATA',[['HEADER1','VALUE1'],['HEADER2','VALUE2'],['HEADER3','V >ALUE3'],['HEADER4','VALUE','4']]]) > DOH!! It never ceases to amaze me what really *stupid* mistakes I make, and compltely fail to notice them, until someone else notices... Not only is it annoying, it's very embarrasing as well ;) > [snip] > Also I wonder why this line is not indented the same as xl = app(). This > will not stop the program from working as long as its name is __main__, but > if you import it, you'll get NameError: name 'xl' is not defined > In the original file it is, But my mail client wraps lines at 79 characters or so, and so it wasn't pasted correctly... > Even in PythonWin the program then gets the error you posted. The reason is > that you are indexing Cells(0,1) and Excel Cell indexing starts at 1. > I changed self.x = 0 to self.x = 1. Then I got yet another error that > required me to change ['HEADER4','VALUE','4'] ot ['HEADER4','VALUE4']. > Yet another really dumb mistake I'm afraid *sigh* Thank you every so much.. I was completely stuck ;) Thanks again. -- Thomi Richards, http://once.sourceforge.net/ From dyoo at hkn.eecs.berkeley.edu Tue Sep 2 01:27:23 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 2 03:27:27 2003 Subject: [Tutor] for x in myClass In-Reply-To: <5.2.0.9.0.20030902004429.025724c0@localhost> Message-ID: On Tue, 2 Sep 2003, Brian Christopher Robinson wrote: > A friend of mine had an assignment to write a program that would take an > array and create another array containing indexes into the first array, > then sort the second array according to the values in the first array. Hi Brian, It looks like you're doing this just out of curiosity, so I'm not too concerned about this being a homework assignment. But if you are doing doing this for homework, please tell us --- we are prohibited from helping much with homework. > So, if you have the array: > > [1, 50, 0, 42] > > Your second array, called the tag array, would start out unsorted as: > > [0, 1, 2, 3] > > Then sorted it would be: > > [2, 0, 3, 1] Ok, this looks like the sort is preceding in decending order. Just wanted to raise that point, since most references to "sorting" assume that we want things in ascending (or more correctly, "nondecending") order. > I wanted to create a TagArray (really TagList, but he's working in VB and > I'm working in Python, oh well) class. So I wrote this: > > class TagArray(list): > def __init__(self, array): > self.array = array > for i in range(len(array)): > self.append(i) Those last two statements can also be written as: self.extend(range(len(array))) extend() is a method that can append multiple elements at a time to a list. One line isn't much, but every bit helps. *grin* > def __getitem__(self, k): > return self.array[list.__getitem__(self, k)] > > def __contains__(self, k): > return k in self.array > > This correctly refers to the original array when you use the bracket > notation to get an element. However, if you loop through it, you get > the indexes instead of the values they're pointing to in the original > array. I overrode __contains__ which is the "in" statement, but > apparently that's not the same one used when you do a for loop. Yes. When we do: for x in L: ... ## Case 1 the 'in' is not the same 'in' as: x in L ## Case 2 and I think the confusion is that they share the same keyword in there. In Case 1, you'll want to override the __iter__() method, which Python uses to get an iterator when it does a 'for' loop: ### >>> class testlist(list): ... def __iter__(self): ... print "Hi, I'm __iter__()!" ... return list.__iter__(self) ... >>> L = testlist([1,2,3]) >>> for x in L: ... print x ... Hi, I'm __iter__()! 1 2 3 ### Case 2 is the one that's handled by __contains__(), so that's why we can see it when we do checks for in-clusion. > Also, will this [overriding __setattr__ and __getattr__] > cause the sort() method to work? This is sorta iffy. This inheritance approach feels fragile to me, because it assumes that sort() will use __getitem__() and __setitem__() during the sort()ing process. There's no such guarantee that sort() will do this, since I don't see any documentation about it in the Library Reference: http://www.python.org/doc/lib/typesseq-mutable.html But let's check this, just to see if it works: ### >>> class test_sort(list): ... def __getitem__(self, index): ... print "I'm __getitem__()!" ... return list.__getitem__(self, index) ... def __setitem__(self, index, value): ... print "I'm __setitem__()!" ... list.__setitem__(self, index, value) ... >>> l = test_sort([3,1,4,1,5,9,2,6]) >>> l.sort() >>> l [1, 1, 2, 3, 4, 5, 6, 9] ### Nope, no go. Looks like sort() does some kind of internal lookup that doesn't use __getitem__() or __setitem__(). It might be better to avoid inheritance here. The approach above tries to augment the list class. But it might be easier to try augmenting the list instance instead. For example, we can "decorate" the original list with indices. ### def decorate_with_indices(L): "Destructively appends L's elements with index numbers." for i in range(len(L)): L[i] = (L[i], i) ### This is something that isn't invisible or transparent --- it does hideously mutate L --- but it's something that's very reversable. Somehow, though, I don't think the original assigment anticipated that sort() was available for use... *grin* Good luck to you. From dyoo at hkn.eecs.berkeley.edu Tue Sep 2 01:40:18 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 2 03:40:28 2003 Subject: [Tutor] for x in myClass In-Reply-To: Message-ID: Hi Brian, >> Your second array, called the tag array, would start out unsorted as: >> >> [0, 1, 2, 3] >> >> Then sorted it would be: >> >> [2, 0, 3, 1] > > Ok, this looks like the sort is preceding in decending order. Just > wanted to raise that point, since most references to "sorting" assume > that we want things in ascending (or more correctly, "nondecending") > order. I'm totally, completely wrong here. I don't know what the heck I was thinking. The sort above is definitely nondecending, not decending. Sorry about that. > Somehow, though, I don't think the original assigment anticipated that > sort() was available for use... *grin* Iff sort() were available to us, then there's an embarassingly simply way to solve this problem. ### >>> def create_tag_array(L): ... tag_array = range(len(L)) ... def mycmp(x, y): ... return cmp(L[x], L[y]) ... tag_array.sort(mycmp) ... return tag_array ... >>> create_tag_array([1, 50, 0, 42]) [2, 0, 3, 1] ### There are other really silly approaches to generate the sorted tag array, and all of the silly approaches involve using sort(). So I'd rather hope that the original assignment does not allow sort() at all. *grin* From marc_barry at hotmail.com Tue Sep 2 05:46:53 2003 From: marc_barry at hotmail.com (Marc Barry) Date: Tue Sep 2 04:47:27 2003 Subject: [Tutor] Compiling Python to Native Machine Code Message-ID: All: Is it possible to compile Python directly to native machine code? The reason I ask is because I am using Python to do some pretty intensive simulations that take anywhere between 10 minutes and a few hours to run. I assume that if I could compile it directly to machine code that this may speed up my simulation times. Does anyone have any experience with doing this? Would there be any significant gains? Regards, Marc P.S. I am doing all this under Windows 2000. _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From RobinHood42 at clickta.com Tue Sep 2 16:49:39 2003 From: RobinHood42 at clickta.com (Robin Hood) Date: Tue Sep 2 04:50:14 2003 Subject: [Tutor] plotting pixels Message-ID: <001501c3712f$25e3e600$605576cb@bangna> Hi everybody. I am very much a newbie to the world of computer programming. I want to do some basic graphics programming under Python, but am having trouble working out what bits and pieces have to be installed where. So far, I have downloaded python itself (2.2.3) (from www.python.org) OpenGLContext-2.0.0b1.win32-py2.2 (from sourceforge.net) and glut-3.7.6-bin What do I do next? Also I'm a little bit confused about the difference between OpenGL and Tkinter. Does Tkinter run "on top" of OpenGL? Please point me to some online documentation if this is an excessively stupid question. Tkinter seems to provide a whole lot of stuff which I don't really need just now (all those widgets) All I really want to be able to do (for now) is to open a window of given pixel dimensions and plot a point at a specified pixel. All additional functionality (such as line and circle drawing algorithms and turtle graphics) I was planning on writting myself (with the help of my computer graphics text book) As a computer programming exercise. You can tell me that this is a complete waste of time because its all been done before. But I don't care. I happen to think its interesting. I have discovered that Tkinter provides turtle graphics. But doesn't seem to let you plot individual pixels. Can somebody please help me get pointed in the right direction? Oh... I should probably mention that I mostly work under Windows 98 But I do also have Linux installed and python installed on Linux (Only problem is that my modem doesn't work under linux, so I'm only connected to the internet via windows) *****A Network is the Opposite of a Hierachy***** From RobinHood42 at clickta.com Tue Sep 2 17:29:00 2003 From: RobinHood42 at clickta.com (Robin Hood) Date: Tue Sep 2 05:29:38 2003 Subject: [Tutor] Windows questions Message-ID: <002f01c37134$a54e0e20$605576cb@bangna> Two dumb questions: 1. How do you set the PATH environment variable for python under windows 98 (So that I can import modules which aren't located in the same folder as python itself) 2. Currently, to execute a python script I have to right click it, choose "edit with IDLE" then choose "run script" from one of the drop down menus. If I just double click on a python script. It automatically executes under the DOS interpreter, and then closes itself too quickly to see what the results were. Is it possible to change this? (That is, make it so that the program doesn't automatically close the DOS Prompt after its finished executing, or get it to automatically execute under the Windows IDLE) *****A Network is the Opposite of a Hierachy***** From dyoo at hkn.eecs.berkeley.edu Tue Sep 2 04:36:50 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 2 06:36:54 2003 Subject: [Tutor] Compiling Python to Native Machine Code In-Reply-To: Message-ID: On Tue, 2 Sep 2003, Marc Barry wrote: > Is it possible to compile Python directly to native machine code? The > reason I ask is because I am using Python to do some pretty intensive > simulations that take anywhere between 10 minutes and a few hours to > run. I assume that if I could compile it directly to machine code that > this may speed up my simulation times. Hi Mark, At the moment, no. You may be able to get some substantial performance by using Psyco, though: http://psyco.sourceforge.net/ If your code is particularly algorithmic in nature, Psyco might do wonders for it. If you can identify which parts of code are performance hogs, we have a few options. For example, it might be possible to recode those performance-critical pieces in another language --- like C or OCaml --- and bind those recoded pieces to Python. If you want to take this route, there's good prior work that's gone into this. *grin* People have written several popular tools to help do this "extending"; you may want to look into Scientific Python's "weave" module: http://www.scipy.org/ as well as SWIG: http://www.swig.org/ > Does anyone have any experience with doing this? Would there be any > significant gains? It really depends on the algorithms that you are using. Do you mind showing us a sample of the kind of calculations you're doing? And do you have a "profile" of your application? Profiles can help pinpoint busy areas of the code. Here's documentation to Python's profiler: http://www.python.org/doc/lib/profile.html Good luck to you! From jboti at integrasoft.ro Tue Sep 2 16:47:34 2003 From: jboti at integrasoft.ro (Jozsa Boti) Date: Tue Sep 2 08:49:22 2003 Subject: [Tutor] TypeError with _mysql module.result.num_rows() Message-ID: <001001c37150$617425b0$3aa2e7c1@integrasoft.ro> Hi, Why do I get a TypeError: function takes no arguments error for a call to num_rows() method of a result object in _mysql module? My usage is: import _mysql db = _mysql.connect() db.query("""show table status""") res = db.store_result() nrws = res.num_rows() and the error message is: Traceback (most recent call last): File "", line 1, in ? TypeError: function takes no arguments -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030902/98e32d1c/attachment.htm From pythontutor at venix.com Tue Sep 2 10:32:10 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Sep 2 09:33:13 2003 Subject: [Tutor] TypeError with _mysql module.result.num_rows() In-Reply-To: <001001c37150$617425b0$3aa2e7c1@integrasoft.ro> References: <001001c37150$617425b0$3aa2e7c1@integrasoft.ro> Message-ID: <3F549BDA.30704@venix.com> This sequence of commands worked for me. Does this query work when using the Python DBI (version 2)? http://www.python.org/peps/pep-0249.html PEP 249 -- Python Database API Specification v2.0 You'd be importing MySQLdb which wraps the _mysql module with the python classes to support the standard DB interface. Jozsa Boti wrote: > Hi, > > Why do I get a > TypeError: function takes no arguments > error for a call to num_rows() method of a result object in _mysql module? > My usage is: > > import _mysql > db = _mysql.connect() > db.query("""show table status""") > res = db.store_result() > nrws = res.num_rows() > > and the error message is: > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: function takes no arguments > > > ------------------------------------------------------------------------ > > _______________________________________________ > 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 idiot1 at netzero.net Tue Sep 2 13:24:52 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Tue Sep 2 12:25:11 2003 Subject: [Tutor] test Message-ID: <3F54C454.8050207@netzero.net> for some reason, I am getting very few messages from the tutor list, and my posts are not appearing. postmaster, listmaster, do you read this list? -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From jeff at ccvcorp.com Tue Sep 2 11:37:42 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Sep 2 13:36:34 2003 Subject: [Tutor] Windows questions References: <002f01c37134$a54e0e20$605576cb@bangna> Message-ID: <3F54D566.5040402@ccvcorp.com> Robin Hood wrote: > 1. How do you set the PATH environment variable for python under windows 98 > (So that I can import modules which aren't located in the same folder as > python itself) The simplest way to do this is to include a file named python.pth in your Python directory -- the filename itself doesn't matter, as long as the extension is '.pth'. Each line of this file should contain a directory name; every directory that's specified in that file will be added to your sys.path, and thus searched for modules. You can also create (in your autoexec.bat or the like) an environment variable named PYTHONPATH, formatted like the PATH variable; those directories will also be searched for modules. > 2. Currently, to execute a python script I have to right click it, choose > "edit with IDLE" then choose "run script" from one of the drop down menus. > If I just double click on a python script. It automatically executes under > the DOS interpreter, and then closes itself too quickly to see what the > results were. Is it possible to change this? (That is, make it so that the > program doesn't automatically close the DOS Prompt after its finished > executing, or get it to automatically execute under the Windows IDLE) One option is to simply add a final line to the script -- 'raw_input("Press Enter to close this program")'. You could also just always start scripts from a command prompt, but that's a bit of a pain. For a more permanent solution, you need to convince Windows to run your scripts with the -i option to Python -- that option will leave Python in interactive mode once the script finishes running. To do this, you need to go to Windows Explorer's Tools menu, select 'Folder Options', and go to the File Types tab. Find the entry for PY files, click on 'Advanced', then select the 'open' entry and hit the Edit button. You'll see the command line that Windows uses when you open files of this type. Now, insert '-i' just after 'python.exe'. You'll probably want to do the same thing for compiled python files (PYC/PYO). Instead of altering the existing open command, you could create a new command that would use the interactive mode, which would let you have the standard behavior for most uses but allow you to right-click and select your new command when you need it. Jeff Shannon Technician/Programmer Credit International From alan.gauld at blueyonder.co.uk Tue Sep 2 20:06:41 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Sep 2 14:07:47 2003 Subject: [Tutor] Compiling Python to Native Machine Code References: Message-ID: <007a01c3717c$f65e1470$6401a8c0@xp> > Is it possible to compile Python directly to native machine code? The reason > I ask is because I am using Python to do some pretty intensive simulations > that take anywhere between 10 minutes and a few hours to run. I assume that > if I could compile it directly to machine code that this may speed up my > simulation times. There has been a recent thread on comp.lang.python about using something called Psycho(?) (sourceforge?) which seemed to get Python code running around half the speed of C (ie about 5-10 times faster than usual!) Significantly this test was done using math calculations so it might work for you too. Another tool in a similar vein that was mentioned was Pyrex... Try searching google groups for the references. Alan g. From amk at asti-usa.com Tue Sep 2 15:20:55 2003 From: amk at asti-usa.com (A.M. Kuchling) Date: Tue Sep 2 14:21:39 2003 Subject: [Tutor] Compiling Python to Native Machine Code In-Reply-To: <007a01c3717c$f65e1470$6401a8c0@xp> References: <007a01c3717c$f65e1470$6401a8c0@xp> Message-ID: <20030902182055.GB32017@vail.asti-usa.com> On Tue, Sep 02, 2003 at 07:06:41PM +0100, Alan Gauld wrote: > There has been a recent thread on comp.lang.python about > using something called Psycho(?) (sourceforge?) which seemed to get psyco: http://psyco.sourceforge.net/ . x86 only. --amk From carroll at tjc.com Tue Sep 2 13:26:01 2003 From: carroll at tjc.com (Terry Carroll) Date: Tue Sep 2 15:26:07 2003 Subject: [Tutor] for x in myClass In-Reply-To: Message-ID: On Tue, 2 Sep 2003, Danny Yoo wrote: > But if you are doing doing this for homework, please tell us --- we are > prohibited from helping much with homework. Really? As long as someone's making an attempt to solve the problem, instead of just stating the problem and asking for a solution, I have no qualms about helping with homework. In my book, "helping with homework" is okay; "doing the homework," not so much. Helping with homework on this list is not too different from the "debug service" I offered as part of the Computer Science Association I was a member of when I was in undergrad. Students would come in with their program listings and ask for help; we'd give it. Sometimes it was true debugging, figuring out why their results were unexpected (or explaining error messages); other times, it was guiding them to the right track. We didn't do their homework, but we helped them with it. As long as the motive is to progress through the work, and not to bypass it, I don't see an issue. Darwin knows you guys have helped me learn a lot (although not with homework). -- Terry Carroll | "I say to you that the VCR is to the American Santa Clara, CA | film producer and the American public as the carroll@tjc.com | Boston strangler is to the woman home alone." | Jack Valenti, MPAA President Modell delendus est | Testimony before Congress, 1982 From idiot1 at netzero.net Tue Sep 2 17:59:55 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Tue Sep 2 17:00:14 2003 Subject: [Fwd: Re: [Tutor] test] Message-ID: <3F5504CB.9080405@netzero.net> Ah, intresting. But they never came through back to me. Is this a mail.python.org issue, a pop3.netzero.net issue, or do I need new glasses? -------- Original Message -------- I have seen a few posts from you. Jerry ----- Original Message ----- From: Kirk Bailey To: Tutor Sent: Tuesday, September 02, 2003 9:24 AM Subject: [Tutor] test for some reason, I am getting very few messages from the tutor list, and my posts are not appearing. postmaster, listmaster, do you read this list? -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From idiot1 at netzero.net Tue Sep 2 18:03:56 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Tue Sep 2 17:04:15 2003 Subject: [Tutor] wikinehesa final Message-ID: <3F5505BC.1080501@netzero.net> Wikinehesa final is out. then I found a version display error, and fixed it. Then I added seed pages to the tarball. The final and no kidding I mean it version with uploader and all, is here: http://www.tinylist.org/wikinehesa.1.2.0.tar.gz and the thing may be inspected and played with here: http://www.tinylist.org/cgi-bin/wikinehesa.py The uploader is working fine, thanks for all the good advice and tolerating my fistrations in working it out. If anyone wants to see the guts of a script to upload files using http/POST, here it is: http://www.tinylist.org/upload.txt end Beers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From dyoo at hkn.eecs.berkeley.edu Tue Sep 2 15:17:19 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 2 17:17:25 2003 Subject: [Tutor] Helping with homework --- reasons for sometimes holding back In-Reply-To: Message-ID: > > But if you are doing doing this for homework, please tell us --- we > > are prohibited from helping much with homework. > > Really? As long as someone's making an attempt to solve the problem, > instead of just stating the problem and asking for a solution, Hi Terry, Questions are perfectly good; I don't have any problems with them at all. It's the latter case, where a person states a Homework Problem and asks for the One Right Answer, where we have to handle things delicately. > I have no qualms about helping with homework. In my book, "helping with > homework" is okay; "doing the homework," not so much. Sure. I feel that there's a thin line between helping and hurting: if we "help" too much, it ends up hurting the learner a lot. That is, if we overdo it, we might risk teaching the wrong lesson, that the learner picks up the habit of coersing the One Right Answer out of a teacher. This isn't to say that this happens on Python-Tutor, but it's something that I've seen happen in classrooms, especially in standardized test-driven curricula. The book "How Children Fail", by John Holt, talks a lot about this: http://educationreformbooks.net/failure.htm and it's just something that's in the back of my mind all the time, because I think Holt's very right. Perhaps it's just baseless to worry about it, but it's still a factor that influences me when I help with a question. For me, personally, I'll often try to answer in a way that doesn't really "answer" --- there's often something that the questioner needs to do to actually get things to work right. Sometimes I do this on accident, but usually, it's on purpose. *grin* More importantly, I also try to link out to primary and secondary URL references, so that the person who's asking knows where to find out more details. Occasionally I forget about restricting myself because the problem is so exciting to me, but in general, I do try to hold back a bit. Anyway, hope that explains my feelings better. Please feel free to ask questions on Python-Tutor; we'll be happy to help! From missive at hotmail.com Tue Sep 2 22:42:31 2003 From: missive at hotmail.com (Lee Harr) Date: Tue Sep 2 17:43:09 2003 Subject: [Tutor] Re: plotting pixels Message-ID: >I want to do some basic graphics programming under Python > >Does Tkinter run "on top" of OpenGL? > No, those are completely separate. You may want to look at pygame (http://pygame.org) which will definitely let you plot points (although it is not generally done that way :o) Also, take a look at my book and the libraries I wrote to help you get started: http://staff.easthighschool.net/lee/computers/book/ http://www.nongnu.org/pygsear/ _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From logiplex at qwest.net Tue Sep 2 16:00:56 2003 From: logiplex at qwest.net (Cliff Wells) Date: Tue Sep 2 18:01:01 2003 Subject: [Tutor] WxArt2d In-Reply-To: <3F539784.9090800@brturbo.com> References: <3F539784.9090800@brturbo.com> Message-ID: <1062540056.28388.62.camel@software1.logiplex.internal> On Mon, 2003-09-01 at 12:01, Diego Galho Prestes wrote: > Hi! Someone know if I can use wxart2d in Python? Check out wxPython: http://www.wxpython.org. It has wxArtProvider, which might be related. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From alan.gauld at blueyonder.co.uk Wed Sep 3 00:23:38 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Sep 2 18:24:43 2003 Subject: [Tutor] Windows questions References: <002f01c37134$a54e0e20$605576cb@bangna> Message-ID: <009701c371a0$dbb5d9e0$6401a8c0@xp> > 1. How do you set the PATH environment variable for python under windows 98 Look it up in the Windows Help file for full info. But basically you add a line in your C:\AUTOEXEC.BAT file that looks like: PATH=%PATH%;C:\PYTHON or wherever you installed Python.... > (So that I can import modules which aren't located in the same folder as > python itself) However to access modules you really need the PYTHONPATH calue set which is similarly in AUTOEXEC.BAT but looks like: SET PYTHONPATH=C:\PROJECTS\PYTHON or wherever you keep you modules > If I just double click on a python script. It automatically executes under > the DOS interpreter, and then closes itself too quickly to see what the > results were. Is it possible to change this? There are several ways. They all have their own advantages: 1) Add a line like raw_input("Hit Enter to quit") at the end of your program. 2) Modify the action associated with opening a Python file using Windows explorer so that the interpreter is called with the -i flag set. This will make your program run then stop in the interpreter at the >>> prompt. 3) Create a shortcut to the file and then set it to leave the window open on completion - only sensible if you ruin the same program a lot. Personally I tend to use the first option. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld (That is, make it so that the > program doesn't automatically close the DOS Prompt after its finished > executing, or get it to automatically execute under the Windows IDLE) > > *****A Network is the Opposite of a Hierachy***** > > > From alan.gauld at blueyonder.co.uk Wed Sep 3 00:26:11 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Sep 2 18:27:14 2003 Subject: [Tutor] Windows questions References: <002f01c37134$a54e0e20$605576cb@bangna> <3F54D566.5040402@ccvcorp.com> Message-ID: <009e01c371a1$367e5c30$6401a8c0@xp> > The simplest way to do this is to include a file named python.pth in > your Python directory -- the filename itself doesn't matter, as long > as the extension is '.pth'. Each line of this file should contain a > directory name; every directory that's specified in that file will be > added to your sys.path, and thus searched for modules. Ooh, thats the first time I've seen this. (Sorry if I just haven't been paying attention!) When did this get added to Python? Has it always been there? Alan G. From jeff at ccvcorp.com Tue Sep 2 17:41:05 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Sep 2 19:38:50 2003 Subject: [Tutor] Windows questions References: <002f01c37134$a54e0e20$605576cb@bangna> <3F54D566.5040402@ccvcorp.com> <009e01c371a1$367e5c30$6401a8c0@xp> Message-ID: <3F552A91.50309@ccvcorp.com> Alan Gauld wrote: >>The simplest way to do this is to include a file named python.pth in >>your Python directory -- the filename itself doesn't matter, as long >>as the extension is '.pth'. Each line of this file should contain a >>directory name; every directory that's specified in that file will >>be added to your sys.path, and thus searched for modules. > > Ooh, thats the first time I've seen this. (Sorry if I just haven't > been > paying attention!) When did this get added to Python? > Has it always been there? It's been there as long as I've been using Python -- since version 2.0 at least. At that point, $pythondir$\Lib\site-packages hadn't been established as the standard place to put third-party packages, so installation of things like PIL tended to require .pth files or the like to allow them to be found (PIL installed its own PIL.pth file, and probably many other packages did as well). It's not so necessary any more, but still useful. Jeff Shannon Technician/Programmer Credit International From klhjhm at hotmail.com Thu Sep 4 17:48:50 2003 From: klhjhm at hotmail.com (kamariah lamim) Date: Thu Sep 4 14:03:33 2003 Subject: [Tutor] spawn Message-ID: Hi.. i just want to know what is the function os.spawn and how to use it _________________________________________________________________ Are you in love? Find a date on MSN Personals http://match.msn.com.my/ From thomi at imail.net.nz Wed Sep 3 23:54:43 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Thu Sep 4 14:42:37 2003 Subject: [Tutor] config file parsing problem. Message-ID: <200309032254.43250.thomi@imail.net.nz> Hi guys, What's the best way to read / write a config file? More specifically: I have a config file with a series of name = value pairs. This file also has comments (line which *start* with a "#" or a ";") amongst the actual data lines. At the moment, I am just opening the file, reading it line by line, and either ignoring it, or exec()ing the line (I know this isn't very safe, but for now it's OK). Now, the problem comes when I want to write the (sometimes changed) values back to this file, without over-writing the comments in the file. What's the best way to do this? I thought of creating a dictionary at file-read-time, containing name : line_number pairs, and then writing the (changed) values back to the same line, but it feels kind of kludgey... Is there a better way? I thought of using reg ex to scan for lines which weren't comments, but then I'd need to identify what the name was, and what line it was on... And I don't know anything about regular expressions. Any ideas? Thanks again ;) -- Thomi Richards, http://once.sourceforge.net/ From marc_barry at hotmail.com Wed Sep 3 05:23:59 2003 From: marc_barry at hotmail.com (Marc Barry) Date: Thu Sep 4 15:09:35 2003 Subject: [Tutor] Compiling Python to Native Machine Code Message-ID: Thanks for the info Danny. First off, I thought that I should download Psyco and install it to see what kind of performance gains could be realised. After running a number of simulations, it looks like I can save about 10% on the execution time. Well this is substantial, I had hoped for more. I think that I may have to recode some of the performance critical code in another language as you mentioned. The type of algorithm I am using is the well known Dijkstra shortest path. I am computing paths in a graph many thousands or even millions of times. To make thinks worse, some of my graphs are very large with 74 - 100 vertices and 230 - 400 bi-directional edges. At each point that a shortest path in the graph is found, the edge weights must be updated (thus changing the graph) and therefore I cannot take any advantage of storing paths that have already been calculated. I have implemented the algorithm as efficient as I know how. I may have to look at implementing the Dijkstra algorithm portion of the simulation in C. Although, it would be a terrible waste of time if I didn't do any better than the 10% reduction I got using Psyco. I thought that there would be more improvement since basically I run the Dijkstra algorithm many times over and over thus making it a prime candidate for compiling to native machine code. Thank you for the help. Cheers, Marc From: Danny Yoo To: Marc Barry CC: tutor@python.org Subject: Re: [Tutor] Compiling Python to Native Machine Code Date: Tue, 2 Sep 2003 03:36:50 -0700 (PDT) On Tue, 2 Sep 2003, Marc Barry wrote: > Is it possible to compile Python directly to native machine code? The > reason I ask is because I am using Python to do some pretty intensive > simulations that take anywhere between 10 minutes and a few hours to > run. I assume that if I could compile it directly to machine code that > this may speed up my simulation times. Hi Mark, At the moment, no. You may be able to get some substantial performance by using Psyco, though: http://psyco.sourceforge.net/ If your code is particularly algorithmic in nature, Psyco might do wonders for it. If you can identify which parts of code are performance hogs, we have a few options. For example, it might be possible to recode those performance-critical pieces in another language --- like C or OCaml --- and bind those recoded pieces to Python. If you want to take this route, there's good prior work that's gone into this. *grin* People have written several popular tools to help do this "extending"; you may want to look into Scientific Python's "weave" module: http://www.scipy.org/ as well as SWIG: http://www.swig.org/ > Does anyone have any experience with doing this? Would there be any > significant gains? It really depends on the algorithms that you are using. Do you mind showing us a sample of the kind of calculations you're doing? And do you have a "profile" of your application? Profiles can help pinpoint busy areas of the code. Here's documentation to Python's profiler: http://www.python.org/doc/lib/profile.html Good luck to you! _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From tpc at csua.berkeley.edu Thu Sep 4 13:40:45 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Sep 4 15:41:01 2003 Subject: [Tutor] multiline comment in Python Message-ID: <20030904123440.C12535-100000@localhost.name> hello all, I am wondering if there is anything other than triple quotes for multiline commenting blocks of code. I am rather disappointed with triple quote commenting because Python sometimes gives me a syntax error which means I have to prepend a # in front of each line which can get tedious. I am running Python 2.2.3 and was really hoping for the /** */ multiline commenting in C and Java. Thanks in advance. From jim_938 at hotmail.com Thu Sep 4 19:55:22 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Thu Sep 4 15:46:58 2003 Subject: [Tutor] hex output Message-ID: Hello *, I am having problem in converting hexadecimal no's according to the format i require. >>>hex(65) '0x41' >>>hex(65)[2:] '41' I want to write it in 4 digits form like this 0041 and also in upper cases. Your suggestion are welcomed. Thanks a lot. Regards, J+ _________________________________________________________________ Need a naukri? Your search ends here. http://www.msn.co.in/naukri/ 50,000 of the best jobs! From jeff at ccvcorp.com Thu Sep 4 14:45:12 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 4 16:43:36 2003 Subject: [Tutor] config file parsing problem. References: <200309032254.43250.thomi@imail.net.nz> Message-ID: <3F57A458.2040209@ccvcorp.com> Thomi Richards wrote: > Hi guys, > > > What's the best way to read / write a config file? More specifically: Have you looked at the ConfigParser module? It's designed to read/write standard Windows INI files -- i.e., name=value pairs grouped into sections. Jeff Shannon Technician/Programmer Credit International From amk at amk.ca Thu Sep 4 13:48:27 2003 From: amk at amk.ca (A.M. Kuchling) Date: Thu Sep 4 16:44:16 2003 Subject: [Tutor] hex output In-Reply-To: References: Message-ID: <20030904164827.GA3483@nyman.amk.ca> On Thu, Sep 04, 2003 at 06:55:22PM +0530, Jimmy verma wrote: >I want to write it in 4 digits form like this 0041 >and also in upper cases. Use the string formatting operator %: >>> '%04X' % 45677 'B26D' --amk From abli at freemail.hu Thu Sep 4 23:55:22 2003 From: abli at freemail.hu (Abel Daniel) Date: Thu Sep 4 16:55:05 2003 Subject: [Tutor] Re: hex output In-Reply-To: (Jimmy verma's message of "Thu, 04 Sep 2003 18:55:22 +0530") References: Message-ID: <871xuwp939.fsf@hooloovoo.i-did-not-set--mail-host-address--so-tickle-me> "Jimmy verma" writes: > I am having problem in converting hexadecimal no's according to the > format i require. > I want to write it in 4 digits form like this 0041 > and also in upper cases. String formatting can do what you want: >>> "%04X"%65 '0041' >>> "%04X"%15 '000F' For more info (and the meaning of the syntax) see chapter 2.2.6.2 of the library reference (String Formatting Operations): http://python.org/doc/current/lib/typesseq-strings.html Abel Daniel ps. the above solution pads to number to get a four-digit one, but won't truncate it, resulting in: >>> "%04X"%65000000 '3DFD240' I don't really think you want to truncate (as that will mangle the number, loosing information). From dyoo at hkn.eecs.berkeley.edu Thu Sep 4 15:21:46 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 4 17:21:52 2003 Subject: [Tutor] multiline comment in Python In-Reply-To: <20030904123440.C12535-100000@localhost.name> Message-ID: On Thu, 4 Sep 2003 tpc@csua.berkeley.edu wrote: > hello all, I am wondering if there is anything other than triple quotes > for multiline commenting blocks of code. Hi tpc, ... that's a novel use of triple quotes that I hadn't thought about! *grin* It's not really meant for commenting --- it's really meant for multi-line string literals. > I am rather disappointed with triple quote commenting because Python > sometimes gives me a syntax error which means I have to prepend a # in > front of each line which can get tedious. Hmmm... what kind of text editor are you using? In the Emacs text editor, there is a single command to do block commenting C-c # which is very convenient to work with. Uncommenting a block is also not too bad, C-u C-c # But that's just Emacs. Tell us which text editor you're using; I'm positive someone here can help you with the correct key contortions. > I am running Python 2.2.3 and was really hoping for the /** */ multiline > commenting in C and Java. I don't think there is one in Python. It's not too much of a loss, though, if you are using a good text editor. But there's a severe problem with multiline commenting in C and Java: it is not nestable! For example, let's take some possible C code: /** commented out; we don't need it printf("This is a test"); /** test to see if standard out works */ **/ This just completely breaks because C and Java's lexical analyzer just doesn't know how to handle it --- the underlying lexer is using a regular expression and therefore can't keep track of nested comments. So if you have code with comments in it, trying to use multi-line commenting on it has the potential to break badly. The single-line commenting character, on the other hand, has no potential to suffer from this problem, //// commented out; we don't need it // System.out.println("This is a test"); // test to see if // // standard out works (But some languages, like OCaml, do have good multi-line commenting features, so I guess that's not quite as strong a reason as I'd like... *grin*) Hope this helps! From idiot1 at netzero.net Tue Sep 2 22:08:25 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Thu Sep 4 17:34:59 2003 Subject: [Tutor] Re: plotting pixels In-Reply-To: References: Message-ID: <3F553F09.1000008@netzero.net> plotting pixels. hmmm... Fractals? MathArt? just musing a little. no application in mind, just musing... And remembering in the book 'Hackers' the breif mention of a great hack- a 'smoking electric clover'. Thing drew a 4 leaf cloverlike shape, eacy ray from the center changed color from the previous slightly, and the thing went around and around, gradually shifting colors, so they were forever slowly rotating around in a rainbow. In the '60's, this was pretty radical stuff, possibly one of the earliest realtime animated computer arts- comment? And I also seem to recall someplace there is a turtle module or add on. just musing... Lee Harr wrote: >> I want to do some basic graphics programming under Python >> > >> Does Tkinter run "on top" of OpenGL? >> > > > No, those are completely separate. > > You may want to look at pygame (http://pygame.org) which > will definitely let you plot points (although it is not generally > done that way :o) > > Also, take a look at my book and the libraries I wrote to > help you get started: > > http://staff.easthighschool.net/lee/computers/book/ > http://www.nongnu.org/pygsear/ > > _________________________________________________________________ > 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 > > -- -- end Cheers! Kirk D Bailey + thunk + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + thunk + Fnord. From david at graniteweb.com Thu Sep 4 17:39:58 2003 From: david at graniteweb.com (David Rock) Date: Thu Sep 4 17:40:04 2003 Subject: [Tutor] config file parsing problem. In-Reply-To: <200309032254.43250.thomi@imail.net.nz> References: <200309032254.43250.thomi@imail.net.nz> Message-ID: <20030904213958.GA27122@wdfs.graniteweb.com> * Thomi Richards [2003-09-03 22:54]: > > Hi guys, > > > What's the best way to read / write a config file? More specifically: > > I have a config file with a series of name = value pairs. This file also has > comments (line which *start* with a "#" or a ";") amongst the actual data > lines. At the moment, I am just opening the file, reading it line by line, > and either ignoring it, or exec()ing the line (I know this isn't very safe, > but for now it's OK). > > Now, the problem comes when I want to write the (sometimes changed) values > back to this file, without over-writing the comments in the file. What's the > best way to do this? I thought of creating a dictionary at file-read-time, > containing name : line_number pairs, and then writing the (changed) values > back to the same line, but it feels kind of kludgey... Is there a better way? > I thought of using reg ex to scan for lines which weren't comments, but then > I'd need to identify what the name was, and what line it was on... And I > don't know anything about regular expressions. Try using the fileinput module: http://python.org/doc/current/lib/module-fileinput.html It has an option for inplace file editing, similar to perl's -i option. -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20030904/aac14bd9/attachment.bin From amk at amk.ca Thu Sep 4 14:46:15 2003 From: amk at amk.ca (A.M. Kuchling) Date: Thu Sep 4 17:42:01 2003 Subject: [Tutor] Python - XML: How to write UNICODE to a file ?? (when using LATIN-1 Chars) In-Reply-To: <001301c36b56$d64436a0$0100a8c0@uno> References: <001301c36b56$d64436a0$0100a8c0@uno> Message-ID: <20030904174615.GA4286@nyman.amk.ca> On Tue, Aug 26, 2003 at 12:18:38AM +0200, Javier JJ wrote: >I have an xml file with ASCII characters (no encoding is specified; it >contains characters valid in the latin-1 charset - it's a log file >generated by MSN Messenger 6.0). >>>> out.write(listado) > >Traceback (most recent call last): > File "", line 1, in -toplevel- > out.write(listado) >UnicodeEncodeError: 'ascii' codec can't encode character '\ued' in >position 2274: ordinal not in range(128) The default encoding in Python is ASCII, so characters over 127 aren't handled by default. If you want some other encoding (for Spanish, Latin-1 is probably what you want), you need to convert it explicitly: s = u'whatever ...' output.write(s.encode('iso-8859-1')) --amk From alan.gauld at blueyonder.co.uk Thu Sep 4 23:48:30 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 4 17:49:03 2003 Subject: [Tutor] Compiling Python to Native Machine Code References: Message-ID: <010501c3732e$47f0d040$6401a8c0@xp> > The type of algorithm I am using is the well known Dijkstra > shortest path. I Ah. That is a difficult one to improve on in Python because its not really compute intensive but doing lots of tests and branches. And as you navigate the graph over and over again the logic, even in C - even in Machine Code! - will be doing lots of loading and unloading of registers and branch instructions. If you can code the algorithm in C then it will go faster, and probably faster than Psyco, but just how much faster is debateable, you are doing something that just plain takes a lot of time. The first thing to do is use Python to optimise the design of the proposed function so that its easy to port to C and profile it to see just how much of the total time is in that functon. Divide that time by 5-10 and that's roughly what you should see the C version doing. If that isn't a big chunk of the total you may be better sticking in Python after all. Alan G. From alan.gauld at blueyonder.co.uk Fri Sep 5 00:09:25 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 4 18:09:20 2003 Subject: [Tutor] multiline comment in Python References: <20030904123440.C12535-100000@localhost.name> Message-ID: <010a01c37331$33a44060$6401a8c0@xp> > hello all, I am wondering if there is anything other than triple quotes > for multiline commenting blocks of code. triple quotes aren't really comments, although they kind of act like that. But if you use IDLE or Pythonwin or Emacs you can select a block and comment it out (and later uncomment it if need be) using editor commands. And using vi(or vim or elvis) its nearly as easy. [using :m,ns/^/#/ and :m,ns/^#// in vim you can use the visual block mode to select the comment region. I suppose you could even map it to a key if you wanted] In other words you can type the comment text in and then retrospectively turn it into a comment... HTH, Alan G. From tpc at csua.berkeley.edu Thu Sep 4 16:14:01 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Sep 4 18:14:06 2003 Subject: [Tutor] multiline comment in Python In-Reply-To: Message-ID: <20030904145724.J12926-100000@localhost.name> hi Danny, thanks I did not know Emacs had that feature. I was wondering how to comment out multiple lines if I use vi on the console. I know 'I' inserts at the beginning of the current line, although I don't know how to do so across multiple lines. That's where a feature like C and Java style multiline commenting would come in handy, although I do see your point and have never had to comment out a code block that already had multiline comments. On Thu, 4 Sep 2003, Danny Yoo wrote: > > > On Thu, 4 Sep 2003 tpc@csua.berkeley.edu wrote: > > > hello all, I am wondering if there is anything other than triple quotes > > for multiline commenting blocks of code. > > Hmmm... what kind of text editor are you using? In the Emacs text editor, > there is a single command to do block commenting > > C-c # > > which is very convenient to work with. Uncommenting a block is also not > too bad, > > C-u C-c # > > But that's just Emacs. Tell us which text editor you're using; I'm > positive someone here can help you with the correct key contortions. > From alan.gauld at blueyonder.co.uk Fri Sep 5 00:19:10 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 4 18:18:55 2003 Subject: [Tutor] multiline comment in Python References: Message-ID: <011801c37332$906e4290$6401a8c0@xp> > ... that's a novel use of triple quotes that I hadn't thought about! > *grin* It's not really meant for commenting --- it's really meant for > multi-line string literals. Not if its a doc string - which is a kind of multi-line comment... Alan G. From brian at dungeoncrawl.org Tue Sep 2 22:35:35 2003 From: brian at dungeoncrawl.org (Brian Christopher Robinson) Date: Thu Sep 4 18:54:17 2003 Subject: [Tutor] Re: Tutor Digest, Vol 2, Issue 2 In-Reply-To: Message-ID: <5.2.0.9.0.20030902210344.02575670@localhost> At 04:50 AM 2/09/03, you wrote: >It looks like you're doing this just out of curiosity, so I'm not too >concerned about this being a homework assignment. But if you are doing >doing this for homework, please tell us --- we are prohibited from helping >much with homework. Actually, a it was a friend's homework assignment but he's completed it already and I'm not a student at all. I just thought it was an interesting problem that would let me try out some things in Python. >Those last two statements can also be written as: > > self.extend(range(len(array))) > >extend() is a method that can append multiple elements at a time to a >list. One line isn't much, but every bit helps. *grin* Ok, thanks. I put this in. >In Case 1, you'll want to override the __iter__() method, which Python >uses to get an iterator when it does a 'for' loop: Ok, this is what I put as a member of my TagSort class: def __iter__(self): return self.array.__iter__() Now, this is actually wrong since it doesn't take in to account the order of the TagArray. But this doesn't even work at all. Instead I get the message: AttributeError: 'list' object has no attribute '__iter__' What's that all about? So then I wrote this: def __iter__(self): class TagIterator: def __init__(self, tagArray): self.tagArray = tagArray self.count = 0 def __iter__(self): return self def next(self): try: value = self.tagArray[self.count] except: raise StopIteration() self.count += 1 return value return TagIterator(self) Which appears to work. I still can't call the sort method on my TagArray class, though. >Iff sort() were available to us, then there's an embarassingly simply way >to solve this problem. > >### > >>> def create_tag_array(L): >... tag_array = range(len(L)) >... def mycmp(x, y): >... return cmp(L[x], L[y]) >... tag_array.sort(mycmp) >... return tag_array >... > >>> create_tag_array([1, 50, 0, 42]) >[2, 0, 3, 1] >### I tried to do something like this originally, but I couldn't quite get the syntax right. Thanks. >There are other really silly approaches to generate the sorted tag array, >and all of the silly approaches involve using sort(). So I'd rather hope >that the original assignment does not allow sort() at all. *grin* It wasn't an assignment about sorting specifically, so I don't see why you couldn't use the sort method. My first attempt was this: def tagSort(array): copy = array[:] # copies the array copy.sort() indexes = [] for number in copy: indexes.append(array.index(number)) return indexes Which works great. My friend was opposed to the copy, though, so I wrote this: def tagSort2(array): tag = range(len(array)) # creates a list from 0 to array length for i in range(len(array)): for j in range(len(array[:-(i+1)])): if array[tag[j + 1]] < array[tag[j]]: tag[j + 1], tag[j] = tag[j], tag[j + 1] return tag Which just does a bubble sort with the indirection. I just wanted to pursue the object way because I'd like to be able to write: def tagSort3(array): tag = TagArray(array) tag.sort() return tag -- reaching out to embrace whatever may come From logiplex at qwest.net Thu Sep 4 16:43:10 2003 From: logiplex at qwest.net (Cliff Wells) Date: Thu Sep 4 19:00:32 2003 Subject: [Tutor] config file parsing problem. In-Reply-To: <200309032254.43250.thomi@imail.net.nz> References: <200309032254.43250.thomi@imail.net.nz> Message-ID: <1062715390.28388.784.camel@software1.logiplex.internal> On Wed, 2003-09-03 at 03:54, Thomi Richards wrote: > Hi guys, > > > What's the best way to read / write a config file? More specifically: > > I have a config file with a series of name = value pairs. This file also has > comments (line which *start* with a "#" or a ";") amongst the actual data > lines. At the moment, I am just opening the file, reading it line by line, > and either ignoring it, or exec()ing the line (I know this isn't very safe, > but for now it's OK). Why not just use the ConfigParser module? -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From dyoo at hkn.eecs.berkeley.edu Thu Sep 4 17:10:24 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 4 19:10:32 2003 Subject: [Tutor] config file parsing problem. In-Reply-To: <20030904213958.GA27122@wdfs.graniteweb.com> Message-ID: On Thu, 4 Sep 2003, David Rock wrote: > > Now, the problem comes when I want to write the (sometimes changed) > > values back to this file, without over-writing the comments in the > > file. What's the best way to do this? I thought of creating a > > dictionary at file-read-time, containing name : line_number pairs, and > > then writing the (changed) values back to the same line, but it feels > > kind of kludgey... Is there a better way? I thought of using reg ex > > to scan for lines which weren't comments, but then I'd need to > > identify what the name was, and what line it was on... And I don't > > know anything about regular expressions. > > > Try using the fileinput module: > > http://python.org/doc/current/lib/module-fileinput.html > > It has an option for inplace file editing, similar to perl's -i option. Hi David, You may also want to try ConfigParser: http://www.python.org/doc/lib/module-ConfigParser.html It does almost exactly what you want, except perhaps not the maintenance of comments. I'm not so sure if ConfigParser preserves comments when a file is saved. Let's check: ### >>> from StringIO import StringIO >>> cfg_file = StringIO(""" ... [My Section] ... ## Fill in name here ... name=david rock ... """) >>> import ConfigParser >>> p = ConfigParser.ConfigParser() >>> p.readfp(cfg_file) >>> p.sections() ['My Section'] >>> p.options('My Section') ['name'] >>> p.get('My Section', 'name') 'david rock' >>> p.set('My Section', 'answer', '42') >>> f2 = StringIO() >>> p.write(f2) >>> f2.getvalue() '[My Section]\nanswer = 42\nname = david rock\n\n' ### Close, but unfortunately, this shows that it doesn't preserves comments. But I think it's very close to what you're asking for. Are you commenting individual options? And how are comments "attached" to the key-value pairs? On the same line, or on top? Perhaps ConfigParser could be extended to preserve comments that are attached to certain options. Tell us a little more about the problem, and perhaps we can see if ConfigParser can be enhanced to do it. Good luck to you! From carroll at tjc.com Tue Sep 2 20:57:58 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Sep 4 20:00:11 2003 Subject: [Tutor] Philosphy on method naming in modules? Message-ID: I've written a little module, and it's gotten me thinking about the philosophy, and maybe even ethics and/or etiquette, of naming methods. My module, which I call Unihan, provides an interface into the Unicode folks' Unihan.txt file. You can see this file, all 10 meg of it, at . I use this to basically do lookups in the file, using the various tags as keys. For example, I can take a sequence of 4 hex digits, and find out whether any character uses that code, either in Unicode, Big Five, or GB, or any of the other encoding methods documented in the Unihan.txt file (although I only know a little Chinese, so the encodings for Korean, Japanese, etc. are pretty much a mystery to me). Right now, this is just for me, but I plan to make it available in case anyone else would care about it. So here's the thing: should the developer of a module that's going to be publicly shared try to use unique method names, to avoid name collisions with other modules? For example, a method I have that uses Tkinter to display the character and its related data is named merely "Display." This happens to be a bound method, so isn't the greatest example, but suppose it wasn't? If everyone used a method name like "Display", it'd be tough to use more than one of the conflicting modules. I suppose part of the problem is my approach to using modules. I almost always used "import foo" rather than "from foo import bar, baz" or "from foo import *" to import; so I usually end up fully-qualifying the method names I use, anyway (the exception being Tkinter, where the code just bogs down too much). So what do you guys think? For an unbound method to display a thing, should you use a nice generic name like "Display", or deliberately alter the name to something a little less mnemonic, but less likely to collide (say, "UnihanDisplay", "UHDisplay" or some such)? -- Terry Carroll | "I say to you that the VCR is to the American Santa Clara, CA | film producer and the American public as the carroll@tjc.com | Boston strangler is to the woman home alone." | Jack Valenti, MPAA President Modell delendus est | Testimony before Congress, 1982 From alan.gauld at blueyonder.co.uk Fri Sep 5 00:16:35 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 4 20:02:04 2003 Subject: [Tutor] hex output References: Message-ID: <010f01c37332$346c7cf0$6401a8c0@xp> > >>>hex(65) > '0x41' > >>>hex(65)[2:] > '41' > I want to write it in 4 digits form like this 0041 > and also in upper cases. Use a format string print "%04X" & 65 The 04 says 4 digits padded with zeros The upper case X says use upper case Hex. Make it a function if you like: >>> def upperHex(d,p=4): ... fmt = "%%0%dX" % p ... return fmt % d ... >>> print upperHex(65) 0041 >>> print upperHex(65,6) 000041 >>> HTH, Alan G. Alan g. From tpc at csua.berkeley.edu Thu Sep 4 15:16:26 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Sep 4 20:35:18 2003 Subject: [Tutor] hex output In-Reply-To: Message-ID: <20030904132458.G12926-100000@localhost.name> hi Jimmy, for the upper casing you use the upper() function like so: >>> hex(3735928559).upper() '0XDEADBEEFL' the L means long type. Now if you require all your decimal to hex conversions to be in the form 0000 without the 0x or L signifiers you might write a function which takes any hexstring, removes the 0x and L, checks the length of the hexstring and does the appropriate thing: >>> def dec2hexconverter(x): hexstring = hex(x).replace('0x', '').replace('L', '').upper() length = len(hexstring) if length == 1: hexstring = '000' + hexstring elif length == 2: hexstring = '00' + hexstring elif length == 3: hexstring = '0' + hexstring elif length == 8: hexstring = hexstring[:4] + ' ' + hexstring[-4:] return hexstring >>> dec2hexconverter(3735928559) 'DEAD BEEF' Granted, not the most elegant solution, but that should get you started. On Thu, 4 Sep 2003, Jimmy verma wrote: > Hello *, > > I am having problem in converting hexadecimal no's according to the format i > require. > > >>>hex(65) > '0x41' > >>>hex(65)[2:] > '41' > > > I want to write it in 4 digits form like this 0041 > and also in upper cases. > > Your suggestion are welcomed. > > Thanks a lot. > > Regards, > > J+ > > _________________________________________________________________ > Need a naukri? Your search ends here. http://www.msn.co.in/naukri/ 50,000 of > the best jobs! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From aschmidt at fredericksburg.com Thu Sep 4 20:54:00 2003 From: aschmidt at fredericksburg.com (Allen Schmidt) Date: Thu Sep 4 20:48:56 2003 Subject: [Tutor] Pouring a list into a dictionary References: Message-ID: <001401c37340$041b1210$03000000@swl001> Maybe the wrong title, but here is my issue: I have a file that I parse out to lists. The first line contains the column headers. The rest of the lines contain the rows of data elements. I need to loop through the each row, grab each column name from the first line and would like to use each one as the key in a dictionary. Then for each subsequent row, grab each data element and use the dictionary key for the correct placement as that key's value. Make sense?? Kinda hard to explain. Any gentle nudges in the right direction would be greatly appreciated. Allen From project5 at redrival.net Fri Sep 5 03:50:36 2003 From: project5 at redrival.net (Andrei) Date: Thu Sep 4 20:52:37 2003 Subject: [Tutor] Re: Philosphy on method naming in modules? In-Reply-To: References: Message-ID: Terry Carroll wrote: > So here's the thing: should the developer of a module that's going to be > publicly shared try to use unique method names, to avoid name collisions > with other modules? For example, a method I have that uses Tkinter to > display the character and its related data is named merely "Display." > I suppose part of the problem is my approach to using modules. I almost > always used "import foo" rather than "from foo import bar, baz" or "from > foo import *" to import; so I usually end up fully-qualifying the method > names I use, anyway (the exception being Tkinter, where the code just bogs > down too much). "from something import *" is bad form in Python and this I suppose is one of the reasons :). > So what do you guys think? For an unbound method to display a thing, > should you use a nice generic name like "Display", or deliberately alter > the name to something a little less mnemonic, but less likely to collide > (say, "UnihanDisplay", "UHDisplay" or some such)? I for one would call it something meaningful (Display isn't really descriptive IMO, especially if it's a function, not a class method - but then again, I haven't seen the module, perhaps the name says it all in your case). When you call it something descriptive, chances of overlap are pretty low. On the other hand, I wouldn't screw up the name especially in order to make it less likely to collide (the important thing is to have an unique module name). On a sidenote, I for one also prefer "displayUnihan" (verb first and starting with a lowercase), but this is very much a matter of taste I suppose. I'd also avoid UHDisplay because it's hard to type and remember - doubly so since Python is case sensitive. Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From jeff at ccvcorp.com Thu Sep 4 18:55:25 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 4 20:53:19 2003 Subject: [Tutor] Philosphy on method naming in modules? References: Message-ID: <3F57DEFD.6090207@ccvcorp.com> Terry Carroll wrote: > So here's the thing: should the developer of a module that's going to be > publicly shared try to use unique method names, to avoid name collisions > with other modules? For example, a method I have that uses Tkinter to > display the character and its related data is named merely "Display." > [...] > I suppose part of the problem is my approach to using modules. I almost > always used "import foo" rather than "from foo import bar, baz" or "from > foo import *" to import; so I usually end up fully-qualifying the method > names I use, anyway (the exception being Tkinter, where the code just bogs > down too much). The way you're using modules is the *safe* way to use modules. Anyone using one of the other mechanisms, especially 'from foo import *', should know that they are doing something that's risky and may cause namespace collisions. In general, I feel that there's too many modules out there for it to be practical to deliberately choose different names. The whole point of using module namespaces is to uniquely qualify a name; adding an additional unique prefix (or whatever) seems redundant. Note that some modules are designed to be imported into the current namespace, and they *do* take care to try to avoid collisions with built-in names. But even there, they don't tend to work too hard to avoid collisions with names in other third-party packages -- there's too many for that to be practical. In short, I think the way you're doing it is fine, and you should continue as-is. Jeff Shannon Technician/Programmer Credit International From sigurd at 12move.de Fri Sep 5 00:22:39 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Thu Sep 4 21:09:02 2003 Subject: [Tutor] multiline comment in Python In-Reply-To: <20030904123440.C12535-100000@localhost.name> (tpc@csua.berkeley.edu's message of "Thu, 4 Sep 2003 12:40:45 -0700 (PDT)") References: <20030904123440.C12535-100000@localhost.name> Message-ID: An unnamed person wrote: > hello all, I am wondering if there is anything other than triple quotes > for multiline commenting blocks of code. I am rather disappointed with > triple quote commenting because Python sometimes gives me a syntax error > which means I have to prepend a # in front of each line which can get Can you give a n example where something like that happens? It's either a bug in Python (very unlikely) or an error in your code. > tedious. I am running Python 2.2.3 and was really hoping for the /** */ > multiline commenting in C and Java. Thanks in advance. Where's the difference if you type /* ... */ or """ ... """? Karl -- Please do *not* send copies of replies to me. I read the list From jeff at ccvcorp.com Thu Sep 4 19:31:11 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 4 21:28:32 2003 Subject: [Tutor] Re: Philosphy on method naming in modules? References: Message-ID: <3F57E75F.9050502@ccvcorp.com> Andrei wrote: > ... On a sidenote, I for one also > prefer "displayUnihan" (verb first and starting with a lowercase), but > this is very much a matter of taste I suppose. Definitely a matter of taste -- I loathe mixed-case names that start with lower case. ;) FirstLetterCaps is good, underscore_for_spaces is okay, but camelCase bugs the snot out of me -- it's the inverse of normal sentence capitalization and has no parallel in normal language usage. I suspect this is a religious issue, though (no amount of logic will convince anyone on either side). > I'd also avoid UHDisplay > because it's hard to type and remember - doubly so since Python is case > sensitive. I agree with this. In wxPython/wxWindows, names are all prepended with 'wx' (e.g. wxFrame, wxDialog, wxEvent), but that was originally dictated by the C++ library that it wraps (which predates C++ namespaces). Even there, though, it's in the process of migrating everything to a wx namespace and referring to them as wx.Frame, wx.Dialog, etc. Jeff Shannon Technician/Programmer Credit International From erikprice at mac.com Thu Sep 4 23:09:58 2003 From: erikprice at mac.com (Erik Price) Date: Thu Sep 4 21:49:34 2003 Subject: [Tutor] Pouring a list into a dictionary In-Reply-To: <001401c37340$041b1210$03000000@swl001> Message-ID: <0C86CE87-DF46-11D7-A2CE-00039351FE6A@mac.com> On Thursday, September 4, 2003, at 07:54 PM, Allen Schmidt wrote: > I have a file that I parse out to lists. > The first line contains the column headers. > The rest of the lines contain the rows of data elements. > > I need to loop through the each row, grab each column name from the > first > line > and would like to use each one as the key in a dictionary. > > Then for each subsequent row, grab each data element and use the > dictionary key for the correct placement as that key's value. > > Make sense?? Kinda hard to explain. > > Any gentle nudges in the right direction would be greatly appreciated. I'm not sure if it does what you're referring to, but if your data records file is in CSV format then perhaps the csv module (new as of 2.3) is of some use to you. Erik From carroll at tjc.com Thu Sep 4 21:38:03 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Sep 4 23:38:09 2003 Subject: [Tutor] Re: Philosphy on method naming in modules? Message-ID: On Fri, 5 Sep 2003, Andrei wrote: > "from something import *" is bad form in Python and this I suppose is > one of the reasons :). Ah, I didn't know that. I see it in a lot of books, so I assumed it was common, or at leat not bad form. I don't like doing it myself. > I for one would call it something meaningful (Display isn't really > descriptive IMO, especially if it's a function, not a class method - but > then again, I haven't seen the module, perhaps the name says it all in > your case). Display's pretty meaningful, actually. It displays all the data in the entry for the character. I wouldn't have the method at all, except that the characters in question are all CJKV characters, and can't be displayed using "print," so I put all the data in a Tkinter window. > On a sidenote, I for one also prefer "displayUnihan" (verb first and > starting with a lowercase), but this is very much a matter of taste I > suppose. I gotta side with Jeff on this one. It bugs me to see a name with uppercase characters in it starting with lower case. Using the XML modules, with names like "setContentHandler", makes me batty. Thanks for the input on this. I'm not going to sweat the names too much, then. People who use my module and use "from Unihan import *" just have to be careful. -- Terry Carroll | "I say to you that the VCR is to the American Santa Clara, CA | film producer and the American public as the carroll@tjc.com | Boston strangler is to the woman home alone." | Jack Valenti, MPAA President Modell delendus est | Testimony before Congress, 1982 From alan.gauld at blueyonder.co.uk Fri Sep 5 08:58:07 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 5 02:57:48 2003 Subject: [Tutor] Philosphy on method naming in modules? References: Message-ID: <013601c3737b$0f803d20$6401a8c0@xp> > I suppose part of the problem is my approach to using modules. I almost > always used "import foo" rather than "from foo import bar, baz" That's not a problem, its what you should do. > ...so I usually end up fully-qualifying the method Which is absolutely correct and how to avoid name collisions - thats what modules and import are all about > the name to something a little less mnemonic, but less likely to collide > (say, "UnihanDisplay", "UHDisplay" or some such)? No that's pointless. Imagine: import unihan unihan.unihanDisplay() urgh, horrible. However one final point is that 'method' really only applies to functions inside a class. Unbound functions inside a module are just plain old functions. It comes from the concept that each object has some method of responding to a message. Which method may or may not be bound to a "function". For example: >>> class C: ... def abc(s): print "ABC" ... >>> o = C() >>> o.abc() ABC >>> o.xyz() So the object o has a method for responding to abc() which prints a message and a method for responding to xyz() which raises an exception. Only one method is implemented as a bound function in the class. Alan G (In nit picking mood!) From alex at gabuzomeu.net Fri Sep 5 11:02:44 2003 From: alex at gabuzomeu.net (Alexandre Ratti) Date: Fri Sep 5 03:57:51 2003 Subject: [Tutor] Compiling Python to Native Machine Code In-Reply-To: References: Message-ID: <3F584324.2000901@gabuzomeu.net> Hi Marc, Marc Barry wrote: > The type of algorithm I am using is the well known Dijkstra shortest > path. > I may have to look at implementing the Dijkstra algorithm portion of > the simulation in C. Although, it would be a terrible waste of time if > I didn't do any better than the 10% reduction I got using Psyco. I don't know this algorithm, so maybe this suggestion won't apply, but have you tried using Pyrex? Pyrex is a tool that takes Pythonic code as input (basically Python + type declarations) and that outputs C extensions. This might make it easier to test whether recoding tne algorithm in C is worth it. "Pyrex lets you write code that mixes Python and C data types any way you want, and compiles it into a C extension for Python." http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ There is a usage example in this doc: /Python 201 -- (Slightly) Advanced Python Topics/: http://www.rexx.com/~dkuhlman/python_201/python_201.html#SECTION006400000000000000000 Cheers. Alexandre From alex at gabuzomeu.net Fri Sep 5 11:43:14 2003 From: alex at gabuzomeu.net (Alexandre Ratti) Date: Fri Sep 5 04:38:09 2003 Subject: [Tutor] Pouring a list into a dictionary In-Reply-To: <001401c37340$041b1210$03000000@swl001> References: <001401c37340$041b1210$03000000@swl001> Message-ID: <3F584CA2.1000003@gabuzomeu.net> Hello Allen, Allen Schmidt wrote: > I have a file that I parse out to lists. > The first line contains the column headers. > The rest of the lines contain the rows of data elements. How are the column separated? Tabs, commas? > I need to loop through the each row, grab each column name from the first > line and would like to use each one as the key in a dictionary. You can use a variable (say lineCount) in your input loop to keep track of the current line number. If lineCount == 1, split the 1st line into chunks. If lineCount > 1, use the chunks as dictionary keys. Or use the "csv" module, as suggested. This class could be useful: class DictReader: Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the fieldnames parameter. http://www.python.org/doc/current/lib/node545.html > Make sense?? Kinda hard to explain. If the answers you got do not solve the problem, can you post a sample of your input file? Cheers. Alexandre From scot at possum.in-berlin.de Fri Sep 5 12:52:56 2003 From: scot at possum.in-berlin.de (Scot W. Stevenson) Date: Fri Sep 5 05:50:18 2003 Subject: [Tutor] multiline comment in Python In-Reply-To: <010a01c37331$33a44060$6401a8c0@xp> References: <20030904123440.C12535-100000@localhost.name> <010a01c37331$33a44060$6401a8c0@xp> Message-ID: <200309051149.03310.scot@possum.in-berlin.de> Hi - > And using vi(or vim or elvis) its nearly as easy. > [using :m,ns/^/#/ and :m,ns/^#// in vim you can use the visual > block mode to select the comment region. I suppose you could even map > it to a key if you wanted] Good grief Alan, you're making it sound like vi is complicated =8)! If vim is set up correctly, all you have to do is start out with a '#' at the beginning of the line and keep typing past the end of the line, and the Best Editor On Earth will put the hash at the start of the next line as well. Now, I'm not sure which option actually does this (to be honest, I discovered this by accident), but it is out of the box with SuSE 8.2. It is not just part of the Python syntax-thingy (/usr/share/vim/vim61/syntax/python.vim), because a quick test shows that vim will does the same with a plain text file. Strange. Y, Scot -- How to quiet a crying baby with the X Window System: nice xlock -inwindow -mode kumppa Scot W. Stevenson - Zepernick, Germany From RASTM2 at aol.com Fri Sep 5 07:03:16 2003 From: RASTM2 at aol.com (RASTM2@aol.com) Date: Fri Sep 5 06:03:27 2003 Subject: [Tutor] Re: Two (not so) dumb questions Message-ID: <43.21b0831b.2c89b964@aol.com> > > Date: Tue, 2 Sep 2003 16:29:00 +0700 > From: "Robin Hood" > Robin Hood writes > > Two dumb questions: > > 1. How do you set the PATH environment variable for python under windows 98 > (So that I can import modules which aren't located in the same folder as > python itself) > Hi Robin, The short answer to your first (not so) dumb question : Make a copy of your autoexec.bat file located in your top directory. This is normally the "C:\" directory. Call the copy something like autoexec.bak or .old or dot anything that isn't going to destroy an already existing file. Open the autoexec.bat file. (Keep in mind that there may be nothing in this file to begin with and that's okay.) On the line after the last entry in the file, type something like this (using your version of Python of course): PATH=C:\Python23\;C:\Python23\lib;%path% and save the file. Restart the computer. Example of my Python path in my autoexec.bat is: PATH=c:\Python23\;c:\Python23\lib;c:\pymy;%path% This line has to be typed exactly as shown or your machine could lock up. This line has the word PATH=, followed by the new path you want to add, followed by a colon. Follow the entire string by a percent sign, followed by the word path, followed by a percent sign. Notice that each individual path has to be followed by a colon. Notice also that the entire path line is followed by %path%. Now, the reason for this is that you already have a pre-existing PATH set up on your machine. ( you can see it by typing "path" at a dos prompt ( also try typing "set" to see all environment variables)) The %path% "environment variable" adds the pre-existing path to your new path that you just created for Python. Please also notice, in the example of my Python path, I also have included the path to the directory where I keep my scripts, modules, and programs that I write. > 2. Currently, to execute a python script I have to right click it, choose > "edit with IDLE" then choose "run script" from one of the drop down menus. > If I just double click on a python script. It automatically executes under > the DOS interpreter, and then closes itself too quickly to see what the > results were. Is it possible to change this? Yes. (That is, make it so that the > program doesn't automatically close the DOS Prompt after its finished > executing, or get it to automatically execute under the Windows IDLE) > > *****A Network is the Opposite of a Hierachy***** Robin, for my next trick... For Python programs that included DOS prompt output. Open a dos prompt and navigate to your program directory that you would like to run. Now that you have set up your python path (above) you can just type something like... C:\pymy\>python "Your_program_name_here".py and the program will execute. When it ends you will still have the output in the dos window until you close the window yourself. If you haven't set the path variable yet, you just have to type the path to the python version you want to run this proggy with. C:\pymy\>C:\Python23\python "your_proggy".py HTH Regards, Ray St.Marie -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030905/a8262e4a/attachment.htm From alan.gauld at blueyonder.co.uk Fri Sep 5 12:44:13 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 5 06:44:14 2003 Subject: [Tutor] Re: Philosphy on method naming in modules? References: <3F57E75F.9050502@ccvcorp.com> Message-ID: <001d01c3739a$a57bd5e0$6401a8c0@xp> > is okay, but camelCase bugs the snot out of me -- it's the inverse of > normal sentence capitalization and has no parallel in normal language > usage. I suspect this is a religious issue, though (no amount of Really just history. Its the convention used in Smalltalk - Class names begin with uppercase, method names begin lowercase. It caught on in OO circles and spread from there. Alan g. From RobinHood42 at clickta.com Fri Sep 5 19:05:35 2003 From: RobinHood42 at clickta.com (Robin Hood) Date: Fri Sep 5 07:05:36 2003 Subject: [Tutor] plotting pixels References: <3F553F09.1000008@netzero.net> Message-ID: <005201c3739d$a29d8dc0$cc5576cb@bangna> > plotting pixels. hmmm... > > Fractals? > > MathArt? > That was the general idea. (My background is mathematics rather than computer science) I still haven't managed to get OpenGL working. I think some kind of a problem with dependencies...... So I still can't even plot a single pixel, let alone a fractal. Does anybody know what has to be done to get OpenGL working with Python 2.2.3 under Windows 95 ? Step by step instructions would be increadibly welcome. :-) From erikprice at mac.com Fri Sep 5 09:01:50 2003 From: erikprice at mac.com (Erik Price) Date: Fri Sep 5 07:41:03 2003 Subject: [Tutor] Re: Philosphy on method naming in modules? In-Reply-To: <001d01c3739a$a57bd5e0$6401a8c0@xp> Message-ID: On Friday, September 5, 2003, at 06:44 AM, Alan Gauld wrote: >> is okay, but camelCase bugs the snot out of me -- it's the inverse > of >> normal sentence capitalization and has no parallel in normal > language >> usage. I suspect this is a religious issue, though (no amount of > > Really just history. Its the convention used in > Smalltalk - Class names begin with uppercase, method > names begin lowercase. > > It caught on in OO circles and spread from there. Seems to have caught on in Java too, because it's the recommended coding conventions according to Sun: Python has its own coding conventions, brought to you by the B.D.F.L. himself: The most important convention (according to "The Elements of Java Style" and "Python Style Guide", which I find applicable most anywhere) is to remain consistent in whichever style you choose. Erik From amonroe at columbus.rr.com Fri Sep 5 11:22:40 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri Sep 5 10:16:57 2003 Subject: [Tutor] plotting pixels In-Reply-To: <005201c3739d$a29d8dc0$cc5576cb@bangna> References: <3F553F09.1000008@netzero.net> <005201c3739d$a29d8dc0$cc5576cb@bangna> Message-ID: <33337459130.20030905102240@columbus.rr.com> > Does anybody know what has to be done to get OpenGL working > with Python 2.2.3 under Windows 95 ? > Step by step instructions would be increadibly welcome. All I did was run this canned installer: http://prdownloads.sourceforge.net/pyopengl/PyOpenGL-2.0.0.44.win32-py2.2.exe?download Once you get it installed, try some of the example programs in C:\Python22\Lib\site-packages\OpenGL\Demo Unfortunately they haven't made a canned installer for 2.3 yet. Alan From dyoo at hkn.eecs.berkeley.edu Fri Sep 5 11:05:07 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 5 13:05:23 2003 Subject: [Tutor] config file parsing problem. (fwd) Message-ID: Hi Thomi, I've got to forward this to Tutor; I'll take a look later on in the day, when things aren't so hectic for me... *grin* Talk to you later! ---------- Forwarded message ---------- Date: Fri, 5 Sep 2003 21:14:46 +1200 From: Thomi Richards To: Danny Yoo Subject: Re: [Tutor] config file parsing problem. On Fri, 05 Sep 2003 11:10, Danny Yoo wrote: Hi, > Are you commenting individual options? And how are comments "attached" to > the key-value pairs? On the same line, or on top? Perhaps ConfigParser > could be extended to preserve comments that are attached to certain > options. > No, comments are over several lines, and are above the actual lines themselfs. here's an excerpt from the file: --- # # The debug option can be set to an integer value. If debug is 0, debugging statements will not get # to the console. otherwise, they will debug = 1 # # verbosity isn't currently implimented, but it will controll how much information is printed to the # apps main outwindow. # verbosity = 3 --- some comment sections span over 10 lines. > > Tell us a little more about the problem, and perhaps we can see if > ConfigParser can be enhanced to do it. > Well, I currently have a main app, which imports a module I have created called "config". At the moment, the config module opens the config file, and reads in, line by line from the file. If the current line is not a file, it processes it accordingly.. The reason I had not used configparser previously was simply because I had not bothered to learn it, and it seemed a little too complex for what I was looking for (and it never mentioned anything about comments ;)). Thanks, -- Thomi Richards, http://once.sourceforge.net/ From jeff at ccvcorp.com Fri Sep 5 11:09:19 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Sep 5 13:13:22 2003 Subject: [Tutor] Re: Two (not so) dumb questions References: <43.21b0831b.2c89b964@aol.com> Message-ID: <3F58C33F.7050709@ccvcorp.com> RASTM2@aol.com wrote: > >> Date: Tue, 2 Sep 2003 16:29:00 +0700 >> From: "Robin Hood" >> >> 1. How do you set the PATH environment variable for python under >> windows 98 >> (So that I can import modules which aren't located in the same folder as >> python itself) > > Open the autoexec.bat file. (Keep in mind that there may be > nothing in this file to begin with and that's okay.) > > On the line after the last entry in the file, type something like this > (using your version of Python of course): > > PATH=C:\Python23\;C:\Python23\lib;%path% > Actually, this won't accomlish what the O.P. wanted, because $PATH is not used when Python is importing modules; $PYTHONPATH is. The above line will ensure that Python is always on your path, so that you don't need to be in C:\Python23 to run it. However, for Python to be able to find a module when that module is imported, it must be in a directory listed in sys.path, which is constructed from a variety of sources. That includes (but is not necessarily limited to) the $PYTHONPATH environment variable and .pth files. (Note that sys.path will also include the current working directory, so if you CD into a directory before running Python, you can import scripts in that directory.) One *can* place a line in autoexec.bat like so: PYTHONPATH=C:\Project1\PythonScripts;C:\Project2\Python And scripts in those directories can then be found by import. (The same can be accomplished by putting those two directories, one per line, in a .pth file in c:\python23, as well.) Jeff Shannon Technician/Programmer Credit International From jmillr at umich.edu Fri Sep 5 14:55:08 2003 From: jmillr at umich.edu (John Miller) Date: Fri Sep 5 13:55:16 2003 Subject: [Tutor] Pouring a list into a dictionary In-Reply-To: Message-ID: <16500F09-DFCA-11D7-A528-00039303967A@umich.edu> With thanks to the Python Cookbook, here's code that will do something like what you're asking for. I imagine there's a list comprehension way to do this, but here it is with 'for' loops: table = [('a','b','c'),(1,2,3),(4,5,6),(7,8,9)] d1 = {} c=0 for i in table[0]: for j in i: for k in table[1:]: d1.setdefault(j, []).append(k[c]) c+=1 print d1 {'a': [1, 4, 7], 'c': [3, 6, 9], 'b': [2, 5, 8]} John Miller On Friday, September 5, 2003, "Allen Schmidt" wrote: > I have a file that I parse out to lists. > The first line contains the column headers. > The rest of the lines contain the rows of data elements. > > I need to loop through the each row, grab each column name from the > first > line > and would like to use each one as the key in a dictionary. > > Then for each subsequent row, grab each data element and use the > dictionary key for the correct placement as that key's value. From tpc at csua.berkeley.edu Fri Sep 5 13:05:11 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Fri Sep 5 15:05:23 2003 Subject: [Tutor] multiline comment in Python In-Reply-To: Message-ID: <20030905120154.D20570-100000@localhost.name> hi Karl, One example is when I use triple quotes to comment out a block of code that already has print statements I had inserted in there earlier for debugging purposes, Python will then give me a syntax error. This gets into the nesting of comments Danny was talking about. On Thu, 4 Sep 2003, Karl [iso-8859-1] Pfl=E4sterer wrote: > An unnamed person wrote: > > > hello all, I am wondering if there is anything other than triple quotes > > for multiline commenting blocks of code. I am rather disappointed with > > triple quote commenting because Python sometimes gives me a syntax erro= r > > which means I have to prepend a # in front of each line which can get > > Can you give a n example where something like that happens? It's either > a bug in Python (very unlikely) or an error in your code. > > > tedious. I am running Python 2.2.3 and was really hoping for the /** *= / > > multiline commenting in C and Java. Thanks in advance. > > Where's the difference if you type /* ... */ or """ ... """? > > > Karl > -- > Please do *not* send copies of replies to me. > I read the list > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From sigurd at 12move.de Fri Sep 5 22:21:37 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Sep 5 15:27:10 2003 Subject: [Tutor] multiline comment in Python In-Reply-To: <20030905120154.D20570-100000@localhost.name> (tpc@csua.berkeley.edu's message of "Fri, 5 Sep 2003 12:05:11 -0700 (PDT)") References: <20030905120154.D20570-100000@localhost.name> Message-ID: An unnamed person wrote: > One example is when I use triple quotes to comment out a block of code > that already has print statements I had inserted in there earlier for > debugging purposes, Python will then give me a syntax error. This gets Can you give an example? For the Python here everything betwenn `"""' is a string. So why should a print statement matter? >>> """ ... 123 ... 3 + 4 ... print 27 * 35 ... 42 ... """ '\n123\n3 + 4\nprint 27 * 35\n42\n' >>> s = _ >>> s '\n123\n3 + 4\nprint 27 * 35\n42\n' >>> print s 123 3 + 4 print 27 * 35 42 >>> Karl -- Please do *not* send copies of replies to me. I read the list From alan.gauld at blueyonder.co.uk Fri Sep 5 21:40:05 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 5 15:39:52 2003 Subject: [Tutor] multiline comment in Python References: <20030904123440.C12535-100000@localhost.name><010a01c37331$33a44060$6401a8c0@xp> <200309051149.03310.scot@possum.in-berlin.de> Message-ID: <003d01c373e5$818d6c20$6401a8c0@xp> > > [using :m,ns/^/#/ and :m,ns/^#// in vim you can use the visual > > block mode to select the comment region. I suppose you could even map > > it to a key if you wanted] > > Good grief Alan, you're making it sound like vi is complicated =8)! vi is unfortunately. Powerful but complicated vim on the other hand is simply wonderful... :-) > If vim is set up correctly, all you have to do is start out with > a '#' at the beginning of the line and keep typing past the end > of the line, Well blow me down with a feather! Yes this works with out of the box vim on Windoze too. The only snag is the line length is longer than I like but that can be changed easily enough. I still like the visual mode for commenting blocks that already exist, but this is good for new comments. Alan g. From dyoo at hkn.eecs.berkeley.edu Fri Sep 5 14:07:46 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 5 16:07:51 2003 Subject: [Tutor] Re: Tutor Digest, Vol 2, Issue 2 In-Reply-To: <5.2.0.9.0.20030902210344.02575670@localhost> Message-ID: On Tue, 2 Sep 2003, Brian Christopher Robinson wrote: > Ok, this is what I put as a member of my TagSort class: > > def __iter__(self): > return self.array.__iter__() > > Now, this is actually wrong since it doesn't take in to account the order > of the TagArray. But this doesn't even work at all. Instead I get the > message: > > AttributeError: 'list' object has no attribute '__iter__' > > What's that all about? Hi Brian, Odd; that should have worked... Ah. Lists do have an __iter__ attribute in Python 2.3: ### >>> l = [] >>> l.__iter__ ### But they don't appear to have one in 2.2: ### >>> l = [] >>> l.__iter__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'list' object has no attribute '__iter__' ### It looks like the implementers did more polishing up of the class/type stuff in Python 2.3; I didn't expect this not to work in 2.2! But there's a way of writing it so it works with both: def __iter__(self): return iter(self.array) > def tagSort(array): > copy = array[:] # copies the array > copy.sort() > indexes = [] > for number in copy: > indexes.append(array.index(number)) > return indexes > > Which works great. My friend was opposed to the copy, though, so I > wrote this: There's a small bug here: it doesn't work if there are duplicates in our original array: ### >>> tagSort([1,1,1,1,1]) [0, 0, 0, 0, 0] ### Instead of array.index(), we'd need to cook up our own function that uses the 'is' operator instead of the '==' operator: ### >>> "4" + "2" == "42" 1 >>> "4" + "2" is "42" 0 ### Talk to you later! From tpc at csua.berkeley.edu Fri Sep 5 14:48:10 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Fri Sep 5 16:48:15 2003 Subject: [Tutor] multiline comment in Python In-Reply-To: Message-ID: <20030905124604.N20766-100000@localhost.name> hi Karl, I am sorry, when I said a block of code that already has print statements in it, I meant print statements using quotes. Take for example a small program I wrote yesterday to be run from the commandline: #!/usr/bin/env python def dec2hexconverter(x): hexstring =3D hex(x).replace('0x', '').replace('L', '').upper() length =3D len(hexstring) if length =3D=3D 1: hexstring =3D '000' + hexstring """elif length =3D=3D 2: hexstring =3D '00' + hexstring elif length =3D=3D 3: hexstring =3D '0' + hexstring""" elif length =3D=3D 8: hexstring =3D hexstring[:4] + ' ' + hexstring[-4:] print hexstring dec2hexconverter(3735928559) As it is, when you run it Python gives you a syntax error. When you take out the triple quotes it runs just fine. This is not the most elegant code, but the issue of nesting quotes remains, you cannot do so in Python just as you cannot nest multiline comments in Java or C. On Fri, 5 Sep 2003, Karl [iso-8859-1] Pfl=E4sterer wrote: > An unnamed person wrote: > > > One example is when I use triple quotes to comment out a block of code > > that already has print statements I had inserted in there earlier for > > debugging purposes, Python will then give me a syntax error. This gets > > Can you give an example? For the Python here everything betwenn `"""' > is a string. So why should a print statement matter? > > >>> """ > ... 123 > ... 3 + 4 > ... print 27 * 35 > ... 42 > ... """ > '\n123\n3 + 4\nprint 27 * 35\n42\n' > >>> s =3D _ > >>> s > '\n123\n3 + 4\nprint 27 * 35\n42\n' > >>> print s > > 123 > 3 + 4 > print 27 * 35 > 42 > > >>> > > > > Karl > -- > Please do *not* send copies of replies to me. > I read the list > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From idiot1 at netzero.net Fri Sep 5 18:17:31 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Fri Sep 5 17:17:09 2003 Subject: [Tutor] cgi server script Message-ID: <3F58FD6B.4020104@netzero.net> I am rereading Python Web Programming. In it on opage 215 is a simple cgicapable script: #! C:\PYTHON22\pythonw.exe # import CGIHTTPServer, BaseHTTPServer httpd=BaseHTTPServer(('',8000), CGIHTTPServer.CGIHTTPRequestHandler) httpd.serve_forever() # this is a small but serviceable cgi server for your pc! Well, I put it in my pc which also has idle. An alias was created, with the properties: target: C:\Python22\pythonw.exe "C:\PYTHON22\cgiserver.py" start in: C:\Python22 It refuses to run, and the pythonw.exe terminates. Anyone care to offer some clues? -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From jonathan.hayward at pobox.com Sat Sep 6 00:10:50 2003 From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com) Date: Fri Sep 5 18:10:56 2003 Subject: [Tutor] Memory optimization problem Message-ID: <3F5909EA.6080402@pobox.com> I have been working on a search engine, which is a memory hog. I originally had it use a hashtable to keep a histogram of occurrences for words for files, then optimized that to a binary searched tuple of integer pairs... I couldn't see any improvement. It seems to take more memory than the files loaded. Do you have any suggestions for what I might look for that's hogging memory? -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From jeff at ccvcorp.com Fri Sep 5 16:15:58 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Sep 5 18:13:26 2003 Subject: [Tutor] multiline comment in Python References: <20030905124604.N20766-100000@localhost.name> Message-ID: <3F590B1E.40307@ccvcorp.com> tpc@csua.berkeley.edu wrote: > hi Karl, I am sorry, when I said a block of code that already has print > statements in it, I meant print statements using quotes. Take for example > a small program I wrote yesterday to be run from the commandline: > > > #!/usr/bin/env python > > def dec2hexconverter(x): > hexstring = hex(x).replace('0x', '').replace('L', '').upper() > length = len(hexstring) > if length == 1: > hexstring = '000' + hexstring > """elif length == 2: > hexstring = '00' + hexstring > elif length == 3: > hexstring = '0' + hexstring""" > elif length == 8: > hexstring = hexstring[:4] + ' ' + hexstring[-4:] > print hexstring > > dec2hexconverter(3735928559) > > > As it is, when you run it Python gives you a syntax error. When you take > out the triple quotes it runs just fine. This is not the most elegant > code, but the issue of nesting quotes remains, you cannot do so in Python > just as you cannot nest multiline comments in Java or C. This is actually not throwing a syntax error because of the embedded quotes -- it's perfectly legal to embed quote characters within a triple-quoted string, and indeed that's half the motivation for allowing triple-quoted strings -- """A bit of "this" and a bit of 'that'""" is a perfectly legal string. The problem here is that your string is not *actually* a comment, and on going through this, the parser writes code to create and then throw away that string. Then you have an 'elif:' ... which is separated from the 'if' by a different statement, and thus is bare. *That* is where your syntax error is coming from. As others have noted, most editors will have block-comment features that will allow you to comment out multiple lines at once (and uncomment them later), so that's the "correct" way to accomplish this. Jeff Shannon Technician/Programmer Credit International From missive at hotmail.com Fri Sep 5 23:14:45 2003 From: missive at hotmail.com (Lee Harr) Date: Fri Sep 5 18:14:49 2003 Subject: [Tutor] Re: another problem Message-ID: >Ok, I managed the missing glade problem, now there is another problem. >The following errorline occurs (1 line! sylpheed wraps it) > >(gui.py:270): libglade-CRITICAL **: file glade-xml.c: line 1172 >(glade_xml_build_interface): assertion `wid != NULL' failed > >The "270" changes, what is this number? >Any ideas about the error? I confess, i didn't do much about it yet, but >I have no idea where to start either ... :( > Hi; I started playing around with this one myself, and I found the problem: Here is the code I am using: import gtk import gtk.glade class appgui: def __init__(self): gladefile="project1.glade" windowname="window1" # HERE IS THE PROBLEM! self.wTree=gtk.glade.XML (gladefile,windowname) dic = { "on_button1_clicked": self.button1_clicked, "on_serverinfo_destroy": gtk.mainquit } self.wTree.signal_autoconnect (dic) def button1_clicked(self,widget): print "button clicked" app=appgui() gtk.mainloop() This comes from the pygtk tutorial at Linux Journal: http://www.linuxjournal.com/article.php?sid=6586 #### You need to make sure that windowname matches up with the name (id) of the window generated by glade. #### You can either change the name in glade or look through the .glade file for the tag that looks like: widget class="GtkWindow" id="window1" I read back through the article and I do not see it mentioned, but if they do not match, you get the error about the missing window. _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From carroll at tjc.com Fri Sep 5 17:08:39 2003 From: carroll at tjc.com (Terry Carroll) Date: Fri Sep 5 19:08:43 2003 Subject: [Tutor] Re: Philosphy on method naming in modules? In-Reply-To: Message-ID: On Fri, 5 Sep 2003, Erik Price wrote: > Python has its own coding conventions, brought to you by the B.D.F.L. > himself: > > Even there, something peeks out: Module names can be either MixedCase or lowercase. Writing "mixedCase" would have just been ugly. -- Terry Carroll | "I say to you that the VCR is to the American Santa Clara, CA | film producer and the American public as the carroll@tjc.com | Boston strangler is to the woman home alone." | Jack Valenti, MPAA President Modell delendus est | Testimony before Congress, 1982 From sigurd at 12move.de Sat Sep 6 02:47:51 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Sep 5 19:48:54 2003 Subject: [Tutor] multiline comment in Python In-Reply-To: <20030905124604.N20766-100000@localhost.name> (tpc@csua.berkeley.edu's message of "Fri, 5 Sep 2003 13:48:10 -0700 (PDT)") References: <20030905124604.N20766-100000@localhost.name> Message-ID: An unnamed person wrote: > statements in it, I meant print statements using quotes. Take for example > a small program I wrote yesterday to be run from the commandline: Now it's clear what you mean. And with a little pice rewritten it works. > > #!/usr/bin/env python > def dec2hexconverter(x): > hexstring = hex(x).replace('0x', '').replace('L', '').upper() > length = len(hexstring) > if length == 1: > hexstring = '000' + hexstring > """elif length == 2: > hexstring = '00' + hexstring > elif length == 3: > hexstring = '0' + hexstring""" > elif length == 8: > hexstring = hexstring[:4] + ' ' + hexstring[-4:] > print hexstring def dec2hexconverter(x): hexstring = hex(x).replace('0x', '').replace('L', '').upper() length = len(hexstring) if length == 1: hexstring = '000' + hexstring """ elif length == 2: hexstring = '00' + hexstring elif length == 3: hexstring = '0' + hexstring """ elif length == 8: hexstring = hexstring[:4] + ' ' + hexstring[-4:] print hexstring Use seperate lines for the triple quotes and Python is happy. What you can't use there you are right are triple quotes around triple quotes. Then it's easier to use your editor (like eg XEmacs :-) ) and use its command for commenting a region. Karl -- Please do *not* send copies of replies to me. I read the list From RobinHood42 at clickta.com Sat Sep 6 09:11:53 2003 From: RobinHood42 at clickta.com (Robin Hood) Date: Fri Sep 5 21:11:54 2003 Subject: [Tutor] pyOpenGL errors when closing window. References: <3F553F09.1000008@netzero.net> <005201c3739d$a29d8dc0$cc5576cb@bangna> <33337459130.20030905102240@columbus.rr.com> Message-ID: <002701c37413$dc81ca80$88a685ca@bangna> Okay guys. I have a new problem. I have installed OpenGL and have been playing with the demos. Most of the demos work most of the time, But none of the demos like to be closed. Whenever I close the window with the graphics in it, I get a "This program has performed an illegal operation". Has anybody else had this problem? And does anybody know exactly what the problem is? *****A Network is the Opposite of a Hierachy***** ----- Original Message ----- From: R. Alan Monroe To: Sent: Friday, September 05, 2003 9:22 PM Subject: Re: [Tutor] plotting pixels > > > Does anybody know what has to be done to get OpenGL working > > with Python 2.2.3 under Windows 95 ? > > > Step by step instructions would be increadibly welcome. > > All I did was run this canned installer: > http://prdownloads.sourceforge.net/pyopengl/PyOpenGL-2.0.0.44.win32-py2.2.ex e?download > > Once you get it installed, try some of the example programs in > C:\Python22\Lib\site-packages\OpenGL\Demo > > Unfortunately they haven't made a canned installer for 2.3 yet. > > Alan > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From peterabrown at froggy.com.au Sat Sep 6 14:38:14 2003 From: peterabrown at froggy.com.au (Peter Brown) Date: Fri Sep 5 23:39:44 2003 Subject: [Tutor] Dynamic inserts into postgresql Message-ID: <3.0.6.32.20030906133814.00b65770@mail.froggy.com.au> Dear Tutor, I feel like a dummy for asking this, but I have been working on it for 2 days without resolution. I'm using pygresql module pg (not pgdb) to communicate to PostgreSQL I can connect, open cursor, insert static data, select etc. But what I can't do is insert data that is not fixed ie using variables. eg statement = " INSERT INTO target VALUES (a, b)" ; res = db.query(statement) Any help would be greatly accepted P From darnold02 at sprynet.com Sat Sep 6 03:05:09 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Sat Sep 6 03:05:52 2003 Subject: [Tutor] cgi server script References: <3F58FD6B.4020104@netzero.net> Message-ID: <0f8501c37445$3bdd2520$c410ba3f@defaultcomp> ----- Original Message ----- From: "Kirk Bailey" To: "Tutor" Sent: Friday, September 05, 2003 4:17 PM Subject: [Tutor] cgi server script > I am rereading Python Web Programming. In it on opage 215 is a simple cgicapable > script: > > #! C:\PYTHON22\pythonw.exe > # > import CGIHTTPServer, BaseHTTPServer > httpd=BaseHTTPServer(('',8000), CGIHTTPServer.CGIHTTPRequestHandler) The above line should read: httpd=BaseHTTPServer.HTTPServer(('',8000), CGIHTTPServer.CGIHTTPRequestHandler) > httpd.serve_forever() > # this is a small but serviceable cgi server for your pc! > > Well, I put it in my pc which also has idle. An alias was created, with the > properties: > target: C:\Python22\pythonw.exe "C:\PYTHON22\cgiserver.py" > start in: C:\Python22 > It refuses to run, and the pythonw.exe terminates. Anyone care to offer some clues? > > end > > Cheers! > Kirk D Bailey > HTH, Don From andi at buxach.de Sat Sep 6 19:17:54 2003 From: andi at buxach.de (Andreas Zwinkau) Date: Sat Sep 6 07:27:17 2003 Subject: [Tutor] lists in re? Message-ID: <20030906181754.68637d0b.andi@buxach.de> Ave I'm currently working on something wiki-like and i use regular expressions very much to format the content. The bad part is, it gets worse, so i'd thought about making it more elegant. Is there any way to make replacements with re and use lists or a dictionary? Here is the code: linkparser = re.compile("\[([\w \=\-\_\.]+)\]") listparser = re.compile("(?<=\n)\* (.*)\n") italicparser = re.compile("''(.+?)''") underlineparser = re.compile("__(.+?)__") boldparser = re.compile("\*\*(.+?)\*\*") headlineparser = re.compile("\!(.+?)\n") filtered = string.replace(raw_data, "\n","
\n") filtered = linkparser.sub("\\1", filtered) filtered = listparser.sub("
  • \\1
\n", filtered) filtered = italicparser.sub("\\1", filtered) filtered = underlineparser.sub("\\1", filtered) filtered = boldparser.sub("\\1", filtered) filtered = headlineparser.sub("

\\1

", filtered) I checked the wikinehesa, but there it doesn't use re at all. -- mfg Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From pythontutor at venix.com Sat Sep 6 11:02:58 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Sep 6 10:03:35 2003 Subject: [Tutor] Dynamic inserts into postgresql In-Reply-To: <3.0.6.32.20030906133814.00b65770@mail.froggy.com.au> References: <3.0.6.32.20030906133814.00b65770@mail.froggy.com.au> Message-ID: <3F59E912.9080208@venix.com> http://www.python.org/peps/pep-0249.html Normally this would give the details for using the DBI. However, the content is missing () as I write this. I'll try to fill in from memory (I have not used pg). The module should have an attribute paramstyle that describes how it handles variable substitution into queries. MySQLdb as a paramstyle of format. It works essentially as follows: import MySQLdb as SQL >>> SQL.paramstyle 'format' conn = SQL.connect(...) curs = conn.cursor() ... curs.execute("INSERT INTO tablename (field1,field2) VALUES (%s,%s)",(a,b)) The values from the a and b variables are interpolated into the %s place holders. Quoting and format issues are handled by the MySQLdb module. Determine which paramstyle pg uses. Find the PEP249 which documents the DBI 2 standard and explains how to use each paramstyle. Peter Brown wrote: > Dear Tutor, > > I feel like a dummy for asking this, but I have been working on it for 2 > days without resolution. > > I'm using pygresql module pg (not pgdb) to communicate to PostgreSQL I can > connect, open cursor, insert static data, select etc. > > But what I can't do is insert data that is not fixed ie using variables. eg > statement = " INSERT INTO target VALUES (a, b)" ; res = db.query(statement) > > Any help would be greatly accepted > > P > > > _______________________________________________ > 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 michael at themontagnes.com Sat Sep 6 08:45:37 2003 From: michael at themontagnes.com (Michael Montagne) Date: Sat Sep 6 10:45:42 2003 Subject: [Tutor] Improper import Message-ID: <20030906144537.GB20257@themontagnes.com> I'm having an issue with Mailman. There is a file called Mailbox.py in the Mailman directory that calls "import mailbox". It is supposed to import /usr/lib/python2.2/mailbox.py. Instead, it imports itself. It appears to not be respecting the case-sensitivity. I can run "vim /var/lib/mailman/Mailman/mailbox.py" and edit the file that is called "/var/lib/mailman/Mailman/Mailbox.py" What in the world can cause something like that? -- Michael Montagne michael@themontagnes.com http://www.themontagnes.com From pythontutor at venix.com Sat Sep 6 12:29:37 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Sep 6 11:29:43 2003 Subject: [Tutor] Improper import In-Reply-To: <20030906144537.GB20257@themontagnes.com> References: <20030906144537.GB20257@themontagnes.com> Message-ID: <3F59FD61.7000702@venix.com> My mailman installation contains the files you describe, but without the confusion. Could ln have been used to link mailbox.py into the Mailman directory?? Michael Montagne wrote: > I'm having an issue with Mailman. There is a file called Mailbox.py > in the Mailman directory that calls "import mailbox". It is supposed > to import /usr/lib/python2.2/mailbox.py. Instead, it imports itself. > It appears to not be respecting the case-sensitivity. I can run "vim > /var/lib/mailman/Mailman/mailbox.py" and edit the file that is called > "/var/lib/mailman/Mailman/Mailbox.py" > > What in the world can cause something like that? -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From pythontutor at venix.com Sat Sep 6 12:53:35 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Sep 6 11:53:39 2003 Subject: [Tutor] Improper import In-Reply-To: <3F59FD61.7000702@venix.com> References: <20030906144537.GB20257@themontagnes.com> <3F59FD61.7000702@venix.com> Message-ID: <3F5A02FF.3070107@venix.com> Actually that was not the correct linkage to suggest. Could Mailbox.py gotten linked to mailbox.py in the Mailman directory?? Lloyd Kvam wrote: > My mailman installation contains the files you describe, but without > the confusion. Could ln have been used to link mailbox.py into the > Mailman directory?? > > Michael Montagne wrote: > >> I'm having an issue with Mailman. There is a file called Mailbox.py >> in the Mailman directory that calls "import mailbox". It is supposed >> to import /usr/lib/python2.2/mailbox.py. Instead, it imports itself. >> It appears to not be respecting the case-sensitivity. I can run "vim >> /var/lib/mailman/Mailman/mailbox.py" and edit the file that is called >> "/var/lib/mailman/Mailman/Mailbox.py" >> >> What in the world can cause something like that? > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From michael at themontagnes.com Sat Sep 6 10:21:22 2003 From: michael at themontagnes.com (Michael Montagne) Date: Sat Sep 6 12:21:29 2003 Subject: [Tutor] Improper import In-Reply-To: <3F5A02FF.3070107@venix.com> References: <20030906144537.GB20257@themontagnes.com> <3F59FD61.7000702@venix.com> <3F5A02FF.3070107@venix.com> Message-ID: <20030906162122.GA21257@themontagnes.com> I think it is related to samba. I used smbmount to mount /var/lib mailman from a different machine, the one that has postfix. The local machine has the web server. When I told smb.conf to be case sensitive then I couldn't ls the mailbox.py file in the Mailman directory but I still have the problem. I've unmounted/remounted, restated samba, apache. Still no joy. >On 09/06/03, Lloyd Kvam busted out the keyboard and typed: > Actually that was not the correct linkage to suggest. Could > Mailbox.py gotten linked to mailbox.py in the Mailman directory?? > > Lloyd Kvam wrote: > > >My mailman installation contains the files you describe, but without > >the confusion. Could ln have been used to link mailbox.py into the > >Mailman directory?? > > > >Michael Montagne wrote: > > > >>I'm having an issue with Mailman. There is a file called Mailbox.py > >>in the Mailman directory that calls "import mailbox". It is supposed > >>to import /usr/lib/python2.2/mailbox.py. Instead, it imports itself. > >>It appears to not be respecting the case-sensitivity. I can run "vim > >>/var/lib/mailman/Mailman/mailbox.py" and edit the file that is called > >>"/var/lib/mailman/Mailman/Mailbox.py" > >> > >>What in the world can cause something like that? -- Michael Montagne michael@themontagnes.com http://www.themontagnes.com From project5 at redrival.net Sat Sep 6 20:12:24 2003 From: project5 at redrival.net (Andrei) Date: Sat Sep 6 13:14:40 2003 Subject: [Tutor] Re: lists in re? In-Reply-To: <20030906181754.68637d0b.andi@buxach.de> References: <20030906181754.68637d0b.andi@buxach.de> Message-ID: Andreas Zwinkau wrote: > Ave Hello, > I'm currently working on something wiki-like and i use regular > expressions very much to format the content. The bad part is, it gets > worse, so i'd thought about making it more elegant. Is there any way to > make replacements with re and use lists or a dictionary? If you mean you want to make a list of re's and apply them all inside a loop (or something like that): sure, why not? You can put anything you like in lists or dictionaries. I've taken your Italic and Underline regexes: >>> relist = [re.compile("''(.+?)''"), re.compile("__(.+?)__")] >>> results = [ r.match("__underscore__ blabla") for r in relist ] >>> print results [None, <_sre.SRE_Match object at 0x01681D20>] Apparently the first regex (the one for the italics) doesn't match, but the second one does. Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From idiot1 at netzero.net Sat Sep 6 16:35:45 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sat Sep 6 15:35:26 2003 Subject: [Tutor] cgi server script In-Reply-To: <0f8501c37445$3bdd2520$c410ba3f@defaultcomp> References: <3F58FD6B.4020104@netzero.net> <0f8501c37445$3bdd2520$c410ba3f@defaultcomp> Message-ID: <3F5A3711.6060301@netzero.net> Steve got back to me and declared he oopsed, and also told me how the line should appear. I am waiting to hear what he thinks of the threading cgi server from the book, which also appears to have a hairball in it. IT WORKS!!! And If I can finger (sic) out how to have it declare a default web directory and cgi-bin and images directory, and NOT let people walts all over the mainframe, this could actually become a useful little tool. In fact, as a giggle, I may just stick it on Critter when it is done, on an alternate port (hmm, firewall rules...) and make the thing available with a few bells and whistles. For an ittybitty, it's pretty nice. Don Arnold wrote: > ----- Original Message ----- > From: "Kirk Bailey" > To: "Tutor" > Sent: Friday, September 05, 2003 4:17 PM > Subject: [Tutor] cgi server script > > > >>I am rereading Python Web Programming. In it on opage 215 is a simple > > cgicapable > >>script: >> >>#! C:\PYTHON22\pythonw.exe >># >>import CGIHTTPServer, BaseHTTPServer >>httpd=BaseHTTPServer(('',8000), CGIHTTPServer.CGIHTTPRequestHandler) > > > The above line should read: > > httpd=BaseHTTPServer.HTTPServer(('',8000), > CGIHTTPServer.CGIHTTPRequestHandler) > > >>httpd.serve_forever() >># this is a small but serviceable cgi server for your pc! >> >>Well, I put it in my pc which also has idle. An alias was created, with > > the > >>properties: >>target: C:\Python22\pythonw.exe "C:\PYTHON22\cgiserver.py" >>start in: C:\Python22 >>It refuses to run, and the pythonw.exe terminates. Anyone care to offer > > some clues? > >>end >> >>Cheers! >> Kirk D Bailey >> > > > HTH, > Don > > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From pythontutor at venix.com Sat Sep 6 19:00:07 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Sep 6 18:00:12 2003 Subject: [Tutor] Improper import In-Reply-To: <20030906162122.GA21257@themontagnes.com> References: <20030906144537.GB20257@themontagnes.com> <3F59FD61.7000702@venix.com> <3F5A02FF.3070107@venix.com> <20030906162122.GA21257@themontagnes.com> Message-ID: <3F5A58E7.5010409@venix.com> The sys.path attribute controls the python search order for loading modules. Python is of course case sensitive and will apply that case sensitivity to import file names even on Windows. I suspect that Samba is doing case mapping so that Mailbox is getting transformed to mailbox. Your sys.path list probably starts with '' which indicates the current directory. You could modify sys.path to put the current directory last. This is an ugly approach, but would enable you to import the correct mailbox and get around the case mapping problem. If it were me, I'd be tempted to add postfix (or sendmail) to the local machine and then use that machine for mailman email and avoid Samba. (I've only used Samba to provide access from Windows to Linux and vice versa. Linux to Linux I use NFS.) Michael Montagne wrote: > I think it is related to samba. I used smbmount to mount /var/lib > mailman from a different machine, the one that has postfix. The local > machine has the web server. When I told smb.conf to be case sensitive > then I couldn't ls the mailbox.py file in the Mailman directory but I > still have the problem. I've unmounted/remounted, restated samba, > apache. Still no joy. > > > > >>On 09/06/03, Lloyd Kvam busted out the keyboard and typed: > > >>Actually that was not the correct linkage to suggest. Could >>Mailbox.py gotten linked to mailbox.py in the Mailman directory?? >> >>Lloyd Kvam wrote: >> >> >>>My mailman installation contains the files you describe, but without >>>the confusion. Could ln have been used to link mailbox.py into the >>>Mailman directory?? >>> >>>Michael Montagne wrote: >>> >>> >>>>I'm having an issue with Mailman. There is a file called Mailbox.py >>>>in the Mailman directory that calls "import mailbox". It is supposed >>>>to import /usr/lib/python2.2/mailbox.py. Instead, it imports itself. >>>>It appears to not be respecting the case-sensitivity. I can run "vim >>>>/var/lib/mailman/Mailman/mailbox.py" and edit the file that is called >>>>"/var/lib/mailman/Mailman/Mailbox.py" >>>> >>>>What in the world can cause something like that? -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dyoo at hkn.eecs.berkeley.edu Sat Sep 6 17:10:27 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Sep 6 19:10:36 2003 Subject: [Tutor] Memory optimization problem [intern() can save space for commonly used strings] In-Reply-To: <3F5909EA.6080402@pobox.com> Message-ID: On Fri, 5 Sep 2003, Jonathan Hayward http://JonathansCorner.com wrote: > I have been working on a search engine, which is a memory hog. I > originally had it use a hashtable to keep a histogram of occurrences for > words for files Hi Jonathan, How many unique words are you running into? Let's use that to estimate memory usage. Also, can you show us how you're constructing the dictionary? Are you using a separate dictionary for each document in your collection? The process that you describe definitely shouldn't be hogging memory: the whole point of doing histogramming and indicing is to summarize a document, so it should take significantly less memory than the document itself, not more. *grin* One thing that you might want to see is if doing a string "intern()" on your keywords will help reduce memory. intern() is a function that stores strings in a global string table, and it's designed to reduce the memory-requirements of storing keywords. Duplicate strings get remapped to the same string --- it reduces redundancy, and since strings are guaranteed to be immutable, doing an intern() should be pretty safe. ### >>> s1 = "hello" >>> s2 = "h" + "ello" >>> id(s1) 135629824 >>> id(s2) 135630520 ### Here, 's1' and 's2' have the same content, but they are different strings since they were constructed differently. Once we use intern() to stuff the strings into our symbol table: ### >>> s1 = intern(s1) >>> s2 = intern(s2) >>> id(s1) 135629824 >>> id(s2) 135629824 ### then s1 and s2 end up being id-entical as well as equal. Keeping a symbol table is especially crucial in search engine applications, since you'll end up seeing the same strings over and over. That being said, it's a very bad idea to use intern() indiscriminately: doing so will probably make the symbol table grow too large! > Do you have any suggestions for what I might look for that's hogging > memory? Besides the string interning tip... I have no idea. *grin* We really do need to see more code to say anything useful. If your codebase is large, please feel free to link it on the web somewhere and post the link; many of us would be happy to take a look. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Sat Sep 6 17:24:10 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Sep 6 19:24:23 2003 Subject: [Tutor] Dynamic inserts into postgresql In-Reply-To: <3.0.6.32.20030906133814.00b65770@mail.froggy.com.au> Message-ID: On Sat, 6 Sep 2003, Peter Brown wrote: > Dear Tutor, > > I feel like a dummy for asking this, but I have been working on it for 2 > days without resolution. > > I'm using pygresql module pg (not pgdb) to communicate to PostgreSQL Hi Peter, Out of curiosity, why not 'pgdb'? The 'pgdb' module uses the standard DB-API 2.0 described by: http://www.python.org/peps/pep-0249.html and is the one that most Python programmers are familiar with. > I can connect, open cursor, insert static data, select etc. > > But what I can't do is insert data that is not fixed ie using variables. > eg statement = " INSERT INTO target VALUES (a, b)" ; res = > db.query(statement) I'm not sure how to do it with PostgreSQL's native interface, since I'm more familiar with the DB API 2.0's. Here's an example that uses 'pgdb' and its prepared statement syntax: ### >>> import pgdb >>> conn = pgdb.connect(database='pub2') >>> cursor = conn.cursor() >>> cursor.execute("create table people (name varchar, email varchar)") >>> conn.commit() >>> cursor.execute("insert into people (name, email) values (%s, %s)", ... ("Danny", "dyoo")) >>> conn.commit() ### Please feel free to ask more questions about this. Good luck! From tony at tcapp.com Sun Sep 7 00:44:21 2003 From: tony at tcapp.com (Tony Cappellini) Date: Sun Sep 7 02:47:40 2003 Subject: [Tutor] TypeError: 'str' object is not callable Message-ID: <5.1.0.14.0.20030906233607.04327fb8@smtp.sbcglobal.net> Hello, I wrote the module below, to walk through a directory tree, and display certain FILE attributes that I'm looking for (this part isn't done yet) While executing this, I would press Ctrl-C to abort execution, when I found what I was looking for, but didn't like the Ctrl-C exception. So I added the the try-except, and a call to exit(), so the program would exit when i press Ctrl-C. This error message is displayed when either of the calls to exit() are executed- but I don't understand why. Exiting Traceback (most recent call last): File "walk.py", line 19, in ? File "E:\apps\Python\lib\ntpath.py", line 324, in walk walk(name, func, arg) File "E:\apps\Python\lib\ntpath.py", line 318, in walk func(arg, top, names) File "walk.py", line 15, in printdirname TypeError: 'str' object is not callable Would someone please explain which str object is being called ? thanks import os import time def printdirname(junk, dirpath, namelist): try: for name in namelist: if( os.path.isdir(name) ): print "%s" % name except KeyboardInterrupt: print "\nExiting" exit(0) if __name__ == '__main__': try: os.path.walk(r"e:\src\python", printdirname, "*.*") except KeyboardInterrupt: print"\nExiting from Exception during call to os.path.walk()" exit(0) From tony at tcapp.com Sun Sep 7 03:04:28 2003 From: tony at tcapp.com (Tony Cappellini) Date: Sun Sep 7 05:07:43 2003 Subject: [Tutor] OT- need PyQt installation help Message-ID: <5.1.0.14.0.20030907020007.01bea3e8@smtp.sbcglobal.net> Hello, I know this isn't the right place for help with PyQt,but the support site pointed to by the Riverbank page http://www.riverbankcomputing.co.uk/pyqt/mailinglist.php http://mats.imk.fraunhofer.de/mailman/listinfo/pykde (this doesn't look like the right link fr yQT, but this is what is at Riverbank) is down. I've tried installing PyQT 3.7, and 3.8nc, for Windows , both were unsuccessfull. If anyone has any experience overcoming install problems with PyQt on Windows 2000, please email me. thanks From thomi at imail.net.nz Sun Sep 7 22:00:52 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sun Sep 7 05:18:27 2003 Subject: [Tutor] config file parsing problem. In-Reply-To: References: Message-ID: <200309072100.52394.thomi@imail.net.nz> > > Are you commenting individual options? And how are comments "attached" to > the key-value pairs? On the same line, or on top? Perhaps ConfigParser > could be extended to preserve comments that are attached to certain > options. > > Comments span multiple lines, and are not always directly associated with the option. How easy / hard would it be to extend ConfigParser to handle this? It would seem to me that it would require a significant code change for the module. Any ideas? -- Thomi Richards, http://once.sourceforge.net/ From erikprice at mac.com Sun Sep 7 09:44:38 2003 From: erikprice at mac.com (Erik Price) Date: Sun Sep 7 08:23:53 2003 Subject: [Tutor] Re: Philosphy on method naming in modules? In-Reply-To: Message-ID: <0B32C7DB-E131-11D7-AFE0-00039351FE6A@mac.com> On Friday, September 5, 2003, at 07:08 PM, Terry Carroll wrote: > Writing "mixedCase" would have just been ugly. I guess it all depends on what you're used to. Erik From missive at hotmail.com Sun Sep 7 14:12:04 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Sep 7 09:12:13 2003 Subject: [Tutor] Re: TypeError: 'str' object is not callable Message-ID: > File "walk.py", line 15, in printdirname >TypeError: 'str' object is not callable > > >import os >import time > >def printdirname(junk, dirpath, namelist): > > try: > for name in namelist: > if( os.path.isdir(name) ): > print "%s" % name > > except KeyboardInterrupt: > print "\nExiting" > exit(0) > >if __name__ == '__main__': > try: > os.path.walk(r"e:\src\python", printdirname, "*.*") > except KeyboardInterrupt: > print"\nExiting from Exception during call to os.path.walk()" > exit(0) > Hi; Is this really all of the code? :o) I do not see exit bound anywhere, so I think the str is whatever exit is bound to. Usually, when I really _really_ want to get out of a program right NOW, I do this: import os os._exit(0) Maybe exit is being bound somewhere inside of os.path.walk and some kind of namespace thing is letting it waft out in to your handler.... _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From erikprice at mac.com Sun Sep 7 11:52:35 2003 From: erikprice at mac.com (Erik Price) Date: Sun Sep 7 10:31:43 2003 Subject: [Tutor] TypeError: 'str' object is not callable In-Reply-To: <5.1.0.14.0.20030906233607.04327fb8@smtp.sbcglobal.net> Message-ID: On Sunday, September 7, 2003, at 02:44 AM, Tony Cappellini wrote: > This error message is displayed when either of the calls to exit() are > executed- but I don't understand why. > > Exiting > Traceback (most recent call last): > File "walk.py", line 19, in ? > File "E:\apps\Python\lib\ntpath.py", line 324, in walk > walk(name, func, arg) > File "E:\apps\Python\lib\ntpath.py", line 318, in walk > func(arg, top, names) > File "walk.py", line 15, in printdirname > TypeError: 'str' object is not callable > > > Would someone please explain which str object is being called ? The str object being called is a string named 'exit' in the built-in attributes (see the __builtins__ module for a list of these, or just type "dir(__builtins__)" at the prompt). It exists so that if someone types "exit" from the prompt, there is a convenient and unmagical way to give the user the message that the proper way to exit the prompt is with EOF, not "exit" (because "exit" could be bound to some other object). I think what you mean to do in your code is call the os.exit function, as opposed to the string named "exit" in the built-ins. Erik From tony at tcapp.com Sun Sep 7 11:04:10 2003 From: tony at tcapp.com (Tony Cappellini) Date: Sun Sep 7 13:10:35 2003 Subject: [Tutor] TypeError: 'str' object is not callable In-Reply-To: References: <5.1.0.14.0.20030906233607.04327fb8@smtp.sbcglobal.net> Message-ID: <5.1.0.14.0.20030907100229.01bdeed0@tcapp.com> > > >>I think what you mean to do in your code is call the os.exit function, > as opposed to the string named "exit" in the built-ins. Ahh yes, that makes much better sense sense. thanks From carroll at tjc.com Sun Sep 7 11:32:47 2003 From: carroll at tjc.com (Terry Carroll) Date: Sun Sep 7 13:32:50 2003 Subject: [Tutor] Re: Philosphy on method naming in modules? In-Reply-To: <0B32C7DB-E131-11D7-AFE0-00039351FE6A@mac.com> Message-ID: On Sun, 7 Sep 2003, Erik Price wrote: > On Friday, September 5, 2003, at 07:08 PM, Terry Carroll wrote: > > > Writing "mixedCase" would have just been ugly. > > I guess it all depends on what you're used to. I'm only pointing out that even Guido inadvertantly slipped toward capitalizing "mixedCase" as "MixedCase". -- Terry Carroll | "I say to you that the VCR is to the American Santa Clara, CA | film producer and the American public as the carroll@tjc.com | Boston strangler is to the woman home alone." | Jack Valenti, MPAA President Modell delendus est | Testimony before Congress, 1982 From shalehperry at comcast.net Sun Sep 7 11:53:17 2003 From: shalehperry at comcast.net (Sean 'Shaleh' Perry) Date: Sun Sep 7 13:53:23 2003 Subject: [Tutor] spawn In-Reply-To: References: Message-ID: <200309071053.17570.shalehperry@comcast.net> On Thursday 04 September 2003 01:48, kamariah lamim wrote: > Hi.. > i just want to know what is the function os.spawn and how to use it > from looking at the docs it appears to be fork + exec(), so it is kind of like system() with a lot more control. The Python Library reference documents the function, start there. If you sstill have questions you could ask for specific help here. From erikprice at mac.com Sun Sep 7 15:40:30 2003 From: erikprice at mac.com (Erik Price) Date: Sun Sep 7 14:19:40 2003 Subject: [Tutor] Re: Philosphy on method naming in modules? In-Reply-To: Message-ID: On Sunday, September 7, 2003, at 01:32 PM, Terry Carroll wrote: > On Sun, 7 Sep 2003, Erik Price wrote: > >> On Friday, September 5, 2003, at 07:08 PM, Terry Carroll wrote: >> >>> Writing "mixedCase" would have just been ugly. >> >> I guess it all depends on what you're used to. > > I'm only pointing out that even Guido inadvertantly slipped toward > capitalizing "mixedCase" as "MixedCase". Oh, true -- I see what you're saying. That's also one of the reasons I hated using MS-Word, since it would always try to decapitalize the "M" in UMass, etc. Sorry for getting off topic. Erik From project5 at redrival.net Sun Sep 7 22:52:08 2003 From: project5 at redrival.net (Andrei) Date: Sun Sep 7 15:54:04 2003 Subject: [Tutor] Webbrowser Message-ID: Hello, I'm having some problems with the webbrowser module under KDE (Mandrake 9.0/9.1). The problem is that it won't open any browser. The code: def OnLinkClicked(self, linkinfo): webbrowser.open(linkinfo.GetHref(), 1) The error: File "/usr/lib/python2.2/webbrowser.py", line 38, in get raise Error("could not locate runnable browser") webbrowser.Error: could not locate runnable browser I think the code works under Gnome (it's some time ago that I tested it) and it also works under Windows. Any idea how I could solve this? On a sidenote: is there any support for browsers which have tabs (as in: open in a new tab)? Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From andi at buxach.de Sun Sep 7 21:53:51 2003 From: andi at buxach.de (Andreas Zwinkau) Date: Sun Sep 7 15:55:34 2003 Subject: [Tutor] Re: lists in re? In-Reply-To: References: <20030906181754.68637d0b.andi@buxach.de> Message-ID: <20030907205351.04c9ea05.andi@buxach.de> Thanks for answering, Andrei > If you mean you want to make a list of re's and apply them all inside > a loop (or something like that): sure, why not? You can put anything > you like in lists or dictionaries. Not exactly, i learned something from your example, but i thought about something like parser = re.compile(["[abc]","abc","[A-Z]"]) parsedString = parser.replace(["-\\1-","def","[A-Z]"], string2parse) lets say we have a dictionary for all replacement actions: {"[abc]":"-\\1-", "abc":"def","[A-Z]":"_\\1_"} how would you use this on "abBabcAbCC"? -- mfg Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From alan.gauld at blueyonder.co.uk Sun Sep 7 22:28:29 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Sep 7 16:27:43 2003 Subject: [Tutor] TypeError: 'str' object is not callable References: Message-ID: <00b501c3757e$99a03b90$6401a8c0@xp> > > TypeError: 'str' object is not callable > > I think what you mean to do in your code is call the os.exit function, > as opposed to the string named "exit" in the built-ins. Or better still raise the SystemExit exception which automatically ensures all the correct exit hooks are called and doesn't need any module involvement. Alan g. From levent_com at yahoo.com Sun Sep 7 14:34:16 2003 From: levent_com at yahoo.com (Levent Çomoðlu) Date: Sun Sep 7 16:34:20 2003 Subject: [Tutor] System time Message-ID: <20030907203416.96356.qmail@web40711.mail.yahoo.com> Hi Tutor, how can i get the time and date? a very short question but i dont know :) --------------------------------- Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030907/bd30044c/attachment.htm From gus.tabares at verizon.net Sun Sep 7 22:02:58 2003 From: gus.tabares at verizon.net (Gus Tabares) Date: Sun Sep 7 17:02:59 2003 Subject: [Tutor] System time Message-ID: <1062968682.29638.1.camel@blackbetty> Hello, Your answer lies in the time module:) Just import it interactively and help(time) or you can just check out the documentation here: http://www.python.org/doc/current/lib/module-time.html HTH, Gus -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20030907/f6f639d5/attachment.bin From Desai.Dinakar at mayo.edu Sun Sep 7 17:03:43 2003 From: Desai.Dinakar at mayo.edu (Desai, Dinakar S.) Date: Sun Sep 7 17:03:55 2003 Subject: [Tutor] System time Message-ID: <95D623B3588AD4119A3300D0B79E8F064F6A3C@excsrv38.mayo.edu> -----Original Message----- From: Levent "?omo?lu To: Tutor@python.org Sent: 9/7/2003 3:34 PM Subject: [Tutor] System time Hi Tutor, how can i get the time and date? a very short question but i dont know :) Hello: take a look at time module. eg import time time.localtime() /dinakar From tony at tcapp.com Sun Sep 7 15:14:21 2003 From: tony at tcapp.com (Tony Cappellini) Date: Sun Sep 7 17:17:33 2003 Subject: [Tutor] TypeError: 'str' object is not callable Message-ID: <5.1.0.14.0.20030907141309.043d2030@smtp.sbcglobal.net> > > >>I think what you mean to do in your code is call the os.exit function, > as opposed to the string named "exit" in the built-ins. Should this be sys.exit( ) ? I dont think there is an os.exit() From tony at tcapp.com Sun Sep 7 15:14:46 2003 From: tony at tcapp.com (Tony Cappellini) Date: Sun Sep 7 17:17:56 2003 Subject: [Tutor] TypeError: 'str' object is not callable In-Reply-To: <00b501c3757e$99a03b90$6401a8c0@xp> References: Message-ID: <5.1.0.14.0.20030907140905.043c31f8@tcapp.com> > >>Or better still raise the SystemExit exception which automatically thanks Alan. From what I read in the Python in a Nutshell book, calling sys.exit() does raise the SystemExit exception From alan.gauld at blueyonder.co.uk Sun Sep 7 23:38:09 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Sep 7 17:37:26 2003 Subject: [Tutor] TypeError: 'str' object is not callable References: <5.1.0.14.0.20030907140905.043c31f8@tcapp.com> Message-ID: <00c001c37588$550eef30$6401a8c0@xp> > > >>Or better still raise the SystemExit exception which automatically > > From what I read in the Python in a Nutshell book, calling sys.exit() does > raise the SystemExit exception Absolutely, but raising it directly saves the need to import sys and particularly within a try/except clause is the natural paradigm to use. Using os._exit() on the other hand is like pulling the ejector seat to land a plane. There's no clean up you just get out as fast as possible. Alan G. From dyoo at hkn.eecs.berkeley.edu Sun Sep 7 23:07:42 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 8 01:07:46 2003 Subject: [Tutor] ANN: BayPIGgies meeting for September 11, 2003 --- Wavelets! Message-ID: Hi everyone, BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group When: September 11, 2003 @ 7:30pm Where: Carnegie Institute of Washington at Stanford University; Palo Alto Agenda: Wavelets for SciPy Speaker: Chad Netzer Abstract: This talk will demonstrate an implementation of a wavelets package for SciPy, and present some applications with signal processing and image classification. There will be discussion of the benefits of doing scientific computation with Python, unit testing with statistical methods, and using SciPy with PythonCard as a learning tool. (Knowledge of wavelets is not a requirement, and the math will be kept to a minimum) For driving directions, please visit: http://baypiggies.net We hope to see you there! From dyoo at hkn.eecs.berkeley.edu Sun Sep 7 23:59:24 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 8 01:59:29 2003 Subject: [Tutor] Webbrowser In-Reply-To: Message-ID: On Sun, 7 Sep 2003, Andrei wrote: > The error: > > File "/usr/lib/python2.2/webbrowser.py", line 38, in get > raise Error("could not locate runnable browser") > webbrowser.Error: could not locate runnable browser > > I think the code works under Gnome (it's some time ago that I tested it) > and it also works under Windows. Hi Andrei, Hmmm... the webbrowser module does the following checks on a Unix environment: ## Within webbrowser.py: if os.environ.get("DISPLAY"): if _iscommand("netscape") or _iscommand("mozilla"): if _iscommand("mozilla"): register("mozilla", None, Netscape("mozilla")) if _iscommand("netscape"): register("netscape", None, Netscape("netscape")) if _iscommand("mosaic"): register("mosaic", None, GenericBrowser ("mosaic %s >/dev/null &")) if _iscommand("kfm") or _iscommand("konqueror"): register("kfm", Konqueror, Konqueror()) if _iscommand("grail"): register("grail", Grail, None) > Any idea how I could solve this? According to the code above, it should have been able to find KDE's Konqueror browser fine, as long as: 1. os.environ.get('DISPLAY') is some kind of true value, and 2. kfm or konqueror can be found by the system. So you may want to check those first. > On a sidenote: is there any support for browsers which have tabs (as in: > open in a new tab)? Good question! I'm not sure how to do this platform-independently yet, but Mozilla does support it: http://www.mozilla.org/docs/command-line-args.html through the 'new-tab' option. To get this to work, we'd probably have to modify the 'Netscape' handler within webbrowser.py. Here's one way we might be able to do it: ### class Netscape: """Launcher class for Netscape browsers. dyoo: Modified to let windows to be opened in tabs. """ def __init__(self, name): self.name = name self.basename = os.path.basename(name) def _remote(self, action, autoraise): raise_opt = ("-noraise", "-raise")[autoraise] cmd = "%s %s -remote '%s' >/dev/null 2>&1" % (self.name, raise_opt, action) rc = os.system(cmd) if rc: import time os.system("%s &" % self.name) time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc def open(self, url, new=0, autoraise=1): if new == 'tab': self._remote("openURL(%s, new-tab)"%url, autoraise) if new: self._remote("openURL(%s, new-window)"%url, autoraise) else: self._remote("openURL(%s)" % url, autoraise) def open_new(self, url): self.open(url, 1) ### This modification augments the 'new' keyword parameter so that it can take in 'tab', in which case it'll try to open using the 'new-tab' option: ### import webbrowser_modified webbrowser_modified.open('http://python.org', new='tab') ### Can't test this on my end, since I'm running on Safari. Can someone check to see if this works? If this were polished up, it might make a nice submission to Sourceforge... *grin* Good luck to you! From jim_938 at hotmail.com Mon Sep 8 14:06:28 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Mon Sep 8 03:36:34 2003 Subject: [Tutor] multiple file output Message-ID: Hi, I want some suggestion again from tutor. Firstly thanks to everyone for their previous responses. I want to write two strings in two different files. Like i want the user to run the program by specifying the name of the program on command line and want to generate a few files based on the strings of information i have in the code. Like ./prgname.py and it should generate two files: a.txt, b.txt without specifying the name of the file on the command line. Your suggestions are welcomed. Thanks in advance. Regards, J+ _________________________________________________________________ MSN Hotmail now on your Mobile phone. http://server1.msn.co.in/sp03/mobilesms/ Click here. From scot at possum.in-berlin.de Mon Sep 8 04:13:46 2003 From: scot at possum.in-berlin.de (Scot W. Stevenson) Date: Mon Sep 8 05:28:43 2003 Subject: [Tutor] Webbrowser In-Reply-To: References: Message-ID: <200309080313.46037.scot@possum.in-berlin.de> Hello Andrei, > def OnLinkClicked(self, linkinfo): > webbrowser.open(linkinfo.GetHref(), 1) > > The error: > > File "/usr/lib/python2.2/webbrowser.py", line 38, in get > raise Error("could not locate runnable browser") > webbrowser.Error: could not locate runnable browser I used the browser module exactly once, and I started it off with try: self.mybrowser = webbrowser.get() except TypeError: [Say you can't find the browser] I'm not sure if you did something like that before the part of the code that you mentioned. The docs say you can "register" a browser; if all else fails, maybe that would be the way to go. Y, Scot -- How to quiet a crying baby with the X Window System: nice xlock -inwindow -mode kumppa Scot W. Stevenson - Zepernick, Germany From glingl at aon.at Mon Sep 8 15:03:45 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Sep 8 08:27:05 2003 Subject: [Tutor] GIFs Using Tkinter Message-ID: <3F5C7021.5050307@aon.at> Hi all! I'm trying to use recipe 9.5 from Python Cookbook, which suggests to read gifs from files using base64.encodestring in order to embed those images into my sourcecode. I've prepared some 20 gifs with Photoshop which are all merely rotated versions of some "master"-gif. (They all are produced in exactly the same way and have (255,255,255) as transparent color.) They all can be used as Tkinter PhotoImages with the file-option perfectly well. However, if I try to use the data-option with strings constructed from those same gifs according to the recipe mentioned above, I observe, that among those gif-images (1) some can be displayed correctly (more than 50%) (2) some are corrupted and are displayed with stripes or other artefacts. (3) and some result in strings only a few characters long which cannot be interpreted as image-data at all. What could be the reason for this annoying behaviour and how can I avoid it. Thanks in advance Gregor From pythontutor at venix.com Mon Sep 8 11:31:59 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Sep 8 10:32:18 2003 Subject: [Tutor] GIFs Using Tkinter In-Reply-To: <3F5C7021.5050307@aon.at> References: <3F5C7021.5050307@aon.at> Message-ID: <3F5C92DF.5000407@venix.com> My guess is that you did this on Windows and did not include "rb" on the open call. Change the recipe fragment: ...open("icon.gif")... to ...open("icon.gif","rb")... In Windows, the default mode when opening a file is "Text Mode" which provides special handling for line mark characters, r"\r\n". This means that bits in your image that accidently match the line handling will get mangled. "rb" opens the file for reading in binary mode. I believe that Microsoft uses raw and cooked to differentiate the two modes of reading files. Gregor Lingl wrote: > Hi all! > > I'm trying to use recipe 9.5 from Python Cookbook, which suggests > to read gifs from files using base64.encodestring in order to embed > those images into my sourcecode. > > I've prepared some 20 gifs with Photoshop which are all merely > rotated versions of some "master"-gif. (They all are produced in > exactly the same way and have (255,255,255) as transparent color.) > > They all can be used as Tkinter PhotoImages with the file-option > perfectly well. > > However, if I try to use the data-option with strings constructed > from those same gifs according to the recipe mentioned above, > I observe, that among those gif-images > (1) some can be displayed correctly (more than 50%) > (2) some are corrupted and are displayed with stripes or other > artefacts. > (3) and some result in strings only a few characters long > which cannot be interpreted as image-data at all. > > What could be the reason for this annoying behaviour and how > can I avoid it. > > Thanks in advance > > Gregor > > > > _______________________________________________ > 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 dyoo at hkn.eecs.berkeley.edu Mon Sep 8 08:38:19 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 8 10:38:23 2003 Subject: [Tutor] multiple file output In-Reply-To: Message-ID: On Mon, 8 Sep 2003, Jimmy verma wrote: > I want to write two strings in two different files. Like i want the user > to run the program by specifying the name of the program on command line > and want to generate a few files based on the strings of information i > have in the code. Hi Jimmy, Not a problem --- we'll want to use the 'open()' builtin function again, but this time, we want to tell it to open the file in 'write' mode. For example: ### f = open('foobar.txt', 'w') f.write("Hello world!\n") ### Hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Sep 8 08:47:04 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 8 10:47:11 2003 Subject: [Tutor] multiple file output [forgot to close() a file!] In-Reply-To: Message-ID: > > I want to write two strings in two different files. Like i want the > > user to run the program by specifying the name of the program on > > command line and want to generate a few files based on the strings of > > information i have in the code. > > Hi Jimmy, > > Not a problem --- we'll want to use the 'open()' builtin function again, > but this time, we want to tell it to open the file in 'write' mode. > For example: > > ### > f = open('foobar.txt', 'w') > f.write("Hello world!\n") > ### Hi Jimmy, Yikes, the example wasn't complete --- I neglected to add one essential line: ### f = open('foobar.txt', 'w') f.write('Hello world!\n') f.close() ### We need to do close() when we're writing files, because it puts some finishing touches on the written file. Many operating systems will "buffer" its disk writes in large batches for efficiency. That is, when we do a close(), we guarantee that the last batch is flushed over to disk. But if we forget to do this close(), we may lose the lines we've just written! I'll try to be more careful next time. Talk to you later! From glingl at aon.at Mon Sep 8 19:13:08 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Sep 8 12:14:51 2003 Subject: [Tutor] GIFs Using Tkinter In-Reply-To: <3F5C92DF.5000407@venix.com> References: <3F5C7021.5050307@aon.at> <3F5C92DF.5000407@venix.com> Message-ID: <3F5CAA94.5010702@aon.at> Lloyd Kvam schrieb: > My guess is that you did this on Windows and did not include "rb" on the > open call. Well guessed! Thanks to all of you. Gregor > Change the recipe fragment: > ...open("icon.gif")... > to > ...open("icon.gif","rb")... > > In Windows, the default mode when opening a file is "Text Mode" which > provides special handling for line mark characters, r"\r\n". This means > that bits in your image that accidently match the line handling will get > mangled. "rb" opens the file for reading in binary mode. I believe that > Microsoft uses raw and cooked to differentiate the two modes of reading > files. > > Gregor Lingl wrote: > >> Hi all! >> >> I'm trying to use recipe 9.5 from Python Cookbook, which suggests >> to read gifs from files using base64.encodestring in order to embed >> those images into my sourcecode. >> >> I've prepared some 20 gifs with Photoshop which are all merely >> rotated versions of some "master"-gif. (They all are produced in >> exactly the same way and have (255,255,255) as transparent color.) >> >> They all can be used as Tkinter PhotoImages with the file-option >> perfectly well. >> >> However, if I try to use the data-option with strings constructed >> from those same gifs according to the recipe mentioned above, >> I observe, that among those gif-images >> (1) some can be displayed correctly (more than 50%) >> (2) some are corrupted and are displayed with stripes or other >> artefacts. >> (3) and some result in strings only a few characters long >> which cannot be interpreted as image-data at all. >> >> What could be the reason for this annoying behaviour and how >> can I avoid it. >> >> Thanks in advance >> >> Gregor >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From idiot1 at netzero.net Sun Sep 7 23:06:20 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Mon Sep 8 12:30:51 2003 Subject: [Tutor] THE CGI SERVER SCRIPT Message-ID: <3F5BE41C.9080702@netzero.net> I am using the cgi server script on my desktop pc so I can devlop scripts without going online. IT WORKS GREAT! I have it living on port 8000, although I tried it out on port 80- either way, it's cherry. And as I am running python 2.2.1, I can take advantage of cgitb, which is startlingly novel after 2 years of working via ssh (well, PuTTY) to get into Critter, who is still running 1.6.2. Anyone want the corrected script, email me. If there is enough intrest, I will post it on the tinylist.org site. -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From project5 at redrival.net Mon Sep 8 21:17:10 2003 From: project5 at redrival.net (Andrei) Date: Mon Sep 8 14:19:13 2003 Subject: [Tutor] Re: Webbrowser In-Reply-To: References: Message-ID: Danny Yoo wrote: > > Hmmm... the webbrowser module does the following checks on a Unix > environment: > > > According to the code above, it should have been able to find KDE's > Konqueror browser fine, as long as: > > 1. os.environ.get('DISPLAY') is some kind of true value, and > 2. kfm or konqueror can be found by the system. > > So you may want to check those first. I'll look at those when I boot in Linux. The annoying bit is that in a standard installation of a popular, modern distro (Mandrake), the Python module doesn't work out of the box. Konqueror is of course present, as well as Mozilla and the Gnome browser (name escapes me atm). >>On a sidenote: is there any support for browsers which have tabs (as in: >>open in a new tab)? > > > Good question! I'm not sure how to do this platform-independently yet, > but Mozilla does support it: > > http://www.mozilla.org/docs/command-line-args.html > > through the 'new-tab' option. To get this to work, we'd probably have to > modify the 'Netscape' handler within webbrowser.py. Here's one way we > might be able to do it: > > > This modification augments the 'new' keyword parameter so that it can take > in 'tab', in which case it'll try to open using the 'new-tab' option: > > ### > import webbrowser_modified > webbrowser_modified.open('http://python.org', new='tab') > ### > > > Can't test this on my end, since I'm running on Safari. Can someone check > to see if this works? If this were polished up, it might make a nice > submission to Sourceforge... *grin* > Thanks, I'll test that too. ===== Scot W. Stevenson wrote: > > I used the browser module exactly once, and I started it off with > > try: > self.mybrowser = webbrowser.get() > except TypeError: > [Say you can't find the browser] > > I'm not sure if you did something like that before the part of the code that > you mentioned. The docs say you can "register" a browser; if all else fails, > maybe that would be the way to go. Yes, I use that method elsewhere in my code and use a different display method (plain text in a message window instead of HTML). However, in this case I don't want that. I *must* have the browser. Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Mon Sep 8 12:40:44 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 8 14:41:02 2003 Subject: [Tutor] ANN: BayPIGgies meeting for September 10, 2003 --- Wavelets! [Correction: it's on Wednesday 9/10] Message-ID: Hi everyone, Sorry for repeating the post, but I mistyped the date! The meeting will be held this Wednesday, not Thursday. ---------------- BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group When: September 10, 2003 @ 7:30pm Where: Carnegie Institute of Washington at Stanford University; Palo Alto Agenda: Wavelets for SciPy Speaker: Chad Netzer Abstract: This talk will demonstrate an implementation of a wavelets package for SciPy, and present some applications with signal processing and image classification. There will be discussion of the benefits of doing scientific computation with Python, unit testing with statistical methods, and using SciPy with PythonCard as a learning tool. (Knowledge of wavelets is not a requirement, and the math will be kept to a minimum) For driving directions, please visit: http://baypiggies.net We hope to see you there! From aicolburn at yahoo.com Mon Sep 8 13:03:00 2003 From: aicolburn at yahoo.com (Alan Colburn) Date: Mon Sep 8 15:03:09 2003 Subject: [Tutor] new book available Message-ID: <20030908190300.7351.qmail@web41612.mail.yahoo.com> Hi all -- Checking my local bookstore last weekend I saw a new Python title: Python Programming for the Absolute Beginner. As most of you know, there's a series of "...for the absolute beginner" books. Whether one likes the book or not, I take it as a good sign that another publisher sees enough interest in Python to create a book about it. I'm curious as to what folks who've looked at the work think. I only had time to leaf through it for a few minutes. One of the things that caught my attention was the author's distinguishing "new" style class definitions from "old" style ones. >>>class Test: is an old style definition. >>>class Test (object): is the newer style. I don't think I've seen this point discussed on PythonTutor or elsewhere. [Have I missed something?] Later -- Al __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From alan.gauld at blueyonder.co.uk Mon Sep 8 21:12:27 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Sep 8 15:11:27 2003 Subject: [Tutor] multiple file output References: Message-ID: <011801c3763d$24e11800$6401a8c0@xp> Jimmy, > I want to write two strings in two different files. What do you perceive stops you? Can you write data to one file? If so then two files is the same, you just open two separate files for writing. Remember to close them both at the end. What exactly do you think is the problem? If you aren't sure about how to open files for writing see my web tutor topic on the subject. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From project5 at redrival.net Tue Sep 9 00:45:56 2003 From: project5 at redrival.net (Andrei) Date: Mon Sep 8 17:47:54 2003 Subject: [Tutor] Re: new book available In-Reply-To: <20030908190300.7351.qmail@web41612.mail.yahoo.com> References: <20030908190300.7351.qmail@web41612.mail.yahoo.com> Message-ID: Alan Colburn wrote: Hello Alan, > Checking my local bookstore last weekend I saw a new > Python title: Python Programming for the Absolute > Beginner. As most of you know, there's a series of > "...for the absolute beginner" books. Whether one > likes the book or not, I take it as a good sign that > another publisher sees enough interest in Python to > create a book about it. I'm not familiar with it, but I don't live in an English speaking country. Is it anything like the "for dummies" books? The ones I've seen on programming weren't very good :(. > One of the things that caught my attention was the > author's distinguishing "new" style class definitions > from "old" style ones. > is the newer style. I don't think I've seen this point > discussed on PythonTutor or elsewhere. [Have I missed > something?] It's documented in the help files of Python (What's new in 2.2): 2 PEPs 252 and 253: Type and Class Changes 2.1 Old and New Classes Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Tue Sep 9 01:55:47 2003 From: project5 at redrival.net (Andrei) Date: Mon Sep 8 18:57:46 2003 Subject: [Tutor] Re: lists in re? In-Reply-To: <20030907205351.04c9ea05.andi@buxach.de> References: <20030906181754.68637d0b.andi@buxach.de> <20030907205351.04c9ea05.andi@buxach.de> Message-ID: Andreas Zwinkau wrote: >Not exactly, i learned something from your example, but i thought about >something like >parser = re.compile(["[abc]","abc","[A-Z]"]) I'd write that pretty much like I wrote in the previous message, with a list comprehension: parser = [ re.compile(item) for item in ["[abc]","abc","[A-Z]"] ] >parsedString = parser.replace(["-\\1-","def","[A-Z]"], string2parse) I have no idea what this is supposed to do. What's string2parse and what's that list of strings in front of it? >lets say we have a dictionary for all replacement actions: >{"[abc]":"-\\1-", "abc":"def","[A-Z]":"_\\1_"} >how would you use this on "abBabcAbCC"? Again, I don't understand what this dictionary contains. If you mean you have a dictionary of uncompiled regexes mapped to... something and you want to get those regexes compiled, you can extract them using the keys() property of the dictionary and combine that with the list comprehension I wrote above, like this: >>> test = {"[abc]":"-\\1-", "abc":"def","[A-Z]":"_\\1_"} >>> parser = [ re.compile(item) for item in test.keys() ] Any chance of an example of what you're putting into it and what the code is supposed to make out of it? It would be most useful if you'd put in some *real* examples, because a key-value pair like "abc":"def" is a bit too abstract for me to understand its purpose. Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From idiot1 at netzero.net Tue Sep 9 02:03:08 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Tue Sep 9 01:03:35 2003 Subject: [Tutor] THE CGI SERVER SCRIPT In-Reply-To: <000901c3762e$44273820$a24c73d5@BAERBAR> References: <3F5BE41C.9080702@netzero.net> <000901c3762e$44273820$a24c73d5@BAERBAR> Message-ID: <3F5D5F0C.4010204@netzero.net> I will be glad to post it here, NOW: #!C:\Python22\pythonw.exe import CGIHTTPServer, BaseHTTPServer httpd=BaseHTTPServer.HTTPServer(('',80), CGIHTTPServer.CGIHTTPRequestHandler) httpd.serve_forever() # this is a small but serviceable cgi server for your pc! That's it. BTW, it is Steve Holden's work, and he deserve the praise, not I. He wrote 'Python Web Programming'. It is there on page 251, but has a bug, which I alerted hom to, and he corrected. This version in this posting WORKS. To have it work on a different port number, change '80' to 'foo', where foo is the number of the port you wish to use. Teh default port used for http transferrs is 80. Your local pc will respond to 'http://localhost/' or to 'http://127.0.0.1/', just like a regular server- because it IS a server. You may have to modify the #! line to point at pythonw.exe if it is not a standard install of IDLE in your pc. You can create an icon on the desktop to point to it. The target should be as: C:\Python22\pythonw.exe C:\PYTHON22\cgiserver.py and it should start in C:\Python22 and it should run minimized. DO NOT run this while online unless you have a firewall in operation, and even then it is more secure if you use a high numbered non standard port- above 1024 at least. To make it simple, try 8080. To talk to the server with port 8080, your link looks like: http://localhost:8080/ Hope this helps. As for cgi writing, this is the list to discuss it. A server has to be told with a special header what is coming along, then you output normally. For example, here is a simple helloworld cgi program in python: #!C:\Python22\pythonw.exe print 'Content-Type: text/html\n' # notice the extra newline-important! print 'Hello world' print '' print '

Hello World!

' print '

' print 'That's all.

' print '' In C:\python22, create the 'cgi-bin' directory, and place it there. In c:\Python22, create 'index.html' with the usual stuff, and a link to the script. This should look like: Hello World Script If the server is working, entering http://localhost:8080/index.html will result in the page displaying. Clicking the link should result in the page generated by the script being displayed. What fun hwe can have testing scripts locally with a local offline server! THANKS, STEVE! Ole Jensen wrote: > Hi Kirk > I don't really have any idea as to how I make CGI scripts(but I would like > to), and if I would be able to experiment with making cgi using your script, > without finding a webspace that supports cgi and all that, I would like a > copy very much. > > Where can I download it, or will you send it? > > Ole > > ----- Original Message ----- > From: "Kirk Bailey" > To: "Tutor" > Sent: Monday, September 08, 2003 4:06 AM > Subject: [Tutor] THE CGI SERVER SCRIPT > > > >>I am using the cgi server script on my desktop pc so I can devlop scripts >>without going online. IT WORKS GREAT! >> >>I have it living on port 8000, although I tried it out on port 80- either > > way, > >>it's cherry. And as I am running python 2.2.1, I can take advantage of > > cgitb, > >>which is startlingly novel after 2 years of working via ssh (well, PuTTY) > > to get > >>into Critter, who is still running 1.6.2. >> >>Anyone want the corrected script, email me. If there is enough intrest, I > > will > >>post it on the tinylist.org site. >> >> >>-- >> >>-- >> >>end >> >>Cheers! >> Kirk D Bailey >> >> + think + >> http://www.howlermonkey.net +-----+ http://www.tinylist.org >> http://www.listville.net | BOX | http://www.sacredelectron.org >> Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus >> + think + >> >>Fnord. >> >> >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From alan.gauld at blueyonder.co.uk Tue Sep 9 09:14:38 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Sep 9 03:13:28 2003 Subject: [Tutor] new book available References: <20030908190300.7351.qmail@web41612.mail.yahoo.com> Message-ID: <014001c376a2$07f397d0$6401a8c0@xp> > author's distinguishing "new" style class definitions > from "old" style ones. > > >>>class Test: > > >>>class Test (object): > > is the newer style. I don't think I've seen this point > discussed on PythonTutor or elsewhere. [Have I missed > something?] Yes, there's been a couple of discussions about new style classes. The fact that they inherit from 'object' (or a subclas of object) is indeed the distinguishing feature. ie >>> class Number(int): is also a new style class because int is a subclass of object... Alan G. From anand_shankar at yahoo.com Tue Sep 9 01:20:49 2003 From: anand_shankar at yahoo.com (Anand Shankar) Date: Tue Sep 9 03:20:53 2003 Subject: [Tutor] List of Methods in a class / library Message-ID: <20030909072049.17640.qmail@web41304.mail.yahoo.com> How can I get a listing of all methods in a class or module, and better still the arguments required? No I do'nt mean the default: Look up documentation!! Anand Shankar __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From op73418 at mail.telepac.pt Tue Sep 9 13:11:20 2003 From: op73418 at mail.telepac.pt (Rodrigues) Date: Tue Sep 9 07:09:56 2003 Subject: [Tutor] new book available In-Reply-To: <014001c376a2$07f397d0$6401a8c0@xp> Message-ID: > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On > Behalf Of Alan Gauld > > > author's distinguishing "new" style class definitions > > from "old" style ones. > > > > >>>class Test: > > > > >>>class Test (object): > > > > is the newer style. I don't think I've seen this point > > discussed on PythonTutor or elsewhere. [Have I missed > > something?] > > Yes, there's been a couple of discussions about new style > classes. The fact that they inherit from 'object' (or > a subclas of object) is indeed the distinguishing feature. > > ie > > >>> class Number(int): > > is also a new style class because int is a subclass of object... > It's also a new-style class if you set the metaclass, e.g. >>> class Test: ... __metaclass__ = type ... >>> Test.mro() [, ] >>> Best regards, G. Rodrigues From op73418 at mail.telepac.pt Tue Sep 9 13:13:22 2003 From: op73418 at mail.telepac.pt (Rodrigues) Date: Tue Sep 9 07:11:58 2003 Subject: [Tutor] List of Methods in a class / library In-Reply-To: <20030909072049.17640.qmail@web41304.mail.yahoo.com> Message-ID: > -----Original Message----- > From: tutor-bounces+op73418=mail.telepac.pt@python.org > [mailto:tutor-bounces+op73418=mail.telepac.pt@python.org]On > Behalf Of > Anand Shankar > > How can I get a listing of all methods in a class or > module, and better still the arguments required? > > No I do'nt mean the default: Look up documentation!! > > Anand Shankar > Use help at the interactive prompt? >>> import socket >>> help(socket) Help on module socket: NAME socket FILE c:\python23\lib\socket.py DESCRIPTION This module provides socket operations and some related functions. On Unix, it supports IP (Internet Protocol) and Unix domain sockets. On other systems, it only supports IP. Functions specific for a socket are available as methods of the socket object. [the list continues...] From erikprice at mac.com Tue Sep 9 09:12:56 2003 From: erikprice at mac.com (Erik Price) Date: Tue Sep 9 07:51:55 2003 Subject: [Tutor] new book available In-Reply-To: <20030908190300.7351.qmail@web41612.mail.yahoo.com> Message-ID: On Monday, September 8, 2003, at 03:03 PM, Alan Colburn wrote: > One of the things that caught my attention was the > author's distinguishing "new" style class definitions > from "old" style ones. > >>>> class Test: > > is an old style definition. > >>>> class Test (object): > > is the newer style. I don't think I've seen this point > discussed on PythonTutor or elsewhere. [Have I missed > something?] It's been tossed around a couple of times (though I'm not sure how recently). If you want to create a new-style class, you inherit from object, otherwise you don't (or you inherit from a superclass that doesn't inherit from object). The differences between old-style and new-style classes are pretty far-reaching, but some of the nice things are that you can subclass the "primitive" (*) types like int. This way you can extend or modify functionality of a "primitive" by subclassing, whereas before if you wanted to create your own special kind of "primitive" you'd have to create it afresh as a new class and create an implementation for every single one of the methods provided by that "primitive" (like __add__, __and__, __or__, etc). Such a delegate would also perform more slowly than a true subclass of the "primitive". ( * I use "primitive" in quotes because my understanding is that Python doesn't have any true primitives, technically "int" and "float" are classes themselves, but I didn't know what else to call them.) There are also some other new features of new-style classes such as "slots" and "properties" which are documented as being for advanced users, and meta-classes (which let you modify the factories that churn out your classes, which in turn churn out your instances -- because a class is also an instance/object itself, just happens to be a callable object). For a good explanation of meta-classes, I would refer to Alex Martelli's "Python in a Nutshell". Erik From erikprice at mac.com Tue Sep 9 09:16:51 2003 From: erikprice at mac.com (Erik Price) Date: Tue Sep 9 07:55:51 2003 Subject: [Tutor] List of Methods in a class / library In-Reply-To: <20030909072049.17640.qmail@web41304.mail.yahoo.com> Message-ID: <7E455440-E2BF-11D7-8DB3-00039351FE6A@mac.com> On Tuesday, September 9, 2003, at 03:20 AM, Anand Shankar wrote: > How can I get a listing of all methods in a class or > module, and better still the arguments required? > > No I do'nt mean the default: Look up documentation!! Try the dir() built-in function to get a List of strings containing the members of an object (including a module or class). You could probably get creative and create a new function that calls dir() on its argument, but also fetches more detailed information on each member and returns it (such as docstring). Erik From magnus at thinkware.se Tue Sep 9 15:38:28 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Sep 9 08:38:39 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gbmV3IGJvb2sgYXZhaWxhYmxl?= Message-ID: > One of the things that caught my attention was the > author's distinguishing "new" style class definitions > from "old" style ones. > > >>>class Test: > > is an old style definition. > > >>>class Test (object): > > is the newer style. I don't think I've seen this point > discussed on PythonTutor or elsewhere. [Have I missed > something?] Yes, you seem to have missed Python 2.2. :) See http://www.python.org/doc/2.2.3/whatsnew/ and http://www.python.org/2.2.3/descrintro.html -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From jim_938 at hotmail.com Tue Sep 9 20:59:15 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Tue Sep 9 10:29:31 2003 Subject: [Tutor] multiple file output Message-ID: Hello tutor, Thanks to everyone for their suggestions. Now i want to open the file with names which are created dynamically. out = open('f[i].txt', 'w') out.write(str) out.close() something like this where f[i] should be coming from some list f Your valuable suggestions are welcomed. Regards, J+ _________________________________________________________________ On the move? Need to access your mails? http://server1.msn.co.in/sp03/mobilesms/index.asp Hotmail is now on your mobile! From tpc at csua.berkeley.edu Tue Sep 9 10:16:29 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Tue Sep 9 12:16:45 2003 Subject: [Tutor] multiple file output In-Reply-To: Message-ID: <20030909090048.L52593-100000@localhost.name> hi Jimmy, you would probably want to use a for statement, so if you have a list of files stored in filelist: for file in filelist: out = open(file, 'w') out.write(str) out.close() On Tue, 9 Sep 2003, Jimmy verma wrote: > Hello tutor, > > Thanks to everyone for their suggestions. Now i want to open the file with > names which are created dynamically. > > > out = open('f[i].txt', 'w') > out.write(str) > out.close() > > something like this where f[i] should be coming from some list f > > > Your valuable suggestions are welcomed. > > Regards, > J+ > > _________________________________________________________________ > On the move? Need to access your mails? > http://server1.msn.co.in/sp03/mobilesms/index.asp Hotmail is now on your > mobile! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From andi at buxach.de Tue Sep 9 14:39:01 2003 From: andi at buxach.de (Andreas Zwinkau) Date: Tue Sep 9 12:43:27 2003 Subject: [Tutor] Re: lists in re? In-Reply-To: References: <20030906181754.68637d0b.andi@buxach.de> <20030907205351.04c9ea05.andi@buxach.de> Message-ID: <20030909133901.26f266e4.andi@buxach.de> > parser = [ re.compile(item) for item in ["[abc]","abc","[A-Z]"] ] I'm not used to such "complex" constructs, but well, I can work with it. > Any chance of an example of what you're putting into it and what the > code is supposed to make out of it? It would be most useful if you'd > put in some *real* examples, because a key-value pair like "abc":"def" > is a bit too abstract for me to understand its purpose. Do you know what a Wiki is? I have some user text with abstract text formations e.g. __underlined__ These should be processed into HTML underlined There are some more rules. ''italic'' -> italic **bold** -> bold [word] -> word [image.gif] -> [http://google.com|Google] -> http://slashdot.org If this gets more and more, i thought a dictionary would be the best way to define it in a obvious way. So this dict needs to be fed to the re module, but instead of processing each item, i wanted to re.compile it in one piece. -- mfg Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From jeff at ccvcorp.com Tue Sep 9 11:27:24 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Sep 9 13:25:14 2003 Subject: [Tutor] multiple file output References: Message-ID: <3F5E0D7C.4090808@ccvcorp.com> Jimmy verma wrote: > Thanks to everyone for their suggestions. Now i want to open the file > with names which are created dynamically. > > out = open('f[i].txt', 'w') > out.write(str) > out.close() > > something like this where f[i] should be coming from some list f You can use string formatting to create dynamic names. names = ['john', 'paul', 'george', 'ringo'] for name in names: filename = 'beatles_%s.txt' % name outfile = file(filename, 'w') outfile.write(foo) outfile.close() The % operator substitutes the contents of 'name' into the %s placeholder location -- %s stands for string, but you can also use %d (for decimal numbers), %x (for hex), and a variety of other formatting specifiers, including specifying a minimum length and a padding character. Check the Python tutorial for "string formatting" to get more details. Jeff Shannon Technician/Programmer Credit International From ronan at melim.com.br Tue Sep 9 15:58:51 2003 From: ronan at melim.com.br (Ronan Lucio) Date: Tue Sep 9 13:57:28 2003 Subject: [Tutor] Productivity Message-ID: <200309091458.51684.ronan@melim.com.br> Hi All, I used to make my Python CGI's in the vi editor. Now, I'm looking for the ways to optimize the productivity of the development tasks. Could anyone say me what the better ways/tools to develop python programs/cgis? Thank's Ronan From dyoo at hkn.eecs.berkeley.edu Tue Sep 9 14:23:56 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 9 16:24:03 2003 Subject: [Tutor] List of Methods in a class / library In-Reply-To: <20030909072049.17640.qmail@web41304.mail.yahoo.com> Message-ID: On Tue, 9 Sep 2003, Anand Shankar wrote: > How can I get a listing of all methods in a class or module, and better > still the arguments required? Hi Anand, The other folks on Tutor have already mentioned using dir() and help(). Another possibility is to use the 'inspect' module: http://www.python.org/doc/lib/module-inspect.html There are a few functions in the 'inspect' module to make it easier to "introspect" things at runtime. For example, there's a nice function called 'getargspec()' that takes a function and returns a description of the arguments it uses: ### >>> def hypotenuse(a, b): ... return (a**2 + b**2) ** (0.5) ... >>> import inspect >>> inspect.getargspec(hypotenuse) (['a', 'b'], None, None, None) ### 'getargspec()' is documented here: http://www.python.org/doc/lib/inspect-classes-functions.html > No I don't mean the default: Look up documentation!! But what's wrong with documentation? *grin* >From your question, it sounds like you might be trying to write some sort of program that works on other programs, and for that kind of metaprogramming, the 'inspect' module might just be the tool you're looking for. But is there anything in particular that you're trying to do? Best of wishes to you! From sigurd at 12move.de Tue Sep 9 23:25:32 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Sep 9 16:26:53 2003 Subject: [Tutor] Re: lists in re? In-Reply-To: <20030909133901.26f266e4.andi@buxach.de> (Andreas Zwinkau's message of "Tue, 9 Sep 2003 13:39:01 +0200") References: <20030906181754.68637d0b.andi@buxach.de> <20030907205351.04c9ea05.andi@buxach.de> <20030909133901.26f266e4.andi@buxach.de> Message-ID: On 9 Sep 2003, Andreas Zwinkau <- andi@buxach.de wrote: > If this gets more and more, i thought a dictionary would be the best way > to define it in a obvious way. So this dict needs to be fed to the re > module, but instead of processing each item, i wanted to re.compile it > in one piece. Did you think about writing it in a functional way? I took the regexps from one one your previous postings to write the example. [lambda string, x=reg, y=exp: re.compile(x).sub(y, string) for (reg, exp) in [ # (regexp, expansion) ("''(.+)''", r"\1"), # italic (r"\*\*(.+)\*\*", r"\1"), #bold ("\[([\w \=\-\_\.]+)\]", r"\1"), #link ("(?<=\n)\* (.*)\n", r"

  • \1
\n"), #list ("__(.+?)__", r"\1") # underline ]] def wikinize (funs, stream): for fun in funs: stream = fun(stream) return stream We do here mainly two things: ( 1) We build a list of anonymous functions. Each function takes three parameters: the string to be altered, a regular expression and an expansion. The regexp and the expansion are taken from a list of tuples (in each function they are bound to the correspondent values from the tuples). ( 2) We write a function which takes a list of functions (our previously build list) and a string. here is an example >>> s = "''abc''def**ghi**jkl[link]__underline__" >>> flist =[lambda string, x=reg, y=exp: re.compile(x).sub(y, string) ... for (reg, exp) in ... [ # (regexp, expansion) ... ("''(.+)''", r"\1"), # italic ... (r"\*\*(.+)\*\*", r"\1"), #bold ... ("\[([\w \=\-\_\.]+)\]", r"\1"), #link ... ("(?<=\n)\* (.*)\n", r"
  • \1
\n"), #list ... ("__(.+?)__", r"\1") # underline ... ]] >>> wikinize(flist, s) 'abcdefghijkllinkunderline' >>> If you want to add new regexps and their expansions you only have to change one list. Karl -- Please do *not* send copies of replies to me. I read the list From jonathan.hayward at pobox.com Tue Sep 9 23:06:11 2003 From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com) Date: Tue Sep 9 17:06:17 2003 Subject: [Tutor] Memory optimization problem [intern() can save space for commonly used strings] In-Reply-To: References: Message-ID: <3F5E40C3.9090905@pobox.com> Danny Yoo wrote: >On Fri, 5 Sep 2003, Jonathan Hayward http://JonathansCorner.com wrote: > > > >>I have been working on a search engine, which is a memory hog. I >>originally had it use a hashtable to keep a histogram of occurrences for >>words for files >> >> > >Hi Jonathan, > > >How many unique words are you running into? Let's use that to estimate >memory usage. Also, can you show us how you're constructing the >dictionary? Are you using a separate dictionary for each document in your >collection? > > > Thank you. The code that's keeping the histogram is: class histogram(ancestor): """Class for a (possibly weighted) histogram.""" def __init__(self): ancestor.__init__(self) self.occurrences = {} self.total_occurrences = 0 def add_occurrence(self, category, number=1): if category in self.occurrences.keys(): self.occurrences[category] += number else: self.occurrences[category] = number self.total_occurrences += number def finalize(self): occurrences_as_list = [] for word in self.occurrences.keys(): occurrences_as_list.append((word_numberer.get_number(word), \ self.occurrences[word])) sort_by_item(occurrences_as_list, 0) self.finalized_data = tuple(occurrences_as_list) self.occurrences = None def get_occurrences(self, category): if self.occurrences == None: result = binary_search(self.finalized_data, category, (0,0))[1] return result else: if category in self.occurrences.keys(): return self.occurrences[category] else: return 0 def get_proportion(self, category): if self.total_occurrences > 0: return float(self.get_occurrences(category)) / \ float(self.total_occurrences) else: return 0 def get_score(self, other_histogram): if self.total_occurrences == 0 or \ other_histogram.total_occurrences == 0: return 0 else: numerator = 0 for pair in self.finalized_data: key = pair[0] numerator += self.get_occurrences(key) * \ other_histogram.get_occurrences(key) denominator = self.total_occurrences * \ other_histogram.total_occurrences return float(numerator) / float(denominator) def get_total_occurrences(self): return total_occurrences def get_words(self): return self.occurrences.keys() def remove_occurrence(self, category, number=1): if category in self.occurrences: difference = min(number, self.occurrences[category]) self.occurrences[category] -= number if self.occurrences[category] <= 0: del self.occurrences[category] self.total_occurrences -= min What it does is read in the document, get a histogram in words, then replace the histogram with a tuple of indices to words. A document might have 50,000 words, 4000 unique. What bugs me is that there's 150M of data, mostly in large text files of no particularly great variation, and when I read it in the histograms are 50M pickled, and 200-250M in live memory--so my optimized version takes more space than if I were keeping the entire document collection in memory. -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From dyoo at hkn.eecs.berkeley.edu Tue Sep 9 15:07:29 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 9 17:07:41 2003 Subject: [Tutor] Re: lists in re? In-Reply-To: <20030909133901.26f266e4.andi@buxach.de> Message-ID: On Tue, 9 Sep 2003, Andreas Zwinkau wrote: > > parser = [ re.compile(item) for item in ["[abc]","abc","[A-Z]"] ] > I'm not used to such "complex" constructs, but well, I can work with it. > > > Any chance of an example of what you're putting into it and what the > > code is supposed to make out of it? It would be most useful if you'd > > put in some *real* examples, because a key-value pair like "abc":"def" > > is a bit too abstract for me to understand its purpose. > Do you know what a Wiki is? I have some user text with abstract text > formations e.g. __underlined__ > These should be processed into HTML underlined > > There are some more rules. > ''italic'' -> italic > **bold** -> bold > [word] -> word > [image.gif] -> > [http://google.com|Google] -> http://slashdot.org > > > If this gets more and more, i thought a dictionary would be the best way > to define it in a obvious way. So this dict needs to be fed to the re > module, but instead of processing each item, i wanted to re.compile it > in one piece. Hi Andreas, Rather than hardcode the list of patterns in the program, it might be useful to define these different constructs in a separate text file instead. We can then write a function to take that text file and generate a class to process it. For example, let's say that we had a text file like: ###### ### wikirules.txt BOLD: \*\*(\w+)\*\* ITALIC: ''(\w+)'' ## The last two rules are 'catchalls' and should be at the bottom of this ## list WHITESPACE: (\s+) ANYTHING: (\S+) ###### We could then write a program that takes these rules, and creates a function that knows how to analyze text. Below is a toy example. I wrote it quickly, so it's definitely not production-quality code, nor is it commented well... *grin* ### def makeAnalyzer(pattern_text): """Creates a generate that can analyze text, and iteratively returns the tokens it can find.""" tagged_regexs = getTaggedRegexs(pattern_text) def analyzer(text): while 1: if not text: break for t, r in tagged_regexs: match = r.match(text) if match: yield (t, match) text = text[match.end():] break return analyzer def getTaggedRegexs(pattern_text): """Takes the pattern text and pulls out a list of tag-regexs pairs.""" tagged_regexs = [] for line in pattern_text.split('\n'): ## ignore comment lines if re.match(r'^\s*#', line): continue try: tag, pattern = re.match(r'''^(\w+):\s*(.*?)\s*$''', line).groups() except: ## Ignore lines that don't fit our pattern-regex format continue tagged_regexs.append((tag, re.compile(pattern))) return tagged_regexs ### Here's the program in action: ### >>> rules = """ ... ### wikirules.txt ... ... BOLD: \*\*(\w+)\*\* ... ITALIC: ''(\w+)'' ... ... ## The last two rules are 'catchalls' ... WHITESPACE: (\s+) ... ANYTHING: (\S+) ... """ >>> lexer = makeAnalyzer(rules) >>> for tag, match in lexer("**hello**, this is a ''test''!"): ... print tag, match.group(0) ... BOLD **hello** ANYTHING , WHITESPACE ANYTHING this WHITESPACE ANYTHING is WHITESPACE ANYTHING a WHITESPACE ITALIC ''test'' ANYTHING ! ### Since the rules are defined in a separate file, it becomes easy to switch in and out different sets of rules, just by copying over a new wiki-definition file. The code might end up being a bit long, though... *grin* Hope this helps! From alan.gauld at blueyonder.co.uk Tue Sep 9 23:22:11 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Sep 9 17:21:50 2003 Subject: [Tutor] multiple file output References: Message-ID: <019601c37718$6e9b2e50$6401a8c0@xp> > out = open('f[i].txt', 'w') > > something like this where f[i] should be coming from some list f String formatting operator to the rescue again for n in range(425): out = open('file%3d.txt' % i, 'w') # do something out.close() or you could just store the names in a list... fileList =['file000.txt', 'file001.txt', 'file002.txt', 'file003.txt', 'file004.txt'] for name in fileList: out = open(name,'w') # do it out.close() Alan G. From alan.gauld at blueyonder.co.uk Tue Sep 9 23:28:14 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Sep 9 17:27:53 2003 Subject: [Tutor] Productivity References: <200309091458.51684.ronan@melim.com.br> Message-ID: <019d01c37719$46d137b0$6401a8c0@xp> > I used to make my Python CGI's in the vi editor. > > Now, I'm looking for the ways to optimize the productivity > of the development tasks. What is slowing you down? Assuming you know vi there are few more productive editing tools so it presumably isn't the typing of the code. (BTW you do use something more modern than vanilla vi I assume? elvis or vim say?) If it is the editor you don't like you probably have access to emacs - which is equally powerful and some think more intuitive(!). Or for something more primitive but with lots of Python speific helps, there is IDLE which should come with Python... A vi(or emacs) expert will likely outperform an IDLE expert but an IDLE beginner will probably be faster than a vi (or emacs) beginner. > Could anyone say me what the better ways/tools to develop > python programs/cgis? So where is the inefficiency do you think? Testing? Looking up the code signatures? Copying the files to the server? Alan G. From tim at johnsons-web.com Tue Sep 9 14:31:14 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Sep 9 17:30:20 2003 Subject: [Tutor] Productivity In-Reply-To: <200309091458.51684.ronan@melim.com.br> References: <200309091458.51684.ronan@melim.com.br> Message-ID: <20030909213114.GK21536@johnsons-web.com> * Ronan Lucio [030909 10:04]: > Hi All, > > I used to make my Python CGI's in the vi editor. I use vim, and vim has a large array of resources for python. Check out http://www.vim.org/scripts/script_search_results.php and do a search on python. I am however, very impressed with PythonWin. Very nice IDE indeed! If you prefer to use linux, you can run windows on top of linux using Win4Lin and have access to the same filesystem for both OSes. Potentially, you could then write CGI scripts for Linux using PythonWin. I think that if Python were the only language that I wrote in, I would use PythonWin. > Now, I'm looking for the ways to optimize the productivity > of the development tasks. I haven't tried Boa Constructor myself, but it is at http://boa-constructor.sourceforge.net/ It got a very good review in a current Linux Mag. tim > Could anyone say me what the better ways/tools to develop > python programs/cgis? > > Thank's > Ronan > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From project5 at redrival.net Wed Sep 10 00:39:58 2003 From: project5 at redrival.net (Andrei) Date: Tue Sep 9 17:41:55 2003 Subject: [Tutor] Webbrowser (contined & new problem) In-Reply-To: References: Message-ID: Hello again, I've looked into it some more and found a sort of solution to my webbrowser problem, but stumbled upon a different issue. >> According to the code above, it should have been able to find KDE's >> Konqueror browser fine, as long as: >> >> 1. os.environ.get('DISPLAY') is some kind of true value, and This returns under Linux ":0.0" (KDE or Gnome, doesn't matter), so it's not the problem. >> 2. kfm or konqueror can be found by the system. Tracking it down, it appears that the "BROWSER" key of the os.environ dictionary is used. Under Gnome, this is defined as '/usr/bin/galeon'. Under KDE, it's 'kfmclient openProfile webbrowsing'. I have no idea what that's supposed to mean - whatever it does, it doesn't start the browser. However, if we change this to "konqueror" before importing the webbrowser module, it works: === import os if os.environ["BROWSER"] == 'kfmclient openProfile webbrowsing': os.environ["BROWSER"] = "konqueror" import webbrowser webbrowser.open("http://google.com") === So far so good. It seems kinda stupid, but it works. However, now I've noticed a different problem: when the browser is started, my (wxPy) application waits for it to close down when running in Linux. It will not react to anything and it will report messages provided from the browser in the console (e.g. making a new Tab in Galeon will produce some text which appears in the console where my app was started). Under Windows, the webbrowser behaves as it should: it starts and my app doesn't care about it any more. Any ideas why the behaviour is different under the two OSes? Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Wed Sep 10 00:51:59 2003 From: project5 at redrival.net (Andrei) Date: Tue Sep 9 17:53:56 2003 Subject: [Tutor] Re: lists in re? In-Reply-To: References: <20030906181754.68637d0b.andi@buxach.de> <20030907205351.04c9ea05.andi@buxach.de> <20030909133901.26f266e4.andi@buxach.de> Message-ID: Karl's solution is really nice, shorter and more elegant than the brute force approache that I have devised. On the other hand, this time mine doesn't use list comprehensions, nor lambdas. And it also handles [http:\\bla.com] as well as [http:\\bla.com|Bla] with a single regex, so I've decided to post it anyway :). This is a possible approach: 1. Make a dictionary mapping the uncompiled regexes to a format-string (strings containing "%") wherein matches are substituted 2. Build a dictionary of the compiled regexes, mapping them to the same format-strings 3. Loop through the keys of that dictionary and use the sub() method of the compiled method to substitute. This method can optionally take a function as parameter instead of a constant string, we'll use this option. 4. In the replace function, build a dictionary of the groups found by the regex (make sure you build your regex in a smart way!) 5. Feed that dictionary to the format string (you can look up the format string in the dictionary of compiled regexes, see step 2) 6. Return the result and continue. I've attached the code which does this at the bottom of this mail. It takes: """ Something can be __underlined__, ''italic'' or **bold**. You can also insert **[http://offsite.org|offsite links]** or [http://links.com] __without__ title. """ and turns it into: """ Something can be underlined, italic or bold. You can also insert offsite links or http://links.com without title. """ However, you should pay attention to a number of things: - a pass by a regex must not affect a previous pass by another regex. This is particularly a problem with the detection of loose URLs: do not change into -links URLs which are inside the href attribute for example (the URL parser should not find a hit in 'href="http://bla.com"'). A couple of weeks ago, I started a thread on exactly this same topic. I have solved it in a safe and complex way (detects all links you through at it), but an easier solution was also posted, which has a minor (not fatal) flaw. - you need a way to distinguish between images and links found between square parentheses. My code doesn't do images at all, it converts everything to links. I think you can build in the distinction into the regex, so that the [link] regex is not triggered by links ending on gif/png/jpg/jpeg. Obviously, the IMG regex [image.gif] shouldn't match any URL if it doesn't end in gif/png/jpg/jpeg. And now to the code. Note that only the "regs" dictionary needs to be modified in order to add more parsing abilities. Without the comments, the thing is about 14 lines. === # define the sample text text = """ Something can be __underlined__, ''italic'' or **bold**. You can also insert **[http://offsite.org|offsite links]** or [http://links.com] __without__ title. """ # define the regexes as plain-text, mapping them to a # format-string representation corresponding with # the number of the match group in the result regs = {"__(.*)__": "%(1)s", # underlined "''(.*)''": "%(1)s", # italic "\*\*(.*)\*\*": "%(1)s", # bold "\[(.+?)(?:\|+(.*?))*?\]": """%(2)s""" # link parser, matches [link|title] or [link] } # compile the regexes, converting regs to a dictionary of compiled # regexes import re compiled = {} for oneregex in regs.keys(): compiled[re.compile(oneregex)] = regs[oneregex] # write a function for formatting def replace(matchobj): gr = {} # contains the groups extracted by the regex, mapping a # str(groupnumber) to that group's contents (string) # make a dictionary of all available groups, used for formatting # with the formatstring # assuming there are never more than 4 groups; you can increase # this number if necessary, # it doesn't matter as far as the code is concerned for i in range(5): # means at max 4 groups not counting group 0 try: # in case there are fewer groups val = matchobj.string[matchobj.start(i):matchobj.end(i)] if val in ['', None]: raise ValueError # force exception; this occurs for # [link] without |title except: if gr.has_key(str(i-1)): # perhaps otherwise errors might occur val = gr[str(i-1)] # this comes in handy for links which # have no caption specified! else: val = "" # keep it empty gr[str(i)] = val # look up the format string for this item in the compiled dictionary formatstring = compiled[matchobj.re] # insert the extracted values into the format string return formatstring % gr for regex in compiled.keys(): text = regex.sub(replace, text) print text === How about that? :) Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Wed Sep 10 01:05:16 2003 From: project5 at redrival.net (Andrei) Date: Tue Sep 9 18:07:12 2003 Subject: [Tutor] Re: List of Methods in a class / library In-Reply-To: <20030909072049.17640.qmail@web41304.mail.yahoo.com> References: <20030909072049.17640.qmail@web41304.mail.yahoo.com> Message-ID: Anand Shankar wrote: > How can I get a listing of all methods in a class or > module, and better still the arguments required? > > No I do'nt mean the default: Look up documentation!! > > Anand Shankar If you have wxPython, you can also use PyCrust. Just import the module and you can use PyFilling to inspect it as a tree structure. I find it very useful. Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From erikprice at mac.com Tue Sep 9 20:11:04 2003 From: erikprice at mac.com (Erik Price) Date: Tue Sep 9 18:50:12 2003 Subject: [Tutor] Productivity In-Reply-To: <200309091458.51684.ronan@melim.com.br> Message-ID: On Tuesday, September 9, 2003, at 01:58 PM, Ronan Lucio wrote: > Could anyone say me what the better ways/tools to develop > python programs/cgis? I've heard SciTE is pretty cool for Python development, and saw it once, but I haven't used it. Erik From arkamir at softhome.net Wed Sep 10 00:48:02 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Tue Sep 9 19:48:05 2003 Subject: [Tutor] Creatively solving math problems -----help Message-ID: <1063151222.5460.28.camel@quercus.home.net> hey i was trying to solve a math problem creativily and i wrote this script. Can anyone tell me why it doesn't work and how to fix it. for x in range(20000): if x/2 == int(x/2) and x/3 == int(x/3) and x/4 == int(x/4) and \ x/5 == int(x/5) and x/6 == int(x/6) and x/7-1 == int(x/7-1): print x else: pass The question is what whole numbers can be divided by 2-6 and have a remainder of 1 but divided by 7 and have no remainder. I already have the answer; 301 and then you add 420 each time. The problem is the program gives me every number between 1 and 19999. Also i was wondering how many line breaks can you use? I believe it gives me 1-19999 because im using == but if i use only 1 = it gives me a syntax error. I believe this has something to do with the int(). Also int() returns it rounded down, is there any subsitute so it rounds to the nearest whole number. Another way i though i could solve this was by a script that looks like this: for x in range(2000): if x/2 = int(x/2): continue else: ?????????? the script would continue like this all the way to 7. The problem is i dont know a command that if if proves true skips that iteration and goes on to the next one.Any help?? thanks From project5 at redrival.net Wed Sep 10 03:25:39 2003 From: project5 at redrival.net (Andrei) Date: Tue Sep 9 20:27:38 2003 Subject: [Tutor] Re: Productivity In-Reply-To: <200309091458.51684.ronan@melim.com.br> References: <200309091458.51684.ronan@melim.com.br> Message-ID: Ronan Lucio wrote: > Hi All, > > I used to make my Python CGI's in the vi editor. > > Now, I'm looking for the ways to optimize the productivity > of the development tasks. > > Could anyone say me what the better ways/tools to develop > python programs/cgis? > > Thank's > Ronan Personally, I like SciTE and PythonWin. There is also a new editor called Spe. It's only at version 0.16 and still has some bugs and lacks some features, but it's looking extremely promising as far as I can tell (code completion, class browser, etc.) - I started using it yesterday. Eric looks nice too, but being mainly a Windows user, I really can't be bothered with all that QT stuff (I think I still haven't found the download location of the free version on the TrollTech page). -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From tgrimes at teleport.com Tue Sep 9 18:46:40 2003 From: tgrimes at teleport.com (TJ) Date: Tue Sep 9 20:47:19 2003 Subject: [Tutor] Creatively solving math problems -----help In-Reply-To: <1063151222.5460.28.camel@quercus.home.net> References: <1063151222.5460.28.camel@quercus.home.net> Message-ID: Try using the modulo operator %. It returns the remainder of a division. Examples: >>> 301 % 2 1 >>> 301 % 3 1 >>> 301 % 4 1 >>> 301 % 5 1 >>> 301 % 6 1 >>> 301 % 7 0 TJ >hey i was trying to solve a math problem creativily and i wrote this >script. Can anyone tell me why it doesn't work and how to fix it. > > >for x in range(20000): > if x/2 == int(x/2) and x/3 == int(x/3) and x/4 == int(x/4) and \ > x/5 == int(x/5) and x/6 == int(x/6) and x/7-1 == int(x/7-1): > > print x > > > else: > pass > > >The question is what whole numbers can be divided by 2-6 and have a >remainder of 1 but divided by 7 and have no remainder. I already have >the answer; >301 and then you add 420 each time. From project5 at redrival.net Wed Sep 10 03:53:06 2003 From: project5 at redrival.net (Andrei) Date: Tue Sep 9 20:55:34 2003 Subject: [Tutor] Re: Creatively solving math problems -----help In-Reply-To: <1063151222.5460.28.camel@quercus.home.net> References: <1063151222.5460.28.camel@quercus.home.net> Message-ID: Conrad Koziol wrote: Hi Conrad, > for x in range(20000): > if x/2 == int(x/2) and x/3 == int(x/3) and x/4 == int(x/4) and \ > x/5 == int(x/5) and x/6 == int(x/6) and x/7-1 == int(x/7-1): > > print x > else: > pass Your indentation is all screwed up. Either use Tabs, or Spaces. Spaces are the preferred solution, with 4 spaces per indentation level. If your current editor does not support this, try Idle, SciTE, PythonWin or any other editor with proper Python support. These editors will also automatically insert 4 spaces when you press the Tab key. Remember, in Python indentation defines the code structure. Depending on what else you're doing, x/2 might return an integer or a floating point (integer division: 5/2 = 2), so you shouldn't use it. If you expected to get a float (and you do get floats if you use "from __future__ import division"), you shouldn't compare a float to an integer, because floats aren't 100% accurate, they're approximations of numbers (very accurate, but not enough to be regarded equal to an integer). This is documented in the Python FAQ. > The question is what whole numbers can be divided by 2-6 and have a > remainder of 1 but divided by 7 and have no remainder. I already have You can test reminder with the % operator: >>> 5%2 1 >>> 4%2 0 Obviously, this is a much better solution than testing equality. > the answer; > 301 and then you add 420 each time. The problem is the program gives me > every number between 1 and 19999. Also i was wondering how many line Given the indentation errors, I have no idea what that snippet is actually doing. > breaks can you use? I believe it gives me 1-19999 because im using == You can break up lines as much as you like, as long as you use the backslash to indicate the code continues on the next line. In certain cases, the backslash is not required (e.g. inside triple-quoted strings or parentheses). > but if i use only 1 = it gives me a syntax error. I believe this has > something to do with the int(). Also int() returns it rounded down, is > there any subsitute so it rounds to the nearest whole number. Your approach for testing the remainder is incorrect, as I explained above. > Another way i though i could solve this was by a script that looks like > this: > > > for x in range(2000): > > if x/2 = int(x/2): > continue > else: > ?????????? > > the script would continue like this all the way to 7. The problem is i > dont know a command that if if proves true skips that iteration and goes > on to the next one.Any help?? What's wrong with continue? It breaks the current iteration and goes to the next one. This won't help you a lot because it's too difficult to understand, but it's fun to see anyway *wink*; a one-line solution: >>> [ x for x in range(20000) if [x%i for i in range(2,8)]==[1]*5+[0] ] [301, 721, 1141, 1561, 1981, 2401, 2821, 3241, 3661, 4081, 4501, 4921, 5341, 5761, 6181, 6601, 7021, 7441, 7861, 8281, 8701, 9121, 9541, 9961, 10381, 10801, 11221, 11641, 12061, 12481, 12901, 13321, 13741, 14161, 14581, 15001, 15421, 15841, 16261, 16681, 17101, 17521, 17941, 18361, 18781, 19201, 19621] -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From jeff at ccvcorp.com Tue Sep 9 18:58:30 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Sep 9 20:56:09 2003 Subject: [Tutor] Creatively solving math problems -----help References: <1063151222.5460.28.camel@quercus.home.net> Message-ID: <3F5E7736.7010306@ccvcorp.com> Conrad Koziol wrote: > hey i was trying to solve a math problem creativily and i wrote this > script. Can anyone tell me why it doesn't work and how to fix it. > > > for x in range(20000): > if x/2 == int(x/2) and x/3 == int(x/3) and x/4 == int(x/4) and \ > x/5 == int(x/5) and x/6 == int(x/6) and x/7-1 == int(x/7-1): > > print x > else: > pass > > > The question is what whole numbers can be divided by 2-6 and have a > remainder of 1 but divided by 7 and have no remainder. I already have > the answer; > 301 and then you add 420 each time. The problem is the program gives me > every number between 1 and 19999. The problem here is because you're using integer math. In integer math, any fractional parts are dropped, which means that (for example) 3/2 == 1 -- not quite the effect that you want. You can fix this by forcing floating point math. Just use x/2.0, x/3.0, etc. Alternatively, if you're using Python 2.2, you can add "from __future__ import division" (IIRC), and that will prevent the truncation of fractional values to integers. (In Python 2.3, this "true division" should be standard.) > Also i was wondering how many line > breaks can you use? I believe it gives me 1-19999 because im using == > but if i use only 1 = it gives me a syntax error. I believe this has > something to do with the int(). Also int() returns it rounded down, is > there any subsitute so it rounds to the nearest whole number. No, it has nothing to do with int(). Python uses two equal signs, 'x == y', to indicate equality ("test whether x equals y"). A single equal sign, 'x = y', indicates assignment ("set x to be equal to y"). > Another way i though i could solve this was by a script that looks like > this: > > for x in range(2000): > > if x/2 = int(x/2): > continue > else: > ?????????? > > the script would continue like this all the way to 7. The problem is i > dont know a command that if if proves true skips that iteration and goes > on to the next one.Any help?? The statement that does that is 'continue' -- you should be able to use exactly what you've got there (with the assignment corrected to an equality test, that is). Except that the 'else' is redundant -- if the if statement is true, you'll never reach that point. for x in range(2000): if x/2.0 == int(x/2.0): continue if x/3.0 == int(x/3.0): continue [...] Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Tue Sep 9 19:21:28 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 9 21:21:33 2003 Subject: [Tutor] Re: Creatively solving math problems -----help In-Reply-To: Message-ID: > This won't help you a lot because it's too difficult to understand, but > it's fun to see anyway *wink*; a one-line solution: > > >>> [ x for x in range(20000) if [x%i for i in range(2,8)]==[1]*5+[0] ] > [301, 721, 1141, 1561, 1981, 2401, 2821, 3241, 3661, 4081, 4501, 4921, 5341, > 5761, 6181, 6601, 7021, 7441, 7861, 8281, 8701, 9121, 9541, 9961, 10381, 10801, > 11221, 11641, 12061, 12481, 12901, 13321, 13741, 14161, 14581, 15001, 15421, > 15841, 16261, 16681, 17101, 17521, 17941, 18361, 18781, 19201, 19621] Hi Andrei, Here's one over-the-top way to solve the problem... using itertools! *grin* ### #!/usr/local/bin/python import itertools """Small program to demonstrate the use of itertools in solving numeric puzzles... *grin*""" def main(): twos = makeStream(lambda x: x*2 + 1) threes = makeStream(lambda x: x*3 + 1) fours = makeStream(lambda x: x*4 + 1) fives = makeStream(lambda x: x*5 + 1) sixes = makeStream(lambda x: x*6 + 1) sevens = makeStream(lambda x: x*7) numbers = reduce(intersect, [twos, threes, fours, fives, sixes, sevens]) for n in numbers: print n def intersect(i1, i2): """Intersects two integer iterators into a single iterator.""" i1, i2 = iter(i1), iter(i2) x, y = i1.next(), i2.next() while 1: if x < y: x = i1.next() elif x > y: y = i2.next() else: yield x x = i1.next() y = i2.next() def makeStream(f): """Produces a stream of numbers based on the given function.""" return itertools.imap(f, itertools.count()) if __name__ == '__main__': main() ### Sorry, I couldn't resist. *grin* From guillermo.fernandez at epfl.ch Wed Sep 10 13:53:28 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez) Date: Wed Sep 10 06:53:38 2003 Subject: [Tutor] Productivity Message-ID: <3F5F02A8.7070003@epfl.ch> Hi, I always hear that vim and emacs are wonderful editors, and that when we know it they enhance productivity without explaining why. I've used emacs for some time, and I've tried without much succes to start using vi. Could someone explain the features that make them enhance productivity in such manner? I know this is not a direct python question though... Thanks! Guille >>Now, I'm looking for the ways to optimize the productivity >> of the development tasks. >What is slowing you down? Assuming you know vi there are few >more productive editing tools so it presumably isn't the >typing of the code. (BTW you do use something more modern >than vanilla vi I assume? elvis or vim say?) >If it is the editor you don't like you probably have access >to emacs - which is equally powerful and some think more >intuitive(!). Or for something more primitive but with lots >of Python speific helps, there is IDLE which should come >with Python... From ronan at melim.com.br Wed Sep 10 10:28:52 2003 From: ronan at melim.com.br (Ronan Lucio) Date: Wed Sep 10 08:27:25 2003 Subject: [Tutor] Productivity In-Reply-To: <019d01c37719$46d137b0$6401a8c0@xp> References: <200309091458.51684.ronan@melim.com.br> <019d01c37719$46d137b0$6401a8c0@xp> Message-ID: <200309100928.52336.ronan@melim.com.br> Alan, Em Ter 09 Set 2003 18:28, Alan Gauld escreveu: > > I used to make my Python CGI's in the vi editor. > > > > Now, I'm looking for the ways to optimize the productivity > > of the development tasks. > > What is slowing you down? Assuming you know vi there are few > more productive editing tools so it presumably isn't the > typing of the code. (BTW you do use something more modern > than vanilla vi I assume? elvis or vim say?) Some months ago I have developed some programs in Java and I used Eclipse IDE. It has many features like: auto-complete loops structures, function declaration and do a sintaxe check on the language. This features give you many times of typing and program depuration I'd like to find similar tools for Python, too. Looking at the Python's home page I see some IDE's for Python and I'd like to know which are the most used. I seed that that is Eclipse plugin for Python, but I thing Eclipse consume CPU machine over than I can. > > Could anyone say me what the better ways/tools to develop > > python programs/cgis? > > So where is the inefficiency do you think? > Testing? Looking up the code signatures? Copying the files > to the server? Thank's Ronan From ronan at melim.com.br Wed Sep 10 10:37:11 2003 From: ronan at melim.com.br (Ronan Lucio) Date: Wed Sep 10 08:35:40 2003 Subject: [Tutor] Productivity In-Reply-To: <200309100928.52336.ronan@melim.com.br> References: <200309091458.51684.ronan@melim.com.br> <019d01c37719$46d137b0$6401a8c0@xp> <200309100928.52336.ronan@melim.com.br> Message-ID: <200309100937.11453.ronan@melim.com.br> Hi, I just like to thank everyone by the help. I'll test the IDE that you have indicated. Thank's Ronan From jim_938 at hotmail.com Wed Sep 10 20:06:21 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Wed Sep 10 09:36:33 2003 Subject: [Tutor] file opening modes Message-ID: Thanks for giving your suggestions regarding creating filenames dynamically. Actually i am caught in a problem with this. I am opening files in a loop and writing information in it and then sometimes the same file is opened and i append some information. The problem starts here. If i use open(filename,'w') or write mode for opening file then as according to the expected behaviour of write mode it erases the contents before writing in the file. So i decided to use open(filename, 'a') i.e. append mode so that i can append information to the file while i am running the program. Now suppose i have ./progname.py somefiletoextractinfo and three files are generated a.txt, b.txt, c.txt Now suppose if i run the program again then i get into problem because now again these three files will be appending the information in the existing files which i created last time i run the program. I know which filenames i will be creating dynamically so i dont want these files to be already present when i run the program again. I hope i am right with the append mode or should i choose some different mode. Thanks again for your suggestions. With best regards, J+ _________________________________________________________________ Hey there, NRIs! Send money home. http://server1.msn.co.in/msnleads/citibankrca/citibankrca2.asp?type=txt Use Citibank RCA From rcher at bezeqint.net Wed Sep 10 19:12:42 2003 From: rcher at bezeqint.net (roman) Date: Wed Sep 10 11:29:46 2003 Subject: [Tutor] Re: Productivity Message-ID: <3F5F4D7A.6090906@bezeqint.net> I think jEdit is an excellent editor. It is easier to learn and use than vim or emacs, and has plugins that can turn it into a full blown ide. It even supports writing macros and plugins in Python with the Jython plugin. From pythontutor at venix.com Wed Sep 10 13:30:02 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Sep 10 12:30:10 2003 Subject: [Tutor] file opening modes In-Reply-To: References: Message-ID: <3F5F518A.2070809@venix.com> Jimmy verma wrote: > > I know which filenames i will be creating dynamically so i dont want > these files to be already present when i run the program again. > > I hope i am right with the append mode or should i choose some different > mode. (I'm surprised I haven't seen replies to this yet.) One alternative would be to use mode w the first time and then mode a thereafter. I believe it is simpler to simply delete the files at the beginning. This can be done by: import os # assumes that your known filenames are in fnamelist for fname in fnamelist: os.remove(fname) If the file names in the fname list refer to file in some other directory, os.remove( os.path.join(r'c:\some_other_dir', fname)) (Code was simply typed in and not tested. it should be close to correct.) -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From tim at johnsons-web.com Wed Sep 10 09:37:06 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Wed Sep 10 12:36:04 2003 Subject: [Tutor] Productivity In-Reply-To: <3F5F02A8.7070003@epfl.ch> References: <3F5F02A8.7070003@epfl.ch> Message-ID: <20030910163706.GO21536@johnsons-web.com> * Guillermo Fernandez [030910 03:01]: > Hi, > > I always hear that vim and emacs are wonderful editors, and that when we > know it they enhance productivity without explaining why. I've used > emacs for some time, and I've tried without much succes to start using vi. It is probably safe to say that both vim and emacs are difficult to learn. It is arguable that the effort can be rewarding. ****************************************************************** What they share is the potential to be primarily keyboard-driven. ****************************************************************** emacs/xemacs: Is almost infinitely extendable because it is 'driven' - that is - modifiable by the elisp language which runs internally. The same could be said of vim. Vim has it's own scripting language which is an extension of the different keystroke modes, and is much more 'terse' than emacs. Also, vim allows you to compile the python, perl, or ruby interpreters into the editor, thus allowing for internal scripting in any of those languages. What makes vim both so productive and so maddening (to some) is the modal approach to editing. Example: (just a simple one) In "normal mode" if I press the 'l' key, I move the cursor right. I press the 'h' key, I move the cursor left. Here's a simple customization: If I press the sequence '\be', I get list of buffers loaded into my editing session. Press , and I get a list of 'hyperlinked' function names that I can jump to. For me, this is much quicker than a 'point and click' method. If I press 'i' in "normal" mode, I am then in 'insert mode' and can type text. There are many potential keystroke mappings that are available and can be added in this mode also. Vim is an acquired taste. I hated it when I first tried it and gave up in disgust, but tried again later. Now it is second nature to me. I wouldn't wish it on somebody who is 'forced' to use it. There are many vim users who are also experienced python programmers and have made numerous 'plugins' for python in vim. Several years ago, a local utility that had a couple of dozen autocad technician sent them all to a special training session that taught them how to use autocad entirely without a mouse. When that session was finished and they were allowed to return to their work stations (still mouse-enabled) they all said they were more productive. Oh, and vim is also mouse-enabled. tim > Could someone explain the features that make them enhance productivity > in such manner? > > I know this is not a direct python question though... > > Thanks! > > Guille > > >>Now, I'm looking for the ways to optimize the productivity > >> of the development tasks. > > >What is slowing you down? Assuming you know vi there are few > >more productive editing tools so it presumably isn't the > >typing of the code. (BTW you do use something more modern > >than vanilla vi I assume? elvis or vim say?) > > >If it is the editor you don't like you probably have access > >to emacs - which is equally powerful and some think more > >intuitive(!). Or for something more primitive but with lots > >of Python speific helps, there is IDLE which should come > >with Python... > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From david at graniteweb.com Wed Sep 10 12:51:00 2003 From: david at graniteweb.com (David Rock) Date: Wed Sep 10 12:51:07 2003 Subject: [Tutor] file opening modes In-Reply-To: <3F5F518A.2070809@venix.com> References: <3F5F518A.2070809@venix.com> Message-ID: <20030910165100.GA24714@wdfs.graniteweb.com> * Lloyd Kvam [2003-09-10 12:30]: > Jimmy verma wrote: > > > >I know which filenames i will be creating dynamically so i dont want > >these files to be already present when i run the program again. > > > >I hope i am right with the append mode or should i choose some different > >mode. > (I'm surprised I haven't seen replies to this yet.) > One alternative would be to use mode w the first time and then mode a > thereafter. > I believe it is simpler to simply delete the files at the beginning. This You need to determine if the file has already been opend by a different process though (which one opens it "first")? Another possibility would be to use os.tmpfile() or os.tempnam() to create a random name temp file to write data to. This way you could create as many as you wanted. The only disadvantage to os.tmpfile is the file will be removed automatically when it is no longer needed. os.tempnam just gives you a random name that you ca then use. Another possibility is to generate names dynamically based on date. -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20030910/fd4d1347/attachment.bin From tpc at csua.berkeley.edu Wed Sep 10 11:30:12 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Sep 10 13:30:23 2003 Subject: [Tutor] Java style assignments in Python Message-ID: <20030910102511.I60442-100000@localhost.name> hello all, I was curious if there is a way to implement Java style assignments in Python. Let's say I have a block of code: list_A = [] list_B = [] list_C = [] and I want to condense it to: list_A, list_B, list_C = [] Is there any way to do this without generating an error: ValueError: unpack list of wrong size ? Thanks in advance From zak at harlekin-maus.com Wed Sep 10 11:40:39 2003 From: zak at harlekin-maus.com (Zak Arntson) Date: Wed Sep 10 13:40:47 2003 Subject: [Tutor] Java style assignments in Python In-Reply-To: <20030910102511.I60442-100000@localhost.name> References: <20030910102511.I60442-100000@localhost.name> Message-ID: <1857.192.206.201.218.1063215639.squirrel@mail.harlekin-maus.com> > hello all, I was curious if there is a way to implement Java style > assignments in Python. Let's say I have a block of code: > > list_A = [] > list_B = [] > list_C = [] > > and I want to condense it to: > > list_A, list_B, list_C = [] First up, don't do this: >>> list_A, list_B, list_C = [[]] * 3 Because you'll get three variables referencing the same list. It's not pretty, but you can do this: >>> list_A, list_B, list_C = [[] for i in range(3)] This creates a unique empty list for each variable. Of course, you'll have to change the range parameter depending on how many variables you're assigning. My question for you is: Why do you want to do this? What kind of problem are you programming for? --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From tpc at csua.berkeley.edu Wed Sep 10 11:46:51 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Sep 10 13:46:57 2003 Subject: [Tutor] Java style assignments in Python In-Reply-To: <1857.192.206.201.218.1063215639.squirrel@mail.harlekin-maus.com> Message-ID: <20030910104321.B60558-100000@localhost.name> hi Zak, well I was more familiar with Java's strong typing that I assumed Python allowed assignment of a type to three variables. On Wed, 10 Sep 2003, Zak Arntson wrote: > My question for you is: Why do you want to do this? What kind of problem > are you programming for? > > --- > Zak Arntson > www.harlekin-maus.com - Games - Lots of 'em > From jeff at ccvcorp.com Wed Sep 10 11:50:05 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Sep 10 13:47:56 2003 Subject: [Tutor] Java style assignments in Python References: <20030910102511.I60442-100000@localhost.name> Message-ID: <3F5F644D.1090209@ccvcorp.com> tpc@csua.berkeley.edu wrote: > hello all, I was curious if there is a way to implement Java style > assignments in Python. Let's say I have a block of code: > > list_A = [] > list_B = [] > list_C = [] > > and I want to condense it to: > > list_A, list_B, list_C = [] > > Is there any way to do this without generating an error: > > ValueError: unpack list of wrong size > > ? Thanks in advance No, because the "condensed" version means something different in Python. >>> foo = [1, 2, 3] >>> a, b, c = foo >>> a 1 >>> b 2 >>> c 3 >>> The line in question actually constructs a temporary tuple with the (previously unassigned) names, and then assigns foo to that tuple. This is called tuple (or list) unpacking, which should explain the wording of the error message you're getting. You can do something that's somewhat similar, however -- >>> a = b = c = 1 >>> a 1 >>> b 1 >>> c 1 >>> Chaining assignments like this will achieve almost the effect you want... but you'll find an interesting twist when using it with lists (or other mutable objects). >>> a = b = c = [] >>> b [] >>> a.append(1) >>> b [1] >>> c [1] >>> The problem here is that a, b, and c all point to the *same* list object. Since there's only one underlying object, changes to one will seem to affect all three. You need to explicitly create a separate empty list for each one in order to have properly independent behavior. (You may want to search the archives of this list or comp.lang.python for "name rebinding" for detailed explanations of how all of this works.) However, combining all of this, we can still do it in a single line -- >>> a, b, c = [], [], [] >>> b.append(23) >>> a [] >>> b [23] >>> c [] >>> Hope this helps... Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Wed Sep 10 12:03:14 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Sep 10 14:01:00 2003 Subject: [Tutor] Java style assignments in Python References: <20030910104321.B60558-100000@localhost.name> Message-ID: <3F5F6762.9030801@ccvcorp.com> tpc@csua.berkeley.edu wrote: > hi Zak, well I was more familiar with Java's strong typing that I assumed > Python allowed assignment of a type to three variables. Python has fairly strong typing too, but the type belongs to the object, *not* to the variable name that is bound to it. It may be somewhat helpful to think of all Python variables as being references... but even that's not completely correct. In Python, everything is an object, and that object is independent of any names that are bound to it, and any object can have any number of names. The assignment operator, =, binds (or re-binds) a name (on the left-hand side) to an object (on the right-hand side). In languages like C and Java, you can think of variables as a box that you put stuff in. Type-checking ensures that the stuff is the same shape as the box. In Python, variables are more like sticky-notes that you can stick to an object. It's easy to move a sticky note from one object to another, even if that other object is of a different shape (type). If you try to perform an operation with two objects, they will let you know if they don't fit together. (Perl, on the other hand, will take a hammer and *make* them fit together! ;) ) Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Wed Sep 10 12:13:48 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Sep 10 14:11:48 2003 Subject: [Tutor] file opening modes References: Message-ID: <3F5F69DC.6010507@ccvcorp.com> Jimmy verma wrote: > If i use open(filename,'w') > or write mode for opening file then as according to the expected > behaviour of write mode it erases the contents before writing in the file. > So i decided to use open(filename, 'a') > i.e. append mode so that i can append information to the file while i am > running the program. > > [...] > > Now suppose if i run the program again then i get into problem because > now again these three files will be appending the information in the > existing files which i created last time i run the program. I think that the easiest way to do this is to continue to use append mode, but to try to delete the files when the program starts up. Of course, you'll have to deal with the case of when the files *don't* exist -- trying to os.remove() a nonexistent file gives an error. There's two ways to do this. One is to check whether the file exists, and if it does, remove it -- if os.path.exists(fname): os.remove(fname) The other is to try to remove it, but catch (and ignore) any errors -- try: os.remove(fname) except OSError: pass Which method you choose is largely a matter of taste. Some feel "safer" if they check first ("look before you leap"); but the second method is slightly more efficient (as it only needs to hit the hard drive once, rather than twice) and fits the Zen of Python ("it's easier to ask forgiveness than permission"). Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Wed Sep 10 12:58:51 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 10 14:58:57 2003 Subject: [Tutor] Java style assignments in Python In-Reply-To: <3F5F6762.9030801@ccvcorp.com> Message-ID: Hi Tpc, > tpc@csua.berkeley.edu wrote: > > > hi Zak, well I was more familiar with Java's strong typing that I > > assumed Python allowed assignment of a type to three variables. (Small rant: I feel that Java's type system is a lot more trouble than it's worth. OCaml, now that's a language that has strong typing. Mark Jason Dominus has written a nice article that talks about type systems here: http://perl.plover.com/yak/typing/typing.html.) > Python has fairly strong typing too, but the type belongs to the object, > *not* to the variable name that is bound to it. yes. Whenever we're saying the expression: [] we're actually constructing an empty list --- in Java, we might say: new ArrayList() for a similar effect. If we try something like this: a = b = c = [] Then the analogous Java code looks like this: Object a, b, c; a = b = c = new ArrayList(); The important part to see in this Java pseudocode is that each variable name is of type Object --- and this is pretty much the situation in Python! Every name in Python is of a base type "PyObject", and the values themselves contain runtime type information. In fact, every method call we make on a value is looked up at runtime; we can see this by co-opting the __getattr__() method: ### >>> class WrapObject: ... def __init__(self, obj): ... self.obj = obj ... def __getattr__(self, attr): ... print "Intercepted call for attribute", attr ... return getattr(self.obj, attr) ... >>> s = WrapObject([]) >>> s.append Intercepted call for attribute append >>> s.extend([4, 5, 6]) Intercepted call for attribute extend >>> s Intercepted call for attribute __repr__ [4, 5, 6] >>> print s Intercepted call for attribute __str__ [4, 5, 6] >>> >>> >>> a, b = WrapObject(5), WrapObject(6) >>> a + b Intercepted call for attribute __coerce__ Intercepted call for attribute __add__ Intercepted call for attribute __coerce__ Intercepted call for attribute __radd__ Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand types for +: 'instance' and 'instance' ### (Hmmm! I wonder why there's a leading space when I did 'print s'. I'll have to look into that sometime... *grin*) Hope this helps! From rahulsen at gmx.net Thu Sep 11 01:47:24 2003 From: rahulsen at gmx.net (Rahul Sen) Date: Wed Sep 10 15:18:10 2003 Subject: [Tutor] Forum??? Message-ID: <002d01c377d0$3ef1c200$0cf50a0a@sen> Hi everyone, I'd like 2 start out by thanking all the regular contributors, although I don't post I read all the threads and it has helped me a great deal. I'd also like to ask whether anyone knows of a good python forum on the internet. Rahul Sen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030911/b185e85f/attachment.htm From zak at harlekin-maus.com Wed Sep 10 13:56:21 2003 From: zak at harlekin-maus.com (Zak Arntson) Date: Wed Sep 10 15:56:29 2003 Subject: [Tutor] Fastest (x,y) distance calculation Message-ID: <2109.192.206.201.218.1063223781.squirrel@mail.harlekin-maus.com> I'm using pygame, but the algorithm is basic enough to be cross-posted. I have two classes, a Temple and a Mover class. Each have the a rect attribute (which for non-pygamers, is an object represented by an (x,y,width,height) tuple). Each Mover analyzes the list of Temples to find the nearest one. My Game class has the following method, called by each Mover during its thinking phase. (non-pygamers: centerx and centery are the x & y values at the center of the rect) ### class Game: ... def get_nearest_temple(self, pos): distances = [((pos[0] - tmp.rect.centerx) ** 2 + (pos[1] - tmp.rect.centery) ** 2, tmp) for tmp in self.temples] return min(distances)[1] ... ### It's basically taking advantage of the fact that: distance = sqrt((x2 - x1)^2 + (y2 - y1)^2) And for integer x & y values, I can square the right side of the equation for purposes of distance comoparison. I can't think of a better algorithm for getting the nearest object than this. Profile tells me this is one of the slower parts of my code. Any thoughts/suggestions? --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From project5 at redrival.net Wed Sep 10 23:27:26 2003 From: project5 at redrival.net (Andrei) Date: Wed Sep 10 16:29:23 2003 Subject: [Tutor] Re: Forum??? In-Reply-To: <002d01c377d0$3ef1c200$0cf50a0a@sen> References: <002d01c377d0$3ef1c200$0cf50a0a@sen> Message-ID: Rahul Sen wrote: > Hi everyone, Hi, > I'd like 2 start out by thanking all the regular contributors, > although I don't post I read all the threads and it has helped me a > great deal. I'd also like to ask whether anyone knows of a good python > forum on the internet. http://dbforums.com/f97 tricks you into thinking the Python mailing list (and hence the c.l.python newsgroup) is a forum. Close enough, I'd say. I don't know of any other ones. > Rahul Sen -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From alan.gauld at blueyonder.co.uk Wed Sep 10 23:32:55 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 10 17:32:58 2003 Subject: [Tutor] Creatively solving math problems -----help References: <1063151222.5460.28.camel@quercus.home.net> Message-ID: <021501c377e3$18f2e940$6401a8c0@xp> > >for x in range(20000): > > if x/2 == int(x/2) and x/3 == int(x/3) and x/4 == int(x/4) and \ > > x/5 == int(x/5) and x/6 == int(x/6) and x/7-1 == int(x/7-1): Somebody already mentioned the modulo operator howebver as a general rule its worth using parens to group your test: if (x/2 == int(x/2)) and (x/3 == int(x/3)) and (x/4 == int(x/4)) and (x/5 == int(x/5)) and (x/6 == int(x/6)) and (x/7-1 == int(x/7-1)): Otherwise there is a danger of the test being interpreted as: if x/2 == (int(x/2) and x/3) ...etc... ie comparing a number to a boolean. This will always be true unless x/2 is zero! The way Python interprets the tests is down to something called operator precedence which is way to complicated to even try to remember(for me anyway!) so just put parens in, space it liberally, and avoid any ambiguity. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Wed Sep 10 23:52:45 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 10 17:52:50 2003 Subject: [Tutor] Productivity References: <3F5F02A8.7070003@epfl.ch> Message-ID: <022001c377e5$de7595d0$6401a8c0@xp> > I always hear that vim and emacs are wonderful editors, and that when we > know it they enhance productivity without explaining why. I've used > emacs for some time, and I've tried without much succes to start using vi. > > Could someone explain the features that make them enhance productivity > in such manner? Its not so much the features, although there are many indeed, but the way those features are accessed. The number of keystrokes to achieve something is very few. Another really powerful feature is the ability to repeat any command seveal times. Thus if you want to substitute(aka replace) a piece of text the next 5 times you just tell the substitute command to repeat 5 times. Or if you only want to peform the substitution within a particular region you select it then execute the replace. It will only replace within the region. The ability to repeat a search using a single key (OK F3 often works in Windows editors too) but a letter on the keyboard is easier to type. The abiliity to use a search string to operate on a bit of text: For example say I want to delete from the current position to the fist occurence of the word perambulate, in vi I type: :.,/perambulate/d And when you add the power if regular expressions to those search strings it gets really powerful. Macros are great too. The joy of vi is the speed of navigation compared to other editors, it started life as a line editor where navigation speed and precision was paramount and that ability to quickly find exactly the text you want is still there. The ability to choose the scope of my editting operations - do I want to operate on a whole line, a word or a character? Or maybe a paragraph? Or a number of lines? All of these are simply a character pre or postfix to my command: cw - change word cc - change line 5cw - change 5 words 5cc - change 5 lines dw - delete word dd = delete line 5dw - delete 5 words 5dd - delete 5 lines yw - copy a word yy - copy a line 5yw - copy 5 words 5yy - copy 5 lines notice the consistency? Also the t and f commands in vi are invaluable dtg - delete up to but not including the next letter g dfg - delete up to and including the letter g I could go on, and many of these may not sound like huge gains but once you get used to them all the hints and suggestions offered by IDLE(*) etc are no compensation when it comes to just cranking out code. (*)I rarely need the hints in IDLE when doing Python because I've been trying the code out at the prompt anyway. In Delphi I love the hints feature... Alan G. PS The above is vi focussed but emacs offers similar types of power editing tools and a bunch more besides (smart grep is one I love) From alan.gauld at blueyonder.co.uk Wed Sep 10 23:55:43 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 10 17:55:49 2003 Subject: [Tutor] Productivity References: <200309091458.51684.ronan@melim.com.br><019d01c37719$46d137b0$6401a8c0@xp> <200309100928.52336.ronan@melim.com.br> Message-ID: <022901c377e6$4870a0b0$6401a8c0@xp> > Some months ago I have developed some programs in Java > and I used Eclipse IDE. > > It has many features like: auto-complete loops structures, function > declaration and do a sintaxe check on the language. OK, if those are the features you use (and for beginners still learning the language they can help I guess) I'd go with Pythons native IDE, IDLE. Provided your installation has Tkinter instaloled(default for Windows) then IDLE will do all of the things you mentioned. If you are on Windows and got the ActiveState version of Python or installed winall you also can use Pytonwin. There is not a lot to choosebetween the two IMHO. Alan G. From python at rcn.com Wed Sep 10 18:52:22 2003 From: python at rcn.com (Raymond Hettinger) Date: Wed Sep 10 17:57:07 2003 Subject: [Tutor] Fastest (x,y) distance calculation References: <2109.192.206.201.218.1063223781.squirrel@mail.harlekin-maus.com> Message-ID: <002501c377e5$d0881060$a1bc958d@oemcomputer> > My Game class has the following method, called by each Mover during its > thinking phase. (non-pygamers: centerx and centery are the x & y values at > the center of the rect) > > ### > class Game: > ... > def get_nearest_temple(self, pos): > distances = [((pos[0] - tmp.rect.centerx) ** 2 + > (pos[1] - tmp.rect.centery) ** 2, > tmp) for tmp in self.temples] > > return min(distances)[1] > ... > > ### > > It's basically taking advantage of the fact that: > distance = sqrt((x2 - x1)^2 + (y2 - y1)^2) > And for integer x & y values, I can square the right side of the equation > for purposes of distance comoparison. > > I can't think of a better algorithm for getting the nearest object than > this. Profile tells me this is one of the slower parts of my code. Any > thoughts/suggestions? Distance calculations are much cheaper if you store the coordinates as complex numbers and use abs(). Also consider grouping the temples into neighborhoods so that the search can be limited to the local and adjacent neighborhoods. To find your closest grocery store, one doesn't have to search the world. Raymond Hettinger ################################################################# ################################################################# ################################################################# ##### ##### ##### ################################################################# ################################################################# ################################################################# From alan.gauld at blueyonder.co.uk Thu Sep 11 00:22:12 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 10 18:22:13 2003 Subject: [Tutor] file opening modes References: Message-ID: <025401c377e9$fb39f270$6401a8c0@xp> > i.e. append mode so that i can append information to the file while i am > running the program. Yes thats the right approach. > and three files are generated > > a.txt, b.txt, c.txt > > > Now suppose if i run the program again then i get into problem because now > again these three files will be appending the information in the existing > files which i created last time i run the program. OK so you need to add a tst for file existence before opening it. Then if it already exists (and the datestamp is within T seconds of the current time) then use append othewise use 'w' which will overwrite the old version. Alternatively do some housekeeping first and copy the old file to a .bak before creating the new one. Put the test in a function: def alreadyExists(fname): # test here then your code looks like: if alreadyExists(fname): mode = 'a' else: mode = 'w' f = open(fname,mode) HTH, Alan g From arkamir at softhome.net Thu Sep 11 01:25:51 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Wed Sep 10 20:25:53 2003 Subject: [Tutor] Creatively solving math problems -----help Message-ID: <1063237360.5773.14.camel@quercus.home.net> hey thanks for all you help, the indenting problem is with evolution. I especially liked the one liner. though I still need help with this program i wrote to take in all you suggestions. for x in range(20000): if [x%y for y in range(2, 7)] == 1 and x % 7 == 0: print x This program works though it doesnt do anything. I believe its how i inserted this statement [x%y for y in range(2, 7)] thanks From magnus at thinkware.se Thu Sep 11 09:54:34 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Sep 11 02:54:41 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRmFzdGVzdCAoeCx5KSBkaXN0YW5jZSBjYWxjdWxhdGlvbg==?= Message-ID: Raymond Hettinger: > Distance calculations are much cheaper if you store the coordinates > as complex numbers and use abs(). I tried that, and the distance calculation (pos-tmp.rect) got much quicker, but abs() ate up all the improvement. :( -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Thu Sep 11 09:56:10 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Sep 11 02:56:15 2003 Subject: =?ISO-8859-1?B?Rnc6IFJlOiBbVHV0b3JdIEZhc3Rlc3QgKHgseSkgZGlzdGFuY2UgY2FsY3VsYXRpb24=?= Message-ID: Oops, I meant to send this to the entire list... -----Ursprungligt meddelande----- Fr?n: Magnus Lycka Skickat: 2003-09-10 22:35:27 Till: Zak Arntson ?mne: Re: [Tutor] Fastest (x,y) distance calculation > def get_nearest_temple(self, pos): > distances = [((pos[0] - tmp.rect.centerx) ** 2 + > (pos[1] - tmp.rect.centery) ** 2, > tmp) for tmp in self.temples] If self.temples is big, you build a big list here. Maybe an explicit loop is better? > I can't think of a better algorithm for getting the nearest object than > this. Profile tells me this is one of the slower parts of my code. Any > thoughts/suggestions? Changing "(a - b) ** 2" to "(a - b) * (a - b)" will probably save you 30-40%. Multiplication is faster than exponentiation. Another idea is to consider pyrex or psyco. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se -------------- next part -------------- An embedded message was scrubbed... From: Magnus Lycka Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRmFzdGVzdCAoeCx5KSBkaXN0YW5jZSBjYWxjdWxhdGlvbg==?= Date: Wed, 10 Sep 2003 22:35:27 +0200 Size: 1317 Url: http://mail.python.org/pipermail/tutor/attachments/20030911/dc0549ef/attachment-0001.eml From Anish.Mehta at enst-bretagne.fr Thu Sep 11 12:25:58 2003 From: Anish.Mehta at enst-bretagne.fr (Mehta, Anish) Date: Thu Sep 11 05:07:12 2003 Subject: [Tutor] file opening modes References: <025401c377e9$fb39f270$6401a8c0@xp> Message-ID: <3F603FA6.7010305@antares.enst-bretagne.fr> I have a suggestion also though i am not an expert in python. I have tried to solve the problem like this: as i have taken a dictionary and i am inserting the filenames which i am creating dynamically. And if you open the file for the first time use the 'w' mode otherwise insert the filename into the dictionary and use the 'a' mode. This way you will automatically delete the file when you create it for the first time because we are using write mode for the first time. class XYZ: def __init__(self): self.fileList = {} self.key = 0 def writefile(self,data): filename = '%s-%s.txt' % (fontname,tag) #Check whether this file has already been opened or not. if filename in self.fileList.values(): mode = 'a' else: self.fileList[self.key] = filename mode = 'w' self.key = self.key+1 outfile = file(filename, mode) outfile.write(data) outfile.close() I hope i am right!!! Suggestions from tutor will make it more suitable for you to use. Thanks a lot. Regards, Anish Alan Gauld wrote: >>i.e. append mode so that i can append information to the file while >> >> >i am > > >>running the program. >> >> > >Yes thats the right approach. > > > >>and three files are generated >> >>a.txt, b.txt, c.txt >> >> >>Now suppose if i run the program again then i get into problem >> >> >because now > > >>again these three files will be appending the information in the >> >> >existing > > >>files which i created last time i run the program. >> >> > >OK so you need to add a tst for file existence before opening it. >Then if it already exists (and the datestamp is within T seconds >of the current time) then use append othewise use 'w' which will >overwrite the old version. > >Alternatively do some housekeeping first and copy the old file to >a .bak before creating the new one. > >Put the test in a function: > >def alreadyExists(fname): > # test here > >then your code looks like: > >if alreadyExists(fname): mode = 'a' >else: mode = 'w' >f = open(fname,mode) > >HTH, > >Alan g > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030911/fe7a4938/attachment.htm From clay at shirky.com Thu Sep 11 10:52:42 2003 From: clay at shirky.com (Clay Shirky) Date: Thu Sep 11 09:52:51 2003 Subject: [Tutor] Creatively solving math problems -----help In-Reply-To: <1063237360.5773.14.camel@quercus.home.net> Message-ID: > for x in range(20000): > if [x%y for y in range(2, 7)] == 1 and x % 7 == 0: > print x This is awfully hard to read -- any reason you're trying to cram so much stuff on one line? Is this what you are trying to do? for x in range(20000): for y in range(2, 7): if x % y == 1 and x % 7 == 0: print x break If so, it will be easy to start altering from there. -clay From alex at gabuzomeu.net Thu Sep 11 18:41:17 2003 From: alex at gabuzomeu.net (Alexandre Ratti) Date: Thu Sep 11 11:41:55 2003 Subject: [Tutor] Java style assignments in Python In-Reply-To: <20030910102511.I60442-100000@localhost.name> References: <20030910102511.I60442-100000@localhost.name> Message-ID: <3F60979D.9070708@gabuzomeu.net> Hello, tpc@csua.berkeley.edu wrote: > hello all, I was curious if there is a way to implement Java style > assignments in Python. Let's say I have a block of code: > list_A, list_B, list_C = [] > > Is there any way to do this without generating an error: As explained by other posters, you need to type: list_A, list_B, list_C = [], [], [] You could also build you own constructor: ## >>> def lists(n): ... l = [[] for x in range(n)] ... return tuple(l) >>> list_A, list_B, list_C = lists(3) >>> list_A.append('titi') >>> list_A ['titi'] >>> list_B [] ## Cheers. Alexandre From jeff at ccvcorp.com Thu Sep 11 11:50:23 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 11 13:48:11 2003 Subject: [Tutor] Creatively solving math problems -----help References: Message-ID: <3F60B5DF.7080105@ccvcorp.com> Clay Shirky wrote: >>for x in range(20000): >> if [x%y for y in range(2, 7)] == 1 and x % 7 == 0: >> print x > > > This is awfully hard to read -- any reason you're trying to cram so much > stuff on one line? Is this what you are trying to do? > > for x in range(20000): > for y in range(2, 7): > if x % y == 1 and x % 7 == 0: > print x > break > > If so, it will be easy to start altering from there. Another thing to consider here -- you've got two loops ('for x...' and 'for y...'), and a compound 'if' statement. Note that one half of the 'if' statement (and thus the entire test) will be true for only one value in seven of the outer loop, and that the value of the inner loop makes *no* difference to this. This means that, by splitting into two if statements, we can run the inner loop one-seventh as many times. for x in range(20000): if x % 7 == 0: for y in range(2, 7): if x % y == 1: print x break This will avoid setup and execution of the inner loop for the six out of seven times that x % 7 is *not* equal to zero. This may be a fairly minor point when you're saving ~17,000 runs of the inner loop, but if your search range grows, it could be *quite* helpful. This is a slight variant on the standard optimization method of lifting loop-invariants out of the loop -- in this case, the invariant means that the if statement will never be true. By lifting that part of the if statement outside of the inner loop, we can optimize away the entire inner loop for certain values of x. And while some might warn about the dangers of premature optimization (for it *is* dangerous), in this case I think it also results in a clearer, more easily read structure (the opposite of many optimization methods). Jeff Shannon Technician/Programmer Credit International From enrica_dente at hotmail.com Thu Sep 4 13:50:04 2003 From: enrica_dente at hotmail.com (enrica dente) Date: Thu Sep 11 14:50:38 2003 Subject: [Tutor] Search and Replace in Zope Message-ID: Dear All, I emailed you sometime ago. I need your help again. This time I really need it. I haven't been able to find a solution that allows me to search for all the I have to read and process a large ASCII file containing a mesh : a list of points and triangles. The file is 100 MBytes. I first tried to do it in memory but I think I am running out of memory therefore I decide to use the shelve module to store my points and elements on disks. Despite the fact it is slow ... Any hint ? I think I have the same memory problem but I don't understand why since my aPoint should be removed by the gc. Have you any idea ? Thanks Guillaume PS : here is the code for your info import string import os import sys import time import resource import shelve import psyco psyco.full() class point: def __init__(self,x,y,z): self.x = x self.y = y self.z = z def SFMImport(filename): print 'UNV Import ("%s")' % filename db = shelve.open('points.db') file = open(filename, "r") linenumber = 1 nbpoints = 0 nbfaces = 0 pointList = [] faceList = [] line = file.readline() words = string.split(line) nbpoints = string.atoi(words[1]) nbtrias = string.atoi(words[0]) print "found %s points and %s triangles" % (nbpoints, nbtrias) t1 = time.time() for i in range(nbpoints): line = file.readline() words = string.split(line) x = string.atof(words[1].replace("D","E")) y = string.atof(words[2].replace("D","E")) z = string.atof(words[3].replace("D","E")) aPoint = point(x, y, z) as = "point%s" % i if (i%250000 == 0): print "%7d points <%s>" % (i, time.time() - t1) t1 = time.time() db[as] = aPoint print "%s points read in %s seconds" % (nbpoints, time.time() - t1) bd.close() t1 = time.time() t2 = time.time() for i in range(nbtrias): line = file.readline() words = string.split(line) i1 = string.atoi(words[0]) i2 = string.atoi(words[1]) i3 = string.atoi(words[2]) faceList.append((i1,i2,i3)) if (i%100000 == 0): print "%s faces <%s>" % (i, time.time() - t1) t1 = time.time() print "%s points read in %s seconds" % (nbpoints, time.time() - t2) file.close() def callback(fs): filename = fs.filename UNVImport(filename) if __name__ == "__main__": # try: # import GUI # except: # print "This script is only working with the new GUI module ..." # else: # fs = GUI.FileSelector() # fs.activate(callback, fs) print sys.argv[0] SFMImport(sys.argv[1]) From valerib at ca.inter.net Sat Sep 6 22:27:57 2003 From: valerib at ca.inter.net (valeri) Date: Thu Sep 11 14:50:54 2003 Subject: [Tutor] need help Message-ID: <000801c374df$46644010$335b0a40@oemsmsi5nqma6n> Hi I am new to Python and programming, but I like it since I've tried Python. I have difficulties using commande' else' after 'if' argument I try to enter 'else' and it gives me an arror message. I am using Python 2.2, Live wires and pygame for beginners. Please give me an advise or a link. Thank you. val. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030906/18a72bf6/attachment-0001.htm From galoosh33 at hotmail.com Sun Sep 7 18:00:12 2003 From: galoosh33 at hotmail.com (Gal Yona) Date: Thu Sep 11 14:50:59 2003 Subject: [Tutor] Python Question Message-ID: Hey. Im curretnly trying to learn Pyton... I saw the archive with A LOT of questions & answers. I have a question... As I said, I just started. I began to read the 'Python for non-programers' tutorial, reached about chapter 8 and stopped. It began to be very hard and confusing, and went on too fast. I was wondering how I can upload my Python Programs online, and how will people see them. Also if I can make it a file evryone can see... I mean, can computers who dont have Python installed can view me programs? And a small question: When I run the finished program, it quits and closes window if it has nothing to do. For example if my program is just print "Hello, World!" it would open it for half a second and immediatly close the window... What to do? :) Thanks a lot! _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From kb6nvh at cox.net Wed Sep 10 02:39:32 2003 From: kb6nvh at cox.net (Brian Carlin) Date: Thu Sep 11 14:51:04 2003 Subject: [Tutor] hex output Message-ID: I just came across your post about hex output. The following Python commands work for me: >>> hex(65)[2:] '41' >>> import string >>> string.zfill(hex(65)[2:],4) '0041' >>> The second parameter of string.zfill() specifies the number of digits you want in the string. If there are fewer digits, the function pads zeros to the left. From Orion72738 at cs.com Wed Sep 10 22:00:08 2003 From: Orion72738 at cs.com (Orion72738@cs.com) Date: Thu Sep 11 14:51:12 2003 Subject: [Tutor] Syntax Question Message-ID: <186.1ef4026c.2c912318@cs.com> I am very new to programming, and i am trying to make this program convert Fahrenheit to celsius and vice-versa. When I try to run it, I get syntax errors. Please help! Thank you! (what i have is below) ____________________________________________________________________ Input the temperature in degrees Fahrenheit (call it Fahrenheit) Calculate Celsius as (5/9)celsius + 32 Output Fahrenheit ------------------------------------------------------------------------------ ------------------ #convert.py # A program to convert Fahrenheit temperatures to Celsius ------------------------------------------------------------------------------ ------------------ def main(): Fahrenheit = input("What is the Fahrenheit Temperature?") Celsius = (5.0 / 9.0) * Fahrenheit - 32 print "The Temperature is", Celsius, "degrees Celsius." main() From niki at vintech.bg Thu Sep 11 11:27:40 2003 From: niki at vintech.bg (Niki Spahiev) Date: Thu Sep 11 14:51:17 2003 Subject: [Tutor] Re: [pygame] Fastest (x,y) distance calculation In-Reply-To: <2109.192.206.201.218.1063223781.squirrel@mail.harlekin-maus.com> References: <2109.192.206.201.218.1063223781.squirrel@mail.harlekin-maus.com> Message-ID: <3F6023EC.8000901@vintech.bg> try math.hypot( x1-x2, y1-y2 ) HTH Niki Spahiev From pythontutor at venix.com Thu Sep 11 16:01:12 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Thu Sep 11 15:01:20 2003 Subject: [Tutor] Creatively solving math problems -----help In-Reply-To: <3F60B5DF.7080105@ccvcorp.com> References: <3F60B5DF.7080105@ccvcorp.com> Message-ID: <3F60C678.7060408@venix.com> One further optimization: x % 6 == 1 implies that x % 3 ==1 and x % 2 == 1 (the factors of the modulus must also result in 1 (asserted without proof)) so for y in range(2, 7): could become for y in (4,5,6): One further point. Along the way, the code deviated from the algorithm. All of the y's are supposed to result in 1, that is: x % y == 1 for all y for an x to be printed. ... for y in (4,5,6): ... if x % y != 1: ... break ... else: ... print x ... 301 721 1141 1561 1981 2401 2821 .... Danny's one liner: [ x for x in range(20000) if [x%i for i in range(2,8)]==[1]*5+[0] ] shows the mod values that we want. [1]*5+[0] might be easier to read as [1,1,1,1,1,0] though counting 1's isn't great either. Jeff Shannon wrote: > Clay Shirky wrote: > >>> for x in range(20000): >>> if [x%y for y in range(2, 7)] == 1 and x % 7 == 0: >>> print x >> >> >> >> This is awfully hard to read -- any reason you're trying to cram so much >> stuff on one line? Is this what you are trying to do? >> >> for x in range(20000): >> for y in range(2, 7): >> if x % y == 1 and x % 7 == 0: >> print x >> break >> >> If so, it will be easy to start altering from there. > > > Another thing to consider here -- you've got two loops ('for x...' and > 'for y...'), and a compound 'if' statement. Note that one half of the > 'if' statement (and thus the entire test) will be true for only one > value in seven of the outer loop, and that the value of the inner loop > makes *no* difference to this. This means that, by splitting into two > if statements, we can run the inner loop one-seventh as many times. > > for x in range(20000): > if x % 7 == 0: > for y in range(2, 7): > if x % y == 1: > print x > break > > This will avoid setup and execution of the inner loop for the six out of > seven times that x % 7 is *not* equal to zero. This may be a fairly > minor point when you're saving ~17,000 runs of the inner loop, but if > your search range grows, it could be *quite* helpful. > > This is a slight variant on the standard optimization method of lifting > loop-invariants out of the loop -- in this case, the invariant means > that the if statement will never be true. By lifting that part of the > if statement outside of the inner loop, we can optimize away the entire > inner loop for certain values of x. And while some might warn about the > dangers of premature optimization (for it *is* dangerous), in this case > I think it also results in a clearer, more easily read structure (the > opposite of many optimization methods). > > Jeff Shannon > Technician/Programmer > Credit International > > > _______________________________________________ > 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 dyoo at hkn.eecs.berkeley.edu Thu Sep 11 13:08:07 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 11 15:08:13 2003 Subject: [Tutor] Syntax Question In-Reply-To: <186.1ef4026c.2c912318@cs.com> Message-ID: On Wed, 10 Sep 2003 Orion72738@cs.com wrote: > I am very new to programming, and i am trying to make this program > convert Fahrenheit to celsius and vice-versa. When I try to run it, I > get syntax errors. Hi Orion, Hello! Hmmm.... Can you show us the syntax error message? From what you've posted: > ------------------------------------------------------------------------------ > ------------------ > #convert.py > # A program to convert Fahrenheit temperatures to Celsius > ------------------------------------------------------------------------------ > ------------------ > > def main(): > Fahrenheit = input("What is the Fahrenheit Temperature?") > Celsius = (5.0 / 9.0) * Fahrenheit - 32 > print "The Temperature is", Celsius, "degrees Celsius." > > main() I actually can't see anything wrong with the code... except potentially all those minus signs that you used to draw the comment lines! *grin*. We want to avoid guessing the problem: do a cut-and-paste of the error message, that SyntaxError, and we'll be able to better understand how to solve the problem. Here are a few examples of error messages: ### >>> 3 + "5" Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand types for +: 'int' and 'str' >>> >>> >>> print "hello world File "", line 1 print "hello world ^ SyntaxError: invalid token >>> >>> >>> muhahaha Traceback (most recent call last): File "", line 1, in ? NameError: name 'muhahaha' is not defined ### In each error report, the "traceback" and the error message are both valuable debugging tools that we can use to put ourselves in Python's shoes. Talk to you later! From amk at asti-usa.com Thu Sep 11 16:11:26 2003 From: amk at asti-usa.com (A.M. Kuchling) Date: Thu Sep 11 15:11:30 2003 Subject: [Tutor] Syntax Question In-Reply-To: <186.1ef4026c.2c912318@cs.com> References: <186.1ef4026c.2c912318@cs.com> Message-ID: <20030911191126.GA17734@vail.asti-usa.com> On Wed, Sep 10, 2003 at 09:00:08PM -0400, Orion72738@cs.com wrote: > ------------------ > #convert.py > # A program to convert Fahrenheit temperatures to Celsius I hope those lines of dashes aren't in your script; they'd certainly be syntax errors. Put a '#' in front of them to turn that line into a comment. > Fahrenheit = input("What is the Fahrenheit Temperature?") input() expects a valid Python expression as input. Use raw_input() instead to get a string, and convert it to a floating-point number with float(). --amk From clay at shirky.com Thu Sep 11 16:23:24 2003 From: clay at shirky.com (Clay Shirky) Date: Thu Sep 11 15:23:32 2003 Subject: [Tutor] Creatively solving math problems -----help In-Reply-To: <3F60B5DF.7080105@ccvcorp.com> Message-ID: > for x in range(20000): > if x % 7 == 0: And reading this, it occurs to me that you could do this with a range stride of 7 as well: for x in range(0, 200, 7): # <--- count by 7s for y in range(2, 7): if x%y == 1: print x break -clay From jeff at ccvcorp.com Thu Sep 11 13:31:46 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 11 15:30:42 2003 Subject: [Tutor] need help References: <000801c374df$46644010$335b0a40@oemsmsi5nqma6n> Message-ID: <3F60CDA2.30105@ccvcorp.com> valeri wrote: > Hi I am new to Python and programming, but I like it since I've tried > Python. I have difficulties using commande' else' > after 'if' argument I try to enter 'else' and it gives me an arror > message. I am using Python 2.2, Live wires and pygame for beginners. Hi Valeri, It'll be a lot easier for us to tell what the problem is, if you show us a simple example of what you're trying to do and the error message that you get. Those error messages contain a lot of useful information, once you learn how to read them, and once we see what they say we can help you to understand what's going wrong. Jeff Shannon Technician/Programmer Credit International From connally at fas.harvard.edu Thu Sep 11 17:18:18 2003 From: connally at fas.harvard.edu (Emily Lea Connally) Date: Thu Sep 11 16:18:24 2003 Subject: [Tutor] different kind of help In-Reply-To: <3F60CDA2.30105@ccvcorp.com> Message-ID: hey all, I'm not asking about python, but about macs.. any mac experts out there? my computer died and I need to use it pronto, thanks! M ************************************************************************* The man of virtue makes the difficulty to be overcome his first business, and success only a subsequent consideration. - Confucius ************************************************************************* From alan.gauld at blueyonder.co.uk Thu Sep 11 22:40:45 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 11 16:40:34 2003 Subject: [Tutor] Python Question References: Message-ID: <02b901c378a4$fa0e59c0$6401a8c0@xp> > I have a question... Lots of questions surely! ... but thats OK :-) > to read the 'Python for non-programers' tutorial, reached about chapter 8 > and stopped. It began to be very hard and confusing, and went on too fast. OK, So try one of the others - like mine :-) Sreriously if you don't understand one tutor take a look at another, they may explain the same cconcept more clearly for you. > was wondering how I can upload my Python Programs online, and how will > people see them. Also if I can make it a file evryone can see... I mean, can > computers who dont have Python installed can view me programs? OK, It gets a wee bit complicated here. To get your Python programs online just put them on a web site (See Useless Python for many examples). But the visitors will need to download them and run them on their PC with Python installed. If they don't have Python and for some reason are not prepared to install it then there is a program called py2exe that you can use to create an EXE file that contains Python and your program bundled together. It will be pretty big though... and py2exe isn't the easiest thing to use, not something I'd tackle for a wee while yet. > When I run the finished program, it quits and closes window if it > has nothing to do. For example if my program is just THis is a common one. The simplest way is probably to just add the line: raw_input("Hit RETURN to quit") This will display the message then wait for the user to hit return before closing the window. Another option is to edit the file association in EXplorer to use python -i in stead of plain python to run the program,. That leaves you in the >>> python prompt. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Sep 11 22:42:30 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 11 16:42:17 2003 Subject: [Tutor] hex output References: Message-ID: <02be01c378a5$38980650$6401a8c0@xp> > >>> import string > >>> string.zfill(hex(65)[2:],4) > '0041' > > The second parameter of string.zfill() specifies the number of digits > you want in the string. If there are fewer digits, the function pads > zeros to the left. The format operator (%) does all of that and is almost certainly faster. See the earlier messages. Alan G. From alan.gauld at blueyonder.co.uk Thu Sep 11 22:45:54 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 11 16:45:39 2003 Subject: [Tutor] Syntax Question References: <186.1ef4026c.2c912318@cs.com> Message-ID: <02c301c378a5$b23376c0$6401a8c0@xp> > #convert.py > # A program to convert Fahrenheit temperatures to Celsius > -------------------------------------------------------------------- ---------- > ------------------ I assume you don't really have all these dashes in your file? If so Python will see them as minus signs and complain that it doesn't understand... You would need to put # signs in front to make them comments. > def main(): > Fahrenheit = input("What is the Fahrenheit Temperature?") > Celsius = (5.0 / 9.0) * Fahrenheit - 32 > print "The Temperature is", Celsius, "degrees Celsius." This all looks OK to me. Alan G. From alan.gauld at blueyonder.co.uk Thu Sep 11 22:47:13 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 11 16:47:02 2003 Subject: [Tutor] need help References: <000801c374df$46644010$335b0a40@oemsmsi5nqma6n> Message-ID: <02cb01c378a5$e10d7b80$6401a8c0@xp> > have difficulties using commande' else' > after 'if' argument I try to enter 'else' and it gives me > an arror message. OK, Can you post an example both of the code and the error message please? Its much easier to see whats going wrong than to try to guess! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From learning.python at dbmail.dk Thu Sep 11 23:53:56 2003 From: learning.python at dbmail.dk (Ole Jensen) Date: Thu Sep 11 16:54:45 2003 Subject: [Tutor] Python Question References: Message-ID: <001c01c378a6$d171db70$844c73d5@BAERBAR> > Hey. Im curretnly trying to learn Pyton... I saw the archive with A LOT of > questions & answers. I have a question... As I said, I just started. I began > to read the 'Python for non-programers' tutorial, reached about chapter 8 > and stopped. It began to be very hard and confusing, and went on too fast. If you find some topics hard in one tutorial, I would suggest trying looking through another tutorial to see if you can find some different angles to the topic you are having trouble with. I guess you've already seen this site, but it doesn't hurt posting it again ;-) http://www.python.org/topics/learn/non-prog.html I > was wondering how I can upload my Python Programs online, and how will > people see them. Also if I can make it a file evryone can see... I mean, can > computers who dont have Python installed can view me programs? are you making a cgi script (or similar) or do you just want to let people see and download your programs? If the latter: Then you can upload your python programs just like a normal file, the browser (Internet Explorer) will then open the file as if it was a normal txt-file and display the contents. You could compress the files to a .zip which when the user clicks the link it will automatically download the file instead of displaying it. I have my own (small) archive on the net: http://www.dbhome.dk/learningtoprogram/programs.html You should be aware that if you upload the files as is, IE and possibly others can corrupt the files by inserting html-code into the script. And a small > question: When I run the finished program, it quits and closes window if it > has nothing to do. For example if my program is just > > print "Hello, World!" > > it would open it for half a second and immediatly close the window... What > to do? :) then you will need to run the program in idle, or... As you say "it close if it has nothing to do", you need to get it to wait for something, maybe put an input() at the end or make a quit-loop as I call it, building on your example: quit = 1 while quit == 1: print "Hello World!" quit = input("press '1' to print again?") Which agreed is a bit overkill here, but if you were to test several different things in your script, its usefull instead of re-running the program. From project5 at redrival.net Fri Sep 12 00:14:06 2003 From: project5 at redrival.net (Andrei) Date: Thu Sep 11 17:16:12 2003 Subject: [Tutor] Re: need help In-Reply-To: <000801c374df$46644010$335b0a40@oemsmsi5nqma6n> References: <000801c374df$46644010$335b0a40@oemsmsi5nqma6n> Message-ID: valeri wrote: Hi Valeri, > Hi I am new to Python and programming, but I like it since I've tried > Python. I have difficulties using commande' else' > after 'if' argument I try to enter 'else' and it gives me an arror > message. I am using Python 2.2, Live wires and pygame for beginners. > Please give me an advise or a link. Shot in the dark here since you didn't provide the problem code, but this is how you *should* use the if/else: if CONDITION: # CONDITION is an expression evaluating to True or False DO_SOMETHING # some statements executed if CONDITION evaluates to True else: DO_SOMETHING_ELSE Pay attention to the indentation and the colons. A less abstract example: username = raw_input("Your name: ") if username == "Valeri": print username, "has a question about if/else" # do more stuff else: print username, "is an unknown user" -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Fri Sep 12 01:10:04 2003 From: project5 at redrival.net (Andrei) Date: Thu Sep 11 18:12:05 2003 Subject: [Tutor] Re: processing large file In-Reply-To: <3F55D711.7000607@eads.net> References: <3F55D711.7000607@eads.net> Message-ID: Hello Guillaume, ALLEON Guillaume wrote: > I have to read and process a large ASCII file containing a mesh : a list > of points and triangles. > The file is 100 MBytes. I just tried creating a million of your points. Python occupies 213 MB of memory now, but it's no problem. How many do you have? Btw, it also takes a bit of time to create them (Athlon 2000+/512 Mb/WinXP). > I first tried to do it in memory but I think I am running out of memory You think or you know? Do you get an error? > therefore I decide to use the shelve > module to store my points and elements on disks. I've never used the shelve module, so I can't comment on that. > Despite the fact it is slow ... Any hint ? I think I have the same > memory problem but I don't understand why > since my aPoint should be removed by the gc. > > Have you any idea ? I can't really read the code because the indentation is impossible to follow. If this is not your mail client's fault, get a proper editor for Python and use 4 spaces per indentation level (proper editors convert the Tab key to 4 spaces). Generally speaking, you should divide your code into smaller functions and profile them. That shows you exactly where the problem is. Profiling is done by adding at the bottom of your module this: if __name__=="__main__": if len(sys.argv)>1 and sys.argv[1].lower()=="profile": import profile profile.run('main()') else: main() This is of course assuming that your main function is called main() and that you want to pass a command parameter "profile". You can also just always do profile.run('main()') when debugging, without the parameter. This is the only way of knowing where the speed problems are. I've put some comments in your code, but I'm not saying that they are the cause of the speed issue, they're more like general remarks. I have also assumed you have a modern Python version. > import string You shouldn't use the string module. Use string methods and builtin functions instead. > import os, sys, time, resource, shelve, psyco > > psyco.full() > > class point: > def __init__(self,x,y,z): > self.x = x > self.y = y > self.z = z > > def SFMImport(filename): > print 'UNV Import ("%s")' % filename > > db = shelve.open('points.db') > > file = open(filename, "r") > > linenumber = 1 > nbpoints = 0 > nbfaces = 0 linenumbers and nbfaces don't seem to be used > pointList = [] neither is pointList > faceList = [] > > line = file.readline() > words = string.split(line) shortcut: words = file.readline().split() > nbpoints = string.atoi(words[1]) > nbtrias = string.atoi(words[0]) The atoi function is deprecated. The int() function seems to be about 30% faster and does the same thing: >>> a = t.Timer("import string; a=string.atoi; [a('345') for i in range(1000000)]") >>> a.timeit(1) 3.2120071126358241 >>> b = t.Timer("import string; [int('345') for i in range(1000000)]") >>> b.timeit(1) 2.1893349573758627 I did more tests, but all results were comparable. But then again, we don't know whether this is the bottleneck because there's no profile. > print "found %s points and %s triangles" % (nbpoints, nbtrias) I wouldn't print this much info. > t1 = time.time() > for i in range(nbpoints): > line = file.readline() > words = string.split(line) Shortcut above. > x = string.atof(words[1].replace("D","E")) > y = string.atof(words[2].replace("D","E")) > z = string.atof(words[3].replace("D","E")) float() should be used instead of atof(). I don't know what the words are, but perhaps you can find a way of not doing all that replacing? > aPoint = point(x, y, z) > > as = "point%s" % i > > if (i%250000 == 0): > print "%7d points <%s>" % (i, time.time() - t1) > t1 = time.time() > > db[as] = aPoint > > print "%s points read in %s seconds" % (nbpoints, time.time() - t1) > bd.close() What's bd? -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From gabriel.cooper at mediapulse.com Thu Sep 11 20:03:12 2003 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Thu Sep 11 19:03:17 2003 Subject: [Tutor] for/else question Message-ID: <3F60FF30.2000108@mediapulse.com> python has this weird "else" after a for loop, like so: for x in y: do stuff else: do other stuff At first glance I thought this was really cool. Instead of hanging onto "found = 1" variables like in C, I could just throw on this handy else and (I presumed) it would, if my for loop never resulted in a success, automatically kick in. But no, that's not the case. So I thought that it would hit the else if you broke out of the for loop (so, perhaps, like catching an exception). But no, that's not the case either. It turns out that it always uses the else unless you break out of your loop. So it's not really an else, it's more like an "if I didn't die in my loop" catch. What use is that? It would seem that the use is so that if you're running through a for loop and are trying to /find something/ rather than /do something/ then if you didn't find what you were looking for (and thus didn't break) then you can set variables appropriately, e.g.: for x in (a,b,c): if x == y: variable = something break else: aw shucks, didn't find anything. variable = 0 But that's lame for a couple of reasons: first, how often do you use a for loop to /look for stuff/ instead of /do stuff/? Secondly, isn't breaking out of a loop considered "bad programming"? Much like GOTO's? Finally, in the example above you would have simply set 'variable' to zero to begin with, so you wouldn't use the else anyway! So... yeah... Do /you/ use "else" with for loops? If so, when? =] From jmillr at umich.edu Thu Sep 11 20:12:19 2003 From: jmillr at umich.edu (John Miller) Date: Thu Sep 11 19:12:30 2003 Subject: [Tutor] Syntax Question In-Reply-To: Message-ID: <649D230F-E4AD-11D7-9575-00039303967A@umich.edu> The code runs fine, but the equation is structured wrong. A pair of parentheses is needed to return the correct answer: C = (F-32) * (5.0 / 9.0) John Miller On Thursday, September 11, 2003, at 05:16 PM, "Alan Gauld" wrote: >> def main(): >> Fahrenheit = input("What is the Fahrenheit Temperature?") >> Celsius = (5.0 / 9.0) * Fahrenheit - 32 >> print "The Temperature is", Celsius, "degrees Celsius." > > This all looks OK to me. From missive at hotmail.com Fri Sep 12 00:36:47 2003 From: missive at hotmail.com (Lee Harr) Date: Thu Sep 11 19:37:05 2003 Subject: [Tutor] Re: for/else question Message-ID: >So... yeah... Do /you/ use "else" with for loops? never _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From erikprice at mac.com Thu Sep 11 20:50:03 2003 From: erikprice at mac.com (Erik Price) Date: Thu Sep 11 20:05:50 2003 Subject: [Tutor] hex output In-Reply-To: <02be01c378a5$38980650$6401a8c0@xp> Message-ID: On Thursday, September 11, 2003, at 04:42 PM, Alan Gauld wrote: >>>>> import string >>>>> string.zfill(hex(65)[2:],4) >> '0041' >> >> The second parameter of string.zfill() specifies the number of > digits >> you want in the string. If there are fewer digits, the function > pads >> zeros to the left. > > The format operator (%) does all of that and is almost certainly > faster. See the earlier messages. Not to mention, no offense to the OP, much easier to comprehend. Erik From project5 at redrival.net Fri Sep 12 03:41:38 2003 From: project5 at redrival.net (Andrei) Date: Thu Sep 11 20:43:37 2003 Subject: [Tutor] Re: for/else question In-Reply-To: <3F60FF30.2000108@mediapulse.com> References: <3F60FF30.2000108@mediapulse.com> Message-ID: Gabriel Cooper wrote: > > python has this weird "else" after a for loop, like so: > > for x in y: > do stuff > else: > do other stuff > > > So... yeah... Do /you/ use "else" with for loops? If so, when? Ha, I didn't even know the possibility existed. Given its function, I agree that the word "else" is a peculiar choice, "then" or "finally" or "whenfinishedwithoutbreak" would be a lot better. Especially the long one, so people wouldn't be too tempted to use it :). I can't think of an instance where I'd have needed this feature. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From jeff at ccvcorp.com Thu Sep 11 19:06:23 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 11 21:04:05 2003 Subject: [Tutor] for/else question References: <3F60FF30.2000108@mediapulse.com> Message-ID: <3F611C0F.50604@ccvcorp.com> Gabriel Cooper wrote: > Secondly, isn't > breaking out of a loop considered "bad programming"? Much like GOTO's? Actually, no it's not. Indeed, one of the recommended idioms in Python (to replace the do ... while loop of some other languages) is: while 1: do_stuff() if (condition): break The normal 'while (condition)' loop performs an action 0 or more times, while the loop above performs an action 1 or more times. This prevents you from needing to initialize variables (say, reading from a file to determine the condition) before the while loop and then again inside of the while loop. > So... yeah... Do /you/ use "else" with for loops? If so, when? I seem to recall a discussion of this on comp.lang.python some time ago, which intimated that it was included as much for symmetry (with if/else) as for practical need. (The implementation of code suites is such that it is essentially free -- 'else' works the same whether it follows a 'for' or an 'if'.) That said, I can see cases where it's important to know whether you've broken out of a loop or not. You might need to take an action only if there are no errors in your loop, for instance. You could use a sentinel variable, but it's cleaner to avoid that, and for/else allows you to avoid it. Jeff Shannon Technician/Programmer Credit International From project5 at redrival.net Fri Sep 12 05:14:19 2003 From: project5 at redrival.net (Andrei) Date: Thu Sep 11 22:16:18 2003 Subject: [Tutor] Re: Creatively solving math problems -----help In-Reply-To: <3F60C678.7060408@venix.com> References: <3F60B5DF.7080105@ccvcorp.com> <3F60C678.7060408@venix.com> Message-ID: Lloyd Kvam wrote: > One further optimization: > x % 6 == 1 implies that x % 3 ==1 and x % 2 == 1 (the factors of the > modulus > must also result in 1 (asserted without proof)) Seems perfectly OK to me. > so > for y in range(2, 7): > could become > for y in (4,5,6): > > Danny's one liner: > [ x for x in range(20000) if [x%i for i in range(2,8)]==[1]*5+[0] ] > shows the mod values that we want. [1]*5+[0] might be easier to read as > [1,1,1,1,1,0] > though counting 1's isn't great either. Actually, it was my oneliner. [1]*5 was indeed to avoid typing the wrong number of 1's - and it's marginally shorter too! Danny's solution is far more excentric - and certainly no oneliner :). Nevertheless, I think a solution with explicit loops is preferred in this sutuation. Funny how the whole discussion turned into an optimization when all Conrad needed was the % operator. Anyway, it's possible to save a bit of time in the list comprehension too using the suggestions provided (not checking 2&3 because 6 already checks them and only evaluating if x%7==0) *wink*. I've done some tests and it seems there's a way to add to the spared time: replace the range() and [1]*4 with their hand-written counterparts. Time for the benchmarks: >>> import timeit as t >>> a = t.Timer("[ x for x in range(20000) if [x%i for i in range(2,8)]==[1]*5+[0] ]") >>> b = t.Timer("[ x for x in range(20000) if not x%7 if [x%i for i in (4,5,6)]==[1,1,1] ]") >>> c = t.Timer("[ x for x in xrange(20000) if not x%7 if not x%6-1 if not x%5-1 if not x%4-1 ]") >>> [ min(X.repeat(30,1)) for X in [a,b,c] ] [0.17663669544572258, 0.022738923522410914, 0.0077345025697468373] ^-- best result for a ^-- best for b ^-- best for c (lower=better) Just to be on the safe side, test if all lists are the same (up to 100k instead of 20k): >>> [ x for x in range(100000) if [x%i for i in range(2,8)]==[1]*5+[0] ]==[ x for x in range(100000) if not x%7 if [x%i for i in (4,5,6)]==[1,1,1] ]==[ x for x in xrange(100000) if not x%7 if not x%6-1 if not x%5-1 if not x%4-1 ] True And the winner is, at nearly 23 times the speed of the original oneliner... [ x for x in xrange(20000) if not x%7 if not x%6-1 if not x%5-1 if not x%4-1 ] Well, that was fun. Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From pythontutor at venix.com Thu Sep 11 23:34:48 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Thu Sep 11 22:34:53 2003 Subject: [Tutor] Re: Creatively solving math problems -----help In-Reply-To: References: <3F60B5DF.7080105@ccvcorp.com> <3F60C678.7060408@venix.com> Message-ID: <3F6130C8.3020508@venix.com> Sorry about that Andrei! I found it in Danny's email and failed to keep the attribution straight. Andrei wrote: > > Lloyd Kvam wrote: >> Danny's one liner: > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From python at rcn.com Thu Sep 11 23:39:12 2003 From: python at rcn.com (Raymond Hettinger) Date: Thu Sep 11 22:43:55 2003 Subject: [Tutor] Fastest (x,y) distance calculation References: Message-ID: <00cb01c378d7$0cea76a0$5234c797@oemcomputer> [Raymond Hettinger] > > Distance calculations are much cheaper if you store the coordinates > > as complex numbers and use abs(). [Magnus] > I tried that, and the distance calculation (pos-tmp.rect) > got much quicker, but abs() ate up all the improvement. :( Make sure you set _abs = abs to save the builtin lookup time. I get a two to one improvement on your code: >>> import timeit >>> setup = """ class Point: pass p = Point() p.x = 11.0 p.y = 5.0 q = Point() q.x = 8.0 q.y = 9.0 r = 8 + 9j class Temple: pass t = Temple() t.rect = p t.complex = 11+5j _abs = abs """ >>> stmt1 = """ distsqrd = (t.rect.x - q.x) ** 2 + (t.rect.y - q.y) **2 """ stmt2 = """ dist = _abs(t.complex - r) """ >>> print timeit.Timer(stmt1, setup).repeat(3) [6.5299007693726008, 7.4887745352754829, 6.5537052246936742] >>> print timeit.Timer(stmt2, setup).repeat(3) [3.1982123401330895, 3.1982919593020362, 3.5620459612128919] Executive summary: abs(z1-z2) beats the (deltax**2 + deltay**2) approach Raymond Hettinger ################################################################# ################################################################# ################################################################# ##### ##### ##### ################################################################# ################################################################# ################################################################# From python at rcn.com Thu Sep 11 23:57:44 2003 From: python at rcn.com (Raymond Hettinger) Date: Thu Sep 11 23:02:30 2003 Subject: [Tutor] for/else question References: <3F60FF30.2000108@mediapulse.com> Message-ID: <00f801c378d9$a40f2c40$5234c797@oemcomputer> > So... yeah... Do /you/ use "else" with for loops? If so, when? Yes. Here's an except from a relevant article in PyZine: """ The for statement syntax is "for target in sequence: suite [else suite]". The semantics are clear ? the else clause is run after the loop if no break statements are encountered. The purpose for the optional else clause may not be as obvious. In the 1970?s debates about Structured Programming, fierce discussion about eliminating goto statements revealed situations where there were no adequate substitutes using structured constructs such as for and while [3]. One of those cases involved being able to tell (after the requisite single entry and exit points) whether a loop had run to completion or had been broken. An optional else clause provided a structured solution: for element in itemlist: if element is target: break else: . . . [3] Structured Programming with goto Statements, Donald Knuth, 1974. """ Raymond Hettinger From pythontutor at venix.com Fri Sep 12 00:34:56 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Thu Sep 11 23:35:06 2003 Subject: [Tutor] for/else question In-Reply-To: <3F60FF30.2000108@mediapulse.com> References: <3F60FF30.2000108@mediapulse.com> Message-ID: <3F613EE0.1000305@venix.com> If you simply set variables (change program state) depending upon whether a loop completes or breaks, then the else doesn't buy you much. One of the things python supports, without forcing it on you, is the ability to reduce the amount of state information used in a program. > for x in (a,b,c): > if x == y: > variable = something > break > else: > aw shucks, didn't find anything. > variable = 0 # might continue if variable: #do what we can knowing x == y else: #do what we do when no x == y rather write this: > for x in (a,b,c): > if x == y: #do what we can knowing x == y > break > else: > aw shucks, didn't find anything. #do what we do when no x == y variable disappears from the program logic. This is a good thing. It is one less piece of state information to manage. Functional programming tries to manage state by eliminating it. OOP tries to manage state by encapsulating it. Python supports both approaches. Gabriel Cooper wrote: > > python has this weird "else" after a for loop, like so: > > for x in y: > do stuff > else: > do other stuff > > At first glance I thought this was really cool. Instead of hanging onto > "found = 1" variables like in C, I could just throw on this handy else > and (I presumed) it would, if my for loop never resulted in a success, > automatically kick in. But no, that's not the case. So I thought that it > would hit the else if you broke out of the for loop (so, perhaps, like > catching an exception). But no, that's not the case either. It turns out > that it always uses the else unless you break out of your loop. So it's > not really an else, it's more like an "if I didn't die in my loop" > catch. What use is that? > > It would seem that the use is so that if you're running through a for > loop and are trying to /find something/ rather than /do something/ then > if you didn't find what you were looking for (and thus didn't break) > then you can set variables appropriately, e.g.: > > for x in (a,b,c): > if x == y: > variable = something > break > else: > aw shucks, didn't find anything. > variable = 0 > > But that's lame for a couple of reasons: first, how often do you use a > for loop to /look for stuff/ instead of /do stuff/? Secondly, isn't > breaking out of a loop considered "bad programming"? Much like GOTO's? > Finally, in the example above you would have simply set 'variable' to > zero to begin with, so you wouldn't use the else anyway! > > So... yeah... Do /you/ use "else" with for loops? If so, when? > > =] > > > _______________________________________________ > 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 Janssen at rz.uni-frankfurt.de Fri Sep 12 15:54:23 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Fri Sep 12 08:54:35 2003 Subject: [Tutor] for/else question In-Reply-To: <3F60FF30.2000108@mediapulse.com> References: <3F60FF30.2000108@mediapulse.com> Message-ID: On Thu, 11 Sep 2003, Gabriel Cooper wrote: > So... yeah... Do /you/ use "else" with for loops? If so, when? some time ago it has really helped me out of an ugly function: def delpattern(inlist, patternl): """clean inlist from entries with certain sub-strings""" backl=[] for elem in inlist: for pattern in patternl: if elem.find(pattern) >-1: break else: backl.append(elem) return backl #without for-if-else it would be (under the assumption you don't want #to investigate further to get some clever list-comprehension or reg-exp #solution): def delpattern(inlist, patternl): """clean inlist from entries with certain sub-strings""" backl=[] for elem in inlist: found = 0 for pattern in patternl: if elem.find(pattern) >-1: found = 1 break # just to save time if not found: backl.append(elem) return backl for-if-else seems much more readable (understandable) than found-not-found to me. You have compared looking for something to doing something. Here we're looking for something and only doing if not found. Michael From cybersamurai at mac.com Fri Sep 12 10:08:33 2003 From: cybersamurai at mac.com (Luiz Siqueira Neto) Date: Fri Sep 12 10:28:36 2003 Subject: [Tutor] validator Message-ID: <3F61D361.4000101@mac.com> I need validate some XML documents with some xsd but a can't find a Python validator, mabe you know some solution. Thanks and sorry about this mail, I know this is not the right place for this question but I can't find another way. From SWidney at ci.las-vegas.nv.us Fri Sep 12 11:48:55 2003 From: SWidney at ci.las-vegas.nv.us (Scott Widney) Date: Fri Sep 12 11:49:39 2003 Subject: [Tutor] for/else question Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC87D3@sovereign.ci.las-vegas.nv.us> > I seem to recall a discussion of this on comp.lang.python some time > ago, which intimated that it was included as much for symmetry (with > if/else) as for practical need. (The implementation of code suites > is such that it is essentially free -- 'else' works the same whether > it follows a 'for' or an 'if'.) > > That said, I can see cases where it's important to know whether > you've broken out of a loop or not. You might need to take an > action only if there are no errors in your loop, for instance. > You could use a sentinel variable, but it's cleaner to avoid that, > and for/else allows you to avoid it. This is probably a moot point (I doubt that they would change this) but I think it's the use of the word 'else' that is confusing. Here is how I tend to think of the 'if' statement: If a condition is true: then do something; otherwise: do something else. This is not symmetrical with 'for: else:' in my mind. Grammatically speaking, it seems backward, and therein lies the tension. Here is my brain map of the 'for' statement: For each item in a group: do something; afterwards (provided nothing went wrong): do this too. "Otherwise" doesn't map cleanly to "afterwards". If we swapped the terms we would get this: If a condition is true: then do something; afterwards: do something else. For each item in a group: do something; otherwise: do this. It just doesn't fit. But there is a term in another statement in Python that seems closer to what I'm thinking: Try: something that might not work; if it fails: do this; finally (whether or not it worked): do this too. This "feels" more comfortable. Finally and afterwards are semantic neighbors. So if I think 'finally' in my head, but type 'else' when dealing with a for statement, it seems to relieve the pressure. And now we return to our regularly scheduled program.... Scott From james_royus at eudoramail.com Fri Sep 12 12:30:14 2003 From: james_royus at eudoramail.com (james roy) Date: Fri Sep 12 12:30:26 2003 Subject: [Tutor] Question on lists Message-ID: Hello, I am new to programming with python. I dont know I am having my problem like this: I am having a few lists that i know in no dynamically. For example: List1 = ['1','2','3'] List2 = ['/'] List3 = ['4','5','6'] I want to make the combinations like this: '1' / '4' '1' / '5' '1' / '6' '2' / '4' '2' / '5' '2' / '6' '3' / '4' '3' / '5' '3' / '6' I want to genearlise this as: I can have 'n' no of elements in 'N' no of lists and i want to make the combinations like i have written. I am waiting to welcome your suggestions. Thanks a lot. With regards, James Need a new email address that people can remember Check out the new EudoraMail at http://www.eudoramail.com From james_royus at eudoramail.com Fri Sep 12 12:36:49 2003 From: james_royus at eudoramail.com (james roy) Date: Fri Sep 12 12:37:07 2003 Subject: [Tutor] Question on list Message-ID: Sorry pressed the wrong button while typing. Hello, I am new to programming with python. I dont know whether i should ask this question here or not. I am having my problem like this: I am having a few lists that i know in no dynamically. For example: List1 = ['1','2','3'] List2 = ['/'] List3 = ['4','5','6'] I want to make the combinations like this: '1' '/' '4' '1' '/' '5' '1' '/' '6' '2' '/' '4' '2' '/' '5' '2' '/' '6' '3' '/' '4' '3' '/' '5' '3' '/' '6' I want to genearlise this as: I can have 'n' no of elements in 'N' no of lists and i want to make the combinations like i have written. I am waiting to welcome your suggestions. Thanks a lot. With regards, James Need a new email address that people can remember Check out the new EudoraMail at http://www.eudoramail.com From dyoo at hkn.eecs.berkeley.edu Fri Sep 12 12:45:24 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 12 12:45:33 2003 Subject: [Tutor] validator In-Reply-To: <3F61D361.4000101@mac.com> Message-ID: On Fri, 12 Sep 2003, Luiz Siqueira Neto wrote: > Thanks and sorry about this mail, I know this is not the right place for > this question but I can't find another way. Hi Luiz, Python.org hosts a complete list of Python's Special Interest Groups (SIGs) that specialize on topics, like XML: http://www.python.org/community/sigs.html The XML-SIG mailing list is here: http://www.python.org/sigs/xml-sig/ and you may find the folks there helpful. I'm hopeful that there are people on xml-sig that know a lot about XML validation. *grin* > I need validate some XML documents with some xsd but a can't find a > Python validator, mabe you know some solution. This topic was on XML-SIG, around March or so: http://mail.python.org/pipermail/xml-sig/2003-March/009243.html One program that people there have mentioned is XSV: http://www.ltg.ed.ac.uk/~ht/xsv-status.html and there are a few other things on that thread that look promising. Unfortunately, although I'm fairly adept with Google, I'm not so good at XML parsing. *grin* So I can't give any personal experience about that tool. If you have more questions on doing XML validation, I think your best bet is to try the XML-SIG; I'm sure they'll be happy to help you. Good luck! From dyoo at hkn.eecs.berkeley.edu Fri Sep 12 12:52:13 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 12 12:52:27 2003 Subject: [Tutor] Question on list In-Reply-To: Message-ID: On Fri, 12 Sep 2003, james roy wrote: > I am new to programming with python. I dont know whether i should ask > this question here or not. Hi James, Welcome aboard! Yes, you're in the right place; Tutor is exactly meant for questions like this. > I am having my problem like this: > > I am having a few lists that i know in no dynamically. > For example: > > List1 = ['1','2','3'] > List2 = ['/'] > List3 = ['4','5','6'] > > I want to make the combinations like this: > > '1' '/' '4' > '1' '/' '5' > '1' '/' '6' > '2' '/' '4' > '2' '/' '5' > '2' '/' '6' > '3' '/' '4' > '3' '/' '5' > '3' '/' '6' If a problem is too complicated, one approach we can take to solve it is to change the problem. *grin* Actually, I'm being slightly serious: if we make the problem simpler and solve the simpler problem, we might learn enough to do the real thing. Here's a simplification of the problem: if you're just given an element of List1, and the whole of List3, ### element = 1 List3 = ['4', '5', 6'] ### Can you generate the three combinations? '1' '/' '4' '1' '/' '5' '1' '/' '6' Good luck to you! From jeff at ccvcorp.com Fri Sep 12 13:10:59 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Sep 12 13:08:54 2003 Subject: [Tutor] need help References: <000801c374df$46644010$335b0a40@oemsmsi5nqma6n> <3F60CDA2.30105@ccvcorp.com> <001301c37932$314447f0$cd5c0a40@oemsmsi5nqma6n> Message-ID: <3F61FE23.60203@ccvcorp.com> Hi Valeri, I'm sending this back to the mailing list as well. It's usually a good idea to keep discussions like this on the list (you can just hit 'reply all' instead of 'reply' in your mail program to do this), for a couple of reasons. One is that I might not be available right away -- if, for example, I'd left on vacation just after replying to your message, you could've been waiting for a long time for a response from me. On the other hand, if you sent it to the list, you'd have a whole lot of people who're just as capable of helping you as I am. The other reason is that somebody else may benefit from seeing the question and answer -- much of what I know about Python, I've picked up from following discussions between other people, so I really like the idea of keeping these discussions where anyone can see them. :) valeri wrote: > Hi Jeff! > Thank you for trying to help.Here is what I enter in my Python IDLE on > windows xp home edition using livewires 2.0 tutorial pack: > >>>if 1 < 2: >> > print 'Something is wrong!' > else: > > When I press after 'else' the 'else' is highlighted in red, and > there is a "SyntaxError:invalid syntax" message. The problem here is that the 'else' needs to be at the same indentation level as the 'if' statement that it matches -- if 1 < 2: print 'Yes, one *is* less than two.' else: print 'Something strange going on here...' Python uses indentation to determine program structure, and code that's at the same indentation level is considered to be a single block. In this case, 'else' should be part of the if statement, and not part of the block that's only run when the if statement evaluates to true. Hope that this helps make sense of the problem. If you have any further questions or problems, don't hesitate to ask again! Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Fri Sep 12 13:27:41 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Sep 12 13:25:40 2003 Subject: [Tutor] for/else question References: <0E5508EBA1620743B409A2B8365DE16FDC87D3@sovereign.ci.las-vegas.nv.us> Message-ID: <3F62020D.8020306@ccvcorp.com> Scott Widney wrote: > This is probably a moot point (I doubt that they would change this) but I > think it's the use of the word 'else' that is confusing. Here is how I tend > to think of the 'if' statement: > > If a condition is true: > then do something; > otherwise: > do something else. > > This is not symmetrical with 'for: else:' in my mind. Grammatically > speaking, it seems backward, and therein lies the tension. Here is my brain > map of the 'for' statement: > > For each item in a group: > do something; > afterwards (provided nothing went wrong): > do this too. This is true, this usage of 'else' doesn't quite match English syntax, and Python is usually pretty good about trying to match English usages where practical. This is one of the features that makes Python so easy to read. However, I think it'd be *more* confusing to have two different keywords that do almost the same thing. Python declines having a "do...while" loop for that reason -- the do-loop part can be fairly easily expressed as a while loop, and thus would be needless duplication. Speaking of while loops, 'else' works with them also -- >>> x = 0 >>> while x < 5: ... print x ... x += 1 ... else: ... print "That's all, folks!" ... 0 1 2 3 4 That's all, folks! >>> In this case, the usage of 'else' is quite a bit closer to the standard English usage -- "While x is less than 5, do one thing; otherwise, do this other thing." Now, if you look at that, and then look at the comparable for loop ... >>> for x in range(5): ... print x ... else: ... print "That's all, folks!" ... 0 1 2 3 4 That's all, folks! >>> The parallel structure is obvious, and it makes it hard to argue that 'else' should be called something else in this one particular case. Jeff Shannon Technician/Programmer Credit International From alan.gauld at blueyonder.co.uk Fri Sep 12 15:45:52 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 12 15:45:24 2003 Subject: [Tutor] need help References: <000801c374df$46644010$335b0a40@oemsmsi5nqma6n> <02cb01c378a5$e10d7b80$6401a8c0@xp> <000701c37931$6d7246b0$cd5c0a40@oemsmsi5nqma6n> Message-ID: <032201c37966$79999800$6401a8c0@xp> Hi Valeri, > Thank you for helping me out. Here is what I enter in my Python IDLE on > windows xp home edition using livewires 2.0 tutorial pack: > >> if 1 < 2: > print 'Something is wrong!' > else: The else should be under the if not under the print. The indentation is all important in Python. BUT there is an extra problem which is a "feature"(Or bug!) in IDLE: >>> if 1<2: print 'foo' else: print 'bar' Notice the else has to go right back at the edge because thats where IDLE thinks the if is located. Its only the >>> prompt that makes it look further in. If you start python in a DOS box (Go to Start->Run and type python) you will find it looks like this: >>> if 1<2: ... print 'foo' ... else: ... print 'bar' ... foo >>> Note the way it inserts three dots so that everything lines up properly? Unfortunately IDLE doesn't do that! HTH, Alan G. From zak at harlekin-maus.com Fri Sep 12 16:01:42 2003 From: zak at harlekin-maus.com (Zak Arntson) Date: Fri Sep 12 16:01:50 2003 Subject: [Tutor] Fastest (x,y) distance calculation In-Reply-To: <00cb01c378d7$0cea76a0$5234c797@oemcomputer> References: <00cb01c378d7$0cea76a0$5234c797@oemcomputer> Message-ID: <2412.192.206.201.218.1063396902.squirrel@mail.harlekin-maus.com> > [Raymond Hettinger] >> > Distance calculations are much cheaper if you store the coordinates >> > as complex numbers and use abs(). I don't know the concept behind using complex numbers and abs to determine distance. How does that work? > Executive summary: abs(z1-z2) beats the (deltax**2 + deltay**2) > approach (deltax * deltax) + (deltay * deltay) beats the **2 approach, but only decreases ~0.8 times when I tried it. I'm also considering creating some sort of data structure that aids in nearest-point calculating. Any suggestions? -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From tpc at csua.berkeley.edu Fri Sep 12 16:23:15 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Fri Sep 12 16:23:45 2003 Subject: [Tutor] need help In-Reply-To: <032201c37966$79999800$6401a8c0@xp> Message-ID: <20030912125807.V76553-100000@localhost.name> hello everyone, oh my Gosh, don't even get me started on the shortcomings of IDLE 0.8, I stared at a long block of code for a while before I figured out that copying from emacs to IDLE meant indents of four spaces were pretty much useless, and the only way to reliably transplant code copied from emacs and pasted to IDLE was on emacs to 8 space for the first level indent, 16 for the second, etc, instead of 4 for the first and 8 for the second as is emacs' default. Another gripe I have with IDLE is when scrolling history using Alt-P and Alt-N if you move cursor from end of line to anywhere in the code and you press Alt-P or Alt-N and then you move the cursor to the end of line to resume scrolling, you cannot Alt-P or Alt-N anymore and you have to clear the prompt before you can resume scrolling history. I emailed this to idle-dev@python.org as an annoyance a month back but didn't get any response. I also wish IDLE had more intuitive copy and paste. Oftentimes I want to copy something from IDLE to emacs just by highlighting it like you can in terminal, and unfortunately IDLE doesn't do that. This means you must learn their non-intuitive copy and paste key combinations, another annoyance. On Fri, 12 Sep 2003, Alan Gauld wrote: > Hi Valeri, > > > Thank you for helping me out. Here is what I enter in my Python > IDLE on > > windows xp home edition using livewires 2.0 tutorial pack: > > >> if 1 < 2: > > print 'Something is wrong!' > > else: > > The else should be under the if not under the print. > The indentation is all important in Python. > BUT there is an extra problem which is a "feature"(Or bug!) > in IDLE: > > >>> if 1<2: > print 'foo' > else: > print 'bar' > > Notice the else has to go right back at the edge because thats > where IDLE thinks the if is located. Its only the >>> prompt > that makes it look further in. > > If you start python in a DOS box (Go to Start->Run and type python) > you will find it looks like this: > > >>> if 1<2: > ... print 'foo' > ... else: > ... print 'bar' > ... > foo > >>> > > Note the way it inserts three dots so that everything lines up > properly? Unfortunately IDLE doesn't do that! > > HTH, > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From zak at harlekin-maus.com Fri Sep 12 16:43:54 2003 From: zak at harlekin-maus.com (Zak Arntson) Date: Fri Sep 12 16:43:58 2003 Subject: [pygame] Re: [Tutor] Fastest (x,y) distance calculation In-Reply-To: <3BFF1930-E55F-11D7-B303-000A95686CD8@threeoh.com> References: <2412.192.206.201.218.1063396902.squirrel@mail.harlekin-maus.com> <3BFF1930-E55F-11D7-B303-000A95686CD8@threeoh.com> Message-ID: <2766.192.206.201.218.1063399434.squirrel@mail.harlekin-maus.com> >> I don't know the concept behind using complex numbers and abs to >> determine >> distance. How does that work? > > You can think of complex numbers as a 2D plane in a lot of respects. > The imaginary component is the Y axis, and the real component is the X > axis. abs(c) is defined as the distance from the origin complex(0, 0j) > or math.sqrt(c.real**2 + c.imag**2). I get it. Unfortunately, this still causes a sqrt to be performed (see below). > In any case, you're doing more computational work with abs or hypot > because they are the actual distance, not the distance**2. > > -bob Exactly. I don't need to determine absolute distances, just values good enough for comparison. Which is why I don't take a sqrt. I tried math.hypot, but it's slower than the straight multiplication & addition. --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From dyoo at hkn.eecs.berkeley.edu Fri Sep 12 16:54:23 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 12 16:54:29 2003 Subject: [Tutor] Fastest (x,y) distance calculation [complex numbers are points in 2d space] In-Reply-To: <2412.192.206.201.218.1063396902.squirrel@mail.harlekin-maus.com> Message-ID: On Fri, 12 Sep 2003, Zak Arntson wrote: > > [Raymond Hettinger] > >> > Distance calculations are much cheaper if you store the coordinates > >> > as complex numbers and use abs(). > > I don't know the concept behind using complex numbers and abs to > determine distance. How does that work? Hi Zak, Complex numbers can be plotted as if they were 2d points. This is actually one of the major ideas in math, and it's cool because it grounds complex numbers in something that most people are familiar with: the 2d cartesian plane. Just as regular numbers, like -3 and 3, can be plotted on a number line: <--.--+--.--> (-3) 0 (3) Complex numbers, like (3+1j) and (-3-1j), can be plotted on a cartesian graph: y ^ | . (3+1j) | <-----+----->x (-3-1j) | . | v When we look at complex numbers this way, the x axis stands for the first "real" component, and the y axis stands for the second "imaginary" component. So complex numbers aren't really so complex: you know about them already. *grin* The "absolute value" of a complex number is defined to be that number's distance from the "origin". Just as we can take the absolute value of normal everyday numbers: ### >>> abs(3) 3 >>> abs(-3) 3 ### we can also take the abs() of complex numbers: ### >>> abs(3+1j) 3.1622776601683795 >>> abs(-3-1j) 3.1622776601683795 ### and this, too, shows that abs() is the distance from (0,0). Another neat thing about complex numbers is that multiplying them has a real meaning: if we multiply one point by a complex number of length one, the end result is a rotation of that point! ### >>> unit = (0.707 + 0.707j) ## represents a 45 degree angle >>> abs(unit) 0.99984898859777815 ## ... well, close enough to one. ## *grin* >>> >>> >>> p = (1+1j) ## p represents the point (1,1) >>> >>> p * unit ## (1,1) is rotated along (0, 0) 1.4139999999999999j ## by 45 degrees! This shows that ## the rotated point is at (0, 1.414) >>> >>> p * unit * unit (-0.99969799999999986+0.99969799999999986j) >>> >>> p * unit * unit * unit >>> (-1.4135729719999997+0j) >>> >>> p * unit * unit * unit * unit (-0.99939609120399975-0.99939609120399975j) ### (Mathworld talks about how complex numbers are multiplied: http://mathworld.wolfram.com/ComplexMultiplication.html) Ok, there's a little bit of numerical inaccuracy showing up, but I hope the main ideas are clear. Hope this helps! From lost_bits1110 at hotmail.com Fri Sep 12 17:20:27 2003 From: lost_bits1110 at hotmail.com (bob green) Date: Fri Sep 12 17:20:34 2003 Subject: [Tutor] help.. just getting started Message-ID: HELLO I'm sorry but I am just getting started in using Python and VTK I am using WinXP I think I have python.. When I go to cmd and type python then I get a prompt like this: >>>> and when I type >>>>import Image etc etc then I get no errors so its all good... However, on the VTK home page I've downloaded all these examples and things so how do I compile and execute and view the source code of these examples...??? thanks... _________________________________________________________________ Get 10MB of e-mail storage! Sign up for Hotmail Extra Storage. http://join.msn.com/?PAGE=features/es From tbstep at tampabay.rr.com Fri Sep 12 17:40:34 2003 From: tbstep at tampabay.rr.com (Todd Stephens) Date: Fri Sep 12 17:45:06 2003 Subject: [Tutor] help.. just getting started In-Reply-To: References: Message-ID: <200309121740.34832.tbstep@tampabay.rr.com> On Friday 12 September 2003 05:20 pm, bob green wrote: > > However, on the VTK home page I've downloaded all these examples and > things so how do I compile and execute and view the source code of > these examples...??? > To view source, you'll need to open the file in a text editor. What you have been using is the interactive prompt. Good for writing short bits of code and testing, but not so useful for writing a program and saving it. -- Todd Stephens From missive at hotmail.com Fri Sep 12 17:46:16 2003 From: missive at hotmail.com (Lee Harr) Date: Fri Sep 12 17:46:26 2003 Subject: [Tutor] Re: for/else question Message-ID: for pattern in patternl: if elem.find(pattern) >-1: break else: backl.append(elem) To me, this says exactly the opposite of what it does... I read it as: "do something for every element in the list, otherwise, if I can't go through the entire list, do that." I suppose there may be times when this is the most concise way to write it, but I would never write it like this. _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From gabriel.cooper at mediapulse.com Fri Sep 12 18:20:02 2003 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Fri Sep 12 18:20:16 2003 Subject: [Tutor] for/else question In-Reply-To: References: <3F60FF30.2000108@mediapulse.com> Message-ID: <3F624692.30301@mediapulse.com> Michael Janssen wrote: >On Thu, 11 Sep 2003, Gabriel Cooper wrote: > > > >>So... yeah... Do /you/ use "else" with for loops? If so, when? >> >> > >some time ago it has really helped me out of an ugly function: > >def delpattern(inlist, patternl): > """clean inlist from entries with certain sub-strings""" > backl=[] > for elem in inlist: > for pattern in patternl: > if elem.find(pattern) >-1: > break > else: > backl.append(elem) > return backl > > >#without for-if-else it would be (under the assumption you don't want >#to investigate further to get some clever list-comprehension or reg-exp >#solution): > >def delpattern(inlist, patternl): > """clean inlist from entries with certain sub-strings""" > backl=[] > for elem in inlist: > found = 0 > for pattern in patternl: > if elem.find(pattern) >-1: > found = 1 > break # just to save time > if not found: > backl.append(elem) > return backl > >for-if-else seems much more readable (understandable) than >found-not-found to me. You have compared looking for something to doing >something. Here we're looking for something and only doing if not found. > >Michael > > > Hm... Still not convinced. Why not do it this way: def delpattern(inlist, patternl): list_copy = inlist[:] for p in patternl: for elem in inlist: if elem.find(p) > -1: list_copy.remove(elem) return list_copy From scot at possum.in-berlin.de Fri Sep 12 18:51:13 2003 From: scot at possum.in-berlin.de (Scot W. Stevenson) Date: Fri Sep 12 18:57:06 2003 Subject: [Tutor] Editors (vim and emacs and productivity) In-Reply-To: <3F5F02A8.7070003@epfl.ch> References: <3F5F02A8.7070003@epfl.ch> Message-ID: <200309122220.48074.scot@possum.in-berlin.de> Hi - > I always hear that vim and emacs are wonderful editors, and that when we > know it they enhance productivity without explaining why. I've used > emacs for some time, and I've tried without much succes to start using vi. > Could someone explain the features that make them enhance productivity > in such manner? I can tell you what does it for me with vim: I can type with all ten fingers (the result of a really, really boring week very, very long ago), and this makes using vim faster than any other editor where you constantly have to hit the CTRL or ALT-key or even (gasp!) use the mouse a lot. No other editor that I know of gives the touch-typist such a good deal. Using h-j-k-l to move the cursor around is strange for the first few days, but once you get the hang of it, not having to fumble for the arrow keys every time you want to switch a line is quite a relief. And it also makes playing Nethack on your laptop a lot easier... Then, you can use vim (and emacs) to edit just about every type of file around -- normal text, Python, C, LaTeX, XML, HTML, etc, etc. This means that you don't have to re-learn any funny special sequences, adjust widgets, etc. Because there are vi-clones for just about every operating system (this is true for emacs, too), this effect is even more pronounced: The very little serious stuff I do under Windows I can do with gvim, too, so I don't have to waste time there, either. If I remember correctly, my first experiences with vi were on the Atari ST. Vim vs. emacs is something of a Holy War topic with Linux, but basically, that is bull. Play around with both of them for a while, pick which ever one you get along with best, and then -- this is the important part -- stick with it. A lot of the productivity gains come from being able to use the editors at a sub-conscious level. Y, Scot -- How to quiet a crying baby with the X Window System: nice xlock -inwindow -mode kumppa Scot W. Stevenson - Zepernick, Germany From project5 at redrival.net Fri Sep 12 19:50:28 2003 From: project5 at redrival.net (Andrei) Date: Fri Sep 12 19:52:27 2003 Subject: [Tutor] Re: help.. just getting started In-Reply-To: References: Message-ID: Idle comes with an editor called Idle, look it up in your Python program group. If you don't like that one (I don't), you could look at PythonWin (Google for "win32all python") or Scite (google for that one too). bob green wrote: > HELLO > > I'm sorry but I am just getting started in using Python and VTK > > I am using WinXP > > I think I have python.. When I go to cmd and type python then I get a > prompt like this: > >>>>> > and when I type > >>>>> import Image > > etc etc then I get no errors so its all good... > > However, on the VTK home page I've downloaded all these examples and > things so how do I compile and execute and view the source code of these > examples...??? > > thanks... -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From python at rcn.com Fri Sep 12 20:06:17 2003 From: python at rcn.com (Raymond Hettinger) Date: Fri Sep 12 20:11:54 2003 Subject: [Tutor] Fastest (x,y) distance calculation References: <00cb01c378d7$0cea76a0$5234c797@oemcomputer> <2412.192.206.201.218.1063396902.squirrel@mail.harlekin-maus.com> Message-ID: <008b01c3798a$f75caec0$b439c797@oemcomputer> > I'm also considering creating some sort of data structure that aids in > nearest-point calculating. Any suggestions? Yes. Divide the world wap in to a n-by-n grid (perhaps with n=20); build a dictionary that mapping each intersection to a list of the closesest temples (with the farthest being no more than a grid step away from the nearest). Then you search goes something like this: def find_nearest_temple(self, pos): possibles = gridmapping[snap_to_grid(pos)] d, t = min([(abs(pos-temple.pos), temple) for temple in possibles]) return t In everyday language: the way to find the closest temple is to go the information booth at the center of your neighborhood and ask for list of the closest temples. Check each to see which one is closest to your house. If the temples are evenly distributed, you can gain a manyfold improvement in search time. Raymond Hettinger From glingl at aon.at Fri Sep 12 20:17:49 2003 From: glingl at aon.at (Gregor Lingl) Date: Fri Sep 12 20:19:33 2003 Subject: [Tutor] Again problem with PhotoImage Message-ID: <3F62622D.6030606@aon.at> Hi, I have a problem using PhotoImage, which I don't understand (and don't know how to solve or get around): I'm using Python 2.2 and IDLE, and I intend the program I develop to be used in this environment. I'll explain the problem with a tiny demo-script: from Tkinter import * root = Tk() cv = Canvas(root) cv.pack() pi = PhotoImage(file="huhn01.gif") cv.create_image(100,100,image=pi) When I run this (within IDLE 0.8, so no mainloop is needed) a canvas appears with a huhn-picture as expected. Now I don't close this window and run the program again. A second window opens, but, alas, the huhn-pic disappears from the first window, but doesn't appear in the new one. Instead I get the following error-message: Traceback (most recent call last): Traceback (most recent call last): File "C:/_/tdev/giftest02.py", line 7, in ? cv.create_image(100,100,image=pi) File "C:\Python22\lib\lib-tk\Tkinter.py", line 1973, in create_image return self._create('image', args, kw) File "C:\Python22\lib\lib-tk\Tkinter.py", line 1963, in _create (self._w, 'create', itemType) TclError: image "pyimage2" doesn't exist -----but----there IS an image-: >>> pi >>> I suppose, that this has to do with the fact that the program and IDLE is running in the same process and there is some clutter with the namespaces (for in Python 2.3 with IDLE 1.0 the first program will be killed before the second one is started - and there I have to use mainloop, which prevents me to interact with the canvas as long as then mainloop is running ...) ... and with some strange property of PhotoImage mentioned elsewhere, but I forgot where ... (Sorry) As I'd like to use the canvas interactively, for instance to move the image, I think I have to stick with IDLE 0.8 or use the -n-option of IDLE 1.0, which would make no difference, I think ... Is there a remedy? Gregor From zak at harlekin-maus.com Fri Sep 12 20:27:17 2003 From: zak at harlekin-maus.com (Zak Arntson) Date: Fri Sep 12 20:27:20 2003 Subject: [Tutor] Fastest (x,y) distance calculation In-Reply-To: <008b01c3798a$f75caec0$b439c797@oemcomputer> References: <00cb01c378d7$0cea76a0$5234c797@oemcomputer> <2412.192.206.201.218.1063396902.squirrel@mail.harlekin-maus.com> <008b01c3798a$f75caec0$b439c797@oemcomputer> Message-ID: <3773.192.206.201.218.1063412837.squirrel@mail.harlekin-maus.com> > Yes. > > Divide the world wap in to a n-by-n grid (perhaps with n=20); > build a dictionary that mapping each intersection to a list of the > closesest temples (with the farthest being no more than a grid > step away from the nearest). > > Raymond Hettinger I was considering this for the Temples. It's a great idea, because the Temples don't move. I'm also planning on implementing the Mover objects being able to find the closest Mover object. I may try to do something similar with those, but I'm not sure what performance would be like, with the grid being updated constantly by moving objects. I hadn't imaged exactly how it would work, though. Thanks! BSP Trees have also been suggested to me, and I'm still studying up on them. I may finish this project and use BSP's on the next one, so I can better figure them out. --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From madz_15220 at yahoo.com Fri Sep 12 22:49:38 2003 From: madz_15220 at yahoo.com (madelene ferrer) Date: Fri Sep 12 22:49:42 2003 Subject: [Tutor] python Message-ID: <20030913024938.28353.qmail@web11104.mail.yahoo.com> My boss asked me to do some research on PYTHON and suggested on learning it. Where do you think should I start. Where and what book can you suggest that I can read that will help me to learn PYTHON. What programming language do you think should I know prior to learning PYTHON. Thanks .. Madelene --------------------------------- Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030912/955bceca/attachment.html From tbstep at tampabay.rr.com Fri Sep 12 22:49:38 2003 From: tbstep at tampabay.rr.com (Todd Stephens) Date: Fri Sep 12 22:54:07 2003 Subject: [Tutor] python In-Reply-To: <20030913024938.28353.qmail@web11104.mail.yahoo.com> References: <20030913024938.28353.qmail@web11104.mail.yahoo.com> Message-ID: <200309122249.38507.tbstep@tampabay.rr.com> On Friday 12 September 2003 10:49 pm, madelene ferrer wrote: > My boss asked me to do some research on PYTHON and suggested on > learning it. Where do you think should I start. Where and what book > can you suggest that I can read that will help me to learn PYTHON. > What programming language do you think should I know prior to > learning PYTHON. > The first and best place to look for information is at www.python.org. You can find many good suggestions on books there as well. As far as knowing another language prior to Python, it is not necessary. Python is actually a great language to start out with. Good luck. -- Todd Stephens From idiot1 at netzero.net Sat Sep 13 02:23:17 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sat Sep 13 02:22:53 2003 Subject: [Tutor] state machines Message-ID: <3F62B7D5.8050909@netzero.net> I am working on a wiki for windows, and this time I want to whack at state machines, and I am using a bit of recursion in it. Here is some code: # wordscanner routine # reset the linepointer we will use it again... for line in page: # see? wordcounter=0 # wordlist = string.split(line,' ') # split the line for word in wordlist: if isin(word,'http://'): # if is hyperlink: if isin(word,'"'): # DO NOT process "http pass # DO NOT process; else: # otherwise, wordlist[wordcounter]='' + word + '' # ware word wrap!!! else: OK, it's not an external link, test 4 wikiword... if iswikiword(word): wordlist[wordcounter]=makewikiword(word) else: pass # leave word alone wordcounter=wordcounter+1 line=string.join(wordlist,' ') page[linecounter]=line linecounter=linecounter+1 # ok, here are some relevant definitions: def iswikiword(word): # Tests to see if a word is a wikiword if word: if word[0] in string.ascii_letters: # must be a letter! return result=isfirstuppercase(word[1:]) # first rule: letters only else: return 0 # word with any nonletter in it is not wikiword. else: return 0 # second rule: no null words. # def isfirstlowercase: if word: if word[0] in string.ascii_lowercase: # if it spins around here, it isfirstlowerercase(word[1:]) # is NOT a wikiword! return 0! else: isuppercase(word[1:]) else: return 0 # def isfirstuppercase(word): if word: # a string of any size is a logical 1 if word[0] in string.ascii_uppercase: return isfirstlowercase(word[1:]) else: return 0 else: return 0 # def isuppercase(word): if word: if word[0] in string.ascii.uppercase: return islowercase(word[1:]) else: return 0 else: return 0 # def islowercase(word): if word: if word[0] in string.ascii_lowercase: return 1 else: return 0 # still working on it. -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From idiot1 at netzero.net Sat Sep 13 02:32:22 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sat Sep 13 02:31:59 2003 Subject: [Tutor] python In-Reply-To: <20030913024938.28353.qmail@web11104.mail.yahoo.com> References: <20030913024938.28353.qmail@web11104.mail.yahoo.com> Message-ID: <3F62B9F6.9040107@netzero.net> None, just dive right in! Books: Learning python if you only purchase one. And stay tuned to this list. madelene ferrer wrote: > My boss asked me to do some research on PYTHON and suggested on learning > it. Where do you think should I start. Where and what book can you > suggest that I can read that will help me to learn PYTHON. What > programming language do you think should I know prior to learning PYTHON. > > Thanks .. > Madelene > > ------------------------------------------------------------------------ > Do you Yahoo!? > Yahoo! SiteBuilder > - Free, > easy-to-use web site design software > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From alan.gauld at blueyonder.co.uk Sat Sep 13 04:05:56 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Sep 13 04:05:23 2003 Subject: [Tutor] help.. just getting started References: Message-ID: <038b01c379cd$dc075330$6401a8c0@xp> > I think I have python.. When I go to cmd and type python then I get a prompt > like this: > >>>> > and when I type > >>>>import Image > etc etc then I get no errors so its all good... Yes that's Python working in interactive mode so you can type commands in and try things out. > However, on the VTK home page I've downloaded all these examples and things > so how do I compile and execute and view the source code of these > examples...??? You need to type the code into a new file (in Notepad or some other text editor) and make the file extension .py. Then you can just click the file in explorer and it will run under python. Alternatively you can run it from the cmd box by typing: C:\WINDOWS> python myfile.py And if it runs too quickly to see the output you can run it as: C:\WINDOWS> python -i myfile.py which will run the program and leave the python >>> prompt. That way you will see the final screenful of output at least! (This also makes it easy to check the values of variables etc at the end of your program if things don't work quite as expected!) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From suzuki at despammed.com Sat Sep 13 04:09:05 2003 From: suzuki at despammed.com (e y suzuki) Date: Sat Sep 13 04:09:14 2003 Subject: [Tutor] python In-Reply-To: Your message of "Fri, 12 Sep 2003 19:49:38 -0700." Message-ID: <200309130809.h8D895Od080508@soda.csua.berkeley.edu> > Where do you think should I start. Where and what book can you suggest that I can read > that will help me to learn PYTHON. i started learning python with the book, _the quick python book_ (harms/mcdonald). it's a decent book, if you don't mind the gazillion typos in there and have a bit of programming experience. i recently discovered the book, _how to think like a computer scientist: learning with python_ (downey). i've read a lot of it, and i think that it's a good beginner's book -- flows nicely, easy to understand, definitions provided. there is a free online copy in pdf/postscript format you can print out and use: http://www.greenteapress.com/thinkpython/ this and other python books are listed at the python.org website: http://www.python.org/cgi-bin/moinmoin/PythonBooks you may find the beginner's guide/index of resources at the python.org site useful: http://www.python.org/topics/learn/ -e. y. suzuki From spiritelllo at interfree.it Sat Sep 13 12:19:55 2003 From: spiritelllo at interfree.it (Andrea Spitaleri) Date: Sat Sep 13 12:37:41 2003 Subject: [Tutor] recursive? Message-ID: <3F6343AB.2090908@interfree.it> Hiya boys ;-) my first post: # andrea import math print "******************************************************************" print "Hi this is a test to resolve 2nd equation" print "******************************************************************" print "tell me the values for a, b and c of the equation ax^2+bx+c=0" a=input('a:') b=input('b:') c=input('c:') if b**2 - 4*(a*c) < 0: print "il risultato sono valori complessi" # with import cmath and cmath.sqrt you can get complex numbers q=raw_input("Do you want try again?") if q == 'y': #without ' ' you get error else: print 'bye' else: print " x1 =", ((-b/2)+(math.sqrt(((b**2)/4)-a*c)))/a, "and x2 =", ((-b/2)-(math.sqrt(((b**2)/4)-a*c)))/a that small silly program works but I would like to insert another condition. after typing y after 'do you want try again?' how I can start again all the program, asking again the three values? thanks andrea From carroll at tjc.com Sat Sep 13 13:33:41 2003 From: carroll at tjc.com (Terry Carroll) Date: Sat Sep 13 13:33:45 2003 Subject: [Tutor] range() or xrange() for non-integers? Message-ID: I found myself needing something like this: for x in xrange(-4.0, 4.0, 0.5): print x (The print line will, of course, in practice, be something more useful.) I found that xrange (and range) do not work except with integers. What's the pythonic way to do this, under 2.2? I ended up doing this, which seems more fortranic than pythonic: start = -4.0 end = 4.0 step = 0.5 x = start while x <= end: print x x += step [ yeah, I know, using < rather than <= would be the actual equivalent, but <= is actually what I need. ] -- Terry Carroll | "I say to you that the VCR is to the American Santa Clara, CA | film producer and the American public as the carroll@tjc.com | Boston strangler is to the woman home alone." | Jack Valenti, MPAA President Modell delendus est | Testimony before Congress, 1982 From bgailer at alum.rpi.edu Sat Sep 13 13:36:01 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Sep 13 13:38:05 2003 Subject: [Tutor] range() or xrange() for non-integers? In-Reply-To: References: Message-ID: <6.0.0.22.0.20030913113259.035a1880@66.28.54.253> At 11:33 AM 9/13/2003, Terry Carroll wrote: >I found myself needing something like this: > > for x in xrange(-4.0, 4.0, 0.5): > print x > >(The print line will, of course, in practice, be something more useful.) > > >I found that xrange (and range) do not work except with integers. > >What's the pythonic way to do this, under 2.2? Probably several ways. One is: from __future__ import division for x in xrange(-8.0, 8.0, 1.0): print x/2 Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From alan.gauld at blueyonder.co.uk Sat Sep 13 13:56:28 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Sep 13 13:55:42 2003 Subject: [Tutor] python References: <200309130809.h8D895Od080508@soda.csua.berkeley.edu> Message-ID: <03b201c37a20$5b7dd060$6401a8c0@xp> > you may find the beginner's guide/index of resources at the python.org site > useful: > http://www.python.org/topics/learn/ And specifically for those new to programmers: http://www.python.org/topics/learn/non-prog.html Where you will find several tutorials explicitly aimed at total beginners (including my own). They all have their own style, pick one, try it, if it doesn't seem to be making sense to you then try one of the others. Once you find one that gels with you, stick with it and post specific questions to this list. It helps if you send the code and any error messages because then we can see exactly whats happening. Finally, is there a specific reason for you learning to program? That is, does your boss habve some jkind of project in mind for you? That kind of context can help us frame suitable replies and examples for you. Good luck, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From carroll at tjc.com Sat Sep 13 14:15:39 2003 From: carroll at tjc.com (Terry Carroll) Date: Sat Sep 13 14:15:43 2003 Subject: [Tutor] range() or xrange() for non-integers? In-Reply-To: <6.0.0.22.0.20030913113259.035a1880@66.28.54.253> Message-ID: On Sat, 13 Sep 2003, Bob Gailer wrote: > for x in xrange(-8.0, 8.0, 1.0): > print x/2 Thanks. I'd thought of something along those lines, but that seems even worse for my particular application. I was going to need to vary the step to find the optimal one. (The actual application is to generate points to graph the x-component of electrical field generated by two particles.) So My first cut might be varying by .5, another by .1, etc. To have to vary by 1 and change the start and end points and an inner divisor to compensate seems very kludgy to me. -- Terry Carroll | "I say to you that the VCR is to the American Santa Clara, CA | film producer and the American public as the carroll@tjc.com | Boston strangler is to the woman home alone." | Jack Valenti, MPAA President Modell delendus est | Testimony before Congress, 1982 From idiot1 at netzero.net Sat Sep 13 15:01:22 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sat Sep 13 15:01:05 2003 Subject: [Tutor] toot! Toot! Message-ID: <3F636982.80205@netzero.net> Tooting my own horn a little. The new miniwiki works. on my pc, in windows, using the server script to serve it locally. Give me a few hours to toss it together, then download it from this link: Anyone intrested, this thing is using some recursion and may have parts qualify as state engines- no counting. It's smaller than wikinehesa, and is written EXPRESSLY to run under windows 9X or NT or 2000, and be served locally by a server. -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From alex at gabuzomeu.net Sat Sep 13 15:08:21 2003 From: alex at gabuzomeu.net (Alexandre Ratti) Date: Sat Sep 13 15:08:52 2003 Subject: [Tutor] recursive? In-Reply-To: <3F6343AB.2090908@interfree.it> References: <3F6343AB.2090908@interfree.it> Message-ID: <3F636B25.8020509@gabuzomeu.net> Hello Andrea, Andrea Spitaleri wrote: > q=raw_input("Do you want try again?") > if q == 'y': #without ' ' you get error > else: > print 'bye' > else: > that small silly program works but I would like to insert another > condition. after typing y after 'do you want try again?' how I can start > again all the program, asking again the three values? You can wrap your program in this kind of structure: >>> while 1: ... q = raw_input("Do you want try again? (y/n)") ... if q == 'n': ... break ... # run your program here Basically, the program runs in an endless loop, since the "while 1" condition is always true. It will run until the user chooses "n" to break out of the loop. Cheers. Alexandre From dyoo at hkn.eecs.berkeley.edu Sat Sep 13 16:14:45 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Sep 13 16:14:52 2003 Subject: [Tutor] recursive? [functions, main loop] In-Reply-To: <3F636B25.8020509@gabuzomeu.net> Message-ID: > > q=raw_input("Do you want try again?") > > if q == 'y': #without ' ' you get error [code cut] > > that small silly program works but I would like to insert another > > condition. after typing y after 'do you want try again?' how I can > > start again all the program, asking again the three values? > > You can wrap your program in this kind of structure: > > >>> while 1: > ... q = raw_input("Do you want try again? (y/n)") > ... if q == 'n': > ... break > ... # run your program here Hello! We can also wrap things a little more, by putting the core of our program in a separate 'function'. For example, the code below: ### def main_loop(): while 1: run_program() if raw_input("Try again? (y/n)") == 'n': break def run_program(): name = raw_input("Enter a name: ") print "Hello", name main_loop() ### shows how we can bundle things together in these functions. It makes it easier to call the whole bundled group by saying the single word "run_program()". Hope this helps! From idiot1 at netzero.net Sat Sep 13 20:33:47 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sat Sep 13 20:33:49 2003 Subject: [Tutor] miniwiki is ready for your personal (ab)use Message-ID: <3F63B76B.7070802@netzero.net> The ZIP FILE is ready. It is on the tinylist.org site. Because it is a windows confogured suite, and my server is FreeBSD, it is not available online- and as there is no security built into it, it never will be. But you can download it and have some fun with it. IT comes with the server script preconfigured for port 8080, all you have to do is unpack it in c:\Python22, create the folder 'text' and 'images', place the pages in 'text' and any images you want to use in 'images', and run with it. Think I'll take the rest of the weekend off and watch TV or something. http://www.tinylist.org/miniwiki100.zip -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From jonathan.hayward at pobox.com Sat Sep 13 21:33:08 2003 From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com) Date: Sat Sep 13 21:33:12 2003 Subject: [Tutor] Memory optimization needed: tarball Message-ID: <3F63C554.1050108@pobox.com> I have a search engine I'm working on which uses memory inefficiently for large data. It indexes to avoid the cost of keeping documents in memory, but with a 150M dataset it takes 250M. Unlike previous requests where I didn't provide a good way to use it, I now have a tarball with installer: http://haywardfamily.org/jonathan/datamine0_0.tar.gz I would welcome help cutting down memory taken by large datasets. Thanks in advance, -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From learning.python at dbmail.dk Sat Sep 13 23:53:35 2003 From: learning.python at dbmail.dk (Ole Jensen) Date: Sat Sep 13 23:54:40 2003 Subject: [Tutor] recursive? References: <3F6343AB.2090908@interfree.it> Message-ID: <002101c37a73$c5fb6300$a64c73d5@BAERBAR> > condition. after typing y after 'do you want try again?' how I can start > again all the program, asking again the three values? When you want to do the same thing over and over agian, you need to tell the computer to *loop* through that code. I'ld suggest you read up on it in some online tutorials, personally I'll recomend Josh Cogliati's online tutorial, you can find it here: http://www.honors.montana.edu/~jjc/easytut/easytut/ But I'm gonna give you a tip more as an example of what you might want to do: >>> again = 1 # We need a value to start the loop. >>> while again == 1: # While 'again' is one keep redoing the indented part print "Add two numbers" a = input("State the 1'st number: ") b = input("State the 2'nd number: ") print "The sum is:", a+b again = input("Press '1' to keep on adding") # if not then press # something else! Bye for now Ol? From kuros at sbcglobal.net Sat Sep 13 23:57:45 2003 From: kuros at sbcglobal.net (Kuros) Date: Sat Sep 13 23:56:20 2003 Subject: [Tutor] python References: <200309130809.h8D895Od080508@soda.csua.berkeley.edu> <03b201c37a20$5b7dd060$6401a8c0@xp> Message-ID: <002d01c37a74$5b65d060$9865fea9@Malkil> Core Python Programming is an excellent book, in my opinion. It covers all the basics, and a bit of the more advanced stuff, such as sockets, threads, and cgi stuff. It starts from the groundup. Python in a Nutshell from O'Rielly is also very good. I have those two books, and I have yet to find a topic I can't find covered in one or the other. Its a reference book, not a tutorial style, but once you work through the Core book it should make sense to you. Good luck, Kuros ----- Original Message ----- From: "Alan Gauld" To: "e y suzuki" ; Sent: Saturday, September 13, 2003 12:56 PM Subject: Re: [Tutor] python > > you may find the beginner's guide/index of resources at the > python.org site > > useful: > > http://www.python.org/topics/learn/ > > And specifically for those new to programmers: > > http://www.python.org/topics/learn/non-prog.html > > Where you will find several tutorials explicitly aimed at > total beginners (including my own). They all have their own > style, pick one, try it, if it doesn't seem to be making > sense to you then try one of the others. Once you find > one that gels with you, stick with it and post specific > questions to this list. > > It helps if you send the code and any error messages > because then we can see exactly whats happening. > > Finally, is there a specific reason for you learning to > program? That is, does your boss habve some jkind of project > in mind for you? That kind of context can help us frame > suitable replies and examples for you. > > Good luck, > > 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 peterabrown at froggy.com.au Sun Sep 14 08:20:40 2003 From: peterabrown at froggy.com.au (Peter Brown) Date: Sun Sep 14 08:21:27 2003 Subject: [Tutor] Permissions Problem with Python Message-ID: <3.0.6.32.20030914222040.00b5c5d0@mail.froggy.com.au> Hope someone can help. For several days I have been trying to solve what I believe is a permissions problem. I have written several programs to update a postgresql database. When I try to run these programs by executing a python file say foo.py in the current RedHat 9 linux directory it says Permission denied or no such file or directory. As user postgres, I can start Postgresql manually and enter python interpreter and open, create tables and select and insert data manually. Also I can import any of these python files say create_tables.py into python command line and it executes the program fine. I have the following line at the start of create_table.py - #! /usr/bin/env python. I wish to be able to execute these python programs from crontab. Any help would be much appreciated. Peter From sandip at linux-delhi.org Sun Sep 14 08:37:03 2003 From: sandip at linux-delhi.org (Sandip Bhattacharya) Date: Sun Sep 14 08:38:04 2003 Subject: [Tutor] Re: Permissions Problem with Python In-Reply-To: <3.0.6.32.20030914222040.00b5c5d0@mail.froggy.com.au> References: <3.0.6.32.20030914222040.00b5c5d0@mail.froggy.com.au> Message-ID: <20030914123703.GA3964@pluto.home> +++ Peter Brown [14/09/03 22:20 +1000]: > I have written several programs to update a postgresql database. When I try > to run these programs by executing a python file say foo.py in the current > RedHat 9 linux directory it says Permission denied or no such file or > directory. Umm. Dumb questions first - Have you made the file executable? Is python installed? - Sandip -- Sandip Bhattacharya http://www.sandipb.net sandip at puroga.com Puroga Technologies Pvt. Ltd. http://www.puroga.com From tbstep at tampabay.rr.com Sun Sep 14 09:12:24 2003 From: tbstep at tampabay.rr.com (Todd Stephens) Date: Sun Sep 14 09:16:53 2003 Subject: [Tutor] Permissions Problem with Python In-Reply-To: <3.0.6.32.20030914222040.00b5c5d0@mail.froggy.com.au> References: <3.0.6.32.20030914222040.00b5c5d0@mail.froggy.com.au> Message-ID: <200309140912.24814.tbstep@tampabay.rr.com> On Sunday 14 September 2003 08:20 am, Peter Brown wrote: > I have the following line at the start of create_table.py - #! > /usr/bin/env python. Here's the "d'oh!" question: Have you made this file executable? Chmod 755 or 555 on that file. Also, if the file is not located in a directory in your path, you'll need to prefix the file name with its own path. If the file is in your home directory, you could not execute it just by #foo.py, you would have to say #~/foo.py. -- Todd Stephens ICQ# 3150790 From project5 at redrival.net Sun Sep 14 10:09:02 2003 From: project5 at redrival.net (Andrei) Date: Sun Sep 14 10:11:03 2003 Subject: [Tutor] Re: range() or xrange() for non-integers? In-Reply-To: References: <6.0.0.22.0.20030913113259.035a1880@66.28.54.253> Message-ID: Terry Carroll wrote: > On Sat, 13 Sep 2003, Bob Gailer wrote: > > >>for x in xrange(-8.0, 8.0, 1.0): >> print x/2 > > > Thanks. > > I'd thought of something along those lines, but that seems even worse for > my particular application. I was going to need to vary the step to find > the optimal one. (The actual application is to generate points to graph > the x-component of electrical field generated by two particles.) So My > first cut might be varying by .5, another by .1, etc. To have to vary by > 1 and change the start and end points and an inner divisor to compensate > seems very kludgy to me. Why don't you just build your own rangef() function which returns a list? >>> def rangef(min, max, step): ... result = [] ... while 1: ... result.append(min) ... min = min+step ... if min>=max: ... break ... return result ... >>> rangef(2,3,.2) [2, 2.2000000000000002, 2.4000000000000004, 2.6000000000000005, 2.8000000000000007] If desired, you can add some parameter checking routines so that min0 or whatever you need. You could also do (with a generator): >>> def rangef(min=1, max=2, step=.2): ... while min>> for item in rangef(3, 5, .3): ... print item ... 3 3.3 3.6 3.9 4.2 4.5 4.8 -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From t0ny1 at knology.net Sun Sep 14 10:13:51 2003 From: t0ny1 at knology.net (Anthony Huddleston) Date: Sun Sep 14 10:13:58 2003 Subject: [Tutor] Beginner @ python Message-ID: <000c01c37aca$6e0771f0$6401a8c0@HUTTFAMILY> Ok, Silly questions here...:) I started learning Python just the other day, mostly because my nephew (11yrs old) wants to learn to be a programmer. I like the language and the way it flows, but so far I haven't seen anything, that I'm aware of, that was written for Windows in Python (i.e. I haven't seen any executable Windows programs *.exe). Is that because people "port" programs over to the Microsoft OS or does Python always need to have the interpreter installed on the machine it's on? Thanks, Tony H. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030914/96e5771a/attachment.html From erikprice at mac.com Sun Sep 14 10:45:50 2003 From: erikprice at mac.com (Erik Price) Date: Sun Sep 14 10:24:50 2003 Subject: [Tutor] for/else question In-Reply-To: <0E5508EBA1620743B409A2B8365DE16FDC87D3@sovereign.ci.las-vegas.nv.us> Message-ID: <2282D02B-E6C2-11D7-9ABF-00039351FE6A@mac.com> On Friday, September 12, 2003, at 11:48 AM, Scott Widney wrote: > It just doesn't fit. But there is a term in another statement in > Python that > seems closer to what I'm thinking: > > Try: > something that might not work; > if it fails: > do this; > finally (whether or not it worked): > do this too. > > This "feels" more comfortable. Finally and afterwards are semantic > neighbors. So if I think 'finally' in my head, but type 'else' when > dealing > with a for statement, it seems to relieve the pressure. And now we > return to > our regularly scheduled program.... Yeah, "finally" would have been a much better token to use here. Erik From erikprice at mac.com Sun Sep 14 10:57:11 2003 From: erikprice at mac.com (Erik Price) Date: Sun Sep 14 10:36:02 2003 Subject: [Tutor] python In-Reply-To: <200309130809.h8D895Od080508@soda.csua.berkeley.edu> Message-ID: On Saturday, September 13, 2003, at 04:09 AM, e y suzuki wrote: > i started learning python with the book, _the quick python book_ > (harms/mcdonald). > it's a decent book, if you don't mind the gazillion typos in there and > have a bit > of programming experience. I learned Python from this book too but I second the idea that you should have a bit of programming experience, and it's also quite out of date. If you are a seasoned programmer, then "Python in a Nutshell" is the definitive (and nearly up-to-date) guide. If no programming experience, go for the online tutorials for non-programmers mentioned at the python.org web site. And unquestionably this list is the best place for a beginner to be, so you can ask questions when you run across them. Erik From guillermo.fernandez at epfl.ch Sun Sep 14 10:48:54 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez) Date: Sun Sep 14 10:48:58 2003 Subject: [Tutor] Problem with environement variables in Windows XP Message-ID: <3F647FD6.9020703@epfl.ch> Hi, First of all, thanks to all of those who answered me for the productivity question. I'll try both editors and choose the one who fits me best :-) I'm working under Windows XP, python 2.2.1 and I'm trying to find a user's home directory. I have this problem when I use the python interpreter: >>> import os.path >>> os.path.expanduser('~') '%USERPROFILE%' >>> os.path.expandvars(os.path.expanduser('~')) '%USERPROFILE%' But when I work with DOS prompt the variable %USERPROFILE% is well identified: > echo %USERPROFILE% C:\Documents and Settings\guille I had a look to the documentation and I did not find my mistake. What i'm doing wrong? Thanks! Guille From missive at hotmail.com Sun Sep 14 10:49:32 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Sep 14 10:49:36 2003 Subject: [Tutor] Re: Permissions Problem with Python Message-ID: >I have the following line at the start of create_table.py - >#!/usr/bin/env python. > >I wish to be able to execute these python programs from crontab. > It is probably not a python problem, but a cron problem. When you run things from cron, then environment (that which is referred to by the /usr/bin/env program above) is different from the environment when you are just manually running the program. In your crontab, try something like ... /usr/local/bin/python /home/lee/bin/update_pgsql.py In other words, use absolute paths for everything. _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From alex at gabuzomeu.net Sun Sep 14 10:54:58 2003 From: alex at gabuzomeu.net (Alexandre Ratti) Date: Sun Sep 14 10:55:25 2003 Subject: [Tutor] Beginner @ python In-Reply-To: <000c01c37aca$6e0771f0$6401a8c0@HUTTFAMILY> References: <000c01c37aca$6e0771f0$6401a8c0@HUTTFAMILY> Message-ID: <3F648142.6000402@gabuzomeu.net> Hello Tony, Anthony Huddleston wrote: > I started learning Python just the other day, mostly because my nephew > (11yrs old) wants to learn to be a programmer. I like the language and > the way it flows, but so far I haven't seen anything, that I'm aware of, > that was written for Windows in Python Actually, Python scripts are cross-platform. I.e. you can run them on Windows, Linux, and many other systems. > (i.e. I haven't seen any > executable Windows programs *.exe). Is that because people "port" > programs over to the Microsoft OS or does Python always need to have the > interpreter installed on the machine it's on? Yes, people usually need to have the interpreter installed on their computer to run Python scripts. You can also freeze a script and its runtime files into a exe file. See the "py2exe" tool for instance: http://starship.python.net/crew/theller/py2exe/ Cheers. Alexandre From jerry at j3iss.com Sun Sep 14 11:20:02 2003 From: jerry at j3iss.com (Jerry Jorgenson) Date: Sun Sep 14 11:20:17 2003 Subject: [Tutor] Beginner @ python In-Reply-To: <000c01c37aca$6e0771f0$6401a8c0@HUTTFAMILY> References: <000c01c37aca$6e0771f0$6401a8c0@HUTTFAMILY> Message-ID: <20030914102002.63a2e72d.jerry@j3iss.com> On Sun, 14 Sep 2003 09:13:51 -0500 "Anthony Huddleston" wrote: > Ok, Silly questions here...:) > I started learning Python just the other day, mostly because my nephew > (11yrs old) wants to learn to be a programmer. I like the language and > the way it flows, but so far I haven't seen anything, that I'm aware of, > that was written for Windows in Python (i.e. I haven't seen any > executable Windows programs *.exe). Is that because people "port" > programs over to the Microsoft OS or does Python always need to have the > interpreter installed on the machine it's on? Thanks, > Tony H. Hi Tony, Python is a scripting language, not a compiled language (only compiled languages create .exe binary files. There are three major kinds of languages (in very simplistic terms--no flames on this please): interpretive, tokenized, and compiled: Interpretive: The parser sees an instruction in the source code and executes it. Think of this as having a set of keys on a key ring and a series of doors to go through. When you come to a door, you search though the ring to find the key, you repeat this step at the next door. This obviously takes time to do. Basic is an example of this kind of language. Pros: simple structure, few lines of code. Cons: slow speed. Mostly used for simple start-up jobs (programs that start other programs). Complied: The executable is already in a format that is machine readable. In this case your set of keys is already in the order of the doors you will encouter, so you only have to go to the next key and turn the lock. This requires a compile step when creating the program. C, FORTRAN, COBOL are examples of this kind of language. Pros: High execution speed, anything can be coded, source code confidentiality. Cons: more work to program, more lines of code, a separate compile step. Used for large production programs, device drivers, kernels and other low level stuff. Tokenized: The parser first compiles the source code at each execution (creates tokens), and then runs the program (to answer your question--yes Python needs to be installed on the machine where the program runs). This slows the start-up, but then executes very fast, often it's hard to distinguish the speed between the compiled program and the tokenized program. Python, Ruby, and Perl are examples of this kind of language. Pros: Fewer lines of code, good to high speed. Cons: More overhead at the start of execution, there is a compile step, but it's not a separate step, works best at the tasks is was designed for. Used for start-up jobs, text parsing, and system adminstration, prototyping. Jerry -- Jerry Jorgenson jerry@j3iss.com http://www.j3iss.com/ From learning.python at dbmail.dk Sun Sep 14 11:46:05 2003 From: learning.python at dbmail.dk (Ole Jensen) Date: Sun Sep 14 11:47:13 2003 Subject: [Tutor] THE CGI SERVER SCRIPT References: <3F5BE41C.9080702@netzero.net> <000901c3762e$44273820$a24c73d5@BAERBAR> <3F5D5F0C.4010204@netzero.net> Message-ID: <003501c37ad7$4f730080$8d4c73d5@BAERBAR> Concerning the before mentioned cgi script by Steve Holden and Kirk Bailey, well I've now tried to experiment with it but I didn't get very far! As a matter of fact I was not even able to run the server, I get a traceback saying it can't find a a/some module(s). This is the the traceback: Traceback (most recent call last): File "C:\Programmer\python\cgi.py", line 2, in ? import CGIHTTPServer, BaseHTTPServer File "C:\PROGRA~1\python\lib\CGIHTTPServer.py", line 28, in ? import SimpleHTTPServer File "C:\PROGRA~1\python\lib\SimpleHTTPServer.py", line 17, in ? import cgi File "C:\Programmer\python\cgi.py", line 3, in ? httpd=BaseHTTPServer.HTTPServer(('',8080), CGIHTTPServer.CGIHTTPRequestHandler) AttributeError: 'module' object has no attribute 'CGIHTTPRequestHandler' Traceback (most recent call last): File "C:\Programmer\python\cgi.py", line 3, in ? httpd=BaseHTTPServer.HTTPServer(('',80), CGIHTTPServer.CGIHTTPRequestHandler) AttributeError: 'module' object has no attribute 'CGIHTTPRequestHandler' Quite alot actually (compared to what I'm used for), I can't say that I fully undstand it, but the way I understand it the error is in the imported modules (is that possible!!!) I use Python 2.2.3 on WinXP, if that matters. The only changes I made to the cgi script was adjusting the libray info in the first line, and the port number to 8080 (which I did try to set to 80, afterwards). The file has been placed in the (root) python library (next to python.exe etc). I've never been working with cgi-script, let alone setting up cgi servers on my PC, so I don't really know it is something I've done wrong as it sounded like Kirk got it up and running. I am looking forward to any replies/solutions. Ol? Below is the cgi code: #!C:\Programmer\python\pythonw.exe import CGIHTTPServer, BaseHTTPServer httpd=BaseHTTPServer.HTTPServer(('',80), CGIHTTPServer.CGIHTTPRequestHandler) httpd.serve_forever() From learning.python at dbmail.dk Sun Sep 14 11:54:15 2003 From: learning.python at dbmail.dk (Ole Jensen) Date: Sun Sep 14 11:55:19 2003 Subject: [Tutor] THE CGI SERVER SCRIPT References: <3F5BE41C.9080702@netzero.net><000901c3762e$44273820$a24c73d5@BAERBAR><3F5D5F0C.4010204@netzero.net> <003501c37ad7$4f730080$8d4c73d5@BAERBAR> Message-ID: <004001c37ad8$73373b70$8d4c73d5@BAERBAR> Hmm I just reran the program a final (two) times and the traceback now changed to this: Traceback (most recent call last): File "C:\Programmer\python\cgi.py", line 3, in ? httpd=BaseHTTPServer.HTTPServer(('',80), CGIHTTPServer.CGIHTTPRequestHandler) AttributeError: 'module' object has no attribute 'CGIHTTPRequestHandler' which is basically the same as the last trhough lines before... It still doesn't help me though, but for any of you saints out there there is less traceback to read. ----- Original Message ----- From: "Ole Jensen" To: "Kirk Bailey" ; "Tutor" Sent: Sunday, September 14, 2003 5:46 PM Subject: [Tutor] THE CGI SERVER SCRIPT > Concerning the before mentioned cgi script by Steve Holden and Kirk Bailey, > well I've now tried to experiment with it but I didn't get very far! > > As a matter of fact I was not even able to run the server, I get a traceback > saying it can't find a a/some module(s). > > This is the the traceback: > Traceback (most recent call last): > File "C:\Programmer\python\cgi.py", line 2, in ? > import CGIHTTPServer, BaseHTTPServer > File "C:\PROGRA~1\python\lib\CGIHTTPServer.py", line 28, in ? > import SimpleHTTPServer > File "C:\PROGRA~1\python\lib\SimpleHTTPServer.py", line 17, in ? > import cgi > File "C:\Programmer\python\cgi.py", line 3, in ? > httpd=BaseHTTPServer.HTTPServer(('',8080), > CGIHTTPServer.CGIHTTPRequestHandler) > AttributeError: 'module' object has no attribute 'CGIHTTPRequestHandler' > Traceback (most recent call last): > File "C:\Programmer\python\cgi.py", line 3, in ? > httpd=BaseHTTPServer.HTTPServer(('',80), > CGIHTTPServer.CGIHTTPRequestHandler) > AttributeError: 'module' object has no attribute 'CGIHTTPRequestHandler' > > Quite alot actually (compared to what I'm used for), I can't say that I > fully undstand it, but the way I understand it the error is in the imported > modules (is that possible!!!) > > I use Python 2.2.3 on WinXP, if that matters. > The only changes I made to the cgi script was adjusting the libray info in > the first line, and the port number to 8080 (which I did try to set to 80, > afterwards). > > The file has been placed in the (root) python library (next to python.exe > etc). > > I've never been working with cgi-script, let alone setting up cgi servers on > my PC, so I don't really know it is something I've done wrong as it sounded > like Kirk got it up and running. > > I am looking forward to any replies/solutions. > Ol? > > Below is the cgi code: > #!C:\Programmer\python\pythonw.exe > import CGIHTTPServer, BaseHTTPServer > httpd=BaseHTTPServer.HTTPServer(('',80), > CGIHTTPServer.CGIHTTPRequestHandler) > httpd.serve_forever() > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From gus at mu.org Sun Sep 14 13:19:51 2003 From: gus at mu.org (Gus Mueller) Date: Sun Sep 14 13:19:55 2003 Subject: [Tutor] cgi's + unicode Message-ID: <20030914171951.GA62664@elvis.mu.org> I'm having a problem running a python cgi script, and gathering unicode data- I've looked at the faq, and tried a bunch of different ways to convert the strings around and such, but nothing seems to work 100% of the time. In this simple example (broken down from a bigger script), I just want a user to enter unicode data into my text field, and have it displayed right back to him/her. Seems simple, but I keep on getting the error: UnicodeError : ASCII encoding error: ordinal not in range(128) Has anyone been down this road, and successfully dealt with it? (btw, I'm running python 2.2.3) #!/usr/bin/python import string, os, sys, cgi import cgitb; cgitb.enable() form = cgi.FieldStorage() # this throws an error.. #sys.setdefaultencoding("utf-8") def getFormValue(name, default): formValue = form.getvalue(name, default) #just set a default value ret = formValue try: ret = unicode(formValue, "ascii") except UnicodeError: ret = unicode(formValue, "utf8") else: # value was valid ASCII data pass return ret print "Content-type: text/html; charset=utf-8\r\n" blah = getFormValue("blah", "Zilch.") print u"""
""" % blah thanks, -gus -- August Mueller http://flyingmeat.com/ VoodooPad - 1st Place U.S., Second O'Reilly Mac OS X Innovaters Contest "Christmas means carnage!" -- Ferdinand, the duck From alan.gauld at blueyonder.co.uk Sun Sep 14 13:58:08 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Sep 14 13:57:05 2003 Subject: [Tutor] Beginner @ python References: <000c01c37aca$6e0771f0$6401a8c0@HUTTFAMILY> Message-ID: <03fa01c37ae9$c16d24b0$6401a8c0@xp> Ok, Silly questions here...:) Nope not silly, in fact one of the most commonly asked beginners questions. So you are in good company. > so far I haven't seen anything, that I'm aware of, that was > written for Windows in Python One of the great things about Python is that a program that runs on Windows will probably work on Linux or Macintosh and vice-versa. > (i.e. I haven't seen any executable Windows programs *.exe). > Is that because people "port" programs over to the Microsoft OS > or does Python always need to have the interpreter installed The latter. Python is like Java and Visual Basic in that respect. It needs some support files to be present. It just so happens that Windows comes with the Java and Visual Basic interpreters already installed whereas you have to install Python yourself. In fact even compiled programs (native .exe files) still need some support libraries before they will run (usually msvcrt.dll and mfc4xx.dll) but again these are provided with Windows. Now some people don't like the idea of asking fols to install Python before being able to run programs so somebody has written a little program (called py2exe) that bundles the essential Python interpreter files with your program to form a .exe. The snag with this approach is that the .exe is much bigger than the .py file that you started with so if you have a lot of programs to distribute you wind up giving out lots of big files each with a copy of Python inside! You pays your money and you makes your choice. If you choose to install Python then the individual .py files can be run by just double clicking in windows explorewr as usual. Usually this will result in a DOS window popping up and displaying the output. If it closes too quickly you can add a line like: raw_input("Hit return to quit") at the end so you can see what happened before the window closes. Eventually you will start writing GUI programs oin Python and then you won't need that trick, but we'll wait till you get there before going any further! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sun Sep 14 14:02:22 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Sep 14 14:01:18 2003 Subject: [Tutor] Problem with environement variables in Windows XP References: <3F647FD6.9020703@epfl.ch> Message-ID: <040301c37aea$58b94a60$6401a8c0@xp> > I'm working under Windows XP, python 2.2.1 and I'm trying to find a > user's home directory. > >>> import os.path > >>> os.path.expanduser('~') > '%USERPROFILE%' expanduser works for me both under cygwin and vanilla XP Python. I'm using 2.3 is the only difference... Alan G. From idiot1 at netzero.net Sun Sep 14 14:09:21 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Sep 14 14:08:53 2003 Subject: [Tutor] THE CGI SERVER SCRIPT In-Reply-To: <003501c37ad7$4f730080$8d4c73d5@BAERBAR> References: <3F5BE41C.9080702@netzero.net> <000901c3762e$44273820$a24c73d5@BAERBAR> <3F5D5F0C.4010204@netzero.net> <003501c37ad7$4f730080$8d4c73d5@BAERBAR> Message-ID: <3F64AED1.1010604@netzero.net> STEVE wrote the server, I simply called a bug in it to his attention; he fixed it. I used it, and made sure it was ok to give out copies, then offered it to you all. As for issues; OK, let's see how mine is set up. I have the desktop icon open to properties, here's what there is: 1. Target: C:\Python22\pythonw.exe C:\PYTHON22\cgiserver.py 2. Start in: C:\Python22 3. Shortcut key: None 4. Run: Minimized It runs on port 8080. To access it, the browser must be addressed to: http://localhost:8080/ It will default to index.html. Paths are below that, and the root directory is the one the script finds itself in. Therefore, webpages are to be placed in that directory. The images dir is off of that one, which is 'C:\Python22'. Create a cgi-bin under it and place the wiki scripts in there. In that, create the 'text' dir and place the pages there. Inage files must be in the C:\Python22\images directory. There are known issues with some firewalls. Either start it first, THEN the firewall, OR edit the firewall to allow it to work with port 8080, OR shut the silly thing off. After all, this is a wiki to be used when off line, after all. IF you are good with firewalls, maybe you can get the local browser to access the server internally and not have to pass through the firewall at all. Ole Jensen wrote: > Concerning the before mentioned cgi script by Steve Holden and Kirk Bailey, > well I've now tried to experiment with it but I didn't get very far! > > As a matter of fact I was not even able to run the server, I get a traceback > saying it can't find a a/some module(s). > (Keep reading, there's more after this breif message from python...) > This is the the traceback: > Traceback (most recent call last): > File "C:\Programmer\python\cgi.py", line 2, in ? > import CGIHTTPServer, BaseHTTPServer > File "C:\PROGRA~1\python\lib\CGIHTTPServer.py", line 28, in ? > import SimpleHTTPServer > File "C:\PROGRA~1\python\lib\SimpleHTTPServer.py", line 17, in ? > import cgi > File "C:\Programmer\python\cgi.py", line 3, in ? > httpd=BaseHTTPServer.HTTPServer(('',8080), > CGIHTTPServer.CGIHTTPRequestHandler) > AttributeError: 'module' object has no attribute 'CGIHTTPRequestHandler' > Traceback (most recent call last): > File "C:\Programmer\python\cgi.py", line 3, in ? > httpd=BaseHTTPServer.HTTPServer(('',80), > CGIHTTPServer.CGIHTTPRequestHandler) > AttributeError: 'module' object has no attribute 'CGIHTTPRequestHandler' > > Quite alot actually (compared to what I'm used for), I can't say that I > fully undstand it, but the way I understand it the error is in the imported > modules (is that possible!!!) > > I use Python 2.2.3 on WinXP, if that matters. I have 2.2.1 and it works fine. Intresting. > The only changes I made to the cgi script was adjusting the libray info in > the first line, and the port number to 8080 (which I did try to set to 80, > afterwards). Try deleting the modified script and replace it wih the unmodified one in the zip file and see if it works, maybe there was a unnoticed typo introduced when you edited it? Here is a mouse copy of the one running in my pc RIGHT THIS MINUTE: #!C:\Python22\pythonw.exe # COPYRIGHT 2003 Steve Holden, free for personal use. # Please visit http://www.holdenweb.com/ to learn more! # import CGIHTTPServer, BaseHTTPServer httpd=BaseHTTPServer.HTTPServer(('',8080), CGIHTTPServer.CGIHTTPRequestHandler) httpd.serve_forever() # > > The file has been placed in the (root) python library (next to python.exe > etc). > it goes into c:Python22 - in the 2.2.1 release. If the dir name is different in 2.2.3, please adjust accordingly. The thing goes in the same dir as 'pythonw.exe'. If that is a different path, you might want to adjust the sheband, although as the command line in the shortcut is directly to pythonw.exe, and feeds it cgiserver.py as a command line arguement, this may not matter at all. > I've never been working with cgi-script, let alone setting up cgi servers on > my PC, so I don't really know it is something I've done wrong as it sounded > like Kirk got it up and running. > OH! Well, then, here is a helloworld script. #!C:\Python22\pythonw.exe # print 'Content-Type: text/html' print print "This is the OFFICAL HelloWorld program, accept no substitutes..." # BEWARE WORD WRAP IN EMAIL TRANSMISSIONS! print '' print '

Helloworld!

' print '

' print "that's it. Goodbye." print '

' > I am looking forward to any replies/solutions. > Ol? > > Below is the cgi code: > #!C:\Programmer\python\pythonw.exe > import CGIHTTPServer, BaseHTTPServer > httpd=BaseHTTPServer.HTTPServer(('',80), > CGIHTTPServer.CGIHTTPRequestHandler) > httpd.serve_forever() > > > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From kalike2003 at netscape.net Sun Sep 14 14:10:28 2003 From: kalike2003 at netscape.net (kalike2003@netscape.net) Date: Sun Sep 14 14:10:34 2003 Subject: [Tutor] Referencing a string Message-ID: <2EAAF330.334E155A.0F56FA1E@netscape.net> Hi, I am having problem in using os.system(cmd) function. The function does not return the correct result when a string variable is given in the pattern field. The code is like this. cmd = "grep -c pattern " + 'filelist3' + " > " + 'grepdata' os.system(cmd) Instead of looking at the contents of variable pattern, it takes pattern as the string to search and searches in the file. The contents of the variable pattern is correctly shown when I do a print. Instaed of variable, when I tried with a fixed pattern like "the", it works fine. Please suggest me the correct method. Thanks. __________________________________________________________________ McAfee VirusScan Online from the Netscape Network. Comprehensive protection for your entire computer. Get your free trial today! http://channels.netscape.com/ns/computing/mcafee/index.jsp?promo=393397 Get AOL Instant Messenger 5.1 free of charge. Download Now! http://aim.aol.com/aimnew/Aim/register.adp?promo=380455 From amonroe at columbus.rr.com Sun Sep 14 16:29:27 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun Sep 14 16:23:36 2003 Subject: Cleanly stopping a Python server? WAS: Re: [Tutor] THE CGI SERVER SCRIPT In-Reply-To: <003501c37ad7$4f730080$8d4c73d5@BAERBAR> References: <3F5BE41C.9080702@netzero.net> <000901c3762e$44273820$a24c73d5@BAERBAR> <3F5D5F0C.4010204@netzero.net> <003501c37ad7$4f730080$8d4c73d5@BAERBAR> Message-ID: <3659911698.20030914162927@columbus.rr.com> > Below is the cgi code: > #!C:\Programmer\python\pythonw.exe > import CGIHTTPServer, BaseHTTPServer > httpd=BaseHTTPServer.HTTPServer(('',80), > CGIHTTPServer.CGIHTTPRequestHandler) > httpd.serve_forever() Is there a nice way of killing a server that's been launched with serve_forever()? (I have SimpleXMLRPCServer in mind, but it would apply to this too). Alan From jmillr at umich.edu Sun Sep 14 19:22:10 2003 From: jmillr at umich.edu (John Miller) Date: Sun Sep 14 19:22:17 2003 Subject: [Tutor] Question on lists In-Reply-To: Message-ID: <43C36BA6-E70A-11D7-B5E8-00039303967A@umich.edu> On Friday, September 12, 2003, at 03:45 PM, "james roy" wrote: > Hello, > I am new to programming with python. I dont know I am having my > problem like this: > I am having a few lists that i know in no dynamically. > For example: > List1 = ['1','2','3'] > List2 = ['/'] > List3 = ['4','5','6'] > I want to make the combinations like this: > > '1' / '4' > '1' / '5' > '1' / '6' > '2' / '4' > '2' / '5' > '2' / '6' > '3' / '4' > '3' / '5' > '3' / '6' > > I want to genearlise this as: > I can have 'n' no of elements in 'N' no of lists and i want to make > the combinations like i have written. I found this to be an intriguing problem. I, too, am having trouble generalizing a solution. *IF* I know ahead of time how many lists there will be, I can simply nest a bunch of for loops like so: ''' all_lists=[['a','b','c'],['*','/'],[1,2,3,4,5],['+','- '],['w','x','y','z']] P = [] #all the resulting permutations for h in all_lists[0]: for i in all_lists[1]: for j in all_lists[2]: for k in all_lists[3]: for l in all_lists[4]: P.append((h,i,j,k,l)) print P ''' But the question was 'N' number of lists. Can I somehow count the number of lists and use that to construct on the fly 'N' for loops that are properly indented? Is this a case where you need to use something like 'exec'? Hmmm, (coding out loud): ''' all_lists=[['a','b','c'],['*','/'],[1,2,3,4,5],['+','- '],['w','x','y','z']] #this 'var_dict' is cheating; I'm assuming a number of variables to cover #the largest possible number of lists could be constructed; #other approaches? var_dict = {0:'h',1:'i',2:'j',3:'k',4:'l'} codelines = {} #a dictionary of lines of code keyed by 'line number' j = 0 #to keep track of the number of lines to add the final line outside the loop P = [] #all the resulting permutations for i in range(len(all_lists)): codelines[i] = '%sfor %s in all_lists[%s]:' % (' ' * i, var_dict[i], i) j += 1 codelines[j]='%sP.append((h,i,j,k,l))' % (' ' * j) codestrings = [] for k in range(len(codelines)): codestrings.append(codelines[k]) code = '\n'.join(codestrings) exec code print P ''' The problem is, this doesn't quite work (although I think it's close). So, basically, I have two questions: 1. Is this (using exec) the right approach to the OP's question? 2. Can anyone see how to make 'exec code' work? Thanks! John Miller From missive at hotmail.com Sun Sep 14 20:13:03 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Sep 14 20:13:17 2003 Subject: [Tutor] Re: Referencing a string Message-ID: >I am having problem in using os.system(cmd) function. >The function does not return the correct result when a string >variable is given in the pattern field. The code is like this. > >cmd = "grep -c pattern " + 'filelist3' + " > " + 'grepdata' >os.system(cmd) > >Instead of looking at the contents of variable pattern, it takes pattern >as the string to search and searches in the file. The contents of the >variable pattern is correctly shown when I do a print. > >Instaed of variable, when I tried with a fixed pattern like "the", >it works fine. > >Please suggest me the correct method. > Hi; Please limit your line lengths to < 80 characters when posting. # after this line: cmd = "grep -c pattern " + 'filelist3' + " > " + 'grepdata' # print out the result before (or instead of) running it print cmd #os.system(cmd) Often when I do something like this, the potential for disaster is high (deleting or corrupting important files) so I will print first, then comment out the print and uncomment the system() call when I am certain it does what I want. As it stands now, the only thing you will ever grep for is 'pattern'. You may want something like this: pattern = "_some_intersting_pat_" search_file = "filelist3" output_file = "grepdata" cmd = "grep -c '%s' %s > %s" % (pattern, search_file, output_file) _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From amk at amk.ca Sun Sep 14 13:04:22 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sun Sep 14 20:59:41 2003 Subject: [Tutor] Question on lists In-Reply-To: <43C36BA6-E70A-11D7-B5E8-00039303967A@umich.edu> References: <43C36BA6-E70A-11D7-B5E8-00039303967A@umich.edu> Message-ID: <20030914170422.GA9638@nyman.amk.ca> On Sun, Sep 14, 2003 at 07:22:10PM -0400, John Miller wrote: >are properly indented? Is this a case where you need to use something >like 'exec'? Hmmm, (coding out loud): Generating code is usually pretty complicated. It would be possible to make it work, but it would be hard to debug. It's easier to solve the problem recursively. A full solution is below. Here's how it's derived. I want a function generate(list1, list2, list3, ...) that outputs an iterator that produces all the possible combination. That gives me the prototype: def generate (*lists): When there are no arguments, the job is easy; there are no combinations to return at all: # No lists to generate from, so don't yield anything. if len(lists) == 0: return If there's a single list, it's also easy; just loop over the list and return a list of every element. # One list, so loop over each element elif len(lists) == 1: for item in lists[0]: yield [item] If there's more than one list, we take the first list and loop over its elements, and call generate() with the rest of the lists. first_list = lists[0] for item in first_list: for output in generate(*lists[1:]): yield [item] + output And that's it. --amk def generate (*lists): # No lists to generate from, so don't yield anything. if len(lists) == 0: return # One list, so loop over each element elif len(lists) == 1: for item in lists[0]: yield [item] first_list = lists[0] for item in first_list: for output in generate(*lists[1:]): yield [item] + output for item in generate ([1,2,3]): print item for item in generate ([1,2,3], ['a', 'b'], ['c', 'd']): print item From python at rcn.com Sun Sep 14 21:01:16 2003 From: python at rcn.com (Raymond Hettinger) Date: Sun Sep 14 21:07:04 2003 Subject: [Tutor] Question on lists References: <43C36BA6-E70A-11D7-B5E8-00039303967A@umich.edu> Message-ID: <000001c37b24$fda69de0$5323c797@oemcomputer> [james roy] > > I am new to programming with python. I dont know I am having my > > problem like this: > > I am having a few lists that i know in no dynamically. > > For example: > > List1 = ['1','2','3'] > > List2 = ['/'] > > List3 = ['4','5','6'] > > I want to make the combinations like this: > > > > '1' / '4' > > '1' / '5' > > '1' / '6' > > '2' / '4' > > '2' / '5' > > '2' / '6' > > '3' / '4' > > '3' / '5' > > '3' / '6' > > > > I want to genearlise this as: > > I can have 'n' no of elements in 'N' no of lists and i want to make > > the combinations like i have written. [John Miller] > I found this to be an intriguing problem. I, too, am having trouble > generalizing a solution. *IF* I know ahead of time how many lists there > will be, I can simply nest a bunch of for loops like so: > > ''' > all_lists=[['a','b','c'],['*','/'],[1,2,3,4,5],['+','- > '],['w','x','y','z']] > P = [] #all the resulting permutations > for h in all_lists[0]: > for i in all_lists[1]: > for j in all_lists[2]: > for k in all_lists[3]: > for l in all_lists[4]: > P.append((h,i,j,k,l)) > print P > ''' > > But the question was 'N' number of lists. Can I somehow count the > number of lists and use that to construct on the fly 'N' for loops that > are properly indented? Is this a case where you need to use something > like 'exec'? Hmmm, (coding out loud): > > ''' > all_lists=[['a','b','c'],['*','/'],[1,2,3,4,5],['+','- > '],['w','x','y','z']] > #this 'var_dict' is cheating; I'm assuming a number of variables to > cover > #the largest possible number of lists could be constructed; > #other approaches? > var_dict = {0:'h',1:'i',2:'j',3:'k',4:'l'} > codelines = {} #a dictionary of lines of code keyed by 'line number' > j = 0 #to keep track of the number of lines to add the final line > outside the loop > P = [] #all the resulting permutations > for i in range(len(all_lists)): > codelines[i] = '%sfor %s in all_lists[%s]:' % (' ' * i, > var_dict[i], i) > j += 1 > codelines[j]='%sP.append((h,i,j,k,l))' % (' ' * j) > codestrings = [] > for k in range(len(codelines)): > codestrings.append(codelines[k]) > code = '\n'.join(codestrings) > exec code > print P > ''' > The problem is, this doesn't quite work (although I think it's close). This can be made *much* simpler. def product(*args): 'Compute the cartesian product of the sequence arguments' if args == (): return [[]] subproblem = prod(*(args[1:])) return [[elem]+tail for elem in args[0] for tail in subproblem] List1 = ['1','2','3'] List2 = ['/'] List3 = ['4','5','6'] for group in product(List1, List2, List3): print ''.join(group) From vibrations at cetlink.net Sun Sep 14 22:59:11 2003 From: vibrations at cetlink.net (SGD) Date: Sun Sep 14 22:59:20 2003 Subject: [Tutor] wsdl Message-ID: <000001c37b35$57982de0$cb37c6d1@whiterhino2> Does any one use wsdl with python? I would like to use wsdl inside of a couple python scripts and modules, I tried it with wsdl4py (ie; wsdllib) but get errores on every use. If anyone thinks it may be ignorance on my part (Note: I am new to wsdl) and is knowledgeable with wsdl4py, here is the error I get when I run test.py that comes with wsdllib. Use Case 1 Read uc1.wsdl from URI Traceback (most recent call last): File "C:\Python23\Lib\site-packages\wsdllib\test\test.py", line 318, in ? test() File "C:\Python23\Lib\site-packages\wsdllib\test\test.py", line 307, in test test_uc('uc1.wsdl',UC1_VALIDATION_DATA) File "C:\Python23\Lib\site-packages\wsdllib\test\test.py", line 7, in test_uc ws = wsdllib.ReadFromUri(fileName) AttributeError: 'module' object has no attribute 'ReadFromUri' Please can somebody, anybody help? I followed the tutorial available but get similar errors on every thing. Are there any alternitives for using wsdl in python. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030914/60108ef9/attachment.html From alan.gauld at blueyonder.co.uk Sun Sep 14 23:50:59 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Sep 14 23:49:50 2003 Subject: [Tutor] Referencing a string References: <2EAAF330.334E155A.0F56FA1E@netscape.net> Message-ID: <044301c37b3c$93929fe0$6401a8c0@xp> The code is like this. > cmd = "grep -c pattern " + 'filelist3' + " > " + 'grepdata' > os.system(cmd) Move pattern outside the quotes: cmd = "grep -c " + pattern + " " + filelist3 + " > " + 'grepdata' I'm assuming filelist3 is also a variable? Alan G From peterabrown at froggy.com.au Mon Sep 15 07:07:42 2003 From: peterabrown at froggy.com.au (Peter Brown) Date: Mon Sep 15 07:08:28 2003 Subject: [Tutor] Permissions Problem with Python In-Reply-To: <200309140912.24814.tbstep@tampabay.rr.com> References: <3.0.6.32.20030914222040.00b5c5d0@mail.froggy.com.au> <3.0.6.32.20030914222040.00b5c5d0@mail.froggy.com.au> Message-ID: <3.0.6.32.20030915210742.00b60830@mail.froggy.com.au> Program has already been chmod 755. I type /usr/TP/foo.py at the bash prompt, this is the fully qualified path - then it says no such file or directory. /usr/bin/python runs I get an interactive >>>> prompts and can execute commands, link to postgresql and create tables, do inserts within Python. But I can't execute create_table.py. However, I can import it into python interactive mode and it runs fine. How do I set PYTHONPATH? In .bash_profile? I'm using RH9. TIA Peter At 09:12 14/09/2003 -0400, you wrote: >On Sunday 14 September 2003 08:20 am, Peter Brown wrote: > >> I have the following line at the start of create_table.py - #! /usr/bin/env python. > >Here's the "d'oh!" question: Have you made this file executable? Chmod >755 or 555 on that file. Also, if the file is not located in a >directory in your path, you'll need to prefix the file name with its >own path. If the file is in your home directory, you could not execute >it just by #foo.py, you would have to say #~/foo.py. > > >-- >Todd Stephens >ICQ# 3150790 > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From g_alleon at yahoo.fr Mon Sep 15 07:32:15 2003 From: g_alleon at yahoo.fr (=?iso-8859-1?q?guillaume=20alleon?=) Date: Mon Sep 15 07:32:20 2003 Subject: [Tutor] Memory optimization needed: tarball In-Reply-To: <3F63C554.1050108@pobox.com> Message-ID: <20030915113215.81511.qmail@web40020.mail.yahoo.com> --- "Jonathan Hayward http://JonathansCorner.com" a ?crit : > I have a search engine I'm working on which uses > memory inefficiently > for large data. It indexes to avoid the cost of > keeping documents in > memory, but with a 150M dataset it takes 250M. > Unlike previous requests > where I didn't provide a good way to use it, I now > have a tarball with > installer: > > http://haywardfamily.org/jonathan/datamine0_0.tar.gz the link looks wrong, I can't get your tarball. Yours Guillaume > > I would welcome help cutting down memory taken by > large datasets. > > Thanks in advance, > > -- > ++ Jonathan Hayward, jonathan.hayward@pobox.com > ** To see an award-winning website with stories, > essays, artwork, > ** games, and a four-dimensional maze, why not visit > my home page? > ** All of this is waiting for you at > http://JonathansCorner.com > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___________________________________________________________ Do You Yahoo!? -- Une adresse @yahoo.fr gratuite et en fran?ais ! Yahoo! Mail : http://fr.mail.yahoo.com From godoy at metalab.unc.edu Mon Sep 15 08:14:01 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Mon Sep 15 08:14:35 2003 Subject: [Tutor] Permissions Problem with Python In-Reply-To: <3.0.6.32.20030915210742.00b60830@mail.froggy.com.au> (Peter Brown's message of "Mon, 15 Sep 2003 21:07:42 +1000") References: <3.0.6.32.20030914222040.00b5c5d0@mail.froggy.com.au> <3.0.6.32.20030914222040.00b5c5d0@mail.froggy.com.au> <3.0.6.32.20030915210742.00b60830@mail.froggy.com.au> Message-ID: Peter Brown writes: > I type /usr/TP/foo.py at the bash prompt, this is the fully qualified path > - then it says no such file or directory. The first thing to try is to change #!/usr/bin/env python for #!/usr/bin/python Also try checking if you have Python's directory into your environment variables. -- Godoy. From intatia at paradise.net.nz Mon Sep 15 08:39:19 2003 From: intatia at paradise.net.nz (Intatia) Date: Mon Sep 15 08:40:46 2003 Subject: [Tutor] Classes and the like... Message-ID: <200309160039.19484.intatia@paradise.net.nz> Hey, new to the list and have a little question.. Does anyone know of a good link that explains classes and what's associated with them in realllly simple terms, because my friend has managed to totally confuse me. A little bit on what they are and how to use them and why they do what they do. Thanks. From Blake.Garretson at dana.com Mon Sep 15 09:08:30 2003 From: Blake.Garretson at dana.com (Blake.Garretson@dana.com) Date: Mon Sep 15 09:08:48 2003 Subject: [Tutor] Cleanly stopping a Python server? Message-ID: "R. Alan Monroe" wrote: >Is there a nice way of killing a server that's been launched with >serve_forever()? (I have SimpleXMLRPCServer in mind, but it would >apply to this too). I never use serve_forever. Instead, try serving one request in a loop until you tell the server otherwise. Here's a template: ### quit = 0 class MyDaemon: def kill_server(self): global quit quit = 1 # perform clean up functions, etc. return 1 #... other functions, etc. server = SimpleXMLRPCServer.SimpleXMLRPCServer((slave_host, slave_port),logRequests=0 ) server.register_instance(MyDaemon()) while not quit: server.handle_request() ### Of course, this requires an external program to bring it down, but that is simple enough: ### # kill server s = xmlrcplib.Server(server_string) s.kill_server() ### - Blake Garretson From charlie at begeistert.org Mon Sep 15 12:40:36 2003 From: charlie at begeistert.org (Charlie Clark) Date: Mon Sep 15 10:38:58 2003 Subject: [Tutor] Help with os.system, os.popen and fellows Message-ID: <20030915164036.2407.4@bepc.wonderland> Dear list, I've got a problem trying to work out how Python works with the shell using system, popen and exec... I'm trying to write a script to replace a shell script. I need to open a program and send it messages via a command line application and occasionally read responses. Although the programs themselves are BeOS specific I'm hoping that the way of handling them isn't. BeOS is fairly POSIX compatible as long as sockets aren't involved. Here's an extract from the initial script (for bash 2.04) /boot/apps/Becasso/Becasso -S3 & sleep 2 hey -s Becasso set ExportFormat to image/jpeg for x in *.jpg do hey -s Becasso create Canvas with Name=spam and Size=BRect[100,100,899,699] So I need to start "Becasso" and keep it running. I've found I've only been able to do this effectively using os.popen although I think os.fork might be more appropriate. Most of the other commands are fairly straight forward as "hey" does the actual work returning values so I think os.popen should be correct here. The problem I've hit is that os.popen commands don't seem to return control to the Python interpreter. Here's what might script currently looks like: import os files = os.listdir(os.curdir) os.popen("/boot/apps/Becasso/Becasso -S3") cmd = "hey -s Becasso " r = os.popen(cmd + "set ExportFormat to image/jpeg") for file in files: r = os.popen(cmd + "create Canvas with Name=spam \ and Size=BRect[100,100,899,699]").read() r = os.popen(cmd + "set Contents of Layer 0 of Canvas 'spam' to file\ %s").read() %file ratio = os.popen("hey -o Becasso get AspectRatio of Canvas 0").read() This seems to get stuck on the second os.popen. Thanx for any pointers. Charlie From project5 at redrival.net Mon Sep 15 13:45:15 2003 From: project5 at redrival.net (Andrei) Date: Mon Sep 15 13:47:16 2003 Subject: [Tutor] Re: Classes and the like... In-Reply-To: <200309160039.19484.intatia@paradise.net.nz> References: <200309160039.19484.intatia@paradise.net.nz> Message-ID: Intatia wrote: > Hey, new to the list and have a little question.. > Does anyone know of a good link that explains classes and what's associated > with them in realllly simple terms, because my friend has managed to totally > confuse me. A little bit on what they are and how to use them and why they do > what they do. Have you looked at http://www.freenetpages.co.uk/hp/alan.gauld/? Under Advanced topics -> Object Oriented Programming. Another good one is http://www.ibiblio.org/obp/thinkCSpy/ (chapters 12 and 13). -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From goki75 at vsnl.net Mon Sep 15 15:53:59 2003 From: goki75 at vsnl.net (G Kiran) Date: Mon Sep 15 15:54:01 2003 Subject: [Tutor] Simple Message-ID: <000201c39355$f2d16be0$0100a8c0@VULCAN> Is it possible for these mailing list digests to stick to a format.. this is a request 'coz i parse these mail messages to keep as a ref guide. using the following script import os dr=os.listdir("c:\\docume~1\\kkk\Desktop\\py") f2=open("c:\\summary.txt","w") for i in range(len(dr)): d=dr[i] f=open('c:\\pymail\\'+d,'r') print d s=f.read() f.close() i=s.find('Date:') dt=s[i:i+22] i=s.find("Today's Topics:") j=s.find("Message",i,len(s)) tpcs=s[i:j] f2.write(dt+"\n") f2.write(tpcs+"\n\n\n"); f2.close and every time u change the format i need to change the program..it has some kind of o//p like this Date: Wed, 06 Aug 2003 Today's Topics: 1. RE: floating point accuracy (Alan Trautman) 2. Re: sys.path (Lee Harr) 3. RE: floating point accuracy [working with Fractions] (Danny Yoo) 4. Options - Format - "String with no terminator" - bgcolor (RASTM2@aol.com) 5. Re: what's a state machine? (Alan Gauld) 6. Re: Graphical object browser? (Alan Gauld) 7. Re: How to get messages from stderr (Michael Lange) 8. Re: why use *get* (A.M. Kuchling) 9. python22 (Seyed Fard) 10. outputting dictionary key/value pairs (Terence Lo) 11. Re: Mutable String Question (Roeland Rengelink) 12. Re: Regular Expression guru saught (A.M. Kuchling) 13. Re: Comments wanted on new Python introduction (A.M. Kuchling) --__--__-- Date: Wed, 06 Aug 2003 Today's Topics: 1. Re: python22 (Alan Gauld) 2. Re: what's a state machine? (pcarey@lexmark.com) 3. Re: python22 (Lee Harr) 4. Re: what's a state machine? (Alan Gauld) 5. Re: what's a state machine? (Alan Gauld) 6. Re: Executing an executable with commandline options (Lee Harr) 7. Re: python22 (Bob Gailer) 8. Re: outputting dictionary key/value pairs (Cliff Wells) 9. Sockets, again (Jonathan Hayward http://JonathansCorner.com) 10. Re: what's a state machine? (R. Alan Monroe) 11. Re: what's a state machine? (Jeff Shannon) ---------------------------------------------------------------------- Date: Thu, 07 Aug 2003 Today's Topics: 1. Re: python22 (Todd Stephens) 2. Re: what's a state machine? (Alan Gauld) 3. Re: outputting dictionary key/value pairs (Terry Carroll) 4. Re: outputting dictionary key/value pairs (Zak Arntson) 5. Re: Re: Using a dictionary to keep a count (Karl Pfl?sterer ) 6. Re: Graphical object browser? (Terry Carroll) 7. wiki project update (Kirk Bailey) 8. 2 functions- are they state machines? (Kirk Bailey) 9. RE: floating point accuracy (Stephen Ng) 10. Re: Regular Expression guru saught (Magnus Lyck?) ---------------------------------------------------------------------- as you can see the topic seperator till 6 aug was --__--__-- and then it changed o -------------------------------------------------------- yes i can write a generalised one with re and python/perl but guess i cud keep it simple... -kiran --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.509 / Virus Database: 306 - Release Date: 8/12/2003 From glingl at aon.at Mon Sep 15 17:01:22 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Sep 15 17:03:06 2003 Subject: [Tutor] How to write protect attributes or names Message-ID: <3F6628A2.1090506@aon.at> Hi all, is it possible to "write-protect" a definitive selection of attributes (a) of a class (b) of an object (c) or a definitve selection of names of a module? e.g. all the callable ones. If so, how has it to be done? Thanks in advance, Gregor From project5 at redrival.net Mon Sep 15 17:48:38 2003 From: project5 at redrival.net (Andrei) Date: Mon Sep 15 17:50:41 2003 Subject: [Tutor] Re: Simple In-Reply-To: <000201c39355$f2d16be0$0100a8c0@VULCAN> References: <000201c39355$f2d16be0$0100a8c0@VULCAN> Message-ID: Hi Kiran, G Kiran wrote: > Is it possible for these mailing list digests to stick to a format.. > this is a request 'coz i parse these mail messages to keep as a > ref guide. > > and every time u change the format i need to change the program..it has some > kind of o//p like this > > > as you can see the topic seperator till 6 aug was --__--__-- > and then it changed > o -------------------------------------------------------- > > yes i can write a generalised one with re and python/perl > but guess i cud keep it simple... All messages are numbered, so just look for the first line which, when stripped, does not start with a digit. At that point the list of titles has ended. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Mon Sep 15 17:52:57 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 15 17:53:15 2003 Subject: [Tutor] Permissions Problem with Python [magic lines need to be the very first line of a file] In-Reply-To: Message-ID: On Mon, 15 Sep 2003, Jorge Godoy wrote: > Peter Brown writes: > > > I type /usr/TP/foo.py at the bash prompt, this is the fully qualified > > path - then it says no such file or directory. > > The first thing to try is to change > > #!/usr/bin/env python > > for > > #!/usr/bin/python Hello! Also, make sure that the magic line really is the very first line in the file. If there's a newline that precedes the magic line, then that will interfere with the magic-line system that Unix uses. For example, let's say we have two programs 'hello.py' and 'hello2.py': ### bash-2.05a$ ls -l hello.py hello2.py -rwxr-xr-x 1 dyoo staff 38 Sep 15 14:49 hello.py -rwxr-xr-x 1 dyoo staff 39 Sep 15 14:49 hello2.py bash-2.05a$ bash-2.05a$ cat hello.py #!/usr/bin/python print "hello world" bash-2.05a$ ./hello.py hello world bash-2.05a$ cat hello2.py #!/usr/bin/python print "hello world" bash-2.05a$ ./hello2.py ./hello2.py: print: command not found ### Both programs are executable --- but notice that in the second example, the extra newline causes the system not to find the magic line where it expects to see it! So it responds with 'command not found'. I don't know if this is the issue you're running into, but I might as well throw something out and see if it sticks... *grin* If you have the time, try this to help us debug things: ### print repr(open('/usr/TP/foo.py', 'rb').read(160)) ### If you show the result to us, we should be able to see about two lines worth of bytes. I just want to make sure we're not chasing some silly newline/carriage-return problem... *grin* Talk to you later! From charlie at begeistert.org Mon Sep 15 20:48:25 2003 From: charlie at begeistert.org (Charlie Clark) Date: Mon Sep 15 18:46:33 2003 Subject: [Tutor] Re: Tutor Digest, Vol 2, Issue 28 In-Reply-To: References: Message-ID: <20030916004825.3729.5@bepc.wonderland> On 2003-09-15 at 16:06:18 [+0000], tutor-request@python.org wrote: > Here's what might script currently looks like: > import os > > files = os.listdir(os.curdir) > > os.popen("/boot/apps/Becasso/Becasso -S3") This seems to be the culprit! Needs to be run as detached process with "&". I'm still struggling with other problems closely associated with my not quite understanding the subtleties of popen, etc. so help still appreciated. Charlie From peterabrown at froggy.com.au Mon Sep 15 19:11:55 2003 From: peterabrown at froggy.com.au (Peter Brown) Date: Mon Sep 15 19:12:07 2003 Subject: [Tutor] Permissions Problem Message-ID: <1063667515.3246.11.camel@localhost.localdomain> bash-2.05b$ /usr/bin/python Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print repr(open('/usr/TP/upload.py', 'rb').read(160)) '#!/usr/bin/python\r\n# upload.py\r\n# program does two main tasks\r\n# 1. Seeks whether two files exist and then process file contents.\r\n# File YYYMMDD.sm is DDR list' >>> bash-2.05b$ /usr/TP/upload.py : bad interpreter: No such file or directory bash-2.05b$ pwd /usr/TP bash-2.05b$ ls -al upload.py -rwxr-xr-x 1 postgres postgres 6945 Sep 16 08:31 upload.py bash-2.05b$ As you can see everything looks OK. /usr/TP is not home directory What could be the problem? Peter From pythontutor at venix.com Mon Sep 15 19:28:39 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Sep 15 19:28:46 2003 Subject: [Tutor] Permissions Problem In-Reply-To: <1063667515.3246.11.camel@localhost.localdomain> References: <1063667515.3246.11.camel@localhost.localdomain> Message-ID: <3F664B27.4020900@venix.com> The python script was mangled by some Windows processing so that the lines are marked with \r\n rather than \n. You need to remove the extra \r characters from the script. Believe it or not, but that will foul up the shebang processing (at least on some systems). Peter Brown wrote: > bash-2.05b$ /usr/bin/python > Python 2.2.2 (#1, Feb 24 2003, 19:13:11) > [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>print repr(open('/usr/TP/upload.py', 'rb').read(160)) > > '#!/usr/bin/python\r\n# upload.py\r\n# program does two main tasks\r\n# > 1. Seeks whether two files exist and then process file contents.\r\n# > File YYYMMDD.sm is DDR list' > > > bash-2.05b$ /usr/TP/upload.py > : bad interpreter: No such file or directory > bash-2.05b$ pwd > /usr/TP > bash-2.05b$ ls -al upload.py > -rwxr-xr-x 1 postgres postgres 6945 Sep 16 08:31 upload.py > bash-2.05b$ > > As you can see everything looks OK. /usr/TP is not home directory > > What could be the problem? > > Peter > > > > _______________________________________________ > 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 peterabrown at froggy.com.au Mon Sep 15 19:58:58 2003 From: peterabrown at froggy.com.au (Peter Brown) Date: Mon Sep 15 19:59:31 2003 Subject: [Tutor] Permissions Problem In-Reply-To: <3F664B27.4020900@venix.com> References: <1063667515.3246.11.camel@localhost.localdomain> <1063667515.3246.11.camel@localhost.localdomain> Message-ID: <3.0.6.32.20030916095858.00b89ac0@mail.froggy.com.au> Lloyd, THanks for your help. I sed' the script and she works. I'm a happy man. Much appreciated, I have to get away from developing on M$ machine. Peter At 19:28 15/09/2003 -0400, you wrote: >The python script was mangled by some Windows processing so that the lines >are marked with \r\n rather than \n. > >You need to remove the extra \r characters from the script. Believe it or not, >but that will foul up the shebang processing (at least on some systems). > >Peter Brown wrote: > >> bash-2.05b$ /usr/bin/python >> Python 2.2.2 (#1, Feb 24 2003, 19:13:11) >> [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>>>>print repr(open('/usr/TP/upload.py', 'rb').read(160)) >> >> '#!/usr/bin/python\r\n# upload.py\r\n# program does two main tasks\r\n# >> 1. Seeks whether two files exist and then process file contents.\r\n# >> File YYYMMDD.sm is DDR list' >> >> >> bash-2.05b$ /usr/TP/upload.py >> : bad interpreter: No such file or directory >> bash-2.05b$ pwd >> /usr/TP >> bash-2.05b$ ls -al upload.py >> -rwxr-xr-x 1 postgres postgres 6945 Sep 16 08:31 upload.py >> bash-2.05b$ >> >> As you can see everything looks OK. /usr/TP is not home directory >> >> What could be the problem? >> >> Peter >> >> >> >> _______________________________________________ >> 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 amonroe at columbus.rr.com Mon Sep 15 22:00:06 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon Sep 15 21:54:03 2003 Subject: [Tutor] what are some alternatives to XMLRPC? In-Reply-To: <3.0.6.32.20030916095858.00b89ac0@mail.froggy.com.au> References: <1063667515.3246.11.camel@localhost.localdomain> <1063667515.3246.11.camel@localhost.localdomain> <3.0.6.32.20030916095858.00b89ac0@mail.froggy.com.au> Message-ID: <147166151162.20030915220006@columbus.rr.com> I ran some tests this evening with XMLRPC, and found it to be a little too slow for my needs... Pulling 85000+ records from a database using XMLRPC: C:\coding\python>python addemcli.py 33.9689999819 seconds Same query, but just a direct connect to the database: C:\coding\python>python dbtest.py 1.13200008869 seconds The database is sqlite, using the sample data from http://pysqlite.sourceforge.net/examples/itis/ The query was "select * from geographic_div" Apart from the speed concerns I also ran into some other problems with unparseable data when selecting from other tables (xml.parsers.expat.ExpatError: not well-formed (invalid token): line 37018, column 27) Can anyone suggest some faster alternatives? I'm trying to make a bare bones 3 tier environment where a client makes an API call to an app server via XMLRPC, the app server gets data from a database and sends it back to the client. Alan From tbstep at tampabay.rr.com Mon Sep 15 22:08:00 2003 From: tbstep at tampabay.rr.com (Todd Stephens) Date: Mon Sep 15 22:12:37 2003 Subject: [Tutor] Permissions Problem with Python In-Reply-To: References: <3.0.6.32.20030914222040.00b5c5d0@mail.froggy.com.au> <3.0.6.32.20030915210742.00b60830@mail.froggy.com.au> Message-ID: <200309152208.00756.tbstep@tampabay.rr.com> On Monday 15 September 2003 08:14 am, Jorge Godoy wrote: > The first thing to try is to change > > #!/usr/bin/env python > > for > > #!/usr/bin/python Hmm. Didn't even catch that. Of course, I am a BSD user, so the first one looks correct to me :) -- Todd Stephens ICQ# 3150790 "A witty saying proves nothing." -Voltaire From tbstep at tampabay.rr.com Mon Sep 15 22:12:02 2003 From: tbstep at tampabay.rr.com (Todd Stephens) Date: Mon Sep 15 22:16:37 2003 Subject: [Tutor] Permissions Problem In-Reply-To: <3.0.6.32.20030916095858.00b89ac0@mail.froggy.com.au> References: <1063667515.3246.11.camel@localhost.localdomain> <3.0.6.32.20030916095858.00b89ac0@mail.froggy.com.au> Message-ID: <200309152212.02773.tbstep@tampabay.rr.com> On Monday 15 September 2003 07:58 pm, Peter Brown wrote: > Much appreciated, I have to get away from developing on M$ machine. There are a few good text editors for MS out there (free ones) that allow you to save a text file as a "UNIX text file". When I used Windows I used a program called Metapad, which replaces the default Windows Notepad app. I really liked it; you can find it at: http://www.liquidninja.com/metapad/ -- Todd Stephens ICQ# 3150790 "A witty saying proves nothing." -Voltaire From zmerch at 30below.com Mon Sep 15 22:29:48 2003 From: zmerch at 30below.com (Roger Merchberger) Date: Mon Sep 15 22:36:26 2003 Subject: [Tutor] Permissions Problem In-Reply-To: <200309152212.02773.tbstep@tampabay.rr.com> References: <3.0.6.32.20030916095858.00b89ac0@mail.froggy.com.au> <1063667515.3246.11.camel@localhost.localdomain> <3.0.6.32.20030916095858.00b89ac0@mail.froggy.com.au> Message-ID: <5.1.0.14.2.20030915222433.00ae1148@mail.30below.com> At 22:12 09/15/2003 -0400, you wrote: >On Monday 15 September 2003 07:58 pm, Peter Brown wrote: > > > Much appreciated, I have to get away from developing on M$ machine. > >There are a few good text editors for MS out there (free ones) that >allow you to save a text file as a "UNIX text file". When I used >Windows I used a program called Metapad, which replaces the default >Windows Notepad app. I really liked it; you can find it at: >http://www.liquidninja.com/metapad/ Despite this wandering wildly off-topic, my personal favorite (whilst not free, it's very inexpensive) is the "GWD Text Editor" which can be found at http://www.gwdsoft.com/ -- it offers text highlighting, regular expression search & replace, and text highlighting. It doesn't have a python module (well, not yet) but you _can_ roll-your-own fairly easily. (I set up my own somewhat, but it's not very comprehensive...) D'oh! Spoke too soon! There *is* a Python text highlighting module now for it... ;-) Single user fee is $29. Yes, I bought mine... ;-) HTH, Roger "Merch" Merchberger From godoy at metalab.unc.edu Tue Sep 16 07:26:01 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Tue Sep 16 07:26:26 2003 Subject: [Tutor] Permissions Problem with Python In-Reply-To: <200309152208.00756.tbstep@tampabay.rr.com> (Todd Stephens's message of "Mon, 15 Sep 2003 22:08:00 -0400") References: <3.0.6.32.20030914222040.00b5c5d0@mail.froggy.com.au> <3.0.6.32.20030915210742.00b60830@mail.froggy.com.au> <200309152208.00756.tbstep@tampabay.rr.com> Message-ID: Todd Stephens writes: > On Monday 15 September 2003 08:14 am, Jorge Godoy wrote: > >> The first thing to try is to change >> >> #!/usr/bin/env python >> >> for >> >> #!/usr/bin/python > > Hmm. Didn't even catch that. Of course, I am a BSD user, so the first > one looks correct to me :) Both work here, but I've seen some machines where they need some tweaking before it works. On this particular point I agree that the BSD behaviour is a little easier to predict than what it is on Linux :-) -- Godoy. From amk at amk.ca Tue Sep 16 08:50:17 2003 From: amk at amk.ca (amk@amk.ca) Date: Tue Sep 16 08:50:22 2003 Subject: [Tutor] what are some alternatives to XMLRPC? In-Reply-To: <147166151162.20030915220006@columbus.rr.com> References: <1063667515.3246.11.camel@localhost.localdomain> <1063667515.3246.11.camel@localhost.localdomain> <3.0.6.32.20030916095858.00b89ac0@mail.froggy.com.au> <147166151162.20030915220006@columbus.rr.com> Message-ID: <20030916125017.GA8265@rogue.amk.ca> On Mon, Sep 15, 2003 at 10:00:06PM -0400, R. Alan Monroe wrote: > Apart from the speed concerns I also ran into some other problems with > unparseable data when selecting from other tables > (xml.parsers.expat.ExpatError: not well-formed (invalid token): line > 37018, column 27) The strings passed in XML-RPC are simply embedded in the generated XML, so they can't contain control characters that are illegal in XML. If strings contain 8-bit characters, they should be encoded in UTF-8. > Can anyone suggest some faster alternatives? I'm trying to make a bare > bones 3 tier environment where a client makes an API call to an app > server via XMLRPC, the app server gets data from a database and sends > it back to the client. Pick some different format for encoding your database queries -- rfc2822-style headers? comma-separated files? -- and just retrieve this format over HTTP. Or, figure out some way to retrieve fewer records at a time. --amk From abli at freemail.hu Tue Sep 16 09:47:58 2003 From: abli at freemail.hu (Abel Daniel) Date: Tue Sep 16 09:48:15 2003 Subject: [Tutor] Re: Simple In-Reply-To: <000201c39355$f2d16be0$0100a8c0@VULCAN> (G. Kiran's message of "Wed, 15 Oct 2003 23:34:09 +0530") References: <000201c39355$f2d16be0$0100a8c0@VULCAN> Message-ID: G Kiran writes: > Is it possible for these mailing list digests to stick to a format.. > this is a request 'coz i parse these mail messages to keep as a > ref guide. > yes i can write a generalised one with re and python/perl > but guess i cud keep it simple... > > -kiran Sorry, but I have to ask: Why are you parsing the digest in the first place? wouldn't handling the non-digest style be easier? Those have on post in each mail, so you could even use the mail-handling libs in the python standard library. What extra do you get by parsing the digest? -- Abel Daniel From jtk at yahoo.com Tue Sep 16 12:44:34 2003 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Tue Sep 16 12:44:47 2003 Subject: [Tutor] string format float omitting decimal point? Message-ID: Is there a way to omit a decimal point directly in float string formatting? >>> ('%0.2f' % 23.06).replace('.','') '2306' From python at dhumketu.cjb.net Tue Sep 16 12:28:36 2003 From: python at dhumketu.cjb.net (Shantanoo Mahajan) Date: Tue Sep 16 13:03:08 2003 Subject: [Tutor] Serial Communication Message-ID: <20030916162836.GC1179@dhumketu.homeunix.net> Hi! I would like to know whether is it possible/preferrable to go for serial communications in python. I would like to know are there any functions/approach in python parallel to interupt driven structure in C/C++. -- Regards, Shantanoo Mahajan From alex at gabuzomeu.net Tue Sep 16 13:58:12 2003 From: alex at gabuzomeu.net (Alexandre Ratti) Date: Tue Sep 16 13:58:32 2003 Subject: [Tutor] How to write protect attributes or names In-Reply-To: <3F6628A2.1090506@aon.at> References: <3F6628A2.1090506@aon.at> Message-ID: <3F674F34.3020604@gabuzomeu.net> Hi Gregor, Gregor Lingl wrote: > is it possible to "write-protect" a definitive selection of attributes > (a) of a class > (b) of an object > (c) or a definitve selection of names of a module? > e.g. all the callable ones. For a class: 1) You could prefix your attribute names with two underscores so that they cannot be (easily) accessed from outside of the class because of the name-mangling feature. Example: ## >>> class Foo(object): ... def __init__(self): ... self.__bar = "titi" ... def test(self): ... print self.__bar ... >>> f = Foo() >>> f.test() titi >>> f.__bar Traceback (most recent call last): File "", line 1, in ? AttributeError: 'Foo' object has no attribute '__bar' >>> print [x for x in dir(f) if "bar" in x] ['_Foo__bar'] ## The attribute name is automatically modified so that it cannot be easily modified. 2) You could also use properties (in Python 2.2+) to create read-only attributes: ## >>> class Foo(object): ... def __init__(self): ... self._bar = "toto" ... def getBar(self): ... return self._bar ... bar = property(getBar) ... >>> f = Foo() >>> print f.bar toto >>> f.bar = "titi" Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute ## If you do not create a mathod to set the attribute value and pass it in the property() call, then the attribute will be read-only. You could also try to override the "__setattr__" method in your class to disallow settng specific attributes. I'm not sure what you can do at the module level. HTH. Alexandre From idiot1 at netzero.net Tue Sep 16 14:02:18 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Tue Sep 16 14:01:42 2003 Subject: [Tutor] Classes and the like... In-Reply-To: <200309160039.19484.intatia@paradise.net.nz> References: <200309160039.19484.intatia@paradise.net.nz> Message-ID: <3F67502A.80705@netzero.net> Here is a series of pages on my wiki which discuss objects and related matters. Is this any help? http://www.tinylist.org/cgi-bin/wikinehesa.py/ObjectOriented Intatia wrote: > Hey, new to the list and have a little question.. > Does anyone know of a good link that explains classes and what's associated > with them in realllly simple terms, because my friend has managed to totally > confuse me. A little bit on what they are and how to use them and why they do > what they do. > > Thanks. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From project5 at redrival.net Tue Sep 16 15:42:54 2003 From: project5 at redrival.net (Andrei) Date: Tue Sep 16 15:45:03 2003 Subject: [Tutor] Re: string format float omitting decimal point? In-Reply-To: References: Message-ID: Jeff Kowalczyk wrote: > Is there a way to omit a decimal point directly in float string formatting? The point of string formatting is to show the number as it is, not to modify it. >>>>('%0.2f' % 23.06).replace('.','') > > '2306' You can either modify the number in advance (multiply by 100 and int/round it), or - if all your numbers have two decimals - use the slightly shorter str(23.06).replace('.',''). But in the end it's all pretty much the same really. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From ATrautman at perryjudds.com Tue Sep 16 17:35:43 2003 From: ATrautman at perryjudds.com (Alan Trautman) Date: Tue Sep 16 17:37:05 2003 Subject: [Tutor] Serial Communication Message-ID: <06738462136C054B8F8872D69DA140DB01090C@corp-exch-1.pjinet.com> It's been a while since I used it but PySerial (Vaults of Parnassas and a personal site ) were quite easy to use. Alan -----Original Message----- From: Shantanoo Mahajan [mailto:python@dhumketu.cjb.net] Sent: Tuesday, September 16, 2003 11:29 AM To: tutor@python.org Subject: [Tutor] Serial Communication Hi! I would like to know whether is it possible/preferrable to go for serial communications in python. I would like to know are there any functions/approach in python parallel to interupt driven structure in C/C++. -- Regards, Shantanoo Mahajan _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From glingl at aon.at Tue Sep 16 20:05:39 2003 From: glingl at aon.at (Gregor Lingl) Date: Tue Sep 16 20:07:29 2003 Subject: [Tutor] How to write protect attributes or names In-Reply-To: <3F674F34.3020604@gabuzomeu.net> References: <3F6628A2.1090506@aon.at> <3F674F34.3020604@gabuzomeu.net> Message-ID: <3F67A553.5060403@aon.at> Alexandre Ratti schrieb: > Hi Gregor, > > > Gregor Lingl wrote: > >> is it possible to "write-protect" a definitive selection of attributes >> (a) of a class >> (b) of an object >> (c) or a definitve selection of names of a module? >> e.g. all the callable ones. > Hi Alexandre! Thanks for your comments! > > For a class: > > 1) You could prefix your attribute names with two underscores so that > they cannot be (easily) accessed from outside of the class because of > the name-mangling feature. Example: This IMHO is not what I need, as it not only write-protects but also read-protects (i. e. makes the attribute sort of private) > > .... > ['_Foo__bar'] > ## > > The attribute name is automatically modified so that it cannot be > easily modified. > > 2) You could also use properties (in Python 2.2+) to create read-only > attributes: Hmmm..., interesting, but I want to write-protect methods, i.e. callable attributes. That will not work with properties > > ## > >>> class Foo(object): > ... def __init__(self): > AttributeError: can't set attribute > ## > > If you do not create a mathod to set the attribute value and pass it > in the property() call, then the attribute will be read-only. > > You could also try to override the "__setattr__" method in your class > to disallow settng specific attributes. This will do what I want. > > I'm not sure what you can do at the module level. Yes, I also have ordinary functions, eg >>> width(5) which sets some hidden variable to 5 Now my program will also be used by very young students, who probably sometimes write >>> width = 5 which will result in the function width not beeing acces2ible anymore along with some (for them) strange errormessages like "int object is not callable" But I fear, there is no way to write-protect functions in __main__'s namespace. Regards, Gregor > > > HTH. > > Alexandre > > > > > > From GREENDAY31087 at aol.com Tue Sep 16 23:44:11 2003 From: GREENDAY31087 at aol.com (GREENDAY31087@aol.com) Date: Tue Sep 16 23:44:19 2003 Subject: [Tutor] simple pygame question Message-ID: <16e.23be8438.2c99328b@aol.com> Skipped content of type multipart/alternative-------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 5611 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20030916/189164d9/attachment.jpe From jonathan.hayward at pobox.com Wed Sep 17 13:34:16 2003 From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com) Date: Wed Sep 17 13:34:21 2003 Subject: [Tutor] Memory optimization needed: tarball In-Reply-To: <20030915113215.81511.qmail@web40020.mail.yahoo.com> References: <20030915113215.81511.qmail@web40020.mail.yahoo.com> Message-ID: <3F689B18.1030101@pobox.com> guillaume alleon wrote: > --- "Jonathan Hayward http://JonathansCorner.com" > a ?crit : > I have a >search engine I'm working on which uses > > >>memory inefficiently >>for large data. It indexes to avoid the cost of >>keeping documents in >>memory, but with a 150M dataset it takes 250M. >>Unlike previous requests >>where I didn't provide a good way to use it, I now >>have a tarball with >>installer: >> >>http://haywardfamily.org/jonathan/datamine0_0.tar.gz >> >> > >the link looks wrong, I can't get your tarball. > > There were a couple of problems on my end. The tarball is online at: http://JonathansCorner.com/datamine0_0b.tar.gz >Yours > >Guillaume > > >>I would welcome help cutting down memory taken by >>large datasets. >> >>Thanks in advance, >> >>-- >>++ Jonathan Hayward, jonathan.hayward@pobox.com >>** To see an award-winning website with stories, >>essays, artwork, >>** games, and a four-dimensional maze, why not visit >>my home page? >>** All of this is waiting for you at >>http://JonathansCorner.com >> >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> > >___________________________________________________________ >Do You Yahoo!? -- Une adresse @yahoo.fr gratuite et en fran?ais ! >Yahoo! Mail : http://fr.mail.yahoo.com > > > -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From vicki at thepenguin.org Wed Sep 17 15:11:58 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Wed Sep 17 15:12:03 2003 Subject: [Tutor] Conversion of each number of an integer to hex Message-ID: <40722.206.53.226.4.1063825918.squirrel@www.thepenguin.org> I am in a situation where I have to take some number like 24 and send it as hex 32 (the 2) and hex 34 (the 4). Is there some builtin function to do this? If not, is there a commonly used method? To be clear, I have to take the number and break it apart into elements which I then have to convert to hex to send as input to another module. --vicki From gerrit at nl.linux.org Wed Sep 17 15:23:04 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed Sep 17 15:23:14 2003 Subject: FW: [Tutor] simple pygame question Message-ID: <20030917192304.GA4644@nl.linux.org> Hi, there is a separate pygame mailing list for pygame questions. I don't know how to close the drive, I don't know if it's possible (hardware-technically), never encountered software doing it... ----- Forwarded message from GREENDAY31087@aol.com ----- Date: Wed, 17 Sep 2003 05:45:20 +0200 Subject: [Tutor] simple pygame question From: GREENDAY31087@aol.com To: tutor@python.org X-BeenThere: tutor@python.org Old-Date: Tue, 16 Sep 2003 23:44:11 EDT X-Mailer: 8.0 for Windows sub 910 Sender: Gerrit Holl This is the code to eject cd/open cd player: import pygame pygame.cdrom.init() CD = pygame.cdrom.CD(0) CD.init() CD.eject() How do I make the drive close? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ----- End forwarded message ----- yours, Gerrit. -- 174. If she bear no sons to her second husband, the sons of her first husband shall have the dowry. -- 1780 BC, 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 jeff at ccvcorp.com Wed Sep 17 15:38:26 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Sep 17 15:35:26 2003 Subject: [Tutor] Conversion of each number of an integer to hex References: <40722.206.53.226.4.1063825918.squirrel@www.thepenguin.org> Message-ID: <3F68B832.3050202@ccvcorp.com> Vicki Stanfield wrote: > I am in a situation where I have to take some number like 24 and send it > as hex 32 (the 2) and hex 34 (the 4). Is there some builtin function to do > this? If not, is there a commonly used method? To be clear, I have to take > the number and break it apart into elements which I then have to convert > to hex to send as input to another module. What you need to do is convert the number to a string with something like 'x = str(24)'. Now, if necessary, you can loop through that string and do something with each character. for char in str(24): print hex(ord(char)) In this example, ord() converts the character to its (integer) ascii code, and hex() converts that integer to a hex-digit string. However, you may not actually need to do that! If you're trying to feed ascii codes to another module, odds are that if you just pass in the string (possibly one character at a time) all of the necessary conversions will be taken care of for you. For instance, if you're trying to write to a serial port, you can simply write characters to it. Keep in mind that, in a language like C, a character is simply a single-byte unsigned integer type. Routines that pass characters back and forth often *look* like they're passing a hex number (i.e. 0x32), but it's actually a char -- or rather, in those languages there's no difference between that hex number and the char. Python does actually treat characters and strings as first-class types, but it knows how the underlying C routines look at characters, too. So usually, if you're trying to pass ascii codes around, you just want to use normal Python characters. Jeff Shannon Technician/Programmer Credit International From tim at johnsons-web.com Wed Sep 17 18:52:32 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Wed Sep 17 18:51:14 2003 Subject: [Tutor] Python 2.3 on Red Hat 9.0 Message-ID: <20030917225232.GB2738@johnsons-web.com> Hello All: I have recently installed Red Hat linux 9.0 The default python version on this distro is Python 2.2.2 When I was using Red Hat 7.2, I had to keep python 1.5 as my default python, because later versions broke some of my system tools. Does anyone know if I can safely install python 2.3 over 2.2.2 without causing any system problems? Comments? Pointers to docs are welcome too. -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From GREENDAY31087 at aol.com Wed Sep 17 23:56:23 2003 From: GREENDAY31087 at aol.com (GREENDAY31087@aol.com) Date: Wed Sep 17 23:56:34 2003 Subject: FW: [Tutor] simple pygame question Message-ID: <102.359f3c54.2c9a86e7@aol.com> Skipped content of type multipart/alternative-------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 5611 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20030917/a5fc48b0/attachment.jpe From intatia at paradise.net.nz Thu Sep 18 00:24:30 2003 From: intatia at paradise.net.nz (Intatia) Date: Thu Sep 18 00:26:14 2003 Subject: FW: [Tutor] simple pygame question In-Reply-To: <102.359f3c54.2c9a86e7@aol.com> References: <102.359f3c54.2c9a86e7@aol.com> Message-ID: <200309181624.30721.intatia@paradise.net.nz> Hey, Just go on over to: http://pygame.org/info.shtml Info about mailing list and IRC channel is at the top.:) Intatia On Thursday 18 Sep 2003 15:56, GREENDAY31087@aol.com wrote: > In a message dated 9/17/03 12:23:29 PM Pacific Daylight Time, > > gerrit@nl.linux.org writes: > > Hi, > > > > there is a separate pygame mailing list for pygame questions. > > I don't know how to close the drive, I don't know if it's > > possible (hardware-technically), never encountered software > > doing it... > > Hi! I didn't know that.. does anyone know what that mailing list is called? > Thanks, > Wayne From alok_rai at persistent.co.in Thu Sep 18 02:39:21 2003 From: alok_rai at persistent.co.in (Alok Rai) Date: Thu Sep 18 02:38:44 2003 Subject: [Tutor] Need help: Want to write a Platform Independent Network Messenger client Message-ID: <001401c37daf$9817ef00$bb07a8c0@midnapore> Hi, I am fairly new to the Python community in terms of writing significant Python code. I want to write a (Platform Independent) LAN messenger client in Python. Any pointers in this regard (existing libraries, tools, etc.) would be appreciated. Regards, Alok Rai -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030918/4d209362/attachment.html From shad at mail.kubtelecom.ru Thu Sep 18 06:04:16 2003 From: shad at mail.kubtelecom.ru (Denis Dzyubenko) Date: Thu Sep 18 06:07:10 2003 Subject: [Tutor] Need help: Want to write a Platform Independent Network Messenger client In-Reply-To: <001401c37daf$9817ef00$bb07a8c0@midnapore> (Alok Rai's message of "Thu, 18 Sep 2003 12:09:21 +0530") References: <001401c37daf$9817ef00$bb07a8c0@midnapore> Message-ID: <878yomquov.fsf@mail.kubtelecom.ru> On Thu, 18 Sep 2003 12:09:21 +0530, Alok Rai(AR) wrote to tutor: AR> I am fairly new to the Python community in terms of writing AR> significant Python code. I want to write a (Platform Independent) LAN AR> messenger client in Python. Any pointers in this regard (existing AR> libraries, tools, etc.) would be appreciated. Few months ago I started writing the same project - platform independent network chat compatible with Vypress Chat for Windows (http://www.vypress.com) - serverless chat using UDP packets - it is very useful for small LAN's. Now it is almost fully functional, but available only for Unix/Linux because I didn't noticed that select() on Windows doesn't support file descriptors, so I am going to rewrite chat using threads. If someone wants to help me writing this chat, welcome to my email or write messages to this list (I don't think it is an offtopic here). -- Denis. Without C we'd have BASI, PASAL, OBOL ;-) From bob at threeoh.com Fri Sep 12 16:25:22 2003 From: bob at threeoh.com (Bob Ippolito) Date: Thu Sep 18 12:42:36 2003 Subject: [pygame] Re: [Tutor] Fastest (x,y) distance calculation In-Reply-To: <2412.192.206.201.218.1063396902.squirrel@mail.harlekin-maus.com> Message-ID: <3BFF1930-E55F-11D7-B303-000A95686CD8@threeoh.com> On Friday, Sep 12, 2003, at 16:01 America/New_York, Zak Arntson wrote: >> [Raymond Hettinger] >>>> Distance calculations are much cheaper if you store the coordinates >>>> as complex numbers and use abs(). > > I don't know the concept behind using complex numbers and abs to > determine > distance. How does that work? You can think of complex numbers as a 2D plane in a lot of respects. The imaginary component is the Y axis, and the real component is the X axis. abs(c) is defined as the distance from the origin complex(0, 0j) or math.sqrt(c.real**2 + c.imag**2). >> Executive summary: abs(z1-z2) beats the (deltax**2 + deltay**2) >> approach But does creating two complex numbers out of two integer pairs add more overhead than the (deltax*deltax + deltay*deltay) version? I don't think it's faster unless MAYBE you store the coordinates as complex numbers internally at all times. The math.hypot(deltax, deltay) version is probably faster in practice. In any case, you're doing more computational work with abs or hypot because they are the actual distance, not the distance**2. -bob From cben at users.sf.net Sat Sep 13 14:42:15 2003 From: cben at users.sf.net (Beni Cherniavsky) Date: Thu Sep 18 12:42:46 2003 Subject: [pygame] Re: [Tutor] Fastest (x,y) distance calculation In-Reply-To: <3BFF1930-E55F-11D7-B303-000A95686CD8@threeoh.com> References: <3BFF1930-E55F-11D7-B303-000A95686CD8@threeoh.com> Message-ID: Bob Ippolito wrote on 2003-09-12: > You can think of complex numbers as a 2D plane in a lot of respects. > The imaginary component is the Y axis, and the real component is the X > axis. abs(c) is defined as the distance from the origin complex(0, 0j) > or math.sqrt(c.real**2 + c.imag**2). > > In any case, you're doing more computational work with abs or hypot > because they are the actual distance, not the distance**2. > There is a way to find abs**2 of complex numbers without sqrt: >>> a = 3 + 4j >>> b = 6 + 8j >>> d = a - b >>> d * d.conjugate() (25+0j) >>> (d * d.conjugate()).real 25.0 The "conjugate" operation simply negates the imaginary part of a complex number, so: (X + Yj) * (X - Yj) == X**2 + XYj - XYj - (Yj)**2 == X**2 + Y**2 Alas, this turns out even less effecient than abs() , probably because we do 4 float mutiplications (of which 2 we throw away) and because we of two extra attribute accesses: $ timeit.py -s 'd = 3 + 4j' '(d * d.conjugate()).real' 1000000 loops, best of 3: 1.45 usec per loop $ timeit.py -s 'd = 3 + 4j' 'abs(d)' 1000000 loops, best of 3: 0.623 usec per loop But `abs` on complex numbers *is* faster than multiplying integers by themselves and adding: $ timeit.py -s 'x = 3; y = 4' 'x * x + y * y' 1000000 loops, best of 3: 0.732 usec per loop So `abs` wins so far (python2.3, x86). If you use psyco, there is little doubt that the simplest integer method will win by far. -- Beni Cherniavsky From dsaussus at fugro-jason.com Mon Sep 15 05:11:58 2003 From: dsaussus at fugro-jason.com (Denis Saussus) Date: Thu Sep 18 12:42:52 2003 Subject: [Tutor] range() or xrange() for non-integers? In-Reply-To: Message-ID: <003701c37b69$6ad01470$920011ac@jason.nl> This is right along the same line of thinking. I have this util function which I find myself using nearly all the time: def floatRange(a, b, inc): """ Returns a list containing an arithmetic progression of floats. This is simply a float version of the built-in range(a, b, step) function. The result is [ , ) as always in Python. """ try: x = [float(a)] except: return False for i in range(1, int(math.ceil((b - a ) / inc))): x. append(a + i * inc) return x -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Andrei Sent: Sunday, September 14, 2003 4:09 PM To: tutor@python.org Subject: [Tutor] Re: range() or xrange() for non-integers? Terry Carroll wrote: > On Sat, 13 Sep 2003, Bob Gailer wrote: > > >>for x in xrange(-8.0, 8.0, 1.0): >> print x/2 > > > Thanks. > > I'd thought of something along those lines, but that seems even worse for > my particular application. I was going to need to vary the step to find > the optimal one. (The actual application is to generate points to graph > the x-component of electrical field generated by two particles.) So My > first cut might be varying by .5, another by .1, etc. To have to vary by > 1 and change the start and end points and an inner divisor to compensate > seems very kludgy to me. Why don't you just build your own rangef() function which returns a list? >>> def rangef(min, max, step): ... result = [] ... while 1: ... result.append(min) ... min = min+step ... if min>=max: ... break ... return result ... >>> rangef(2,3,.2) [2, 2.2000000000000002, 2.4000000000000004, 2.6000000000000005, 2.8000000000000007] If desired, you can add some parameter checking routines so that min0 or whatever you need. You could also do (with a generator): >>> def rangef(min=1, max=2, step=.2): ... while min>> for item in rangef(3, 5, .3): ... print item ... 3 3.3 3.6 3.9 4.2 4.5 4.8 -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From rodolfo49 at hotmail.com Tue Sep 16 19:02:31 2003 From: rodolfo49 at hotmail.com (Rodolfo Rosario) Date: Thu Sep 18 12:42:56 2003 Subject: [Tutor] don`t know how to begin...or what to do... Message-ID: Hello all, i have to do the following..."Write a program that continually reads in numbers from the user and adds them together until the sum reaches 100. Write another program that reads 100 numbers from the user and prints out the sum." i don`t know what to do..i know i`m supposed to use for or while, or for and while...please help me with this... dark poet.- _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From dyoo at hkn.eecs.berkeley.edu Thu Sep 18 12:54:27 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 18 12:54:50 2003 Subject: [Tutor] Need help: Want to write a Platform Independent Network Messenger client In-Reply-To: <001401c37daf$9817ef00$bb07a8c0@midnapore> Message-ID: On Thu, 18 Sep 2003, Alok Rai wrote: > I am fairly new to the Python community in terms of writing > significant Python code. I want to write a (Platform Independent) LAN > messenger client in Python. Any pointers in this regard (existing > libraries, tools, etc.) would be appreciated. Hi alok, Time to toss a bunch of URLs out! *grin* There's a IM protocol called "Jabber" that's in wide use: http://www.jabber.org/ There are a few Python projects out there that are using the Jabber protocol: http://imcom.floobin.cx/ http://bigasterisk.com/hiss/FrontPage so you can take a look at those as examples of clients. There is a Jabber library that you can use: http://www.jabber.org/developer/librarylist.php http://jabberpy.sourceforge.net/ and there may even be an alternative Jabber library in the 'Twisted Python' network framework, according to a thread here: http://twistedmatrix.com/pipermail/twisted-python/2003-February/003072.html Good luck to you! From python at dhumketu.cjb.net Thu Sep 18 13:41:20 2003 From: python at dhumketu.cjb.net (Shantanoo Mahajan) Date: Thu Sep 18 13:43:31 2003 Subject: [Tutor] Re: Serial Communication In-Reply-To: <06738462136C054B8F8872D69DA140DB01090C@corp-exch-1.pjinet.com> References: <06738462136C054B8F8872D69DA140DB01090C@corp-exch-1.pjinet.com> Message-ID: <20030918174120.GA343@dhumketu.homeunix.net> +-- Alan Trautman [python-tutor] [17-09-03 03:05 IST]: | It's been a while since I used it but PySerial (Vaults of Parnassas and a | personal site ) were quite easy to use. | | Alan nice thing to use. but i have few probs. 1) a='AB' let b = a[0]^a[1] in C/C++ how do i do this in python 2) a='ABC' let print("%X,%X",a[0],a[1]); output is 41,42 in C/C++ again how do i get this one. Final aim: a=[a,b,c,d,e] a is start byte which is equal to 0x02 b is command byte which is between 0x40 and 0x5E c is data byte which is between 0x30 and 0x3F d,e are checksum bytes are between 0x30 and 0x3F calculation of d,e chksum = a; chksum ^= b; chksum ^= c; d = (((chksum & 0xF0) >> 4) | 0x30) e = ((chksum & 0x0F) | 0x30) I am not able to get this thing in python. In what direction should I look? | | -----Original Message----- | From: Shantanoo Mahajan [mailto:python@dhumketu.cjb.net] | Sent: Tuesday, September 16, 2003 11:29 AM | To: tutor@python.org | Subject: [Tutor] Serial Communication | | | Hi! | I would like to know whether is it | possible/preferrable to go for serial communications | in python. I would like to know are there any | functions/approach in python parallel to interupt | driven structure in C/C++. | -- | Regards, | Shantanoo Mahajan | | _______________________________________________ | Tutor maillist - Tutor@python.org | http://mail.python.org/mailman/listinfo/tutor | | | | ------------------------------ -- With Best Regards, Shantanoo Mahajan From alex at gabuzomeu.net Thu Sep 18 15:25:35 2003 From: alex at gabuzomeu.net (Alexandre Ratti) Date: Thu Sep 18 15:25:52 2003 Subject: [Tutor] How to write protect attributes or names In-Reply-To: <3F67A553.5060403@aon.at> References: <3F6628A2.1090506@aon.at> <3F674F34.3020604@gabuzomeu.net> <3F67A553.5060403@aon.at> Message-ID: <3F6A06AF.6020803@gabuzomeu.net> Hello Gregor, Gregor Lingl wrote: > Alexandre Ratti schrieb: >> 2) You could also use properties (in Python 2.2+) to create read-only >> attributes: > > Hmmm..., interesting, but I want to write-protect methods, i.e. callable > attributes. That will not work with properties This reminds me of this document I read a few weeks ago about the descriptor protocol: How-To Guide for Descriptors, Raymond Hettinger http://users.rcn.com/python/download/Descriptor.htm I found it very interesting, though a bit complex. As I understand it, properties are a special case of descriptors. A descriptor is basically a go-between class that controls how you access an attribute or a method. We could write a descriptor that wraps a normal method to prevent anyone from remapping (or deleting) its name. This is based on the last example in the "How-To Guide for Descriptors": ## class Protector(object): def __init__(self, f): self.f = f def __set__(self, *args): print "Oh no. You cannot remap this method name." def __delete__(self, *args): print "Don't you even think of deleting this name!" def __get__(self, obj, cls = None): # When called from an instance, # obj = instance and cls = class. def f(*args): return self.f(obj, *args) return f class Foo(object): def _doer(self, arg): """Simulates a method that does something.""" return "toto: %s" % arg doer = Protector(_doer) ## Let's try it: ## >>> f = Foo() >>> f.doer('titi') 'toto: titi' >>> f.doer(2) 'toto: 2' >>> f.doer = "new name" Oh no. You cannot remap this method name. >>> del f.doer Don't you even think of deleting this name! ## Now you just need to find a way to automate the creation of the descriptor methods for every callable name that starts with a specific prefix. This example might be interesting: http://groups.google.fr/groups?hl=fr&lr=&ie=UTF-8&oe=UTF-8&selm=just-AA3639.09530820052003%40news1.news.xs4all.nl Overriding "__setattr__" might be more straightforward, though. Cheers. Alexandre From ronan at melim.com.br Thu Sep 18 15:32:59 2003 From: ronan at melim.com.br (Ronan Lucio) Date: Thu Sep 18 15:31:42 2003 Subject: [Tutor] MS-SQL Message-ID: <200309181632.59409.ronan@melim.com.br> Hello, Is there a way to access a MS-MSQL Server of a Windows 2000 Server from a Python CGI located in a FreeBSD box? Thank's Ronan From pythontutor at venix.com Thu Sep 18 16:26:51 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Thu Sep 18 16:27:19 2003 Subject: [Tutor] MS-SQL In-Reply-To: <200309181632.59409.ronan@melim.com.br> References: <200309181632.59409.ronan@melim.com.br> Message-ID: <3F6A150B.6070806@venix.com> Yes. The Sybase module works talking to an MS SQL database. I've used it, but can not guarantee that everything will work correctly. I've had no problems. import Sybase as MSSQL # reminder to me that this could be cheating self.conn = MSSQL.connect("1.2.3.4", user='me', passwd='mypassword') Ronan Lucio wrote: > Hello, > > Is there a way to access a MS-MSQL Server of a Windows > 2000 Server from a Python CGI located in a FreeBSD box? > > Thank's > Ronan > > _______________________________________________ > 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 amonroe at columbus.rr.com Thu Sep 18 17:57:34 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Sep 18 17:51:40 2003 Subject: [Tutor] don`t know how to begin...or what to do... In-Reply-To: References: Message-ID: <17170563985.20030918175734@columbus.rr.com> > i have to do the following..."Write a program that continually reads in > numbers from the user and adds them together until the sum reaches 100. > Write another program that reads 100 numbers from the user and prints out > the sum." > i don`t know what to do..i know i`m supposed to use for or while, or for and > while...please help me with this... For loops are meant for those times in life when you know in advance how many times you want to do something. Alan From paultaney at yahoo.com Thu Sep 18 18:10:06 2003 From: paultaney at yahoo.com (paul taney) Date: Thu Sep 18 18:10:13 2003 Subject: [Tutor] module object is not callable Message-ID: <20030918221006.42924.qmail@web80604.mail.yahoo.com> Hi, I am trying to use HTMLgen tor page generation. Everything was working fine as straight defs, but whenever I move stuff into a class structure I get into trouble. So, to try to get a clue I build a file called test_class_ctructure.py Here it is: ----------------- # This graphic represents the structure # # (stylesheet) # | # -> frontpage, contactpage, resumepage, trainpage # | | | | # ----------------------------------------- # | # V # generateMyIndex # class stylesheet: # no parents def __init__(self): print "random_brackets2 I am running..." class gen_frontpage(stylesheet): def __init__(self): print "gen_frontpage I am running..." class gen_contactpage(stylesheet): def __init__(self): print "gen_contactpage I am running.." class gen_resumepage(stylesheet): def __init__(self): print "gen_resumepage I am running..." class gen_trainpage(stylesheet): def __init__(self): print "gen_trainpage I am running..." class generateMyIndex(gen_frontpage, gen_trainpage, gen_contactpage, gen_resumepage): def __init__(self): print "generateMyIndex I am running __init__()..." print "generateMyIndex instantiating 1..." gen_frontpage.__init__(self) print "generateMyIndex instantiating 2..." gen_trainpage.__init__(self) print "generateMyIndex instantiating 3..." gen_contactpage.__init__(self) print "generateMyIndex instantiating 4..." gen_resumepage.__init__(self) if __name__ == "__main__": print "generateMyIndex instantiating me..." print "++++ main begin ++++" g = generateMyIndex() print "++++ main done ++++" ----------------- Runs well. Here's the output: $ python test_class_structure.py generateMyIndex instantiating me... ++++ main begin ++++ generateMyIndex I am running __init__()... generateMyIndex instantiating 1... gen_frontpage I am running... generateMyIndex instantiating 2... gen_trainpage I am running... generateMyIndex instantiating 3... gen_contactpage I am running.. generateMyIndex instantiating 4... gen_resumepage I am running... ++++ main done ++++ ------------------------------- When I apply this exact structure to my project space I get the now-dreaded error: TypeError: 'module' object is not callable I pulled tutor.mbox and grepped for this but only got 2 hits. What am I doing wrong? Thank you, paul taney __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From alan.gauld at blueyonder.co.uk Thu Sep 18 18:14:43 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 18 18:14:45 2003 Subject: [Tutor] Classes and the like... References: <200309160039.19484.intatia@paradise.net.nz> Message-ID: <002f01c37e32$435f00b0$6401a8c0@xp> > Hey, new to the list and have a little question.. > Does anyone know of a good link that explains classes If you are new to programming in general then you can pretty much ignore classes for now. Wait till you are confident with the basics. Only then do what I suggest next ;-) If you have programmed a little bit before but not used objects then you might try my OO page in my tutorial. It tries to explain OOP at a basic level. There are also loads of intros on the cetus-links web page. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Sep 18 18:22:35 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 18 18:22:37 2003 Subject: [Tutor] what are some alternatives to XMLRPC? References: <1063667515.3246.11.camel@localhost.localdomain><1063667515.3246.11.camel@localhost.localdomain><3.0.6.32.20030916095858.00b89ac0@mail.froggy.com.au> <147166151162.20030915220006@columbus.rr.com> Message-ID: <004a01c37e33$5c710b10$6401a8c0@xp> > I ran some tests this evening with XMLRPC, and found it to be a little > too slow for my needs... Thats a feature of using a text based protocol for RPC. XML/RPC as well as SOAP are really designed to make systems easily accessed from outside via lots of platforms. If you know the platforms you are using a binary protocol (using raw sockets or SQL for example) will be faster(*). If for some reason you can't use SQL in the final product then consider raw socket strings. If you have to come through firewalls etc XML over http is probably the best bet though. One way to improve performance is to encoide the result as a large binary block and send that as a single XML field. That will remove a whole heap of XML parsing, but leave you with the task of unpicking the binary data (sometimes called *marshalling*). HTH, Alan G. (*) XML is typically 10 or more times less efficient at transmittting data than a proprietary binary format. From alan.gauld at blueyonder.co.uk Thu Sep 18 18:37:03 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 18 18:37:05 2003 Subject: [Tutor] don`t know how to begin...or what to do... References: Message-ID: <00b901c37e35$61be3e10$6401a8c0@xp> > i have to do the following..."Write a program that continually reads in > numbers from the user and adds them together until the sum reaches 100. > Write another program that reads 100 numbers from the user and prints out > the sum." > > i don`t know what to do.. Divide and conquer, and use the Python >>> prompt to do it. Write a program to read in two numbers and add them together. Write a program that keeps on reading new numbers and prints out the running total Write a program that adds two numbers and prints a message when the total is more than 100 Write a program that keeps on reading numbers and prints out the running total if its greater than 100 Do the homework questions... As to further clues you are correct. Use "while" to repeatedly do something until some condition changes(like a total being bigger than 100 say...). Use "for" to repeatedly do something to or with each item in a sequence - the sequence could be a list of numbers such as produced by the range() function for example). HTH, Alan G. From jeff at ccvcorp.com Thu Sep 18 19:01:19 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 18 18:58:22 2003 Subject: [Tutor] module object is not callable References: <20030918221006.42924.qmail@web80604.mail.yahoo.com> Message-ID: <3F6A393F.5010308@ccvcorp.com> paul taney wrote: > When I apply this exact structure to my > project space I get the now-dreaded error: > > TypeError: 'module' object is not callable I can't point to exactly what your error is, because you've stripped off the rest of the traceback stack, but I can tell you what that error means and you can probably figure out the rest for yourself. You're trying to call a module object as if it were a function, and that's not working. Probably you're importing a module that has the same name as a function or class; when you think you're calling that function (or instantiating that class), Python thinks that you're referring to the imported module instead. If you carefully check through your code (especially the code indicated by the traceback) and remove any name conflicts, you should be good. Jeff Shannon Technician/Programmer Credit International From learning.python at dbmail.dk Thu Sep 18 20:16:29 2003 From: learning.python at dbmail.dk (Ole Jensen) Date: Thu Sep 18 20:18:14 2003 Subject: [Tutor] THE CGI SERVER SCRIPT References: <3F5BE41C.9080702@netzero.net><000901c3762e$44273820$a24c73d5@BAERBAR><3F5D5F0C.4010204@netzero.net><003501c37ad7$4f730080$8d4c73d5@BAERBAR> <3F64AED1.1010604@netzero.net> Message-ID: <000701c37e43$45f7c440$bc4c73d5@BAERBAR> How does it work when importing modules? I am asking because I have been trying to get the CGIserver program to work with som problems I might add. However I got it working by changing this: import BaseHTTPServer, CGIHTTPServer to this: import BaseHTTPServerv import CGIHTTPServer I was under the impression that it was fully possiple to import two (and more) modules at the same time, besides Kirk apparently had the program working using the former code bit? Basically I'm asking this why was I not able to import both modules in one go? > STEVE wrote the server, I simply called a bug in it to his attention; he fixed > it. I used it, and made sure it was ok to give out copies, then offered it to you all. Hmm I should be able to remember that now, third time lucky, eh ;-) > Just want to appolgies for the little late reply, work's been keeping me focused elsewhere... I set up a desktop shortcut like you described Kirk, but it still shut down right away, I'm expecting python to remain open but minimized. I have discovered something else though, the trace back that I get when running the server, is the same when I just open idle and try to import CGIHTTPServer. >>> import CGIHTTPServer Traceback (most recent call last): File "", line 1, in ? import CGIHTTPServer File "C:\PROGRA~1\python\lib\CGIHTTPServer.py", line 28, in ? import SimpleHTTPServer File "C:\PROGRA~1\python\lib\SimpleHTTPServer.py", line 17, in ? import cgi File "C:\Programmer\python\cgi.py", line 3, in ? httpd=BaseHTTPServer.HTTPServer(('',80), CGIHTTPServer.CGIHTTPRequestHandler) AttributeError: 'module' object has no attribute 'CGIHTTPRequestHandler' As can be seen I cannot even import the module without getting an error, I have tried to download an reinstall python (2.3) and still get the same result (the above trace back is copied from IDLE). I don't understand this I am sure that I have spelled it correct, and as From shalehperry at comcast.net Fri Sep 19 00:32:20 2003 From: shalehperry at comcast.net (Sean 'Shaleh' Perry) Date: Fri Sep 19 00:32:26 2003 Subject: [Tutor] moving, will be back in 2 or 3 weeks Message-ID: <200309182132.20366.shalehperry@comcast.net> Finally getting out of the apartment (YAY). While the new place is still a rental at least it is bigger and has windows. See you all in a couple of weeks. From idiot1 at netzero.net Fri Sep 19 00:39:28 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Fri Sep 19 00:38:50 2003 Subject: [Tutor] THE CGI SERVER SCRIPT In-Reply-To: <000701c37e43$45f7c440$bc4c73d5@BAERBAR> References: <3F5BE41C.9080702@netzero.net><000901c3762e$44273820$a24c73d5@BAERBAR><3F5D5F0C.4010204@netzero.net><003501c37ad7$4f730080$8d4c73d5@BAERBAR> <3F64AED1.1010604@netzero.net> <000701c37e43$45f7c440$bc4c73d5@BAERBAR> Message-ID: <3F6A8880.8050000@netzero.net> Ole Jensen wrote: > How does it work when importing modules? Not bad, once you sneak them past customs... > I am asking because I have been trying to get the CGIserver program to work > with some problems I might add. > However I got it working by changing this: > > import BaseHTTPServer, CGIHTTPServer > > to this: > > import BaseHTTPServerv > import CGIHTTPServer > > I was under the impression that it was fully possiple to import two (and > more) modules at the same time, besides Kirk apparently had the program > working using the former code bit? > STEVE! STEVE! I JUST REPORT THE THING! STEVE HOLDEN! ARG! :-) > Basically I'm asking this why was I not able to import both modules in one > go? > That's odd; it works for me just fine. Could this be a quirk of a divferent version of python? I am running 2.2.1; how about you? > > > >>STEVE wrote the server, I simply called a bug in it to his attention; he > > fixed > >>it. I used it, and made sure it was ok to give out copies, then offered it > > to you all. > > Hmm I should be able to remember that now, third time lucky, eh ;-) > > > Just want to appolgies for the little late reply, work's been keeping me > focused elsewhere... > > I set up a desktop shortcut like you described Kirk, but it still shut down > right away, I'm expecting python to remain open but minimized. > > I have discovered something else though, the trace back that I get when > running the server, is the same when I just open idle and try to import > CGIHTTPServer. > > > >>>>import CGIHTTPServer > > Traceback (most recent call last): > File "", line 1, in ? > import CGIHTTPServer > File "C:\PROGRA~1\python\lib\CGIHTTPServer.py", line 28, in ? > import SimpleHTTPServer > File "C:\PROGRA~1\python\lib\SimpleHTTPServer.py", line 17, in ? > import cgi > File "C:\Programmer\python\cgi.py", line 3, in ? > httpd=BaseHTTPServer.HTTPServer(('',80), > CGIHTTPServer.CGIHTTPRequestHandler) > AttributeError: 'module' object has no attribute 'CGIHTTPRequestHandler' > > > As can be seen I cannot even import the module without getting an error, I > have tried to download an reinstall python (2.3) and still get the same > result (the above trace back is copied from IDLE). I don't understand this I > am sure that I have spelled it correct, and as > > > > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From dyoo at hkn.eecs.berkeley.edu Fri Sep 19 03:25:41 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 19 03:25:46 2003 Subject: [Tutor] moving, will be back in 2 or 3 weeks In-Reply-To: <200309182132.20366.shalehperry@comcast.net> Message-ID: On Thu, 18 Sep 2003, Sean 'Shaleh' Perry wrote: > Finally getting out of the apartment (YAY). While the new place is > still a rental at least it is bigger and has windows. > > See you all in a couple of weeks. Good luck to you, Sean. Come by for next month's Baypiggies meeting! *grin* From learning.python at dbmail.dk Fri Sep 19 07:31:23 2003 From: learning.python at dbmail.dk (Ole Jensen) Date: Fri Sep 19 07:33:08 2003 Subject: [Tutor] THE CGI SERVER SCRIPT References: <3F5BE41C.9080702@netzero.net><000901c3762e$44273820$a24c73d5@BAERBAR><3F5D5F0C.4010204@netzero.net><003501c37ad7$4f730080$8d4c73d5@BAERBAR><3F64AED1.1010604@netzero.net><000701c37e43$45f7c440$bc4c73d5@BAERBAR> <3F6A8880.8050000@netzero.net> Message-ID: <001401c37ea1$8e717320$b44c73d5@BAERBAR> > > > > import BaseHTTPServer, CGIHTTPServer > > > > to this: > > > > import BaseHTTPServerv > > import CGIHTTPServer > > > That's odd; it works for me just fine. Could this be a quirk of a divferent > version of python? I am running 2.2.1; how about you? > Argh... I was gonna write that(must have forgot). first I was using python 2.2.3, but as I couldn't get it to work I tried downloading 2.3 which I using now. I couldn't get the script to work as you supplied in any of these, and then I tried to test different things and got it working using the above change. But I got it working now and am looking forward toying around with making CGI script, and thanks goes to Jirk for sending this to the tutor, it is gonna be a very useful. From pythontutor at venix.com Fri Sep 19 08:51:38 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Fri Sep 19 08:51:59 2003 Subject: [Tutor] Python 2.3 on Red Hat 9.0 In-Reply-To: <20030917225232.GB2738@johnsons-web.com> References: <20030917225232.GB2738@johnsons-web.com> Message-ID: <3F6AFBDA.3040804@venix.com> I think it is OK, but I have not yet done it, so this is NOT the voice of experience. However, when I spot checked a couple of redhat utilities, the shebang was simply: #!/usr/bin/python Hopefully, any version specific utilities will point to the specific version of Python that they need. Tim Johnson wrote: > Hello All: > I have recently installed Red Hat linux 9.0 > The default python version on this distro > is Python 2.2.2 > > When I was using Red Hat 7.2, I had to keep > python 1.5 as my default python, because later > versions broke some of my system tools. > > Does anyone know if I can safely install > python 2.3 over 2.2.2 without causing any > system problems? > > Comments? > Pointers to docs are welcome too. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From carlo_bif at yahoo.com Fri Sep 19 08:50:59 2003 From: carlo_bif at yahoo.com (Carlo Bifulco) Date: Fri Sep 19 08:53:08 2003 Subject: [Tutor] Permutations Message-ID: <3F6AFBB3.2070707@yahoo.com> Hi folks, I have a small computing problem that I solved in an extremely ugly and ad hoc way. I am submitting it here since I am sure that there must be much better ways to address it (and I am obviously not able to find them). Here is what I would like to be able to do: >>> permute(["a"]) [['a']] >>> permute(["a","b"]) [['a'], ['a', 'b'], ['b']] >>> permute(["a","b","c"]) [['a'], ['a', 'b'], ['a', 'c'], ['a', 'b', 'c'], ['b'], ['b', 'c'], ['c']] >>> permute (["a","b","c","d"]) [['a'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'c', 'd'], ['a', 'b', 'c', 'd'], ['b'], ['b', 'c'], ['b', 'd'], ['b', 'c', 'd'], ['c'], ['c', 'd'], ['d']] >>> permute ("a","b",...) and so on... It's actually a practical problem, since I am analyzing all possible combinations of a group of restriction enzymes and 1) I do not care in which order they are. 2) I don't care of repeated items. I.e. in this setting: >>> ["a","b"]==["b","a"] >>> ["a","a"]==["a"] I appended to the bottom of this my current solution to the problem; the code is ugly and obviously does not scale at all; don't bother reading it unless you have a lot of free time... Thanks for your help, Carlo class Permutator (list): """ >>> cleaner(Permutator(["a","b","None","None"])()) [['a'], ['a', 'b'], ['b']] >>> cleaner(Permutator(["a","b","c","None"])()) [['a'], ['a', 'b'], ['a', 'c'], ['a', 'b', 'c'], ['b'], ['b', 'c'], ['c']] >>> """ def __init__(self,listOfEnzymes): self.listOfEnzymes=listOfEnzymes self.a,self.b,self.c,self.d=self.listOfEnzymes self.append([]) def add(self,item): for i in self: #print item, if self.equal(i,item): #print "EQUAL" return self.append(item) def combine(self): #XXX THESE IS AD HOCK FOR 4 ENZYMES; UGLY self.tempList=[[a,b,c,d] for a in self.listOfEnzymes for b in self.listOfEnzymes for c in self.listOfEnzymes for d in self.listOfEnzymes] def equal(self,x,y): #XXX AGAIN AD HOC if x.count(self.a)==y.count(self.a) and x.count(self.b)==y.count(self.b) and x.count(self.c)==y.count(self.c) and x.count(self.d)==y.count(self.d): return 1 return 0 def __call__(self): self.combine() for i in self.tempList: self.add(i) try: self.remove([]) except ValueError: pass return self def cleaner(listOfPermutations): """ >>> cleaner([["a"],["a"],["a","a","b"],["b","b","a"]]) [['a'], ['a', 'b'], ['b', 'a']] >>> """ newList=[] for i in listOfPermutations: temp=[] for e in i: if e not in temp: if e=="None": continue temp.append(e) newList.append(temp) d=[] for i in newList: if i not in d: d.append(i) try: d.remove([]) except ValueError: pass return d -- Carlo B. Bifulco, MD Yale University School of Medicine EP2-608 310 Cedar Street New Haven, CT 06520 Tel: 203 737 2818 Fax: 203 737 2922 From bgailer at alum.rpi.edu Fri Sep 19 10:18:04 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Sep 19 10:20:20 2003 Subject: [Tutor] MS-SQL In-Reply-To: <3F6A150B.6070806@venix.com> References: <200309181632.59409.ronan@melim.com.br> <3F6A150B.6070806@venix.com> Message-ID: <6.0.0.22.0.20030919081737.0391c140@66.28.54.253> At 02:26 PM 9/18/2003, Lloyd Kvam wrote: >Yes. >The Sybase module works talking to an MS SQL database. I've used >it, but can not guarantee that everything will work correctly. I've had >no problems. > >import Sybase as MSSQL # reminder to me that this could be cheating >self.conn = MSSQL.connect("1.2.3.4", user='me', passwd='mypassword') Where can we get the Sybase module? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From krier115 at student.liu.se Fri Sep 19 11:26:24 2003 From: krier115 at student.liu.se (Kristoffer Erlandsson) Date: Fri Sep 19 11:32:30 2003 Subject: [Tutor] Permutations In-Reply-To: <3F6AFBB3.2070707@yahoo.com> References: <3F6AFBB3.2070707@yahoo.com> Message-ID: <20030919152624.GA17788@n14.ryd.student.liu.se> On Fri, Sep 19, 2003 at 08:50:59AM -0400, Carlo Bifulco wrote: > Hi folks, > > I have a small computing problem that I solved in an extremely ugly and > ad hoc way. I am submitting it here since I am sure that there must be > much better ways to address it (and I am obviously not able to find > them). > > Here is what I would like to be able to do: > >>> permute(["a"]) > [['a']] > >>> permute(["a","b"]) > [['a'], ['a', 'b'], ['b']] > >>> permute(["a","b","c"]) > [['a'], ['a', 'b'], ['a', 'c'], ['a', 'b', 'c'], ['b'], ['b', 'c'], ['c']] > >>> permute (["a","b","c","d"]) > [['a'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'b', 'c'], ['a', 'b', > 'd'], ['a', 'c', 'd'], ['a', 'b', 'c', 'd'], ['b'], ['b', 'c'], ['b', > 'd'], ['b', 'c', 'd'], ['c'], ['c', 'd'], ['d']] [snip] Check this out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 especially the xuniqueCombinations function, which seems to be exactly what you are looking for: >>> for i in range(len(l)): ... for a in xuniqueCombinations(l, i): ... print a ... [] ['a'] ['b'] ['c'] ['d'] ['a', 'b'] ['a', 'c'] ['a', 'd'] ['b', 'c'] ['b', 'd'] ['c', 'd'] ['a', 'b', 'c'] ['a', 'b', 'd'] ['a', 'c', 'd'] ['b', 'c', 'd'] Hope that helps. Regards, -- Kristoffer Erlandsson http://errl.info From krier115 at student.liu.se Fri Sep 19 11:40:56 2003 From: krier115 at student.liu.se (Kristoffer Erlandsson) Date: Fri Sep 19 11:42:04 2003 Subject: [Tutor] Permutations In-Reply-To: <20030919152624.GA17788@n14.ryd.student.liu.se> References: <3F6AFBB3.2070707@yahoo.com> <20030919152624.GA17788@n14.ryd.student.liu.se> Message-ID: <20030919154056.GA17977@n14.ryd.student.liu.se> On Fri, Sep 19, 2003 at 05:26:24PM +0200, Kristoffer Erlandsson wrote: > On Fri, Sep 19, 2003 at 08:50:59AM -0400, Carlo Bifulco wrote: > > Hi folks, > > > > I have a small computing problem that I solved in an extremely ugly and > > ad hoc way. I am submitting it here since I am sure that there must be > > much better ways to address it (and I am obviously not able to find > > them). > > > > Here is what I would like to be able to do: > > >>> permute(["a"]) > > [['a']] > > >>> permute(["a","b"]) > > [['a'], ['a', 'b'], ['b']] > > >>> permute(["a","b","c"]) > > [['a'], ['a', 'b'], ['a', 'c'], ['a', 'b', 'c'], ['b'], ['b', 'c'], ['c']] > > >>> permute (["a","b","c","d"]) > > [['a'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'b', 'c'], ['a', 'b', > > 'd'], ['a', 'c', 'd'], ['a', 'b', 'c', 'd'], ['b'], ['b', 'c'], ['b', > > 'd'], ['b', 'c', 'd'], ['c'], ['c', 'd'], ['d']] > > [snip] > > Check this out: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 > > especially the xuniqueCombinations function, which seems to be exactly > what you are looking for: > > >>> for i in range(len(l)): > ... for a in xuniqueCombinations(l, i): > ... print a > ... > [] > ['a'] > ['b'] > ['c'] > ['d'] > ['a', 'b'] > ['a', 'c'] > ['a', 'd'] > ['b', 'c'] > ['b', 'd'] > ['c', 'd'] > ['a', 'b', 'c'] > ['a', 'b', 'd'] > ['a', 'c', 'd'] > ['b', 'c', 'd'] Argh, there I get for not proof reading as I should :P. My example got messed up, here's a working one: >>> l = list('abcd') >>> for i in range(len(l)+1): ... for a in xuniqueCombinations(l, i): ... print a ... [] ['a'] ['b'] ['c'] ['d'] ['a', 'b'] ['a', 'c'] ['a', 'd'] ['b', 'c'] ['b', 'd'] ['c', 'd'] ['a', 'b', 'c'] ['a', 'b', 'd'] ['a', 'c', 'd'] ['b', 'c', 'd'] ['a', 'b', 'c', 'd'] As you can guess, you can do other things besides only printing the elements. -- Kristoffer Erlandsson http://errl.info From godoy at metalab.unc.edu Fri Sep 19 12:28:55 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Fri Sep 19 12:29:50 2003 Subject: [Tutor] moving, will be back in 2 or 3 weeks In-Reply-To: <200309182132.20366.shalehperry@comcast.net> (Sean Perry's message of "Thu, 18 Sep 2003 21:32:20 -0700") References: <200309182132.20366.shalehperry@comcast.net> Message-ID: Sean 'Shaleh' Perry writes: > Finally getting out of the apartment (YAY). While the new place is still a > rental at least it is bigger and has windows. > > See you all in a couple of weeks. Good look. And take pictures of both. :-) I'm very curious. hehehe. -- Godoy. From godoy at metalab.unc.edu Fri Sep 19 12:31:02 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Fri Sep 19 12:31:44 2003 Subject: [Tutor] Getting username from the system on Windows 95/98 Message-ID: Hi! For Windows XP and I suppose NT I can use the module getpass (getpass.getuser(), specifically) to get the username from the user logged on the system. Is there something that also works on Windows 95/98/98SE? TIA, -- Godoy. From pythontutor at venix.com Fri Sep 19 12:52:12 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Fri Sep 19 12:52:38 2003 Subject: [Tutor] MS-SQL In-Reply-To: <6.0.0.22.0.20030919081737.0391c140@66.28.54.253> References: <200309181632.59409.ronan@melim.com.br> <3F6A150B.6070806@venix.com> <6.0.0.22.0.20030919081737.0391c140@66.28.54.253> Message-ID: <3F6B343C.8090508@venix.com> http://www.python.org/topics/database/modules.html Python Database Modules The Sybase module is towards the bottom of the list. (An aside: I've gotten a few emails addressed to my pythontutor address that were bogus microsoft security emails. Naturally there is an evil executable attachment. http://www.theregister.com/content/56/32925.html) Bob Gailer wrote: > At 02:26 PM 9/18/2003, Lloyd Kvam wrote: > >> Yes. >> The Sybase module works talking to an MS SQL database. I've used >> it, but can not guarantee that everything will work correctly. I've had >> no problems. >> >> import Sybase as MSSQL # reminder to me that this could be cheating >> self.conn = MSSQL.connect("1.2.3.4", user='me', passwd='mypassword') > > > Where can we get the Sybase module? > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 > > > ------------------------------------------------------------------------ > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 > > > ------------------------------------------------------------------------ > > _______________________________________________ > 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 ATrautman at perryjudds.com Fri Sep 19 17:48:06 2003 From: ATrautman at perryjudds.com (Alan Trautman) Date: Fri Sep 19 17:48:12 2003 Subject: [Tutor] FW: Serial Communication Message-ID: <06738462136C054B8F8872D69DA140DB01C08A0D@corp-exch-1.pjinet.com> Shantanoo, I am forwarding this to the tutor list. I am very busy right now and am not as experienced as most posters on the list. Alan -----Original Message----- From: Shantanoo Mahajan [mailto:python@dhumketu.cjb.net] Sent: Thursday, September 18, 2003 12:41 PM To: Alan Trautman Cc: tutor@python.org Subject: Re: Serial Communication +-- Alan Trautman [python-tutor] [17-09-03 03:05 IST]: | It's been a while since I used it but PySerial (Vaults of Parnassas and a | personal site ) were quite easy to use. | | Alan nice thing to use. but i have few probs. 1) a='AB' let b = a[0]^a[1] in C/C++ how do i do this in python 2) a='ABC' let print("%X,%X",a[0],a[1]); output is 41,42 in C/C++ again how do i get this one. Final aim: a=[a,b,c,d,e] a is start byte which is equal to 0x02 b is command byte which is between 0x40 and 0x5E c is data byte which is between 0x30 and 0x3F d,e are checksum bytes are between 0x30 and 0x3F calculation of d,e chksum = a; chksum ^= b; chksum ^= c; d = (((chksum & 0xF0) >> 4) | 0x30) e = ((chksum & 0x0F) | 0x30) I am not able to get this thing in python. In what direction should I look? | | -----Original Message----- | From: Shantanoo Mahajan [mailto:python@dhumketu.cjb.net] | Sent: Tuesday, September 16, 2003 11:29 AM | To: tutor@python.org | Subject: [Tutor] Serial Communication | | | Hi! | I would like to know whether is it | possible/preferrable to go for serial communications | in python. I would like to know are there any | functions/approach in python parallel to interupt | driven structure in C/C++. | -- | Regards, | Shantanoo Mahajan | | _______________________________________________ | Tutor maillist - Tutor@python.org | http://mail.python.org/mailman/listinfo/tutor | | | | ------------------------------ -- With Best Regards, Shantanoo Mahajan From dyoo at hkn.eecs.berkeley.edu Fri Sep 19 18:22:31 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 19 18:23:16 2003 Subject: [Tutor] FW: Serial Communication In-Reply-To: <06738462136C054B8F8872D69DA140DB01C08A0D@corp-exch-1.pjinet.com> Message-ID: Hi Shantanoo, Looks like you're doing a lot of bit manipulation here; you'll definitely want to look into the 'struct' module: http://www.python.org/doc/lib/module-struct.html to convert between bytes and Python objects. > 1) a='AB' > let > b = a[0]^a[1] > in C/C++ > how do i do this in python When you say: b = a[0] ^ a[1] it looks like you're trying to use the bitwise XOR operator. But since 'a' is a string, this won't work. To use bit operations, you need to be working with numbers. We can convert between strings and their ascii ordinal values by using the ord() builtin: ### >>> s = "AB" >>> b1 = ord(s[0]) >>> b2 = ord(s[1]) >>> b1 65 >>> b2 66 ### And once we have numbers, bitwise manipulation should work as you expect: ### >>> b1 ^ b2 3 ### One way to more easily convert a string into a list of its ordinal numbers a list comprehension or the map() builtin function: ### >>> [ord(x) for x in "Hello world"] [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] >>> >>> >>> map(ord, "Hello world") [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] ### > > 2) a='ABC' > let > print("%X,%X",a[0],a[1]); > output is 41,42 > in C/C++ > again how do i get this one. You can find a way to do that in Python by using the String Formatting operator: http://www.python.org/doc/lib/typesseq-strings.html Good luck to you! From intatia at paradise.net.nz Fri Sep 19 21:56:21 2003 From: intatia at paradise.net.nz (Intatia) Date: Fri Sep 19 21:58:07 2003 Subject: [Tutor] Classes and the like... In-Reply-To: <002f01c37e32$435f00b0$6401a8c0@xp> References: <200309160039.19484.intatia@paradise.net.nz> <002f01c37e32$435f00b0$6401a8c0@xp> Message-ID: <200309201356.22820.intatia@paradise.net.nz> Hi, Thanks all for the links on classes/OO. On Friday 19 Sep 2003 10:14, Alan Gauld wrote: > > Hey, new to the list and have a little question.. > > Does anyone know of a good link that explains classes > > If you are new to programming in general then you can pretty > much ignore classes for now. Wait till you are confident with > the basics. Only then do what I suggest next ;-) > Yerp, done a bit before in various languages, though nothing too extensive. Computer programming class in school is rather uninformative due to certain louts, but that happens.:) > If you have programmed a little bit before but not used objects > then you might try my OO page in my tutorial. It tries to > explain OOP at a basic level. There are also loads of intros > on the cetus-links web page. > Object? What's an object? Didn't actually really know until just recently and it looks like it might take a bit for the whole idea to sink in and for me to use OO more. Of course, the OO page started to make some sense after reading the bottom part of 'The Raw Materials'. Any ideas on a fairly simple project I could do next? > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld Intatia From kp8 at mac.com Sat Sep 20 00:21:49 2003 From: kp8 at mac.com (kevin parks) Date: Sat Sep 20 00:22:08 2003 Subject: [Tutor] rotating a list Message-ID: Hi. My python chops are a bit rusty but i need another pair of eyes to tell me what i am doing wrong. I am sure that it is something very stupid but i can't see what it is.. I am trying to cycle through a list like so [a, b, c] [b, c, a] [c, a, b] [a, b, c] only, that aint be what is coming out the other side... anyone see where things are going wrong? cheers, -kp-- --^---------------------------------------- kevin parks university of virginia k p p 9 c @ virginia . edu PS. If my man Danny is out there... 'Hi' P.P.S if there are any pythonistas out here at UVa, i'd love to hear from you. i am new here. import sys import random # cyclically rotate a sequence # should work on any sequence type (list, tuple, string) and should work with # any hop(n) interval and also work in both directions (left or right) def rotate(seq, n=1): if len(seq) == 0: return seq n = n % len(seq) # Normalize n, using modulo - even works for negative n return seq[n:] + seq[:n] def test(): random.seed(720) # reproducable results x = range(0, 12, 1) # create a list for test purposes print x; print # look at it random.shuffle(x) # scramble it up print x; print # look at again... # Now rotate the list one at a time till we've done come to # the beginning once again for i in range(len(x)): y = rotate(x) print y if __name__ == "__main__": test() output is something like: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] [2, 5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] [5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] --[End of dumb question]--- From alok_rai at persistent.co.in Sat Sep 20 04:03:14 2003 From: alok_rai at persistent.co.in (Alok Rai) Date: Sat Sep 20 04:02:40 2003 Subject: [Tutor] How to set PYTHONPATH variable at Python startup Message-ID: <004f01c37f4d$a4b26570$bb07a8c0@midnapore> Hi, I might sound pretty naive to ask this question which must have been asked here umpteen times, but since I am fairly new to this community I think I can get away with this :-). None of the previous replies posted on similar topics have been of any help to me. My question is there a way by which my current working directory would automatically get added to Python path along with all its sub-directories (on both Windows and Linux platforms). I am aware of how one can set the PYTHONPATH variable but I wish to know how one can automatically configure Python to set this path on starting up. I would also like to know about something called PYTHONSTARTUP which tells Python what commands to run before starting the interpreter. Currently in Windows I edit a registry entry called Python Path to set PYTHONPATH variable. But I wish to know how this can be done automatically (or through the PYTHONSTARTUP option). Regards, Alok. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030920/8400b423/attachment.html From project5 at redrival.net Sat Sep 20 05:09:25 2003 From: project5 at redrival.net (Andrei) Date: Sat Sep 20 05:11:30 2003 Subject: [Tutor] Re: rotating a list In-Reply-To: References: Message-ID: Hi Kevin, kevin parks wrote: > Hi. My python chops are a bit rusty but i need another pair of eyes to > tell me what i am doing wrong. I am sure that it is something very > stupid but i can't see what it is.. I am trying to cycle through a list > like so > > [a, b, c] > [b, c, a] > [c, a, b] > [a, b, c] > > only, that aint be what is coming out the other side... > > anyone see where things are going wrong? > # cyclically rotate a sequence > > # should work on any sequence type (list, tuple, string) and should work > with > # any hop(n) interval and also work in both directions (left or right) > > def rotate(seq, n=1): > if len(seq) == 0: > return seq > n = n % len(seq) # Normalize n, using modulo - even works for > negative n > > return seq[n:] + seq[:n] Works fine here: >>> rotate([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0] >>> rotate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0]) [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1] >>> rotate([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1]) [3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2] > > def test(): > random.seed(720) # reproducable results > x = range(0, 12, 1) # create a list for test purposes > print x; print # look at it > random.shuffle(x) # scramble it up > print x; print # look at again... > # Now rotate the list one at a time till we've done come to > # the beginning once again > for i in range(len(x)): Here's your problem your rotate x and assign the result to y: > y = rotate(x) Now x is unchanged, y is the result, so you go back and rotate the same old x again. Obviously the result won't change. > print y Here's the improved version: for i in range(len(x)): x = rotate(x) print x Results: >>> test() [0, 1, 2, 3, 4] [0, 1, 4, 2, 3] [1, 4, 2, 3, 0] [4, 2, 3, 0, 1] [2, 3, 0, 1, 4] [3, 0, 1, 4, 2] [0, 1, 4, 2, 3] -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From erikprice at mac.com Sat Sep 20 11:48:29 2003 From: erikprice at mac.com (Erik Price) Date: Sat Sep 20 11:27:10 2003 Subject: [Tutor] Classes and the like... In-Reply-To: <200309201356.22820.intatia@paradise.net.nz> Message-ID: On Friday, September 19, 2003, at 09:56 PM, Intatia wrote: > Object? What's an object? Didn't actually really know until just > recently and > it looks like it might take a bit for the whole idea to sink in and > for me to > use OO more. A class is a definition of an object. Your original question asked about classes, so I'm guessing people assumed that you were really asking about objects. You define an object by writing a class block, similar to how you define a function by writing a function block. Think for a moment only about functions: 1. You define a function once in your code. 2. Later, you can call that function in other places of your code. Calling the function might produce a value (such as 3.14, or "Hello, World!"), or it might just perform a side effect (such as storing data into a database or writing text to a file). Or both. The difference between a class definition and a function definition is that whereas a function definition describes what should happen when a function is called, a class definition describes the object that is generated when the class's constructor is called. You call a constructor to create an object. The constructor belongs to the class, and in Python it looks an awful lot like a function. Think of the constructor as a class-specific function, so if you create a "Book" class and a "Magazine" class, you call the "Book" class constructor to create Book objects and you call the "Magazine" class constructor to create Magazine objects. However, if writing a constructor was the only aspect of defining a class, and a constructor is just a class-specific function, then why not just write constructor functions and dispense with the whole hassle of writing a class definition? The reason is because the constructor is only one part of a class -- there can be other class-specific functions, and even class-specific variables. In OO parlance, these functions are often called "methods" and these variables are often called "fields". Here is an example of a simple Book class written in Python: class Book: def __init__(self): self.title = "" self.author = "" self.publisher = "" def getInformation(self): info = "%s, by %s (%s)" % (self.title, self.author, self.publisher) return info The fact that we are dealing with a class is identified by the first line, "class Book:". There are two methods of this class. You can probably recognize that they look much like any other function, since they start with the "def" keyword and are followed by parentheses and an argument ("self" in this case). The first method is called "__init__" and the second method is called "getInformation". In Python (and only in Python), you create a constructor with a method named "__init__". So as you can see, this class has a constructor. The method accepts an argument ("self") and assigns an empty string to three different attributes of the argument -- "self.title", "self.author", and "self.publisher". In a class definition, the "self" variable typically refers to the object that is to be created by this class. So, knowing this, we can re-think our understanding of the constructor -- it is assigning an empty string to the "title", "author", and "publisher" attributes of the object that the constructor is going to produce when it is invoked. And a variable that is specific to a class is known as a "field" (just like a function that is specific to a class is known as a "method"). Every object of a certain class contains the fields identified by the class, so every Book object that we create will have "title", "author", and "publisher" fields. This sounds a bit confusing, so before going further why not try typing in the above class into your interactive Python interpreter: | wintermute:~$ python | | Python 2.2 (#1, 07/14/02, 23:25:09) | [GCC Apple cpp-precomp 6.14] on darwin | Type "help", "copyright", "credits" or "license" for more information. | >>> class Book: | ... def __init__(self): | ... self.title = "" | ... self.author = "" | ... self.publisher = "" | ... def getInformation(self): | ... info = "%s, by %s (%s)" % (self.title, self.author, | ... self.publisher) | ... return info | ... | >>> Now that we've defined a Book class, let's create an object from this class: | >>> book_1 = Book() | >>> We need some name by which to refer to our Book object, so I just used the name "book_1". However, this choice is arbitrary, you can use any legal Python variable name to refer to an object. Now that we have a Book object, let's see what value is stored in its "title" field. You can access an object's field by using the object's name, followed by a period, followed by the name of the field. This is sometimes called "dot notation": | >>> book_1.title | '' | >>> An empty string, just like we programmed our constructor to do. If you try it with the "author" and "publisher" fields you will find the same thing is true as well. So let's assign a name to our Book object by using the traditional variable assignment: | >>> book_1.title = "The Da Vinci Code" | >>> Now that we've assigned a title to the Book object, let's test it to make sure that it actually got saved. | >>> book_1.title | 'The Da Vinci Code' | >>> Okay, let's continue to flesh out our object by storing values in its other fields: | >>> book_1.author = "Dan Brown" | >>> book_1.publisher = "Doubleday" | >>> Now we have an object created by the constructor of the Book class, so it is a Book object. We can refer to the three fields of our Book object with dot notation. But there was another method of the Book class that we defined -- "getInformation". You can access a method of an object just like you access a field of an object, by using dot notation. But methods, just like functions, are "called", so you need to apply the parentheses at the end just like when you call a function (this is how you indicate to Python that you are "calling" something). So try it: | >>> book_1.getInformation() | 'The Da Vinci Code, by Dan Brown (Doubleday)' | >>> See what has happened? The "getInformation" method creates a string containing the title, author, and publisher fields, and returns it. This is how we programmed our "getInformation" method back when we defined the class. (Quick side note: you might be wondering why neither the constructor nor the "getInformation" method were passed an argument, even though the method definitions list an argument called "self". The reason for this is actually pretty straightforward, but at this point not very helpful to understanding how classes and object oriented programming work, so simply take it at face value that class methods need the "self" argument when they are defined (to refer to the object they are invoked upon) but not when they are called.) Of course, you can write any kind of method for a class, so that it will be available to all objects of that class. And you can use methods just like functions, so the following will work too: | >>> message = "I am currently reading %s" % (book_1.getInformation()) | >>> message | 'I am currently reading The Da Vinci Code, by Dan Brown (Doubleday)' | >>> One thing that makes OO programming so cool (there are actually many things that make it cool IMHO) is that you can create as many instances (objects) of a given class as you need. And, while all the instances of the class share the same fields and methods, each can have its own instance-specific data stored in those methods: | >>> book_2 = Book() | >>> book_2.title = "Text Processing in Python" | >>> book_2.author = "David Mertz" | >>> book_2.publisher = "Addison Wesley" The information stored in book_2 is completely separate from the information stored in book_1: | >>> book_2.getInformation() | 'Text Processing in Python, by David Mertz (Addison Wesley)' | >>> book_1.getInformation() | 'The Da Vinci Code, by Dan Brown (Doubleday)' | >>> Hope that makes some sense -- it should at least give you something to go on as you explore classes and OO programming. Erik From alan.gauld at blueyonder.co.uk Sat Sep 20 12:15:58 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Sep 20 12:15:42 2003 Subject: [Tutor] Classes and the like... References: <200309160039.19484.intatia@paradise.net.nz><002f01c37e32$435f00b0$6401a8c0@xp> <200309201356.22820.intatia@paradise.net.nz> Message-ID: <003001c37f92$79eb91a0$6401a8c0@xp> > Object? What's an object? :-) > Any ideas on a fairly simple project I could do next? THe ones I always use when trying out a new OO language for the first time are: 1) A Hello World program using a message object Initialise it with no parameters it prints Hello World. Initialise it with a string parameter and it prints the string. Change the text attribute and it prints the new value. 2) A switch. It can have state ON or OFF. You can Set it to ON or OFF. It can tell you its state. 3) A Toggle switch inheriting from the switch above. It only has 1 extra method which Toggles the state to the opposite of whatever its current state is. 4) A bank of switches that I can manipulate(to tst polymorphism) Thats it, after doing that I usually have a good feel of basic OO programming in whatever language it is. Alan G. From bgailer at alum.rpi.edu Sat Sep 20 13:53:30 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Sep 20 13:55:43 2003 Subject: [Tutor] rotating a list In-Reply-To: References: Message-ID: <6.0.0.22.0.20030920115010.0348fcd0@66.28.54.253> At 10:21 PM 9/19/2003, kevin parks wrote: >Hi. My python chops are a bit rusty but i need another pair of eyes to >tell me what i am doing wrong. I am sure that it is something very stupid >but i can't see what it is.. I am trying to cycle through a list like so > >[a, b, c] >[b, c, a] >[c, a, b] >[a, b, c] > >only, that aint be what is coming out the other side... > >anyone see where things are going wrong? > > > >cheers, >-kp-- > >--^---------------------------------------- > >kevin parks >university of virginia >k p p 9 c @ virginia . edu > >PS. If my man Danny is out there... 'Hi' > >P.P.S if there are any pythonistas out here at UVa, i'd love to hear from >you. i am new here. > > >import sys >import random > ># cyclically rotate a sequence > ># should work on any sequence type (list, tuple, string) and should work with ># any hop(n) interval and also work in both directions (left or right) > >def rotate(seq, n=1): > if len(seq) == 0: > return seq > n = n % len(seq) # Normalize n, using modulo - even works for negative n > > return seq[n:] + seq[:n] > > >def test(): > random.seed(720) # reproducable results > x = range(0, 12, 1) # create a list for test purposes > print x; print # look at it > random.shuffle(x) # scramble it up > print x; print # look at again... > # Now rotate the list one at a time till we've done come to > # the beginning once again > for i in range(len(x)): > y = rotate(x) > print y > >if __name__ == "__main__": > test() > >output is something like: > >[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] > >[2, 5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8] > >[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] >[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] >[5, 4, 10, 11, 6, 0, 3, 9, 7, 1, 8, 2] Exactly what I'd expect. Why did you think you'd get a different result? Do you suppose you were thinking that n would have a different value for each pass thru the loop? Yet you are not passing a 2nd parameter in the function call, so n always takes its default value of 1. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From bgailer at alum.rpi.edu Sat Sep 20 14:10:44 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Sep 20 14:12:58 2003 Subject: [Tutor] Re: rotating a list In-Reply-To: References: Message-ID: <6.0.0.22.0.20030920120949.03499eb0@66.28.54.253> At 03:09 AM 9/20/2003, Andrei wrote: >Hi Kevin, > >kevin parks wrote: >>Hi. My python chops are a bit rusty but i need another pair of eyes to >>tell me what i am doing wrong. I am sure that it is something very stupid >>but i can't see what it is.. I am trying to cycle through a list like so >>[a, b, c] >>[b, c, a] >>[c, a, b] >>[a, b, c] >>only, that aint be what is coming out the other side... >>anyone see where things are going wrong? > >># cyclically rotate a sequence >># should work on any sequence type (list, tuple, string) and should work with >># any hop(n) interval and also work in both directions (left or right) >>def rotate(seq, n=1): >> if len(seq) == 0: >> return seq >> n = n % len(seq) # Normalize n, using modulo - even works for negative n >> return seq[n:] + seq[:n] > >Works fine here: > >>> rotate([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) >[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0] > >>> rotate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0]) >[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1] > >>> rotate([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1]) >[3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2] > >>def test(): >> random.seed(720) # reproducable results >> x = range(0, 12, 1) # create a list for test purposes >> print x; print # look at it >> random.shuffle(x) # scramble it up >> print x; print # look at again... >> # Now rotate the list one at a time till we've done come to >> # the beginning once again >> for i in range(len(x)): > >Here's your problem your rotate x and assign the result to y: > >> y = rotate(x) > >Now x is unchanged, y is the result, so you go back and rotate the same >old x again. Obviously the result won't change. > >> print y No that is NOT the problem. That is an alternative algorithm. I explained the problem in my post. >Here's the improved version: > for i in range(len(x)): > x = rotate(x) > print x > >Results: > >>> test() >[0, 1, 2, 3, 4] > >[0, 1, 4, 2, 3] > >[1, 4, 2, 3, 0] >[4, 2, 3, 0, 1] >[2, 3, 0, 1, 4] >[3, 0, 1, 4, 2] >[0, 1, 4, 2, 3] > >-- >Yours, > >Andrei > >===== >Mail address in header catches spam. Real contact info (decode with rot13): >cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V >ernq gur yvfg, fb gurer'f ab arrq gb PP. > > > >_______________________________________________ >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.506 / Virus Database: 303 - Release Date: 8/1/2003 Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From project5 at redrival.net Sat Sep 20 16:33:33 2003 From: project5 at redrival.net (Andrei) Date: Sat Sep 20 16:35:44 2003 Subject: [Tutor] Re: rotating a list In-Reply-To: <6.0.0.22.0.20030920120949.03499eb0@66.28.54.253> References: <6.0.0.22.0.20030920120949.03499eb0@66.28.54.253> Message-ID: Bob Gailer wrote: >> Here's your problem your rotate x and assign the result to y: >> >>> y = rotate(x) >> >> >> Now x is unchanged, y is the result, so you go back and rotate the >> same old x again. Obviously the result won't change. >> >>> print y > > > No that is NOT the problem. That is an alternative algorithm. I > explained the problem in my post. As far as I can tell, that's a matter of taste: the algorithm is exactly the same and the result is the same: he uses the default value of n=1 in this case to test his rotation which is just fine. One can either increment n in the loop or reassign x every time. Personally, I find reassigning more intuitive and I pretty much ignored the optional n parameter. Could you explain why incrementing n is a superior solution? -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From glingl at aon.at Sat Sep 20 17:06:54 2003 From: glingl at aon.at (Gregor Lingl) Date: Sat Sep 20 17:08:38 2003 Subject: [Tutor] Re: rotating a list In-Reply-To: References: <6.0.0.22.0.20030920120949.03499eb0@66.28.54.253> Message-ID: <3F6CC16E.4010001@aon.at> Andrei schrieb: > ... Could you explain why incrementing n is a superior solution? Superior or not?! Here a definitely different solution: >>> def rotate(x): x[:-1],x[-1] = x[1:],x[0] >>> x = range(12) >>> print x, id(x) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 11554712 >>> for i in range(12): rotate(x) print x [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0] [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1] [3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2] [4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3] [5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4] [6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5] [7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6] [8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7] [9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8] [10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>> print id(x) 11554712 >>> Of course, which one you use depends on what you need Regards, Gregor From dyoo at hkn.eecs.berkeley.edu Sat Sep 20 21:22:11 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Sep 20 21:22:15 2003 Subject: [Tutor] rotating a list In-Reply-To: Message-ID: > PS. If my man Danny is out there... 'Hi' Hey Kevin, it's been a long time! Looks like you've gotten a few responses to the list-rotation question, so I'd better not regurgitate them too much. *grin* But just out of curiosity, is it necessary that we do have to account for rotating the list of length one or zero? If so, Gregor's solution: ### def rotate(x): x[:-1],x[-1] = x[1:],x[0] ### will need an amendment to make it work on empty lists, or else we may run into an IndexError: ### >>> L = [] >>> rotate(L) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in rotate IndexError: list index out of range ### One way we can fix the definition is to redefine it so that it always does list slicing on its input: ### >>> def rotate(L): ... """Mutates list L and rotates all the elements to the left.""" ... x[:-1], x[-1:] = x[1:], x[:1] ... ### The symmetry in the definition here appeals to me. *grin* Talk to you later! From bgailer at alum.rpi.edu Sat Sep 20 22:00:08 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Sep 20 22:27:02 2003 Subject: [Tutor] Re: rotating a list In-Reply-To: References: <6.0.0.22.0.20030920120949.03499eb0@66.28.54.253> Message-ID: <6.0.0.22.0.20030920194925.03314eb0@66.28.54.253> At 02:33 PM 9/20/2003, Andrei wrote: >Bob Gailer wrote: >>>Here's your problem your rotate x and assign the result to y: >>> >>>> y = rotate(x) >>> >>> >>>Now x is unchanged, y is the result, so you go back and rotate the same >>>old x again. Obviously the result won't change. >>> >>>> print y >> >>No that is NOT the problem. That is an alternative algorithm. I explained >>the problem in my post. > >As far as I can tell, that's a matter of taste: the algorithm is exactly >the same and the result is the same: he uses the default value of n=1 in >this case to test his rotation which is just fine. One can either >increment n in the loop or reassign x every time. Personally, I find >reassigning more intuitive and I pretty much ignored the optional n >parameter. Could you explain why incrementing n is a superior solution? I guess I overreacted in my reply. I did see what you saw first, then when I tested the code and saw the missing parameter I assumed the OP meant to provide it. Sorry for the reaction. As a (mostly former) APL programmer I still like APL's approach best: n$matrix where $ is replaced by the non-ascii symbol for rotate. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From karld at ugcs.caltech.edu Sun Sep 21 00:53:29 2003 From: karld at ugcs.caltech.edu (karl d'adamo) Date: Sun Sep 21 00:53:34 2003 Subject: [Tutor] multiline comment in Python In-Reply-To: <20030904145724.J12926-100000@localhost.name> References: <20030904145724.J12926-100000@localhost.name> Message-ID: <20030921045329.GB6410@ugcs.caltech.edu> On Thu, Sep 04, 2003 at 03:14:01PM -0700, tpc@csua.berkeley.edu wrote: > > hi Danny, thanks I did not know Emacs had that feature. I was wondering > how to comment out multiple lines if I use vi on the console. I know 'I' > inserts at the beginning of the current line, although I don't know how > to do so across multiple lines. That's where a feature like C i think the easiest way to do this with vi is using block-wise selection. this will comment out the next 10 lines: 0[ctrl-v]10jI# 0 go to the beginning of the first line you want to comment out ctrl-v this start block-wise selection (note, this is mapped to ctrl-^q on windows) j now, just issue a movement command and vi will select the first character of each line. with python, you can experiment with } and ] and see how blocks like functions can be selected with one key I to insert text at the beginning of eash line you selected # the comment character you want to insert uncommenting is just selecting the same region blockwise and then doing x to remove the comment character. you might also like to use the python.vim [0] set of mappings. this provides better block detection and similar comment mappings along with other cool features. peace [0] http://vim.sourceforge.net/scripts/script.php?script_id=30 From dyoo at hkn.eecs.berkeley.edu Sun Sep 21 03:34:45 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Sep 21 03:34:50 2003 Subject: [Tutor] Re: rotating a list [Programmer Pearls] In-Reply-To: <6.0.0.22.0.20030920194925.03314eb0@66.28.54.253> Message-ID: > >>No that is NOT the problem. That is an alternative algorithm. I explained > >>the problem in my post. > > > >As far as I can tell, that's a matter of taste: the algorithm is > >exactly the same and the result is the same: he uses the default value > >of n=1 in this case to test his rotation which is just fine. One can > >either increment n in the loop or reassign x every time. Personally, I > >find reassigning more intuitive and I pretty much ignored the optional > >n parameter. Could you explain why incrementing n is a superior > >solution? > > I guess I overreacted in my reply. I did see what you saw first, then > when I tested the code and saw the missing parameter I assumed the OP > meant to provide it. Sorry for the reaction. Hi Bob, No problem; it just sounded a little confrontational at first. Glad it's cleared up now. By the way, this subject about List Rotation is one that Jon Bentley talks about in his excellent book, "Programming Pearls": http://www.cs.bell-labs.com/cm/cs/pearls/index.html as Column 2. I really like his handwavy analogy to doing the problem. Unfortunately, Bentley only gives a sketch of Column 2 on his web site: http://www.cs.bell-labs.com/cm/cs/pearls/sketch02.html http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdf but I guess that makes sense, as it's an incentive for people to buy the book. Everyone, go visit your local bookstore sometime and read Column 2: it's good! *grin* Anyway, for people who are interested: here's an implementation of the handwavy example he describes: ### >>> def reverse(L, a, b): ... """Mutates a list L by reversing all the elements in L between ... indices a and b, inclusive.""" ... while a < b: ... L[a], L[b] = L[b], L[a] ... a = a + 1 ... b = b - 1 ... >>> def rotate(L, n=1): ... """Mutates list L by rotating it in a handwavy way.""" ... reverse(L, 0, n-1) ... reverse(L, n, len(L) - 1) ... reverse(L, 0, len(L) - 1) ... >>> numbers = range(10) >>> numbers [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> reverse(numbers, 0, 9) >>> numbers [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> >>> >>> rotate(numbers) >>> numbers [8, 7, 6, 5, 4, 3, 2, 1, 0, 9] >>> rotate(numbers, 2) >>> numbers [6, 5, 4, 3, 2, 1, 0, 9, 8, 7] ### Hope this helps! From glingl at aon.at Sun Sep 21 04:34:53 2003 From: glingl at aon.at (Gregor Lingl) Date: Sun Sep 21 04:36:40 2003 Subject: [Tutor] rotating a list In-Reply-To: References: Message-ID: <3F6D62AD.6050607@aon.at> Danny Yoo schrieb: > > >>PS. If my man Danny is out there... 'Hi' >> >> > >Hey Kevin, it's been a long time! > >Looks like you've gotten a few responses ... >If so, Gregor's solution ... will need an amendment ... > >One way we can fix the definition is to redefine it so that it always does >list slicing on its input: > >### > > >>>>def rotate(L): >>>> >>>> >... """Mutates list L and rotates all the elements to the left.""" >... x[:-1], x[-1:] = x[1:], x[:1] >... >### > >The symmetry in the definition here appeals to me. *grin* > > > Me too! Thanks for the idea! (Of course we should replace L by x (or vice versa) ;-) ). May we use it to generalize it in order to achieve Kevin's original funcionality without sacrificing the symmetry? >>> def rotate(x, n=1): x[:-n], x[-n:] = x[n:], x[:n] This works also for n > len(x), but not correctly. Sometimes this will be needed to have some sort of continued rotation: >>> def rotate(x, n=1): n %= len(x) x[:-n], x[-n:] = x[n:], x[:n] >>> rotate(l,11) >>> l [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] >>> >>> rotate(l,-2) >>> l [9, 0, 1, 2, 3, 4, 5, 6, 7, 8] (btw, this idea could be applied also to your handwavy solution from programming pearls, which will run into an IndexError, if n is not in range(len(l)) Have a happy Sunday! Gregor >Talk to you later! > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From goki75 at vsnl.net Sun Sep 21 10:13:33 2003 From: goki75 at vsnl.net (G Kiran) Date: Sun Sep 21 10:13:49 2003 Subject: [Tutor] SMS-JABBER-ICQ Message-ID: <000c01c3804a$8ba1ae30$be4c41db@VULCAN> Can someone give me how i can use icq / jabber transport ot "receive" sms messages through python i had gone thru pyicqlib...but couldn't get it up? links and tuorials are welcome... -kiran --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.520 / Virus Database: 318 - Release Date: 9/18/2003 From missive at hotmail.com Sun Sep 21 10:28:12 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Sep 21 10:28:16 2003 Subject: [Tutor] Re: SMS-JABBER-ICQ Message-ID: >Can someone give me how i can use icq / jabber transport ot "receive" sms >messages through python >i had gone thru pyicqlib...but couldn't get it up? >links and tuorials are welcome... > http://www.google.com/search?q=python+jabber http://jabberpy.sourceforge.net/ _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From dyoo at hkn.eecs.berkeley.edu Sun Sep 21 13:17:35 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Sep 21 13:17:41 2003 Subject: [Tutor] rotating a list In-Reply-To: <3F6D62AD.6050607@aon.at> Message-ID: > >>>>def rotate(L): > >>>> > >>>> > >... """Mutates list L and rotates all the elements to the left.""" > >... x[:-1], x[-1:] = x[1:], x[:1] > >... > >### > > > >The symmetry in the definition here appeals to me. *grin* > > > > > > > Me too! Thanks for the idea! (Of course we should replace L by x (or > vice versa) ;-) ). Uh, yeah. Doh! Serves me right for trying to in-place edit the text after I cut and pasted it to my email. I sometimes do that to make my variable names make more sense, but this time, it really bit me badly. Thanks for correcting me. > >>> def rotate(x, n=1): > x[:-n], x[-n:] = x[n:], x[:n] > > This works also for n > len(x), but not correctly. Sometimes this will > be needed to have some sort of continued rotation: > > >>> def rotate(x, n=1): > n %= len(x) > x[:-n], x[-n:] = x[n:], x[:n] > > >>> rotate(l,11) > >>> l > [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] > >>> > >>> rotate(l,-2) > >>> l > [9, 0, 1, 2, 3, 4, 5, 6, 7, 8] Wow, that looks great! I didn't even think about using modulo arithmetic to handle negative rotations. Thanks again! From alan.gauld at blueyonder.co.uk Sun Sep 21 13:29:50 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Sep 21 13:29:26 2003 Subject: [Tutor] multiline comment in Python References: <20030904145724.J12926-100000@localhost.name> <20030921045329.GB6410@ugcs.caltech.edu> Message-ID: <002501c38065$f674fc60$6401a8c0@xp> > i think the easiest way to do this with vi is using > block-wise selection. this will comment out the next 10 > lines: > > 0[ctrl-v]10jI# Note that is is not standard vi, its a vim feature. In vi the way to do blocks is to provide the line numbers at the start of the command, the numbers can be relative or absolute: .,+5 applies command from the current line(.) to the next 5 lines(+5) 15,20 applies the command to lines 15 thru 20. The latter is easiest if you have line numbering switched on. But you can also use searches to define the block: :+3,/foo/ applies command to the block starting 3 lines down and extending to the next line containing 'foo'. To create comment lines I usually use the substitute command: :.,/foo/s/^/#/ This substitutes the start of a line(^) with a # :.,/foo/s/^#// removes it again. Alan G. From charlie at begeistert.org Sun Sep 21 14:43:52 2003 From: charlie at begeistert.org (Charlie Clark) Date: Sun Sep 21 14:42:01 2003 Subject: [Tutor] rotating a list In-Reply-To: References: Message-ID: <20030921204352.731.3@bepc.wonderland> On 2003-09-21 at 10:36:43 [+0200], tutor-request@python.org wrote: > ### > >>> def rotate(L): > ... """Mutates list L and rotates all the elements to the left.""" > ... x[:-1], x[-1:] = x[1:], x[:1] > ... > ### > > The symmetry in the definition here appeals to me. *grin* As usual Danny's solution is elegant an conclusive but his catch-all for empty lists is maybe a bit too much. I actually found all of the solutions too mathematic and not expressive enuff so came up with the following: >>> l = [1, 2, 3] >>> l.append(l.pop(0)) This will give IndexError for empty lists but with a helpful error message telling you the list is empty. You can also rotate at different positions using different values of pop() and you're using real list methods so it's nice OO, I think. Charlie From glingl at aon.at Sun Sep 21 16:58:12 2003 From: glingl at aon.at (Gregor Lingl) Date: Sun Sep 21 17:00:08 2003 Subject: [Tutor] rotating a list In-Reply-To: <20030921204352.731.3@bepc.wonderland> References: <20030921204352.731.3@bepc.wonderland> Message-ID: <3F6E10E4.1000909@aon.at> Charlie Clark schrieb: > ... *grin* > >As usual Danny's solution is elegant an conclusive but his catch-all for >empty lists is maybe a bit too much. I actually found all of the solutions >too mathematic and not expressive enuff so came up with the following: > > >>>>l = [1, 2, 3] >>>>l.append(l.pop(0)) >>>> >>>> > >This will give IndexError for empty lists but with a helpful error message >telling you the list is empty. > Hi, Charlie, you can easily amend this (in Dannies sense) by writing: if l: l.append(l.pop()) >You can also rotate at different positions >using different values of pop() > hmm..., how do you mean should this be done? > and you're using real list methods so it's >nice OO, I think. > > O.k. And, moreover it's MUCH faster for long list, already nearly twice as fast for lists with 100 elements. Thanks for this idea, Gregor >Charlie > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From charlie at begeistert.org Mon Sep 22 03:50:49 2003 From: charlie at begeistert.org (Charlie Clark) Date: Mon Sep 22 03:49:00 2003 Subject: [Tutor] rotating a list In-Reply-To: <3F6E10E4.1000909@aon.at> References: <20030921204352.731.3@bepc.wonderland> <3F6E10E4.1000909@aon.at> Message-ID: <20030922095049.986.3@bepc.wonderland> On 2003-09-21 at 22:58:12 [+0200], Gregor Lingl wrote: > >You can also rotate at different positions > >using different values of pop() > > > hmm..., how do you mean should this be done? It will allow you to rotate only parts of lists or back-to-front, not necessarily with append(), admittedly. Charlie From lonetwin at yahoo.com Mon Sep 22 06:56:05 2003 From: lonetwin at yahoo.com (lonetwin) Date: Mon Sep 22 07:07:22 2003 Subject: [Tutor] rotating a list In-Reply-To: <20030922095049.986.3@bepc.wonderland> References: <3F6E10E4.1000909@aon.at> <20030922095049.986.3@bepc.wonderland> Message-ID: <200309221626.05765.lonetwin@yahoo.com> On Monday 22 Sep 2003 1:20 pm, Charlie Clark wrote: > On 2003-09-21 at 22:58:12 [+0200], Gregor Lingl wrote: > > >You can also rotate at different positions > > >using different values of pop() > > > > hmm..., how do you mean should this be done? > > It will allow you to rotate only parts of lists or back-to-front, not > necessarily with append(), admittedly. How about ... l.insert(x, l.pop(y)) ...to rotate within lists :o) where x, is the index where the rotation will start and y is the index where it will end. Peace Steve -- The clothes have no emperor. -- C.A.R. Hoare, commenting on ADA. From peterabrown at froggy.com.au Mon Sep 22 08:46:01 2003 From: peterabrown at froggy.com.au (Peter Brown) Date: Mon Sep 22 08:46:48 2003 Subject: [Tutor] Printing to file on one line Message-ID: <1064234760.4295.21.camel@localhost.localdomain> Hi, This is a portion of my program: #print header for debits in debits file aba.write('0' + (' ' * 17) + string.zfill(d_batch, 2) + 'MET' + (' ' * 7) + conf_name.ljust(26) + conf_apca[:6] + conf_desc.ljust(12) + str(smdate) + '\r\n') a = '1' + a8f + a9f + ' ' + a3 + a4f + a5f + a6f + a1f + a2f + a10 + '00000000\r\n' aba.write(a) The first write goes over two lines - I want it all on one line: 0 32MET PB Exports 233381Payments 220903^M The second works as expected. How do I get the first aba.write to be all on one line? Peter From vicki at thepenguin.org Mon Sep 22 15:24:31 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Mon Sep 22 15:24:41 2003 Subject: [Tutor] Serial Com Question (How to detect non-response) Message-ID: <59989.206.53.226.4.1064258671.squirrel@www.thepenguin.org> In the project I am working on, which is coming along nicely thanks to this list, my Python program establishes serial communication with a device which may be turned on or off. How would I detect whether the device is off? When I establish the serial port with: port = serial.Serial(0, 9600, 8, 'N', 2, timeout=60) The program has no way of knowing whether or not the device on the other end is on or off, correct? If I attempt to send a command to the device, I get no response (obviously) if the device is off, but my program keeps trying. Is there a way to tell it to attempt to send a command but to stop after a few seconds and throw up an error? Or is there already a standard way to do this? --vicki From pythontutor at venix.com Mon Sep 22 15:41:32 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Sep 22 15:41:41 2003 Subject: [Tutor] Serial Com Question (How to detect non-response) In-Reply-To: <59989.206.53.226.4.1064258671.squirrel@www.thepenguin.org> References: <59989.206.53.226.4.1064258671.squirrel@www.thepenguin.org> Message-ID: <3F6F506C.4000508@venix.com> If your device provides hardware handshaking signals, and if your cable is carrying them across to your computer, and if serial supports examining the signals then you can check DataSetReady (DSR) which would be pin 6 on a 25 pin connector. DSR indicates that it is powered on and in a ready state as opposed to a a test or stand-by state (or off). Your computer would normally be a DTE serial pinout. Your device is a DCE pinout if works with a "regular" modem cable. ClearToSend (CTS) could be used to indicate that the device is ready for your program to send data. Vicki Stanfield wrote: > In the project I am working on, which is coming along nicely thanks to > this list, my Python program establishes serial communication with a > device which may be turned on or off. How would I detect whether the > device is off? When I establish the serial port with: > > port = serial.Serial(0, 9600, 8, 'N', 2, timeout=60) > > The program has no way of knowing whether or not the device on the other > end is on or off, correct? If I attempt to send a command to the device, I > get no response (obviously) if the device is off, but my program keeps > trying. Is there a way to tell it to attempt to send a command but to stop > after a few seconds and throw up an error? Or is there already a standard > way to do this? > > --vicki > > _______________________________________________ > 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 vicki at thepenguin.org Mon Sep 22 16:30:35 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Mon Sep 22 16:30:43 2003 Subject: [Tutor] Serial Com Question (How to detect non-response) In-Reply-To: <3F6F506C.4000508@venix.com> References: <59989.206.53.226.4.1064258671.squirrel@www.thepenguin.org> <3F6F506C.4000508@venix.com> Message-ID: <12884.206.53.226.4.1064262635.squirrel@www.thepenguin.org> > If your device provides hardware handshaking signals, > and if your cable is carrying them across to your computer, > and if serial supports examining the signals > then you can check DataSetReady (DSR) which would be pin 6 on a 25 pin > connector. > DSR indicates that it is powered on and in a ready state as opposed to a > a test or stand-by state (or off). > > Your computer would normally be a DTE serial pinout. Your device is > a DCE pinout if works with a "regular" modem cable. > > ClearToSend (CTS) could be used to indicate that the device is ready for > your > program to send data. > I looked in the serial module and didn't see a ClearToSend. I loaded the module and did a dir on it. Is there somewhere else I should be looking? --vicki From peterabrown at froggy.com.au Tue Sep 23 00:47:49 2003 From: peterabrown at froggy.com.au (Peter Brown) Date: Tue Sep 23 00:48:09 2003 Subject: [Tutor] Printing to file on one line In-Reply-To: <1064234760.4295.21.camel@localhost.localdomain> Message-ID: <3.0.6.32.20030923144749.00b7f1c0@mail.froggy.com.au> Could anyone pls help with my problem? Peter At 22:46 22/09/2003 +1000, I wrote: >Hi, > >This is a portion of my program: > > #print header for debits in debits file > >aba.write('0' + (' ' * 17) + string.zfill(d_batch, 2) + 'MET' + (' ' * >7) + conf_name.ljust(26) + conf_apca[:6] + conf_desc.ljust(12) + >str(smdate) + '\r\n') >a = '1' + a8f + a9f + ' ' + a3 + a4f + a5f + a6f + a1f + a2f + a10 + >'00000000\r\n' > aba.write(a) >The first write goes over two lines - I want it all on one line: > >0 32MET PB Exports 233381Payments > 220903^M > >The second works as expected. > >How do I get the first aba.write to be all on one line? > >Peter > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From ahewitt at globaldial.com Tue Sep 23 04:54:20 2003 From: ahewitt at globaldial.com (Adam Hewitt) Date: Tue Sep 23 04:54:37 2003 Subject: [Tutor] Hi Message-ID: <1064307260.26687.2.camel@phoenix> Hi All, I am relatively new to programming (I have done a little c++, java, basic and logo and *long* time ago) and I have never programmed in python before but I am keen to learn a language and python seems to be the one to choose. Anyways I just thought I would say hi and see what projects people are working on right now?? Cheers, Adam. From ronan at melim.com.br Tue Sep 23 07:35:29 2003 From: ronan at melim.com.br (Ronan Lucio) Date: Tue Sep 23 07:34:10 2003 Subject: [Tutor] Printing to file on one line In-Reply-To: <1064234760.4295.21.camel@localhost.localdomain> References: <1064234760.4295.21.camel@localhost.localdomain> Message-ID: <200309230835.29738.ronan@melim.com.br> > This is a portion of my program: > > #print header for debits in debits file > > aba.write('0' + (' ' * 17) + string.zfill(d_batch, 2) + 'MET' + (' ' * > 7) + conf_name.ljust(26) + conf_apca[:6] + conf_desc.ljust(12) + > str(smdate) + '\r\n') > a = '1' + a8f + a9f + ' ' + a3 + a4f + a5f + a6f + a1f + a2f + a10 + > '00000000\r\n' > aba.write(a) > The first write goes over two lines - I want it all on one line: > > 0 32MET PB Exports 233381Payments > 220903^M I'm not so good in Python, but, it seems something should be wrong or at least, weird. Perhaps some character in the value returned by the function conf_desc.ljust(12) is causing this behavior. []s Ronan From clay at shirky.com Tue Sep 23 08:44:10 2003 From: clay at shirky.com (Clay Shirky) Date: Tue Sep 23 08:44:26 2003 Subject: [Tutor] Printing to file on one line In-Reply-To: <3.0.6.32.20030923144749.00b7f1c0@mail.froggy.com.au> Message-ID: >> #print header for debits in debits file >> >> aba.write('0' + (' ' * 17) + string.zfill(d_batch, 2) + 'MET' + (' ' * >> 7) + conf_name.ljust(26) + conf_apca[:6] + conf_desc.ljust(12) + >> str(smdate) + '\r\n') >> a = '1' + a8f + a9f + ' ' + a3 + a4f + a5f + a6f + a1f + a2f + a10 + >> '00000000\r\n' >> aba.write(a) >> The first write goes over two lines - I want it all on one line: >> >> 0 32MET PB Exports 233381Payments >> 220903^M See the Control-M (^M) character? That's a line ending. What that suggests is that python is outputting the line correctly, and your display program (word processor, telnet window, etc) is line-wrapping the output. Try looking at the output in a window at least 132 characters wide, instead of 80. Another way to test this hypothesis would be to reduce your ljust amounts down from 26 and 12 to something like 2, and/or, reduce the initial space-padding from 17 as well, to see if the line still wraps. -clay From bgailer at alum.rpi.edu Tue Sep 23 09:07:54 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Sep 23 09:10:10 2003 Subject: [Tutor] Hi In-Reply-To: <1064307260.26687.2.camel@phoenix> References: <1064307260.26687.2.camel@phoenix> Message-ID: <6.0.0.22.0.20030923065449.032a1940@66.28.54.253> At 02:54 AM 9/23/2003, Adam Hewitt wrote: >Hi All, > >I am relatively new to programming (I have done a little c++, java, >basic and logo and *long* time ago) and I have never programmed in >python before but I am keen to learn a language and python seems to be >the one to choose. Anyways I just thought I would say hi and see what >projects people are working on right now?? -converter that reads visual foxpro programs and emits Python code -report generator using Word, including powerful user-defined Word templates -graph generator using Excel -PC version of IBM's CMS Pipelines -generate dynamic PL/SQL and send to Oracle -using SQLite as intermediate database -e-mail sender which fills in values based on several levels of user-specified data and sends to selected targets -converting existing foxpro application* to a web-delivered application -various utility modules to support the above -contributing to python lists *Note - this application helps school districts streamline their processing of student data, especially achievement data. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From vicki at thepenguin.org Tue Sep 23 10:28:00 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Tue Sep 23 10:28:08 2003 Subject: [Tutor] pyserial question Message-ID: <15256.206.53.226.4.1064327280.squirrel@www.thepenguin.org> I am still unable to figure out how to test whether or not the device on the other end of the serial connection is on. Is there a simple way to do a conditional read that times out with an error after some given amount of time. I am using pyserial version 1.18. When I open the port, I specify a timeout of 1 second, but that doesn't seem to do what I expect it to. Maybe I have to do something different with the write command to look for an error code? Right now, it is simply: port.write('\x09') I don't see anything documented. --vicki From idiot1 at netzero.net Tue Sep 23 11:32:01 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Tue Sep 23 11:31:17 2003 Subject: [Tutor] Printing to file on one line In-Reply-To: <3.0.6.32.20030923144749.00b7f1c0@mail.froggy.com.au> References: <3.0.6.32.20030923144749.00b7f1c0@mail.froggy.com.au> Message-ID: <3F706771.5080201@netzero.net> Peter, is this homework? Peter Brown wrote: > Could anyone pls help with my problem? > > Peter > > At 22:46 22/09/2003 +1000, I wrote: > >>Hi, >> >>This is a portion of my program: >> >>#print header for debits in debits file >> >>aba.write('0' + (' ' * 17) + string.zfill(d_batch, 2) + 'MET' + (' ' * >>7) + conf_name.ljust(26) + conf_apca[:6] + conf_desc.ljust(12) + >>str(smdate) + '\r\n') >>a = '1' + a8f + a9f + ' ' + a3 + a4f + a5f + a6f + a1f + a2f + a10 + >>'00000000\r\n' >>aba.write(a) >>The first write goes over two lines - I want it all on one line: >> >>0 32MET PB Exports 233381Payments >> 220903^M >> >>The second works as expected. >> >>How do I get the first aba.write to be all on one line? >> >>Peter >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From pythontutor at venix.com Tue Sep 23 11:45:23 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Sep 23 11:45:27 2003 Subject: [Tutor] pyserial question In-Reply-To: <15256.206.53.226.4.1064327280.squirrel@www.thepenguin.org> References: <15256.206.53.226.4.1064327280.squirrel@www.thepenguin.org> Message-ID: <3F706A93.4060804@venix.com> I downloaded the current pyserial (1.20). I looked at the serialposix.py file. dev = Serial(rtscts=1,#plus other necessary parameters) dev.getDSR() # should be true if device is turned on dev.getCTS() # should be true if device is ready to receive data This only works if the device actually supports hardware flow control signalling AND if you are using a cable that actually carries the signals. The timeout will only affect commands that read from the device. Vicki Stanfield wrote: > I am still unable to figure out how to test whether or not the device on > the other end of the serial connection is on. Is there a simple way to do > a conditional read that times out with an error after some given amount of > time. I am using pyserial version 1.18. When I open the port, I specify a > timeout of 1 second, but that doesn't seem to do what I expect it to. > Maybe I have to do something different with the write command to look for > an error code? Right now, it is simply: > > port.write('\x09') > > I don't see anything documented. > > > --vicki > > _______________________________________________ > 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 oyvind.sporck at eniro.no Tue Sep 23 12:43:02 2003 From: oyvind.sporck at eniro.no (=?iso-8859-1?Q?=D8yvind_Dale_Sp=F8rck?=) Date: Tue Sep 23 12:40:45 2003 Subject: [Tutor] Unicode Message-ID: Hello, I have been making a little program that goes onto the net and picks down some information. The program has to put some adresses together to find the adress that it is going to look for. It works great if I use only english letters. However, I need to use a few non-english letters, ???. Python seems to change the adress to unicode, even thought I make sure that all the variables are in string format. In the error the letter ? gets translated into \xf8. The correct adress is http://www.kvasir.no/cgi-bin/search.cgi?what=bransje&q=agreement.level%3A204 +S%F8keord&loc= where the ? gets translated into %F8. How can I get the program to translate the ? to %F8 and to run the adress without the Unicode error? Thanks in advance, ?yvind The error: Traceback (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:\Documents and Settings\oyvind.sporck\My Documents\Python\agreement_level_excel4.py", line 147, in ? n.lastned() File "C:\Documents and Settings\oyvind.sporck\My Documents\Python\agreement_level_excel4.py", line 55, in lastned definisjoner.res4 = urlopen(definisjoner.level4) File "C:\Python22\lib\urllib.py", line 73, in urlopen return _urlopener.open(url) File "C:\Python22\lib\urllib.py", line 151, in open fullurl = unwrap(toBytes(fullurl)) File "C:\Python22\lib\urllib.py", line 913, in toBytes raise UnicodeError("URL " + repr(url) + UnicodeError: URL u'http://www.kvasir.no/cgi-bin/search.cgi?what=bransje&q=agreement.level%3A2 04+S\xf8keord&loc=&Submit=S%F8k' contains non-ASCII characters The program: from win32com.client import Dispatch from urllib import urlopen import re from sys import exit class definisjoner: xlApp = Dispatch("Excel.Application") xlApp.visible = 1 xlApp.Workbooks.Open(Filename='C:\\Documents and Settings\oyvind.sporck\My Documents\Agreementliste.xls') xlBook = xlApp.Workbooks(1) xlSheet = xlApp.Sheets(1) level4 ='' level5 ='' level6 ='' level7 ='' level8 ='' res4 = '' res5 = '' res6 = '' res7 = '' res8 = '' bransje = '' forst = "http://www.kvasir.no/cgi-bin/search.cgi?what=bransje&q=agreement.level%3A" midten = "+" slutten = "&loc=&Submit=S%F8k" linje_standard = '' linje_pluss = '' linje_bilde = '' linje_slide = '' linje_slidepluss = '' xlrad = 2 xlkolonne = 1 def __init__(self): pass def spor(self): definisjoner.bransje = definisjoner.xlSheet.Cells(definisjoner.xlrad, definisjoner.xlkolonne).Value print(type(definisjoner.bransje)) print definisjoner.bransje print definisjoner.bransje #definisjoner.bransje = str(definisjoner.bransje) print definisjoner.bransje definisjoner.bransje if definisjoner.bransje == '': sys.exit() definisjoner.level4 = definisjoner.forst + "204" + definisjoner.midten + definisjoner.bransje + definisjoner.slutten definisjoner.level5 = definisjoner.forst + "205" + definisjoner.midten + definisjoner.bransje + definisjoner.slutten definisjoner.level6 = definisjoner.forst + "206" + definisjoner.midten + definisjoner.bransje + definisjoner.slutten definisjoner.level7 = definisjoner.forst + "207" + definisjoner.midten + definisjoner.bransje + definisjoner.slutten definisjoner.level8 = definisjoner.forst + "208" + definisjoner.midten + definisjoner.bransje + definisjoner.slutten print definisjoner.bransje def lastned(self): definisjoner.res4 = urlopen(definisjoner.level4) definisjoner.res5 = urlopen(definisjoner.level5) definisjoner.res6 = urlopen(definisjoner.level6) definisjoner.res7 = urlopen(definisjoner.level7) definisjoner.res8 = urlopen(definisjoner.level8) def finn(self): i = 1 print "Bransje" print definisjoner.bransje while definisjoner.res4.readline() != '\n': i = i + 1 if i > 1000: break m = definisjoner.res4.readline() print m definisjoner.linje_standard = re.search('(?<=)[0-9][0-9][0-9]', m) or re.search('(?<=)[0-9][0-9]', m) or re.search('(?<=)[0-9]', m) i = 1 while definisjoner.res5.readline() != '\n': i = i + 1 if i > 1000: break m = definisjoner.res5.readline() print m definisjoner.linje_pluss = re.search('(?<=)[0-9][0-9][0-9]', m) or re.search('(?<=)[0-9][0-9]', m) or re.search('(?<=)[0-9]', m) i = 1 while definisjoner.res6.readline() != '\n': i = i + 1 if i > 1000: break m = definisjoner.res6.readline() print m definisjoner.linje_bilde = re.search('(?<=)[0-9][0-9][0-9]', m) or re.search('(?<=)[0-9][0-9]', m) or re.search('(?<=)[0-9]', m) i = 1 while definisjoner.res7.readline() != '\n': i = i + 1 if i > 1000: break m = definisjoner.res7.readline() print m definisjoner.linje_slide = re.search('(?<=)[0-9][0-9][0-9]', m) or re.search('(?<=)[0-9][0-9]', m) or re.search('(?<=)[0-9]', m) i = 1 while definisjoner.res8.readline() != '\n': i = i + 1 if i > 1000: break m = definisjoner.res8.readline() print m definisjoner.linje_slidepluss = re.search('(?<=)[0-9][0-9][0-9]', m) or re.search('(?<=)[0-9][0-9]', m) or re.search('(?<=)[0-9]', m) def plukkut(self): if definisjoner.linje_standard == None: definisjoner.linje_standard = 0 else: definisjoner.linje_standard = int(definisjoner.linje_standard.group()) if definisjoner.linje_pluss == None: definisjoner.linje_pluss = 0 else: definisjoner.linje_pluss = int(definisjoner.linje_pluss.group()) if definisjoner.linje_bilde == None: definisjoner.linje_bilde = 0 else: definisjoner.linje_bilde = int(definisjoner.linje_bilde.group()) if definisjoner.linje_slide == None: definisjoner.linje_slide == 0 else: definisjoner.linje_slide = int(definisjoner.linje_slide.group()) if definisjoner.linje_slidepluss == None: definisjoner.linje_slidepluss == 0 else: definisjoner.linje_slidepluss = int(definisjoner.linje_slidepluss.group()) def settinn(self): definisjoner.xlkolonne = definisjoner.xlkolonne + 1 definisjoner.xlSheet.Cells(definisjoner.xlrad, definisjoner.xlkolonne).Value = definisjoner.linje_standard definisjoner.xlkolonne = definisjoner.xlkolonne + 1 definisjoner.xlSheet.Cells(definisjoner.xlrad, definisjoner.xlkolonne).Value = definisjoner.linje_pluss definisjoner.xlkolonne = definisjoner.xlkolonne + 1 definisjoner.xlSheet.Cells(definisjoner.xlrad, definisjoner.xlkolonne).Value = definisjoner.linje_bilde definisjoner.xlkolonne = definisjoner.xlkolonne + 1 definisjoner.xlSheet.Cells(definisjoner.xlrad, definisjoner.xlkolonne).Value = definisjoner.linje_slide definisjoner.xlkolonne = definisjoner.xlkolonne + 1 definisjoner.xlSheet.Cells(definisjoner.xlrad, definisjoner.xlkolonne).Value = definisjoner.linje_slidepluss definisjoner.xlkolonne = 1 definisjoner.xlrad = definisjoner.xlrad + 1 if __name__ == "__main__": n = definisjoner() while 1 == 1: n.spor() n.lastned() n.finn() n.plukkut() n.settinn() From pythontutor at venix.com Tue Sep 23 13:28:16 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Sep 23 13:28:22 2003 Subject: [Tutor] Unicode In-Reply-To: References: Message-ID: <3F7082B0.3060103@venix.com> If I read your code correctly, the \xf8 is coming from the spreadsheet when you execute this line: definisjoner.bransje = definisjoner.xlSheet.Cells(definisjoner.xlrad, definisjoner.xlkolonne).Value I think you can fix this by using urllib.quote on the URL string. import urllib .... definisjoner.res4 = urllib.urlopen(urllib.quote(definisjoner.level4)) I hope it will do the right thing given a line that is already partially quoted. Otherwise: definisjoner.bransje = urllibquote(definisjoner.bransje) should help. ?yvind Dale Sp?rck wrote: > Hello, > > I have been making a little program that goes onto the net and picks down > some information. The program has to put some adresses together to find the > adress that it is going to look for. It works great if I use only english > letters. However, I need to use a few non-english letters, ???. Python > seems to change the adress to unicode, even thought I make sure that all the > variables are in string format. > > In the error the letter ? gets translated into \xf8. The correct adress > is > http://www.kvasir.no/cgi-bin/search.cgi?what=bransje&q=agreement.level%3A204 > +S%F8keord&loc= where the ? gets translated into %F8. How can I get the > program to translate the ? to %F8 and to run the adress without the Unicode > error? > > Thanks in advance, > ?yvind > > > The error: > > Traceback (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:\Documents and Settings\oyvind.sporck\My > Documents\Python\agreement_level_excel4.py", line 147, in ? > n.lastned() > File "C:\Documents and Settings\oyvind.sporck\My > Documents\Python\agreement_level_excel4.py", line 55, in lastned > definisjoner.res4 = urlopen(definisjoner.level4) > File "C:\Python22\lib\urllib.py", line 73, in urlopen > return _urlopener.open(url) > File "C:\Python22\lib\urllib.py", line 151, in open > fullurl = unwrap(toBytes(fullurl)) > File "C:\Python22\lib\urllib.py", line 913, in toBytes > raise UnicodeError("URL " + repr(url) + > UnicodeError: URL > u'http://www.kvasir.no/cgi-bin/search.cgi?what=bransje&q=agreement.level%3A2 > 04+S\xf8keord&loc=&Submit=S%F8k' contains non-ASCII characters > > The program: > > from win32com.client import Dispatch > from urllib import urlopen > import re > from sys import exit > > class definisjoner: > xlApp = Dispatch("Excel.Application") > xlApp.visible = 1 > xlApp.Workbooks.Open(Filename='C:\\Documents and > Settings\oyvind.sporck\My Documents\Agreementliste.xls') > xlBook = xlApp.Workbooks(1) > xlSheet = xlApp.Sheets(1) > level4 ='' > level5 ='' > level6 ='' > level7 ='' > level8 ='' > res4 = '' > res5 = '' > res6 = '' > res7 = '' > res8 = '' > bransje = '' > forst = > "http://www.kvasir.no/cgi-bin/search.cgi?what=bransje&q=agreement.level%3A" > midten = "+" > slutten = "&loc=&Submit=S%F8k" > linje_standard = '' > linje_pluss = '' > linje_bilde = '' > linje_slide = '' > linje_slidepluss = '' > xlrad = 2 > xlkolonne = 1 > > def __init__(self): > pass > > def spor(self): > definisjoner.bransje = > definisjoner.xlSheet.Cells(definisjoner.xlrad, definisjoner.xlkolonne).Value > print(type(definisjoner.bransje)) > print definisjoner.bransje > print definisjoner.bransje > #definisjoner.bransje = str(definisjoner.bransje) > print definisjoner.bransje > definisjoner.bransje > if definisjoner.bransje == '': > sys.exit() > definisjoner.level4 = definisjoner.forst + "204" + > definisjoner.midten + definisjoner.bransje + definisjoner.slutten > definisjoner.level5 = definisjoner.forst + "205" + > definisjoner.midten + definisjoner.bransje + definisjoner.slutten > definisjoner.level6 = definisjoner.forst + "206" + > definisjoner.midten + definisjoner.bransje + definisjoner.slutten > definisjoner.level7 = definisjoner.forst + "207" + > definisjoner.midten + definisjoner.bransje + definisjoner.slutten > definisjoner.level8 = definisjoner.forst + "208" + > definisjoner.midten + definisjoner.bransje + definisjoner.slutten > print definisjoner.bransje > > def lastned(self): > definisjoner.res4 = urlopen(definisjoner.level4) > definisjoner.res5 = urlopen(definisjoner.level5) > definisjoner.res6 = urlopen(definisjoner.level6) > definisjoner.res7 = urlopen(definisjoner.level7) > definisjoner.res8 = urlopen(definisjoner.level8) > > def finn(self): > i = 1 > print "Bransje" > print definisjoner.bransje > while definisjoner.res4.readline() != ' SIZE=2 face="Verdana,Arial,Geneva">\n': > i = i + 1 > if i > 1000: > break > m = definisjoner.res4.readline() > print m > definisjoner.linje_standard = re.search('(?<=)[0-9][0-9][0-9]', > m) or re.search('(?<=)[0-9][0-9]', m) or re.search('(?<=)[0-9]', m) > i = 1 > while definisjoner.res5.readline() != ' SIZE=2 face="Verdana,Arial,Geneva">\n': > i = i + 1 > if i > 1000: > break > m = definisjoner.res5.readline() > print m > definisjoner.linje_pluss = re.search('(?<=)[0-9][0-9][0-9]', m) > or re.search('(?<=)[0-9][0-9]', m) or re.search('(?<=)[0-9]', m) > i = 1 > while definisjoner.res6.readline() != ' SIZE=2 face="Verdana,Arial,Geneva">\n': > i = i + 1 > if i > 1000: > break > m = definisjoner.res6.readline() > print m > definisjoner.linje_bilde = re.search('(?<=)[0-9][0-9][0-9]', m) > or re.search('(?<=)[0-9][0-9]', m) or re.search('(?<=)[0-9]', m) > i = 1 > while definisjoner.res7.readline() != ' SIZE=2 face="Verdana,Arial,Geneva">\n': > i = i + 1 > if i > 1000: > break > m = definisjoner.res7.readline() > print m > definisjoner.linje_slide = re.search('(?<=)[0-9][0-9][0-9]', m) > or re.search('(?<=)[0-9][0-9]', m) or re.search('(?<=)[0-9]', m) > i = 1 > while definisjoner.res8.readline() != ' SIZE=2 face="Verdana,Arial,Geneva">\n': > i = i + 1 > if i > 1000: > break > m = definisjoner.res8.readline() > print m > definisjoner.linje_slidepluss = re.search('(?<=)[0-9][0-9][0-9]', > m) or re.search('(?<=)[0-9][0-9]', m) or re.search('(?<=)[0-9]', m) > > def plukkut(self): > if definisjoner.linje_standard == None: > definisjoner.linje_standard = 0 > else: > definisjoner.linje_standard = > int(definisjoner.linje_standard.group()) > if definisjoner.linje_pluss == None: > definisjoner.linje_pluss = 0 > else: > definisjoner.linje_pluss = int(definisjoner.linje_pluss.group()) > if definisjoner.linje_bilde == None: > definisjoner.linje_bilde = 0 > else: > definisjoner.linje_bilde = int(definisjoner.linje_bilde.group()) > if definisjoner.linje_slide == None: > definisjoner.linje_slide == 0 > else: > definisjoner.linje_slide = int(definisjoner.linje_slide.group()) > if definisjoner.linje_slidepluss == None: > definisjoner.linje_slidepluss == 0 > else: > definisjoner.linje_slidepluss = > int(definisjoner.linje_slidepluss.group()) > > > def settinn(self): > > definisjoner.xlkolonne = definisjoner.xlkolonne + 1 > definisjoner.xlSheet.Cells(definisjoner.xlrad, > definisjoner.xlkolonne).Value = definisjoner.linje_standard > definisjoner.xlkolonne = definisjoner.xlkolonne + 1 > definisjoner.xlSheet.Cells(definisjoner.xlrad, > definisjoner.xlkolonne).Value = definisjoner.linje_pluss > definisjoner.xlkolonne = definisjoner.xlkolonne + 1 > definisjoner.xlSheet.Cells(definisjoner.xlrad, > definisjoner.xlkolonne).Value = definisjoner.linje_bilde > definisjoner.xlkolonne = definisjoner.xlkolonne + 1 > definisjoner.xlSheet.Cells(definisjoner.xlrad, > definisjoner.xlkolonne).Value = definisjoner.linje_slide > definisjoner.xlkolonne = definisjoner.xlkolonne + 1 > definisjoner.xlSheet.Cells(definisjoner.xlrad, > definisjoner.xlkolonne).Value = definisjoner.linje_slidepluss > definisjoner.xlkolonne = 1 > definisjoner.xlrad = definisjoner.xlrad + 1 > > if __name__ == "__main__": > n = definisjoner() > while 1 == 1: > n.spor() > n.lastned() > n.finn() > n.plukkut() > n.settinn() > > _______________________________________________ > 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 jeff at ccvcorp.com Tue Sep 23 13:57:48 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Sep 23 13:55:00 2003 Subject: [Tutor] Printing to file on one line References: <3.0.6.32.20030923144749.00b7f1c0@mail.froggy.com.au> Message-ID: <3F70899C.2020101@ccvcorp.com> Peter Brown wrote: >>aba.write('0' + (' ' * 17) + string.zfill(d_batch, 2) + 'MET' + (' ' * >>7) + conf_name.ljust(26) + conf_apca[:6] + conf_desc.ljust(12) + >>str(smdate) + '\r\n') >>a = '1' + a8f + a9f + ' ' + a3 + a4f + a5f + a6f + a1f + a2f + a10 + >>'00000000\r\n' >>aba.write(a) >>The first write goes over two lines - I want it all on one line: >> >>0 32MET PB Exports 233381Payments >> 220903^M It's hard to be sure, but this *looks* to me like it's a case of normal line-wrapping, rather than that it's been written to the file as separate lines. One thing that might help is to break up your string-building and your write statement into several parts. That will make it easier to inspect what you're writing out to the file. Also, if you use string formatting with the % operator, that might make things a little clearer than your current formatting. I've dummied up something that seems to follow the same formatting rules that you're using, printing to the screen instead of writing to a file (but once the string is constructed, either should be the same). >>> def write_debit(aba_file, d_batch, conf_name, conf_apca, conf_desc, smdate): ... batchname = '%02dMET' % d_batch ... format = '%-18s%-12s%-26s%-6s%-12s%s\r\n' ... output = format % ('0', batchname, conf_name, conf_apca[:6], conf_desc, str(smdate)) ... print "Outputting %d bytes to file" % len(output) ... #aba_file.write(output) ... print output ... >>> write_debit(aba_file, batch, name, apca, desc, smdate) Outputting 82 bytes to file 0 32MET PB Exports 233381Payments 220903 >>> Notice that this string is 82 characters long -- most mailers wrap at 76 characters (as mine is doing), but on my screen this started as a single line. (That is to say, it's my mailer that's wrapping it, not Python.) Most editors will wrap long lines, too. So I do believe that your "two lines" problem is just a matter of how you're viewing it. As for why the second line you give doesn't show the problem, it's hard to say without seeing sample output or values for all those variables, but I expect that that line is just a couple characters shorter, so it doesn't hit your line-wrap point. That line would also be more clear using string formatting instead of addition. As a minor additional point, string formatting is also quite a bit more efficient than repeated string addition. The performance hit is probably not significant unless you're doing it in a long loop, but keep in mind that every addition creates a temporary string, and most of those are thrown away -- for example, your second line generates 11 more temporary strings than an equivalent formatting-based algorithm. If you're writing 100 lines to a file, that's over a thousand temporary strings that the interpreter has to allocate memory for, construct, and then throw away. All that extra work can start to add up... Jeff Shannon Technician/Programmer Credit International From ATrautman at perryjudds.com Tue Sep 23 14:02:30 2003 From: ATrautman at perryjudds.com (Alan Trautman) Date: Tue Sep 23 14:02:35 2003 Subject: [Tutor] Hi Message-ID: <06738462136C054B8F8872D69DA140DB01C08A1B@corp-exch-1.pjinet.com> Hi Adam, Two main projects: - Learn wxPython and create a financial tracking system w/gui and gadfly - A non-thumb speed based ice hockey simulation w/xml based game and team files Welcome, Alan To: tutor@python.org Subject: [Tutor] Hi Hi All, I am relatively new to programming (I have done a little c++, java, basic and logo and *long* time ago) and I have never programmed in python before but I am keen to learn a language and python seems to be the one to choose. Anyways I just thought I would say hi and see what projects people are working on right now?? Cheers, Adam. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From project5 at redrival.net Tue Sep 23 14:16:15 2003 From: project5 at redrival.net (Andrei) Date: Tue Sep 23 14:18:28 2003 Subject: [Tutor] Re: Hi In-Reply-To: <1064307260.26687.2.camel@phoenix> References: <1064307260.26687.2.camel@phoenix> Message-ID: Hi Adam, > I am relatively new to programming (I have done a little c++, java, > basic and logo and *long* time ago) and I have never programmed in > python before but I am keen to learn a language and python seems to be > the one to choose. Anyways I just thought I would say hi and see what I agree :). > projects people are working on right now?? My public projects are an RSS newsreader/aggregator in wxPython (http://project5.freezope.org/pears) and a regular expression development/testing tool called Kiki, also in wxPython, which is not yet released because it's not yet usable enough - but it should be in a matter of (hopefully) days. I also tend to write small scripts here and there for all kinds of tasks varying from web scraping to MP3 tag manipulation. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From andi at buxach.de Tue Sep 23 14:40:16 2003 From: andi at buxach.de (Andreas Zwinkau) Date: Tue Sep 23 14:40:42 2003 Subject: [Tutor] Hi In-Reply-To: <1064307260.26687.2.camel@phoenix> References: <1064307260.26687.2.camel@phoenix> Message-ID: <20030923204016.47194a0e.andi@buxach.de> > Hi All, Hi Adam > I am relatively new to programming (I have done a little c++, java, > basic and logo and *long* time ago) and I have never programmed in > python before but I am keen to learn a language and python seems to be > the one to choose. Anyways I just thought I would say hi and see what > projects people are working on right now?? I'm working on a jukebox daemon http://sourceforge.net/projects/dj-py/ And i made some small hackish scripts before. Logging net traffic etc. Hope your entry is smooth ;) -- mfg Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From VICKI.STANFIELD at ROCHE.COM Tue Sep 23 14:37:49 2003 From: VICKI.STANFIELD at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Tue Sep 23 14:50:45 2003 Subject: [Tutor] pyserial question Message-ID: Actually this functionality is just what I need, but it doesn't work in my application (always returns 0). I am using an infrared dongle, does that not meet your second spec of using a cable that actually carries the signals? If not, how can I accomplish the same thing with a read or write or something else? --vicki -----Original Message----- From: Lloyd Kvam [mailto:pythontutor@venix.com] Sent: Tuesday, September 23, 2003 10:45 AM To: Vicki Stanfield Cc: tutor@python.org Subject: Re: [Tutor] pyserial question I downloaded the current pyserial (1.20). I looked at the serialposix.py file. dev = Serial(rtscts=1,#plus other necessary parameters) dev.getDSR() # should be true if device is turned on dev.getCTS() # should be true if device is ready to receive data This only works if the device actually supports hardware flow control signalling AND if you are using a cable that actually carries the signals. The timeout will only affect commands that read from the device. Vicki Stanfield wrote: > I am still unable to figure out how to test whether or not the device on > the other end of the serial connection is on. Is there a simple way to do > a conditional read that times out with an error after some given amount of > time. I am using pyserial version 1.18. When I open the port, I specify a > timeout of 1 second, but that doesn't seem to do what I expect it to. > Maybe I have to do something different with the write command to look for > an error code? Right now, it is simply: > > port.write('\x09') > > I don't see anything documented. > > > --vicki > > _______________________________________________ > 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 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From pythontutor at venix.com Tue Sep 23 15:28:39 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Sep 23 15:28:44 2003 Subject: [Tutor] pyserial question In-Reply-To: References: Message-ID: <3F709EE7.8000700@venix.com> Serial Communications never standardized on a software protocol for these kinds of issues. The wiring spec is often abused as well. Essentially you throw bits onto the wire without any way of knowing if the other end is listening. A valid response means that all is well. An invalid response at least tells you that you've made contact with the device. Silence just means that something is wrong. A break signal could indicate a connection problem. serialposix.py provides a function for sending a break (sendBreak), I did not see any support for detecting a break. You probably need to consult your device documentation to determine what is available for signalling and troubleshooting. Stanfield, Vicki {D167~Indianapolis} wrote: > Actually this functionality is just what I need, but it doesn't work in my application (always returns 0). I am using an infrared dongle, does that not meet your second spec of using a cable that actually carries the signals? If not, how can I accomplish the same thing with a read or write or something else? > > --vicki > > -----Original Message----- > From: Lloyd Kvam [mailto:pythontutor@venix.com] > Sent: Tuesday, September 23, 2003 10:45 AM > To: Vicki Stanfield > Cc: tutor@python.org > Subject: Re: [Tutor] pyserial question > > > I downloaded the current pyserial (1.20). I looked at the serialposix.py > file. > > dev = Serial(rtscts=1,#plus other necessary parameters) > dev.getDSR() # should be true if device is turned on > dev.getCTS() # should be true if device is ready to receive data > > This only works if the device actually supports hardware flow > control signalling AND if you are using a cable that actually carries > the signals. > > The timeout will only affect commands that read from the device. > > Vicki Stanfield wrote: > > >>I am still unable to figure out how to test whether or not the device on >>the other end of the serial connection is on. Is there a simple way to do >>a conditional read that times out with an error after some given amount of >>time. I am using pyserial version 1.18. When I open the port, I specify a >>timeout of 1 second, but that doesn't seem to do what I expect it to. >>Maybe I have to do something different with the write command to look for >>an error code? Right now, it is simply: >> >>port.write('\x09') >> >>I don't see anything documented. >> >> >>--vicki >> >>_______________________________________________ >>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 VICKI.STANFIELD at ROCHE.COM Tue Sep 23 15:32:31 2003 From: VICKI.STANFIELD at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Tue Sep 23 15:38:11 2003 Subject: [Tutor] pyserial question Message-ID: Actually it is not the device is it? If the device is off, I won't get anything back from it at all. If I don't get anything back for 1 minute, I want to presume it is off. I just need to be able to try to read and, if I get no response, throw an error. Is this possible? --vicki -----Original Message----- From: Lloyd Kvam [mailto:pythontutor@venix.com] Sent: Tuesday, September 23, 2003 2:29 PM To: Stanfield, Vicki {D167~Indianapolis} Cc: Vicki Stanfield; tutor@python.org Subject: Re: [Tutor] pyserial question Serial Communications never standardized on a software protocol for these kinds of issues. The wiring spec is often abused as well. Essentially you throw bits onto the wire without any way of knowing if the other end is listening. A valid response means that all is well. An invalid response at least tells you that you've made contact with the device. Silence just means that something is wrong. A break signal could indicate a connection problem. serialposix.py provides a function for sending a break (sendBreak), I did not see any support for detecting a break. You probably need to consult your device documentation to determine what is available for signalling and troubleshooting. Stanfield, Vicki {D167~Indianapolis} wrote: > Actually this functionality is just what I need, but it doesn't work in my application (always returns 0). I am using an infrared dongle, does that not meet your second spec of using a cable that actually carries the signals? If not, how can I accomplish the same thing with a read or write or something else? > > --vicki > > -----Original Message----- > From: Lloyd Kvam [mailto:pythontutor@venix.com] > Sent: Tuesday, September 23, 2003 10:45 AM > To: Vicki Stanfield > Cc: tutor@python.org > Subject: Re: [Tutor] pyserial question > > > I downloaded the current pyserial (1.20). I looked at the serialposix.py > file. > > dev = Serial(rtscts=1,#plus other necessary parameters) > dev.getDSR() # should be true if device is turned on > dev.getCTS() # should be true if device is ready to receive data > > This only works if the device actually supports hardware flow > control signalling AND if you are using a cable that actually carries > the signals. > > The timeout will only affect commands that read from the device. > > Vicki Stanfield wrote: > > >>I am still unable to figure out how to test whether or not the device on >>the other end of the serial connection is on. Is there a simple way to do >>a conditional read that times out with an error after some given amount of >>time. I am using pyserial version 1.18. When I open the port, I specify a >>timeout of 1 second, but that doesn't seem to do what I expect it to. >>Maybe I have to do something different with the write command to look for >>an error code? Right now, it is simply: >> >>port.write('\x09') >> >>I don't see anything documented. >> >> >>--vicki >> >>_______________________________________________ >>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 amonroe at columbus.rr.com Tue Sep 23 15:54:18 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Sep 23 15:48:06 2003 Subject: [Tutor] Checking for the existence of a file on workstations in Windows LAN Message-ID: <12468782323.20030923155418@columbus.rr.com> I'd like to check client machines on a LAN for the existence of certain files, via their C$ share, in a corporate environment. I can use the os.stat or os.path.exists functions to see whether the file is there, but on those times when the functions fail, how do I know if it was because the file genuinely didn't exist, or because I didn't have rights to their c$ share? I need to distinguish between the two cases. Even better would be to distinguish the third case where the machine couldn't be found at all, likely because it's powered off. Alan From alan.gauld at blueyonder.co.uk Tue Sep 23 16:51:16 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Sep 23 16:50:17 2003 Subject: [Tutor] Re: Hi References: <1064307260.26687.2.camel@phoenix> Message-ID: <00b801c38214$6eb0c060$6401a8c0@xp> > > projects people are working on right now?? Right now none coz I'm off on vacation tomorrow! :-) But once I get back I'll be working on a call queue simulator for a contact centre - modelling the call presentation to agents with a blended mix of voice, email and web chats. If that looks realistic then I will extend it to see what happens if we add Instant Messaging to the mix. And if I can find the spare time I might also try to build a little COM utility for Outlook to generate a distribution list from the list of addresses on the To: and CC: lines in an email. It would probably be easier in VBA but I'd like to try it in Python... But time will be at a premium when I return, so its a long shot. Welcome to the tutor list, :-) Alan G. From idiot1 at netzero.net Wed Sep 24 00:57:24 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Wed Sep 24 00:56:40 2003 Subject: [Tutor] test Message-ID: <3F712434.4020907@netzero.net> test-please SMASH INTO THE BARE METAL WITH A 20 LB SLEDGE HAMMER, A ROLL OF BARBED WIRE, ALL THE DUCT TAPE YOU CAN FIND, AND ***NO*** LUBRICANT! -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From peterabrown at froggy.com.au Wed Sep 24 08:43:01 2003 From: peterabrown at froggy.com.au (Peter Brown) Date: Wed Sep 24 08:43:48 2003 Subject: [Tutor] Printing to file on one line Message-ID: <1064407381.19197.24.camel@localhost.localdomain> Jeff, Thanks for your good work. The example you gave works well for Windows but not Linux. The example I sent yesterday was from Redhat 9. The output below shows outputting 82 characters, but the line is still wrapped note '\n' on first line (after payments). How did that \n get there? My programme didn't include it, is it a bug in Python on Redhat 9 - Python 2.2.2? Secondly, the date has two spaces preceeding it, but no formatting to accomplish this? TIA Peter def write_header(aba_file, batchtype,conf_name,conf_apca,conf_desc,smdate): batchname = '%02sMET' % batchtype format = '%-18s%-12s%-26s%-6s%-12s%6s\r\n' output = format % ('0', batchname, conf_name, str(conf_apca[:6]), conf_desc, smdate) aba_file.write(output) print "Outputting %d bytes to file" % len(output) print output Outputting 82 bytes to file 0 68PET PA Exports 239381Payments 240903 print repr(open('/usr/TP/20030924.aba', 'rb').read(82)) '0 68PET PA Exports 239381Payments\n 240903\r\n' From jtk at yahoo.com Wed Sep 24 12:05:27 2003 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Wed Sep 24 12:05:34 2003 Subject: [Tutor] simple MS office addins, spambayes style Message-ID: I'm interested in bundling python code into office addins. I want to get rid of VBA for various object-model manipulation functions that I write to automate end-user tasks. The Spambayes Outlook plugin is extremely impressive and I would like to emulate it, but its getting a bit daunting to factor out the minumum code necessary for a non-graphical user function library. http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/spambayes/spambayes/Outlook2000/addin.py Does anyone have any 'hello world' office addin samples along these lines? I'm just looking to import the host object model, then expose a few functions to the 'run macros' interface, or something equivalent. I'd like to generalize the addin boilerplate code across other office Apps supporting addins if I can, so I want to start with the simplest possible python code and work my way up. Thanks. From jeff at ccvcorp.com Wed Sep 24 12:54:14 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Sep 24 12:52:15 2003 Subject: [Tutor] Printing to file on one line References: <1064407381.19197.24.camel@localhost.localdomain> Message-ID: <3F71CC36.50402@ccvcorp.com> Peter Brown wrote: > Jeff, > > Thanks for your good work. The example you gave works well for Windows > but not Linux. > > The example I sent yesterday was from Redhat 9. The output below shows > outputting 82 characters, but the line is still wrapped note '\n' on > first line (after payments). How did that \n get there? My programme > didn't include it, is it a bug in Python on Redhat 9 - Python 2.2.2? > Secondly, the date has two spaces preceeding it, but no formatting to > accomplish this? > print repr(open('/usr/TP/20030924.aba', 'rb').read(82)) > '0 68PET PA Exports > 239381Payments\n 240903\r\n' Those spaces are part of the conf_desc column -- %-12s indicates that the string should be left-justified in a twelve-character-wide space. As for the extra '\n', is there a chance that it's part of the string that you're passing in? Where are you reading conf_desc from? The most likely explanation I can see is that you're formatting in 'Payments\n' rather than just 'Payments'. You can test this by changing the formatting line, modifying conf_desc to be conf_desc.strip() -- that will remove all whitespace (including newlines) from the beginning and end of the string. Indeed, the fact that there's only two spaces preceding the date suggests that the \n *is* part of conf_desc. 'Payments' is only nine characters, and if that was formatted into a 12-char wide field, there should be three spaces following. However, 'Payments\n' is ten characters long, so that would only leave two spaces... Jeff Shannon Technician/Programmer Credit International From bgailer at alum.rpi.edu Wed Sep 24 13:18:16 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Sep 24 13:20:30 2003 Subject: [Tutor] Checking for the existence of a file on workstations in Windows LAN In-Reply-To: <12468782323.20030923155418@columbus.rr.com> References: <12468782323.20030923155418@columbus.rr.com> Message-ID: <6.0.0.22.0.20030924111438.0340e630@66.28.54.253> At 01:54 PM 9/23/2003, R. Alan Monroe wrote: >I'd like to check client machines on a LAN for the existence of >certain files, via their C$ share, in a corporate environment. > >I can use the os.stat or os.path.exists functions to see whether the >file is there, but on those times when the functions fail, how do I >know if it was because the file genuinely didn't exist, or because I >didn't have rights to their c$ share? I need to distinguish between >the two cases. Even better would be to distinguish the third case >where the machine couldn't be found at all, likely because it's >powered off. My experience with windows says that even though the API knows where the failure was no way will it tell you. I have had numerous occasions where knowing the reason for failure would have been very helpful, but the information is not available. I can suggest testing for a known file (e.g. autoexec.bat) to tell whether you can see the drive, and using ping to see if the machine is running (and, of course, responding to pings, and that the firewall lets you thru, etc etc) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From learning.python at dbmail.dk Wed Sep 24 21:26:39 2003 From: learning.python at dbmail.dk (Ole Jensen) Date: Wed Sep 24 21:28:19 2003 Subject: [Tutor] formating a string (partly) Message-ID: <001c01c38304$11ec42f0$a54c73d5@BAERBAR> Is there any way to ?nclude percentage signs (as text) in a string, that also contains format modulos (%s)? I'm sorry if the above makes no sense, but thats the reason for posting! I have no clue what to search for... I tried but... So I better give an example of what I want to do: >>> txt = "Hello %s. This is a percentagesign: %" >>> name = "Thomas" >>> print txt % name Traceback (most recent call last): File "", line 1, in ? print txt % name ValueError: incomplete format >>> # should be this: >>> # Hello Thomas. This is a percentagesign: % Basically I want to use the modulo thing to insert variable values on a web page (cgi output) where there are a lot of percentages signs that shouldn't be formated because they are part of the html-code. Alright I hope it made better sense in the end. And thanks in advance for any suggestions. For now Ole -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030925/026b71b1/attachment.html From tpc at csua.berkeley.edu Wed Sep 24 21:53:53 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Sep 24 21:54:01 2003 Subject: [Tutor] formating a string (partly) In-Reply-To: <001c01c38304$11ec42f0$a54c73d5@BAERBAR> Message-ID: <20030924185049.L78976-100000@localhost.name> hi Ole, you just use a double percent like so: txt =3D "Hello %s. This is a percentagesign: %%" The reference for this is on: http://www.python.org/doc/current/lib/typesseq-strings.html % No argument is converted, results in a "%" character in the result. I hope that helps you. On Thu, 25 Sep 2003, Ole Jensen wrote: > Is there any way to =EDnclude percentage signs (as text) in a string, tha= t also contains format modulos (%s)? > > I'm sorry if the above makes no sense, but thats the reason for posting! = I have no clue what to search for... I tried but... > > So I better give an example of what I want to do: > > >>> txt =3D "Hello %s. This is a percentagesign: %" > >>> name =3D "Thomas" > >>> print txt % name > Traceback (most recent call last): > File "", line 1, in ? > print txt % name > ValueError: incomplete format > >>> # should be this: > >>> # Hello Thomas. This is a percentagesign: % > > Basically I want to use the modulo thing to insert variable values on a w= eb page (cgi output) where there are a lot of percentages signs that should= n't be formated because they are part of the html-code. > > Alright I hope it made better sense in the end. > And thanks in advance for any suggestions. > > For now > Ole > From mhansen at cso.atmel.com Thu Sep 25 14:58:06 2003 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Sep 25 14:58:08 2003 Subject: [Tutor] simple MS office addins, spambayes style In-Reply-To: References: Message-ID: <3F733ABE.3080500@cso.atmel.com> I not sure why you'd want to do this. As much as I love python, this doesn't seem appropriate to me. Those who want to use the addin would need to have python installed on their system as well as Office making distribution more complex. Mike > > Subject: > [Tutor] simple MS office addins, spambayes style > From: > Jeff Kowalczyk > Date: > Wed, 24 Sep 2003 12:05:27 -0400 > To: > tutor@python.org > > >I'm interested in bundling python code into office addins. I want to get >rid of VBA for various object-model manipulation functions that I write to >automate end-user tasks. > >The Spambayes Outlook plugin is extremely impressive and I would like to >emulate it, but its getting a bit daunting to factor out the minumum code >necessary for a non-graphical user function library. > >http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/spambayes/spambayes/Outlook2000/addin.py > >Does anyone have any 'hello world' office addin samples along these lines? >I'm just looking to import the host object model, then expose a few >functions to the 'run macros' interface, or something equivalent. > >I'd like to generalize the addin boilerplate code across other office Apps >supporting addins if I can, so I want to start with the simplest possible >python code and work my way up. > >Thanks. > > > > > From mhansen at cso.atmel.com Thu Sep 25 15:17:05 2003 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Sep 25 15:17:11 2003 Subject: [Tutor] RE: simple MS office addins, spambayes style (Jeff Kowalczyk) In-Reply-To: References: Message-ID: <3F733F31.9070105@cso.atmel.com> As much as I love python, this doesn't seem appropriate. I'm not sure why you'd want to do this. Those who'd use the addins would need to install python to get them to work. It makes distribution more complicated. > Subject: > [Tutor] simple MS office addins, spambayes style > From: > Jeff Kowalczyk > Date: > Wed, 24 Sep 2003 12:05:27 -0400 > To: > tutor@python.org > > >I'm interested in bundling python code into office addins. I want to get >rid of VBA for various object-model manipulation functions that I write to >automate end-user tasks. > >The Spambayes Outlook plugin is extremely impressive and I would like to >emulate it, but its getting a bit daunting to factor out the minumum code >necessary for a non-graphical user function library. > >http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/spambayes/spambayes/Outlook2000/addin.py > >Does anyone have any 'hello world' office addin samples along these lines? >I'm just looking to import the host object model, then expose a few >functions to the 'run macros' interface, or something equivalent. > >I'd like to generalize the addin boilerplate code across other office Apps >supporting addins if I can, so I want to start with the simplest possible >python code and work my way up. > >Thanks. > > > > > > From glingl at aon.at Thu Sep 25 16:47:25 2003 From: glingl at aon.at (Gregor Lingl) Date: Thu Sep 25 16:49:58 2003 Subject: [Tutor] How to explore Tkinter interactively with IDLE 1.0 Message-ID: <3F73545D.3080006@aon.at> Hi Pythonistas! Today I'd like to ask a question, which at first may look a bit technical, but which in fact for me is of high didactical importance. It concerns the proper use of IDLE in Python 2.3. With Python 2.2 (and IDLE 0.8) I used to use IDLE interactively with my students to explore different features of Tkinter. I'll give you two short examples: 1. Exploring Widgets: >>> root = Tk() >>> cv = Canvas(root, bg="white") >>> cv.pack() >>> btn = Button(root,text="Push") >>> btn.pack() >>> btn.config(bg="red") >>> # pushing the button doesn't do anything! >>> def action(): cv.create_rectangle(50,50,150,100,fill="red") >>> btn.config(command=action) >>> # pushing button creates red rectangle >>> cv.find_all() (1,) >>> cv.move(cv.find_all()[0], 100,150) >>> # rectangle moved , now create a new one >>> # or config existing widgets or canvasitems etc. etc. Shortly, learn how Tkinter works 2. Using turtle-graphics >>> from turtle import * >>> forward(100) A Canvas pops up and the turtle starts to move and remains ready for the user to interact with her interactively. Alas! Both examples don't work in ordinary IDLE 1.0 - mode I'm well aware of the advantages of IDLE 1.0, especially the one always to have a clean workspace for testing programs - and I'd like to port as much of them to a customized development environment I use in my classes. Now, I'm considering to work with both of the two modes in my classes, although I'm not sure, if this will be easy to explain to my students. How do you proceed to "keep it as simple as possible, but not simpler?" Are there other ways for developing Tkinter-GUI-programs interactively. Specifically: can the turtle.module only be used interactively (as intended) with the IDLE -n switch? Although there are many other graphics modules around I certainly will stick to using Tkinter (and IDLE), because I consider it to be a big advantage for beginners to start with tools as they come out of the box. (Aside: nevertheless I use to use IDLE with pythons -Qnew - switch to avoid complications with division, i. e. In my classes I silently import the future - one of my means to minimize computer-hatred ;-) ) Therefore I'm interested in every comment and every idea on how to use the new IDLE optimally for educational purposes. So I'll post this question (in contrast to my usual habit) on tutor, edu-sig and idle-dev. This will remain an exception. Regards Gregor Lingl P.S.: The new possibilities of printing the content of windows and of customizing the appearance of IDLE (fonts, colors etc.) easily e.g. for use with a beamer in a classroom is imho a big advance. Especially when I try to convince my colleagues to use Python, who, accustomed to the usual Windows, VisualBasic etc. comfort, used to critisize the spartanic features of the old IDLE. If you believe it or not, for many teachers (and students) those things matter! P.P.S: Moreover a gentle update of Dennies gentle introduction to the use of IDLE would be a hit! From glingl at aon.at Thu Sep 25 16:57:06 2003 From: glingl at aon.at (Gregor Lingl) Date: Thu Sep 25 16:58:58 2003 Subject: [Tutor] Additional remark concerning -Qnew with IDLE 1.0 Message-ID: <3F7356A2.80706@aon.at> Hi, just observed (for the second time :-( ) that the -Qnew switch dowsn't work with IDLE 1.0 except in -n mode. I.e.: With python.exe -Qnew idle.pyw IDLE does not perform float-division with integer arguments, whereas with python.exe -Qnew idle.pyw -n new division works. This seem strange and inconsistent? Regards Gregor Lingl From dyoo at hkn.eecs.berkeley.edu Thu Sep 25 17:00:31 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 25 17:00:35 2003 Subject: [Tutor] simple MS office addins, spambayes style In-Reply-To: Message-ID: On Wed, 24 Sep 2003, Jeff Kowalczyk wrote: > I'm interested in bundling python code into office addins. I want to get > rid of VBA for various object-model manipulation functions that I write > to automate end-user tasks. Hi Jeff, Hmmm... you might want to ask your question on the Python-win32 list. I'm not sure if many of us have enough experience with this to help you effectively. The win32 folks, though, should be better equipped to point you in the right direction You can find Python-Win32 here: http://mail.python.org/mailman/listinfo/python-win32 > The Spambayes Outlook plugin is extremely impressive and I would like to > emulate it, but its getting a bit daunting to factor out the minumum > code necessary for a non-graphical user function library. > > http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/spambayes/spambayes/Outlook2000/addin.py I haven't yet had the time to look at how Spambayes does its communication with Outlook, unfortunately. If I get the chance, I'll take a glance. > I'd like to generalize the addin boilerplate code across other office > Apps supporting addins if I can, so I want to start with the simplest > possible python code and work my way up. It sounds like a very interesting project! Definitely get in touch with the other win32 developers on the Python-win32 list: I'm sure you'll get good responses there. Good luck to you! From arkamir at softhome.net Thu Sep 25 21:38:15 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Thu Sep 25 21:40:39 2003 Subject: [Tutor] sending an email Message-ID: <1064540295.5559.9.camel@quercus.home.net> hey can anyone point me to a tutorial or a link where it explains pretty clearly how to send an email??? Or perhaps describe the process here.It's going to be used for a cgi program where i need to send the user back some data. Thanks Conrad From jtk at yahoo.com Thu Sep 25 21:55:11 2003 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Thu Sep 25 21:55:18 2003 Subject: [Tutor] RE: simple MS office addins, spambayes style (Jeff Kowalczyk) References: <3F733F31.9070105@cso.atmel.com> Message-ID: Mike Hansen: > As much as I love python, this doesn't seem appropriate. I'm not sure > why you'd want to do this. Those who'd use the addins would need to > install python to get them to work. It makes distribution more > complicated. I find myself writing VBA code for Outlook, Access and Excel users quite often. The situations typically involve a repetitve task that isn't regular enough (or important enough) to write a full blown application for, or to hold the users over until their application comes up in the development queue. Deployments are usually very small, and I put python and python-win32 on most computers I'm given access to, just on principle ;) After spending time almost exclusively using python, going back to write some more VBA recently was aggravating. I miss the string manipulations, sequences, dictionaries, exception handling - All those virtues are ideally suited for the types of data-normalization/object-model manipulation code that I try to spend as little time writing and maintaining as possible. From exnihilo at myrealbox.com Thu Sep 25 22:40:28 2003 From: exnihilo at myrealbox.com (nihilo) Date: Thu Sep 25 22:41:03 2003 Subject: [Tutor] sending an email In-Reply-To: <1064540295.5559.9.camel@quercus.home.net> References: <1064540295.5559.9.camel@quercus.home.net> Message-ID: <3F73A71C.6030900@myrealbox.com> See the example they give in the documentation for the smtplib module, at http://python.org/doc/current/lib/SMTP-example.html. You'll be amazed at how easy it is ;-) Conrad Koziol wrote: >hey can anyone point me to a tutorial or a link where it explains pretty >clearly how to send an email??? Or perhaps describe the process >here.It's going to be used for a cgi program where i need to send the >user back some data. Thanks > >Conrad > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From camartin at snet.net Fri Sep 26 09:20:25 2003 From: camartin at snet.net (Cliff Martin) Date: Fri Sep 26 09:18:03 2003 Subject: [Tutor] datenum Message-ID: <3F743D19.1040502@snet.net> Hi, There is a function in MatLab called DATENUM which converts a date (in M D Y format) to a number referenced to some zero. Is there such a function already written in Python or one of its modules? I'm porting a MatLab program and would like not to have to write this function from scratch, if possible. Thanks Cliff From glingl at aon.at Fri Sep 26 11:01:18 2003 From: glingl at aon.at (Gregor Lingl) Date: Fri Sep 26 11:03:10 2003 Subject: [Tutor] datenum In-Reply-To: <3F743D19.1040502@snet.net> References: <3F743D19.1040502@snet.net> Message-ID: <3F7454BE.3060303@aon.at> Hi, Cliff! There is a powerful *new* datetime-module in Python 2.3 Its documented here (and in the Global Module Index): http://www.python.org/doc/current/lib/module-datetime.html Maybe the toordinal method of the date class is something you could use: >>> from datetime import date >>> date(2003,9,25).toordinal() 731483 (Maybe you will need anoter "some zero" ?) Have a look at the docu. You cerainly will find something which at least will make your life easier. Regards, Gregor Cliff Martin schrieb: > Hi, > > There is a function in MatLab called DATENUM which converts a date (in > M D Y format) to a number referenced to some zero. Is there such a > function already written in Python or one of its modules? I'm porting > a MatLab program and would like not to have to write this function > from scratch, if possible. Thanks > > Cliff > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From jeff at ccvcorp.com Fri Sep 26 16:20:01 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Sep 26 16:17:18 2003 Subject: [Tutor] sending an email References: <1064540295.5559.9.camel@quercus.home.net> <3F73A71C.6030900@myrealbox.com> Message-ID: <3F749F71.1020504@ccvcorp.com> nihilo wrote: > Conrad Koziol wrote: > >> hey can anyone point me to a tutorial or a link where it explains pretty >> clearly how to send an email??? Or perhaps describe the process >> here.It's going to be used for a cgi program where i need to send the >> user back some data. Thanks > > See the example they give in the documentation for the smtplib module, > at http://python.org/doc/current/lib/SMTP-example.html. You'll be > amazed at how easy it is ;-) > Also be sure to check out the email package -- http://python.org/doc/current/lib/module-email.html You would typically use the email package to create and format a message, and then the smtplib module to send that message to your mailserver. Jeff Shannon Technician/Programmer Credit International From pan at uchicago.edu Fri Sep 26 19:15:23 2003 From: pan at uchicago.edu (pan@uchicago.edu) Date: Fri Sep 26 19:15:29 2003 Subject: [Tutor] python.org mail server? Message-ID: <1064618123.3f74c88b7b05d@webmail.uchicago.edu> Hi all, I'm making a "pyAR" ---a python archive reader, which is able to read many different py-related archives. The objective, aside from being able to read many archives on a single page, is to allow read and reply/post on that same page. When replying/posting a msg, what I like to do is to call the mail server on python.org for the mail transfer. That means, anyone, even he doesn't have a mail account, can still make use of it. So, my question is, is this possible ? Or If yes, then, how can I get the info (address) of a mail server for me to use to send mails ? Thx in advance. pan From project5 at redrival.net Fri Sep 26 21:04:26 2003 From: project5 at redrival.net (Andrei) Date: Fri Sep 26 21:06:34 2003 Subject: [Tutor] Re: python.org mail server? In-Reply-To: <1064618123.3f74c88b7b05d@webmail.uchicago.edu> References: <1064618123.3f74c88b7b05d@webmail.uchicago.edu> Message-ID: pan@uchicago.edu wrote: > Hi all, > > I'm making a "pyAR" ---a python archive reader, which is able to > read many different py-related archives. The objective, aside from > being able to read many archives on a single page, is to allow > read and reply/post on that same page. I'm curious about that: is it webbased? > When replying/posting a msg, what I like to do is to call the mail > server on python.org for the mail transfer. That means, anyone, even > he doesn't have a mail account, can still make use of it. > So, my question is, is this possible ? Or I hope not, it sounds like an excellent way to distribute spam. I've never used a SMTP server which didn't require authentication (but then again, I'm not an oldtimer :)). > If yes, then, how can I get the info (address) of a mail server for > me to use to send mails ? Perhaps you could ask the user to install a local smtp server? Perhaps there's even one in Python somewhere in the libs or on the net. Otherwise, there are free ones available for Windows and Linux comes with a whole battery of servers, so that shouldn't be a problem. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From pan at uchicago.edu Fri Sep 26 23:32:06 2003 From: pan at uchicago.edu (pan@uchicago.edu) Date: Fri Sep 26 23:32:09 2003 Subject: [Tutor] python.org mail server? Message-ID: <1064633526.3f7504b610f3d@webmail.uchicago.edu> |> I'm making a "pyAR" ---a python archive reader, which is able to |> read many different py-related archives. The objective, aside from |> being able to read many archives on a single page, is to allow |> read and reply/post on that same page. | |I'm curious about that: is it webbased? I hope to make it webbased, so I can use it both at home and at work or even on travel. And sure, any pythonist can use it too. But I need to learn how this can be done. If I have some company host my website, I should be able to use their mail server on my webpage, right ? |> When replying/posting a msg, what I like to do is to call the mail |> server on python.org for the mail transfer. That means, anyone, even |> he doesn't have a mail account, can still make use of it. |> So, my question is, is this possible ? Or | |I hope not, it sounds like an excellent way to distribute spam. I've never used |a SMTP server which didn't require authentication (but then again, I'm not an |oldtimer :)). If I am convinced that it could cause spam, then I will make it password protected and use it for private only. |> If yes, then, how can I get the info (address) of a mail server for |> me to use to send mails ? | |Perhaps you could ask the user to install a local smtp server? Perhaps there's |even one in Python somewhere in the libs or on the net. Otherwise, there are |free ones available for Windows and Linux comes with a whole battery of servers, |so that shouldn't be a problem. Well this is basically for my own convinience. I like to be able to watch, learn, and help with py related stuff easily and hassle-free. But subscribing to too many list managers brings too many emails to me. pan From rahulk at bhartitelesoft.com Sat Sep 27 02:01:18 2003 From: rahulk at bhartitelesoft.com (Rahul Kumar) Date: Sat Sep 27 01:50:58 2003 Subject: [Tutor] Asynch i/o in Python ? In-Reply-To: References: Message-ID: <20030927060118.GA19278@bhartitelesoft.com> Does Python support aio (asynch io). I dont mean just the non-blocking select(). From pythontutor at venix.com Sat Sep 27 12:01:51 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Sep 27 12:15:42 2003 Subject: [Tutor] python.org mail server? In-Reply-To: <1064633526.3f7504b610f3d@webmail.uchicago.edu> References: <1064633526.3f7504b610f3d@webmail.uchicago.edu> Message-ID: <3F75B46F.8060404@venix.com> pan@uchicago.edu wrote: > I hope to make it webbased, so I can use it both at home and > at work or even on travel. And sure, any pythonist can use it > too. > > But I need to learn how this can be done. If I have some company > host my website, I should be able to use their mail server on > my webpage, right ? That is correct. When one mail server accepts email for delivery to another mail server, it is relaying. An ISP will normally allow relaying only for connections from the ISP's block of IP addresses. Your script should have no trouble sending email. An email server that will allow anyone to relay is an "open relay" and will be discovered and abused by spammers. The problem is that SPAMMERs WILL attempt to subvert your script. I've seen many web logs where there are more hits from spammers and would be crackers attempting to subvert the site, than from legitimate web traffic. My mail server log shows almost as many spam attempts as real emails. For instance, if your script is an accepted sender of email to the tutor list, a spammer would be able to use it to spam us all. An email script that ONLY allows email to a corporate customer service office is not of much interest to a spammer. However, a script that provided access to a relatively spam free list would be quite attractive. Even worse is a script that supports specifying the email recipient. My ISP was victimized by spammers when a client of the ISP naively installed a script that had a parameter to specify the recipient email address. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dyoo at hkn.eecs.berkeley.edu Sat Sep 27 22:35:38 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Sep 27 22:35:51 2003 Subject: [Tutor] Asynch i/o in Python ? In-Reply-To: <20030927060118.GA19278@bhartitelesoft.com> Message-ID: On Sat, 27 Sep 2003, Rahul Kumar wrote: > Does Python support aio (asynch io). I dont mean just the non-blocking > select(). Hi Rahul, The language itself doesn't specify blocking/nonblocking IO features, but there are several libraries that do. For example, there's a library module called asyncore: http://www.python.org/doc/lib/module-asyncore.html http://www.python.org/doc/lib/module-asynchat.html that provides core support for asynchronous IO. Not only is there good support from the Standard Library, but there are also some nice third-party modules. In particular, there's a comprehensive package called "Twisted Python": http://www.twistedmatrix.com/products/twisted The Twisted folks are wrapping all kinds of network protocols with an asynchronous IO interface, including ftp, telnet, http, instant messaging, and a whole lot of other protocols... *grin* Anyway, hope those links are helpful for you. If you have more questions, please feel free to ask. Good luck! From tbstep at tampabay.rr.com Sat Sep 27 22:30:45 2003 From: tbstep at tampabay.rr.com (Todd Stephens) Date: Sat Sep 27 22:36:39 2003 Subject: [Tutor] Test, sorry Message-ID: <200309272230.45036.tbstep@tampabay.rr.com> I have been getting precious little from this list that used to fill my inbox. Just checking to see if this shows up or not. -- Todd Stephens "Good people do not need laws to tell them to act responsibly, while bad people will find a way around the laws." - Plato From rahulk at bhartitelesoft.com Sun Sep 28 02:52:24 2003 From: rahulk at bhartitelesoft.com (Rahul Kumar) Date: Sun Sep 28 02:41:53 2003 Subject: [Tutor] Asynch i/o in Python ? In-Reply-To: References: <20030927060118.GA19278@bhartitelesoft.com> Message-ID: <20030928065224.GA31843@bhartitelesoft.com> Thanks. i shall check out twisted. Actually, asyncore uses select() which is *not* really asynch. I was hoping that there is a module that wraps around "aio". thanks rahul On Sat, Sep 27, 2003 at 07:35:38PM -0700, Danny Yoo wrote: > Date: Sat, 27 Sep 2003 19:35:38 -0700 (PDT) > From: Danny Yoo > To: Rahul Kumar > cc: tutor@python.org > Subject: Re: [Tutor] Asynch i/o in Python ? > > > > On Sat, 27 Sep 2003, Rahul Kumar wrote: > > > Does Python support aio (asynch io). I dont mean just the non-blocking > > select(). > > Hi Rahul, > > > The language itself doesn't specify blocking/nonblocking IO features, but > there are several libraries that do. For example, there's a library > module called asyncore: > > http://www.python.org/doc/lib/module-asyncore.html > http://www.python.org/doc/lib/module-asynchat.html > > that provides core support for asynchronous IO. > > > Not only is there good support from the Standard Library, but there are > also some nice third-party modules. In particular, there's a > comprehensive package called "Twisted Python": > > http://www.twistedmatrix.com/products/twisted > From jim_938 at hotmail.com Sun Sep 28 10:31:32 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Sun Sep 28 10:31:42 2003 Subject: [Tutor] handling tuples in a dictionary Message-ID: Hello, Thanks to everyone on tutor list for providing their valuable support. I am having my problem like this: I have a dictionary with items of the following form: dict = {('x',1): -100, ('y',2):-200, ('x',2):100, ('z',3):150, ('y', 4):50} I have tuple as the keys. What i want is to have this information in this form in order to make the combinations: Letter 'X' set 1 R -100 set 2 R 100 Letter 'Y' set 2 R -200 set 4 R 50 Letter 'Z' set 3 R 150 I mean i want for all the tuples that whose first letter is same they should be put in one group and their values listed like i have written above. I have tried to take the dict.keys() and then sort these values but not getting to know completely how can i achieve this. You suggestions will be highly appriciated. Thanks in advance. Regards, J+ _________________________________________________________________ Calling all NRIs! Avail of the best financial services. http://server1.msn.co.in/msnspecials/nriservices/index.asp Smile all the way with ICICI Bank. From rclilly at cox.net Sun Sep 28 11:50:21 2003 From: rclilly at cox.net (Robert Lilly) Date: Sun Sep 28 11:50:27 2003 Subject: [Tutor] Introduction and ? re: searching the list's archives Message-ID: <001801c385d8$39570420$797ba8c0@rclilly.com> Hello everyone, My name is Robert and I just signed up to the list. I am looking forward to learning how to program using Python. My background in programming is limited to Visual Basic, which some would say means I don't know anything about programming. ;-) I have written several sophisticated programs using MS Excel and VB, including a real-time signaling program for stock trading. I am not familiar with programming that isn't tied into some other application's object model, however. So, for all intents and purposes, I am learning both the Python programming language and object-oriented programming. I know that many of the questions I will want to ask have probably already been discussed. So I've downloaded the mbox archive so that I may search through it before asking a question. However, I'm not sure what an efficient means for searching it may be. Does anyone have any recommendations on how to go about searching an mbox archive? I am working primarily under Windows 2000, but I have Cygwin installed, so a *nix solution may be viable as well. I'm not sure what the etiquette for this group is yet, so forgive me if this post is off-topic. Thanks, Robert Lilly From idiot1 at netzero.net Sun Sep 28 11:55:09 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Sep 28 11:54:36 2003 Subject: [Tutor] cgi server default directory In-Reply-To: References: Message-ID: <3F77045D.8080408@netzero.net> Steve, how do redefine the default folder the thing referrs to as it's webpage root? Having this live in the same dir as the pages can create confusion for less experienced users- but the script definition does not declare a path, but instead assumes it's path. Would it be hard to modify things so the cgiserver would referr to a internally defined folder- OR, to one defined by a external config file? Internally might be easier. Assume there is a dir UNDER the script's place of residence, and we call it 'webpage' or 'www' or 'root', and that is the root of the web accessable tree, with ALL accessable directories under it. This makes the server a bit more secure, and less confusing. Outisde users cannot acces host system files, or anything else above the web root dir, and one structures local sites off that directory normally- and don't place anything in the subtree you would not want amalicious person to be able to access. Any thoughts on this? -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From darnold02 at sprynet.com Sun Sep 28 12:14:35 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Sun Sep 28 12:18:55 2003 Subject: [Tutor] handling tuples in a dictionary References: Message-ID: <081701c385dc$2b5584b0$7610ba3f@defaultcomp> ----- Original Message ----- From: "Jimmy verma" To: Sent: Sunday, September 28, 2003 9:31 AM Subject: [Tutor] handling tuples in a dictionary > Hello, > > Thanks to everyone on tutor list for providing their valuable support. > > I am having my problem like this: > > I have a dictionary with items of the following form: > > dict = {('x',1): -100, ('y',2):-200, ('x',2):100, ('z',3):150, ('y', 4):50} > > I have tuple as the keys. > > > What i want is to have this information in this form in order to make the > combinations: > > Letter 'X' > set 1 R -100 > set 2 R 100 > > > Letter 'Y' > set 2 R -200 > set 4 R 50 > > > Letter 'Z' > set 3 R 150 > > > > I mean i want for all the tuples that whose first letter is same they should > be put in one group and their values listed like i have written above. > > > I have tried to take the dict.keys() and then sort these values but not > getting to know completely how can i achieve this. > > You suggestions will be highly appriciated. > > Thanks in advance. > > Regards, > > J+ I'm sure this isn't the most succinct way to do it, but it's fairly easy to follow: mydict = {('x',1): -100, ('y',2):-200, ('x',2):100, ('z',3):150, ('y', 4):50} newdict = {} for akey in mydict.keys(): if newdict.has_key(akey[0]): newdict[akey[0]].append((akey[1],mydict[akey])) else: newdict[akey[0]] = [(akey[1],mydict[akey])] keylist = newdict.keys() keylist.sort() for akey in keylist: print 'letter', akey for atuple in newdict[akey]: print 'set', atuple[0], 'R', atuple[1] >>> >>>letter x >>>set 1 R -100 >>>set 2 R 100 >>>letter y >>>set 2 R -200 >>>set 4 R 50 >>>letter z >>>set 3 R 150 >>> HTH, Don From idiot1 at netzero.net Sun Sep 28 12:20:50 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Sep 28 12:20:16 2003 Subject: [Tutor] path in BaseHttpServer.py module Message-ID: <3F770A62.8060002@netzero.net> Apparently BaseHTTPServer.py module defines self.path as path from the command line. relevant exerpt: requestline = self.raw_requestline if requestline[-2:] == '\r\n': requestline = requestline[:-2] elif requestline[-1:] == '\n': requestline = requestline[:-1] self.requestline = requestline words = requestline.split() if len(words) == 3: [command, path, version] = words (line 224-232) self.command, self.path, self.request_version = command, path, version (line 245) OKFINE. But I want the server script to referr to a directory UNDER that point on the tree, so webpages (in fact all of the web accessable tree) is rooted in a directory UNDER that directory. This means modifying the path declaration in the module- which means editing the module, OR declaring it in the top level script. Now this gets back to how python works, espically how it handles building up it's dictionary when it imports functions in modules. If I redefine a function defined in an imported module, will this break other functions? Again, the existing script is: #!C:\Python22\pythonw.exe # COPYRIGHT 2003 Steve Holden, free for personal use. # Please visit http://www.holdenweb.com/ to learn more! # import CGIHTTPServer, BaseHTTPServer httpd=BaseHTTPServer.HTTPServer(('',8080), CGIHTTPServer.CGIHTTPRequestHandler) httpd.serve_forever() # Any discussion? -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From missive at hotmail.com Sun Sep 28 12:45:49 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Sep 28 12:45:53 2003 Subject: [Tutor] Re: Asynch i/o in Python ? Message-ID: >Actually, asyncore uses select() which is *not* really asynch. I was >hoping that there is a module that wraps around "aio". > I am not really familiar with these modules, but asyncore.loop() can take a use_poll parameter to make it use poll instead of select. >From the select module page, it looks like poll is not available on all operating systems, but is available on most unix systems and can provide better scalability for network servers. _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From idiot1 at netzero.net Sun Sep 28 12:47:32 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Sep 28 12:46:59 2003 Subject: [Tutor] oop introduction pages Message-ID: <3F7710A4.5080702@netzero.net> my wiki mounts a series of pages on Objects and Object Oriented Programming. they are rather terse, and I would like to invite anyone at all to go and see if they can contribute to them. One member of this list did, but the pages got eaten, and had to be recreated from my notes- so the extra material was lost, alas. The pages can be edited by any reader (it's a wiki after all) so whosoever wishes, CLICK THIS and dive in. http://www.tinylist.org/cgi-bin/wikinehesa.py/ObjectOriented -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From abli at freemail.hu Sun Sep 28 13:15:27 2003 From: abli at freemail.hu (Abel Daniel) Date: Sun Sep 28 13:15:17 2003 Subject: [Tutor] Re: Introduction and ? re: searching the list's archives In-Reply-To: <001801c385d8$39570420$797ba8c0@rclilly.com> (Robert Lilly's message of "Sun, 28 Sep 2003 08:50:21 -0700") References: <001801c385d8$39570420$797ba8c0@rclilly.com> Message-ID: "Robert Lilly" writes: > I know that many of the questions I will want to ask have probably already > been discussed. So I've downloaded the mbox archive so that I may search > through it before asking a question. However, I'm not sure what an efficient > means for searching it may be. Does anyone have any recommendations on how > to go about searching an mbox archive? I am working primarily under Windows > 2000, but I have Cygwin installed, so a *nix solution may be viable as well. The mbox files are plain text. This means that a simple grep could work. Some ideas: $ grep string mbox.file looks for string in the mbox.file $ grep string * looks for string in every file in the current directory $ grep string -A 5 -B 5 mbox.file looks for string and prints not only the line which contains it, but 5-5 lines before and after that line you can also use regexes ( and set the case-senseitiveness I guess), but as I'm too lazy to read grep's manpage on those rare occasions I would need it, I usually resort to a simple (and resource-wasting) pipeing: $ grep foo file.txt | grep bar | grep -v baz looks for lines in file.txt which contain 'foo' and 'bar' but not 'baz' As an alternative approach, you could try importing the mbox files into your favourite mail program and use it's search function. (Provided it has one.) Or, instead of all this, you can use everyone's favourite search engine: google! Searching the whole web has the advantage that you might find the answer you are looking for somewhere else. It also has the drawback that the signal-to-noise ratio is worse, so you might have to fine-tune your search-terms to get good results. If, however, you want to restrict searching to the python-tutor archives, you can try something like 'foo inurl:mail.python.org/pipermail/tutor/' as a searchterm (without the quotes) when looking for 'foo'. In this case you'll most likely have to click on the 'repeat the search with the omitted results included' link at the bottom of the results page. Looking for 'dict' with this method gives 488 hits, but only 2 are shown, google claiming that the rest is too similar to that 2. :) -- Abel Daniel From rclilly at cox.net Sun Sep 28 13:29:15 2003 From: rclilly at cox.net (Robert Lilly) Date: Sun Sep 28 13:31:43 2003 Subject: [Tutor] Re: Introduction and ? re: searching the list's archives References: <001801c385d8$39570420$797ba8c0@rclilly.com> Message-ID: <006b01c385e6$0a0a10f0$797ba8c0@rclilly.com> > > Does anyone have any recommendations on how > > to go about searching an mbox archive? I am working primarily under Windows > > 2000, but I have Cygwin installed, so a *nix solution may be viable as well. > The mbox files are plain text. This means that a simple grep could work. > > you can also use regexes ( and set the case-senseitiveness I guess), > > As an alternative approach, you could try importing the mbox files > into your favourite mail program and use it's search > function. (Provided it has one.) > > Or, instead of all this, you can use everyone's favourite search > engine: google! > > If, however, you want to restrict searching to the python-tutor > archives, you can try something like > 'foo inurl:mail.python.org/pipermail/tutor/' > as a searchterm (without the quotes) when looking for 'foo'. Thanks for the suggestions. I can see that, depending on what I'm looking for, there is no "best" way. I really appreciate the last suggest, because I didn't know what the URL for this list is for Googling purposes. Robert From rclilly at cox.net Sun Sep 28 13:29:15 2003 From: rclilly at cox.net (Robert Lilly) Date: Sun Sep 28 13:34:33 2003 Subject: [Tutor] Re: Introduction and ? re: searching the list's archives References: <001801c385d8$39570420$797ba8c0@rclilly.com> Message-ID: <007001c385e6$4ce627b0$797ba8c0@rclilly.com> > > Does anyone have any recommendations on how > > to go about searching an mbox archive? I am working primarily under Windows > > 2000, but I have Cygwin installed, so a *nix solution may be viable as well. > The mbox files are plain text. This means that a simple grep could work. > > you can also use regexes ( and set the case-senseitiveness I guess), > > As an alternative approach, you could try importing the mbox files > into your favourite mail program and use it's search > function. (Provided it has one.) > > Or, instead of all this, you can use everyone's favourite search > engine: google! > > If, however, you want to restrict searching to the python-tutor > archives, you can try something like > 'foo inurl:mail.python.org/pipermail/tutor/' > as a searchterm (without the quotes) when looking for 'foo'. Thanks for the suggestions. I can see that, depending on what I'm looking for, there is no "best" way. I really appreciate the last suggest, because I didn't know what the URL for this list is for Googling purposes. Robert From erikprice at mac.com Sun Sep 28 13:59:15 2003 From: erikprice at mac.com (Erik Price) Date: Sun Sep 28 13:37:34 2003 Subject: [Tutor] Introduction and ? re: searching the list's archives In-Reply-To: <001801c385d8$39570420$797ba8c0@rclilly.com> Message-ID: <7979CB51-F1DD-11D7-AFBF-00039351FE6A@mac.com> On Sunday, September 28, 2003, at 11:50 AM, Robert Lilly wrote: > I know that many of the questions I will want to ask have probably > already > been discussed. So I've downloaded the mbox archive so that I may > search > through it before asking a question. However, I'm not sure what an > efficient > means for searching it may be. Does anyone have any recommendations on > how > to go about searching an mbox archive? I am working primarily under > Windows > 2000, but I have Cygwin installed, so a *nix solution may be viable as > well. Here is a Jython-based solution: (Jython is a version of Python that is implemented in Java rather than C, and offers excellent integration with existing Java code.) Erik From rclilly at cox.net Sun Sep 28 13:54:00 2003 From: rclilly at cox.net (Robert Lilly) Date: Sun Sep 28 14:05:37 2003 Subject: [Tutor] Sorry for the double posting! Message-ID: <001f01c385e9$96458b00$797ba8c0@rclilly.com> My mail server was hanging up and it appeared to me that my original attempt to post didn't go through, so I clicked again. I see now that it did go through and that I double posted. Sorry! I will be more careful in the future. Robert From rclilly at cox.net Sun Sep 28 21:45:41 2003 From: rclilly at cox.net (Robert Lilly) Date: Sun Sep 28 21:45:47 2003 Subject: [Tutor] Introduction and ? re: searching the list's archives References: <7979CB51-F1DD-11D7-AFBF-00039351FE6A@mac.com> Message-ID: <001701c3862b$64294d90$797ba8c0@rclilly.com> > > On Sunday, September 28, 2003, at 11:50 AM, Robert Lilly wrote: > > > Does anyone have any recommendations on > > how > > to go about searching an mbox archive? I am working primarily under > > Windows > > 2000, but I have Cygwin installed, so a *nix solution may be viable as > > well. > > Here is a Jython-based solution: > > > > (Jython is a version of Python that is implemented in Java rather than > C, and offers excellent integration with existing Java code.) Thanks Erik, but since I'm just starting to learn Python, understanding the subtle, or not so subtle, differences between it and Jython is not something I'm ready to do yet. I have downloaded the scripts, however, and will get back to them when I have a little more experience under my belt. Thanks, Robert From rclilly at cox.net Sun Sep 28 13:29:15 2003 From: rclilly at cox.net (Robert Lilly) Date: Sun Sep 28 22:23:02 2003 Subject: [Tutor] Re: Introduction and ? re: searching the list's archives References: <001801c385d8$39570420$797ba8c0@rclilly.com> Message-ID: <006b01c385e6$0a0a10f0$797ba8c0@rclilly.com> > > Does anyone have any recommendations on how > > to go about searching an mbox archive? I am working primarily under Windows > > 2000, but I have Cygwin installed, so a *nix solution may be viable as well. > The mbox files are plain text. This means that a simple grep could work. > > you can also use regexes ( and set the case-senseitiveness I guess), > > As an alternative approach, you could try importing the mbox files > into your favourite mail program and use it's search > function. (Provided it has one.) > > Or, instead of all this, you can use everyone's favourite search > engine: google! > > If, however, you want to restrict searching to the python-tutor > archives, you can try something like > 'foo inurl:mail.python.org/pipermail/tutor/' > as a searchterm (without the quotes) when looking for 'foo'. Thanks for the suggestions. I can see that, depending on what I'm looking for, there is no "best" way. I really appreciate the last suggest, because I didn't know what the URL for this list is for Googling purposes. Robert From rclilly at cox.net Sun Sep 28 13:29:15 2003 From: rclilly at cox.net (Robert Lilly) Date: Sun Sep 28 23:09:01 2003 Subject: [Tutor] Re: Introduction and ? re: searching the list's archives References: <001801c385d8$39570420$797ba8c0@rclilly.com> Message-ID: <007001c385e6$4ce627b0$797ba8c0@rclilly.com> > > Does anyone have any recommendations on how > > to go about searching an mbox archive? I am working primarily under Windows > > 2000, but I have Cygwin installed, so a *nix solution may be viable as well. > The mbox files are plain text. This means that a simple grep could work. > > you can also use regexes ( and set the case-senseitiveness I guess), > > As an alternative approach, you could try importing the mbox files > into your favourite mail program and use it's search > function. (Provided it has one.) > > Or, instead of all this, you can use everyone's favourite search > engine: google! > > If, however, you want to restrict searching to the python-tutor > archives, you can try something like > 'foo inurl:mail.python.org/pipermail/tutor/' > as a searchterm (without the quotes) when looking for 'foo'. Thanks for the suggestions. I can see that, depending on what I'm looking for, there is no "best" way. I really appreciate the last suggest, because I didn't know what the URL for this list is for Googling purposes. Robert From dyoo at hkn.eecs.berkeley.edu Mon Sep 29 02:46:50 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 29 02:51:52 2003 Subject: [Tutor] handling tuples in a dictionary In-Reply-To: <081701c385dc$2b5584b0$7610ba3f@defaultcomp> Message-ID: > > I have a dictionary with items of the following form: > > > > dict = {('x',1): -100, ('y',2):-200, ('x',2):100, ('z',3):150, ('y', > 4):50} > > > > I have tuple as the keys. Hi Jimmy, Out of curiosity, would it be ok to change the data structure slightly? Right now, we're using tuples as our keys, and integers as our values. The problem might be simpler if we make our keys single letters, and the values be another dictionary that maps a number to another number. Something like: d = { 'x' : { 1: -100, 2, 100}, 'y' : { 2: -200, 4, 50}, 'z' : { 3: 150 } } is a possible restructuring of the data. I have no idea if it's a good one though --- it depends on what the structure is trying to represent. The structure above better mimics the output that you're requesting, so I'm wondering if your program can use this representation. The problem still feels a little abstract to me; can you tell us more about what the single letter, and those numbers stand for in: dict = {('x', 1): -100, ('y',2):-200, ('x',2):100, ('z',3):150, ('y', 4):50} What is this data? I just want to understand what we're trying to do, and why. *grin* Talk to you later! From rclilly at cox.net Sun Sep 28 13:54:00 2003 From: rclilly at cox.net (Robert Lilly) Date: Mon Sep 29 04:52:39 2003 Subject: [Tutor] Sorry for the double posting! Message-ID: <001f01c385e9$96458b00$797ba8c0@rclilly.com> My mail server was hanging up and it appeared to me that my original attempt to post didn't go through, so I clicked again. I see now that it did go through and that I double posted. Sorry! I will be more careful in the future. Robert From thomi at imail.net.nz Mon Sep 29 05:55:45 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Mon Sep 29 05:55:49 2003 Subject: [Tutor] small problem with lists/tuples Message-ID: <200309292155.45183.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi all, Here's a small problem I'm trying to nut out: I have a function which returns some data in different forms. for example: sometimes, it will return: ['data'] or: [['data']] or even: ([['data']]) what I'm trying to do, is "unpack" the duples, until i get to the actual data inside. Originally, i thought I could do it something like this: while 1: if (len(data) > 1): data = data[0] else: break however, it turns out that the actual data itself could be a single character long. I guess I could use the type() builtin function, but I thought aybe there was a cleaner/nicer way to do this? any ideas? Thanks, - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/eAGh2tSuYV7JfuERAlrgAJ4vyXpBfC9JB1Irg9oY0xsMRJJsdwCfdSzA lqCwJ8+Puvrp9ZI6DkLAsY8= =iZ9d -----END PGP SIGNATURE----- From guillermo.fernandez at epfl.ch Mon Sep 29 08:16:03 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez) Date: Mon Sep 29 08:19:12 2003 Subject: [Tutor] Database acces vs XML Message-ID: <3F782283.4080307@epfl.ch> Hi, I think my question is a little bit off topic... sorry. I'm working with a large file of network logs (a file of 25Mb or 150000 lines). What I do is parse the file, identify the fields that interest me most, put them on lists and then play with the lists to print out the information I want. This takes 5 minutes and eats a lot of RAM (150000 list elements is quite a lot :-) so I though about creating a database with all the fiels I want. Thinking about the database I'm studying the possibility of using a classical MySQL database or using an XML document as a database using XPath. The XML possibility would allow me to run my program in any computer with python installed and eliminates the need of database installation and management. My questions are: 1- Would I gain in speed and RAM with the use of a database? 2- If it's the case, would XML resist the search over 150000 entries? 3- How much would I loose in speed with an XML document compared to the MySQL database? This is, of course, implemented in python :-) I'm very new to databases and XMl. Thanks! Guille From godoy at metalab.unc.edu Mon Sep 29 10:34:24 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Mon Sep 29 10:35:00 2003 Subject: [Tutor] Database acces vs XML In-Reply-To: <3F782283.4080307@epfl.ch> (Guillermo Fernandez's message of "Mon, 29 Sep 2003 14:16:03 +0200") References: <3F782283.4080307@epfl.ch> Message-ID: Guillermo Fernandez writes: > 1- Would I gain in speed and RAM with the use of a database? > 2- If it's the case, would XML resist the search over 150000 entries? > 3- How much would I loose in speed with an XML document compared to > the MySQL database? Depending on how you're going to traverser the XML tree, I think you'd end using more RAM than you're using now. The RDBMS solution (you can use sqlite for that, there's a pysqlite binding --- it's a file based database, very fast and requires no maintenance work) seems better to me (but we already use databases for other projects here)... It is also faster and can simplify a lot of the work if it's done on the server instead of on the client (again, we use PostgreSQL and I don't know if MySQL support stored procedures and triggers). See you, -- Godoy. From glingl at aon.at Mon Sep 29 11:46:24 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Sep 29 11:48:12 2003 Subject: [Tutor] small problem with lists/tuples In-Reply-To: <200309292155.45183.thomi@imail.net.nz> References: <200309292155.45183.thomi@imail.net.nz> Message-ID: <3F7853D0.8060501@aon.at> Thomi Richards schrieb: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > > >Hi all, > >Here's a small problem I'm trying to nut out: > Hello Thomi, there are a few problems in your problem description: > >I have a function which returns some data in different forms. for example: > >sometimes, it will return: > >['data'] > >or: > >[['data']] > >or even: > >([['data']]) > do you mean a tuple with 1 element? Here: ([['data']],) (Otherwise [['data']] and ([['data']]) are the same thing - the latter one beeing an expression, which is simly a list (which contains a list)) > >what I'm trying to do, is "unpack" the duples, until i get to the actual data >inside. Originally, i thought I could do it something like this: > >while 1: > if (len(data) > 1): > data = data[0] > else: > break > >however, it turns out that the actual data itself could be a single character >long. > If this is the case or not, with your data your loop is always terminated during the first execution of the loop body and doesn't change data at all. Or did you mean len(data) == 1 ? >I guess I could use the type() builtin function, but I thought aybe >there was a cleaner/nicer way to do this? any ideas? > > Finally you have to decide, if you mind that the content of data will change. Here an example solution (nothing special): a tiny function, which leaves data unchanged and returns 'data' ... hmm (perhaps I should use different names...): >>> data1 = ["data"] >>> data2 = [["data"]] >>> data3 = ([["data"]],) >>> def getdata(data): while not isinstance(data,str): data = data[0] return data >>> print data3, getdata(data3) ([['data']],) data >>> print data1, getdata(data1) ['data'] data >>> print data2, getdata(data2) [['data']] data >>> print data3, getdata(data3) ([['data']],) data >>> data = ([['d']],) >>> print data, getdata(data) ([['d']],) d >>> Best wishes, Gregor >Thanks, > >- -- >Thomi Richards, >http://once.sourceforge.net/ > > >-----BEGIN PGP SIGNATURE----- >Version: GnuPG v1.2.3 (GNU/Linux) > >iD8DBQE/eAGh2tSuYV7JfuERAlrgAJ4vyXpBfC9JB1Irg9oY0xsMRJJsdwCfdSzA >lqCwJ8+Puvrp9ZI6DkLAsY8= >=iZ9d >-----END PGP SIGNATURE----- > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From glingl at aon.at Mon Sep 29 12:08:28 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Sep 29 12:10:18 2003 Subject: [Tutor] small problem with lists/tuples In-Reply-To: <200309292155.45183.thomi@imail.net.nz> References: <200309292155.45183.thomi@imail.net.nz> Message-ID: <3F7858FC.9030200@aon.at> Thomi Richards schrieb: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > > >Hi all, > >... > >['data'] > >or: > >[['data']] > >or even: > >([['data']]) > >what I'm trying to do, is "unpack" the duples, until i get to the actual data >inside. Originally, i thought I could do it something like this: > > > Sometimes you will encounter the problem to get to the "actual data", when they are packed in some more complicated ("nested") lists or tuples, e.g.: ([1],[[2]],[[3,[[[4]]],[5]]]) ==> [1,2,3,4,5] This can be accomplished by "flattening" these nested lists: >>> def flatten(seq): flat = [] for item in seq: # simple member if not (isinstance(item,list) or isinstance(item,tuple)): flat.append(item) else: # sequence, so flatten this one too flat.extend(flatten(item)) return flat # or if you want: return tuple(flat) >>> flatten((1,(2,3))) [1, 2, 3] >>> flatten(([1],[[2]],[[3,[[[4]]],[5]]])) [1, 2, 3, 4, 5] >>> flatten([0,[1],[[2]],[[3,[([4],)],[5]]],("wow",)]) [0, 1, 2, 3, 4, 5, 'wow'] With flatten you can easily define a getdata like you need it: >>> def getdata(data): return flatten(data)[0] >>> print data1, getdata(data1) ['data'] data >>> print data2, getdata(data2) [['data']] data >>> print data3, getdata(data3) ([['data']],) data >>> print data, getdata(data) ([['d']],) d >>> Regards, Gregor From pan at uchicago.edu Mon Sep 29 13:39:08 2003 From: pan at uchicago.edu (pan@uchicago.edu) Date: Mon Sep 29 13:43:57 2003 Subject: [Tutor] Introduction and ? re: searching the list's archives Message-ID: <1064857148.3f786e3c1baf2@webmail.uchicago.edu> > On Sunday, September 28, 2003, at 11:50 AM, Robert Lilly wrote: > > > Does anyone have any recommendations on > > how > > to go about searching an mbox archive? I am working primarily under > > Windows > > 2000, but I have Cygwin installed, so a *nix solution may be viable as > > well. > > Here is a Jython-based solution: > > > > (Jython is a version of Python that is implemented in Java rather than > C, and offers excellent integration with existing Java code.) There's a searchable python tutor site already well-built: http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor pan From rclilly at cox.net Mon Sep 29 13:46:44 2003 From: rclilly at cox.net (Robert Lilly) Date: Mon Sep 29 13:48:39 2003 Subject: [Tutor] Introduction and ? re: searching the list's archives References: <1064857148.3f786e3c1baf2@webmail.uchicago.edu> Message-ID: <00d101c386b1$a606c220$797ba8c0@rclilly.com> > > There's a searchable python tutor site already well-built: > > http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor > > pan Perfect! Thanks! Robert From jeff at ccvcorp.com Mon Sep 29 13:56:36 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon Sep 29 13:54:29 2003 Subject: [Tutor] small problem with lists/tuples References: <200309292155.45183.thomi@imail.net.nz> Message-ID: <3F787254.2030105@ccvcorp.com> Thomi Richards wrote: > I have a function which returns some data in different forms. for example: > sometimes, it will return: > > ['data'] > > or: > > [['data']] > > or even: > > ([['data']]) > > what I'm trying to do, is "unpack" the duples, until i get to the actual data > inside. Any chance you can change what the original function returns? It seems to me that a function that may return single-item nested lists is confusing, and my inclination would be to make the function return something sensible, instead of trying to make sense of the mess that it currently returns. I'm not sure *why* this function might have variable levels of nesting, especially since it seems that you expect all of them to have only a single item, but I'd bet that it'd be easier to attack this problem by not building the extra levels than by stripping them off later. Of course, it may be that the source of this function is outside of your control, in which case you have little choice. But it seems to me that the earlier you eliminate the confusing extra levels, the better. If you *do* have access to the source code for the function, post that here and we'll see what we can do to simplify it and normalize its output. Jeff Shannon Technician/Programmer Credit International From erikprice at mac.com Mon Sep 29 14:46:24 2003 From: erikprice at mac.com (Erik Price) Date: Mon Sep 29 14:46:31 2003 Subject: [Tutor] Database acces vs XML Message-ID: <4331107.1064861184411.JavaMail.erikprice@mac.com> On Monday, September 29, 2003, at 08:16AM, Guillermo Fernandez wrote: >I'm working with a large file of network logs (a file of 25Mb or 150000 >lines). What I do is parse the file, identify the fields that interest >me most, put them on lists and then play with the lists to print out the >information I want. > >This takes 5 minutes and eats a lot of RAM (150000 list elements is >quite a lot :-) so I though about creating a database with all the fiels >I want. Thinking about the database I'm studying the possibility of >using a classical MySQL database or using an XML document as a database >using XPath. The XML possibility would allow me to run my program in any >computer with python installed and eliminates the need of database >installation and management. > >My questions are: >1- Would I gain in speed and RAM with the use of a database? Yes, but if you are using a relational database server such as PostgreSQL or MySQL, then you have the overhead of the database itself, which may occupy additional RAM etc. Plus there is usually a certain level of installation issues to work through, unless you have a database already installed and you will simply be creating a new DB instance. >2- If it's the case, would XML resist the search over 150000 entries? XML parsing isn't super hard, but it's not easy unless you're working with some library or other that abstracts away all of the details into programmer-friendly API (for instance, the Jakarta Digester libraries, but that's Java and not Python). For one thing, if you build an in-memory tree of the logs using a DOM-based or other in-memory -based model, you will probably incur a similar or perhaps even greater overhead. However, if you implement a SAX listener and simply parse through the file and perform callbacks as you do so, then you will use very little RAM. But this would really only be useful if your logs were already in an XML format, or if you were converting the logs from their original format to XML. In all, the XML-based solution doesn't require a database, but can be more work to implement in the end depending on how complex your needs are. And a DOM-based solution will not spare you much RAM since it uses the same model as your current approach. >3- How much would I loose in speed with an XML document compared to the >MySQL database? You can't get numbers for this easily without your own benchmarking. It's too specific to your problem/hardware. Perhaps the best approach would be to write some kind of parser (not necessarily XML-based) to read through your log files in the same fashion as a SAX parser, performing callbacks as it goes, without actually reading everything into memory. If each entry is on a separate line, you can use the xreadlines method of the file object to do this. Erik From pan at uchicago.edu Mon Sep 29 16:05:47 2003 From: pan at uchicago.edu (pan@uchicago.edu) Date: Mon Sep 29 16:05:54 2003 Subject: [Tutor] Re: small problem with lists/tuples Message-ID: <1064865947.3f78909b2213a@webmail.uchicago.edu> Thomi Richards wrote: > I have a function which returns some data in different forms. for example: > sometimes, it will return: > > ['data'] > > or: > > [['data']] > > or even: > > ([['data']]) > > what I'm trying to do, is "unpack" the duples, until i get to the actual data > inside. The following simple trick might work: >>> a = ([['data']]) >>> a [['data']] >>> def unpack(target): .. tmp = str(target) .. tmp = tmp.replace('[','').replace(']','') .. tmp = tmp.replace('(','').replace(')','') .. return eval(tmp) .. >>> unpack(a) 'data' You can make the function a one-liner if you want: >>> def unpack(target): .. return eval(str(target).replace('[','').replace(']','').replace ('(','').replace(')','')) >>> unpack(a) 'data' pan From dyoo at hkn.eecs.berkeley.edu Mon Sep 29 16:35:59 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 29 16:36:11 2003 Subject: [Tutor] Re: small problem with lists/tuples [evil test cases] In-Reply-To: <1064865947.3f78909b2213a@webmail.uchicago.edu> Message-ID: > The following simple trick might work: > > >>> a = ([['data']]) > >>> a > [['data']] > > >>> def unpack(target): > .. tmp = str(target) > .. tmp = tmp.replace('[','').replace(']','') > .. tmp = tmp.replace('(','').replace(')','') > .. return eval(tmp) > .. Hi Pan, Unfortunately, the implementation above is a little unsafe. It's not just because of the call to 'eval()', but because it is too sensitive to the contents of the target. For example, the following input: s = [['this: [', 'is a]'], 'test'] will break unpack(): it doesn't distinguish between the '[' that is part of a string vs the '[' that represents the real structure of the object. Is this example evil? Yup. *grin* But it's the sort of thing that unpack() should be able to handle. I think that a string-handling approach to this is more trouble than it's worth, and it might just be better to bite down and go with the approach that deals with the list structure explicitely. Good luck to you! From jeff at ccvcorp.com Mon Sep 29 16:42:26 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon Sep 29 16:40:10 2003 Subject: [Tutor] Re: small problem with lists/tuples References: <1064865947.3f78909b2213a@webmail.uchicago.edu> Message-ID: <3F789932.8020000@ccvcorp.com> pan@uchicago.edu wrote: > The following simple trick might work: >>>>def unpack(target): >>> > .. tmp = str(target) > .. tmp = tmp.replace('[','').replace(']','') > .. tmp = tmp.replace('(','').replace(')','') > .. return eval(tmp) > .. I strongly dislike the idea of using eval() in this case. This is, to my mind, approximately similar to peeling potatoes with a battleaxe. (Or possibly to killing roaches with mustard gas.) There are very few situations where eval() is the best answer to the problem, and many situations where it will cause a lot of grief. eval() should almost always be (at least close to) the last option you look at, not the first. In addition, this function does not properly respond to the full range of possible input. First, a single-element tuple will have not only parentheses, but also a comma (i.e., '(item,)'). You could add another replace() to eliminate commas, true... but what happens if the inner data item contains commas, or brackets, or parens? You may end up mangling the item that you're actually interested in. Jeff Shannon Technician/Programmer Credit International From pan at uchicago.edu Mon Sep 29 16:54:43 2003 From: pan at uchicago.edu (pan@uchicago.edu) Date: Mon Sep 29 16:54:48 2003 Subject: [Tutor] Re: small problem with lists/tuples [evil test cases] In-Reply-To: References: Message-ID: <1064868883.3f789c13ce25f@webmail.uchicago.edu> > > The following simple trick might work: > > > > >>> a = ([['data']]) > > >>> a > > [['data']] > > > > >>> def unpack(target): > > .. tmp = str(target) > > .. tmp = tmp.replace('[','').replace(']','') > > .. tmp = tmp.replace('(','').replace(')','') > > .. return eval(tmp) > > .. > > Hi Pan, > > Unfortunately, the implementation above is a little unsafe. Ya, you are right. My example only works when you are sure what is in the data. That's why I said **might** work. :) pan From dyoo at hkn.eecs.berkeley.edu Mon Sep 29 17:21:23 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 29 17:21:33 2003 Subject: [Tutor] Introduction and ? re: searching the list's archives In-Reply-To: <001701c3862b$64294d90$797ba8c0@rclilly.com> Message-ID: On Sun, 28 Sep 2003, Robert Lilly wrote: > > > > On Sunday, September 28, 2003, at 11:50 AM, Robert Lilly wrote: > > > > > Does anyone have any recommendations on > > > how > > > to go about searching an mbox archive? I am working primarily under > > > Windows > > > 2000, but I have Cygwin installed, so a *nix solution may be viable as > > > well. > > > > Here is a Jython-based solution: > > > > > > > > (Jython is a version of Python that is implemented in Java rather than > > C, and offers excellent integration with existing Java code.) > > Thanks Erik, but since I'm just starting to learn Python, understanding > the subtle, or not so subtle, differences between it and Jython is not > something I'm ready to do yet. I have downloaded the scripts, however, > and will get back to them when I have a little more experience under my > belt. Hi Robert, Yes, I'll have to clean up that code and package it nicely sometime. I'm so embarassed that I can't seem to finish what I start... *sigh* (It turns out that someone else has written about using Jython to drive Lucene: http://webservices.xml.com/pub/a/ws/2003/05/13/email.html ... wait! Oh, nice! According to a comment on the bottom of that page, someone has written a Python port of Lucene called 'Lupy'! http://www.divmod.org/Lupy/index.html ) Anyway, talk to you later! From hec.villafuerte at telgua.com.gt Mon Sep 29 20:42:52 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Mon Sep 29 18:42:50 2003 Subject: [Tutor] List's name in a string Message-ID: <3F78D18C.4090900@telgua.com.gt> Hi! is there a way to get a list's (or any variable) name in a string? For example: >>> list1 = [1, 2, 3] I would like to do something like this: >>> var = list1.name() So that var contains 'list1'. Thanks in advance, Hector From aschmidt at fredericksburg.com Mon Sep 29 18:51:21 2003 From: aschmidt at fredericksburg.com (Allen) Date: Mon Sep 29 18:51:53 2003 Subject: [Tutor] Pouring a list into a dictionary In-Reply-To: <16500F09-DFCA-11D7-A528-00039303967A@umich.edu> References: <16500F09-DFCA-11D7-A528-00039303967A@umich.edu> Message-ID: <3F78B769.3060601@fredericksburg.com> The answer to my last inquiry worked out to be this: (thanks for the suggestions) I have two lists (same length) and needed field ONE from list A (headings) be the key to the value of field ONE of list B (foundData). Iterate through these to create my dictionary. dataDict={} for k, v in map(None, headings, foundData): dataDict[k]= v Next question: How to use %s formatting (I think) to access those key/value pairs in an sql insert statement. Here is what I need: for k, v in map(None, headings, foundData): dataDic[k]= v sql = "replace into tablename %s values(%s)" crsr.execute(sql, (dataDict.keys(),dataDict.values())) The order does not really matter when the stuff is taken from the dict but the key/value order obviously makes a difference when presented. Not sure if I spelled it out right...but thought I would try. Thanks Allen From project5 at redrival.net Mon Sep 29 19:21:12 2003 From: project5 at redrival.net (Andrei) Date: Mon Sep 29 19:23:26 2003 Subject: [Tutor] Re: List's name in a string In-Reply-To: <3F78D18C.4090900@telgua.com.gt> References: <3F78D18C.4090900@telgua.com.gt> Message-ID: H?ctor Villafuerte D. wrote: Hi, > is there a way to get a list's (or any variable) name in a string? > > For example: > >>> list1 = [1, 2, 3] > I would like to do something like this: > >>> var = list1.name() > So that var contains 'list1'. Well, there's something odd about Python here: >>> a = b = [5,4] >>> a.append(4) >>> a, b ([5, 4, 4], [5, 4, 4]) So, which name would you like to get when you look up [5,4]? a or b or both? The closest thing I can think of is using the locals() dictionary, like this: >>> for key in loc: ... if loc[key] == [5,4,4]: ... print key, ... a b You can do some tweaking, like only get the first match, or don't get duplicates if they have the same id(). -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Mon Sep 29 19:38:18 2003 From: project5 at redrival.net (Andrei) Date: Mon Sep 29 19:40:23 2003 Subject: [Tutor] Re: List's name in a string In-Reply-To: References: <3F78D18C.4090900@telgua.com.gt> Message-ID: Forgot to paste important part of the session: >>> loc = locals() # before aceessing loc in the loop Looking at my code, I just noticed I'm looping over a dictionary. I didn't even know that was possible. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Mon Sep 29 19:40:17 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 29 19:40:49 2003 Subject: [Tutor] Pouring a list into a dictionary In-Reply-To: <3F78B769.3060601@fredericksburg.com> Message-ID: On Mon, 29 Sep 2003, Allen wrote: > The answer to my last inquiry worked out to be this: (thanks for the > suggestions) > > I have two lists (same length) and needed field ONE from list A > (headings) be the key to the value of field ONE of list B (foundData). > Iterate through these to create my dictionary. > > dataDict={} > for k, v in map(None, headings, foundData): > dataDict[k]= v Hi Allen, Ah! As of Python 2.3, there's another concise way of saying this: ### dataDict={} for k, v in map(None, headings, foundData): dataDict[k]= v ### Using some of 2.3's new features, we can now say it this way: ### dataDict = dict(zip(headers, foundData)) ### This takes advantage of two "builtins" that have been improved: 'dict()' and 'zip()'. http://www.python.org/doc/lib/built-in-funcs.html#l2h-22 http://www.python.org/doc/lib/built-in-funcs.html#l2h-78 > Next question: How to use %s formatting (I think) to access those > key/value pairs in an sql insert statement. Here is what I need: > > for k, v in map(None, headings, foundData): > dataDic[k]= v > sql = "replace into tablename %s values(%s)" > crsr.execute(sql, (dataDict.keys(),dataDict.values())) One way to do this is to move the crsr.execute() within the loop body itself: ### sql = "replace into tablename %s values (%s)" for k, v in map(None, headings, foundData): ## we can use zip() crsr.execute(sql, (k, v)) ### According to the DB-API 2.0 spec, http://www.python.org/peps/pep-0249.html you can also call the executemany() method to do this operation on your whole list of key/value pairs. So you should be able to say: ### sql = "replace into tablename %s values (%s)" crsr.executemany(zip(headings, foundData)) ### Just to clear things up: In the code above, I subsituted map(None, ...) with zip(), since zip() is a nice way to pairwise glue two sequences together. > The order does not really matter when the stuff is taken from the dict > but the key/value order obviously makes a difference when presented. Ah, then that's something you don't have to worry about! Python does guarantee that if we call keys() and values(), that the order should correspond: http://www.python.org/doc/lib/typesmapping.html Note 3 is the one that guarantees this for us. Darn obscure, but possibly useful to know. *grin* Good luck to you! From thomi at imail.net.nz Mon Sep 29 19:59:29 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Mon Sep 29 20:16:52 2003 Subject: [Tutor] small problem with lists/tuples In-Reply-To: <3F787254.2030105@ccvcorp.com> References: <200309292155.45183.thomi@imail.net.nz> <3F787254.2030105@ccvcorp.com> Message-ID: <200309301159.29293.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, > > Any chance you can change what the original function returns? It > seems to me that a function that may return single-item nested lists > is confusing, and my inclination would be to make the function return > something sensible, instead of trying to make sense of the mess that > it currently returns. I'm not sure *why* this function might have > variable levels of nesting, especially since it seems that you expect > all of them to have only a single item, but I'd bet that it'd be > easier to attack this problem by not building the extra levels than by > stripping them off later. > unfortunately no. The original function actually works very well for other parts of the program, and I am using it to do something which it was not originally designed to do ;( However, apart from the various nested list evels, it works just fine ;) Gregor's solutions is awesome, I think I'll just stick to that... thanks! - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/eMdh2tSuYV7JfuERAm6PAJ9CiYWGjiBONNrYtazzcsFXNIsYMACbBB0F Hmu6imjGoo/CRVV9u6sO0Yg= =hEmJ -----END PGP SIGNATURE----- From jeff at ccvcorp.com Mon Sep 29 20:31:52 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon Sep 29 20:29:19 2003 Subject: [Tutor] List's name in a string References: <3F78D18C.4090900@telgua.com.gt> Message-ID: <3F78CEF8.4020804@ccvcorp.com> H?ctor Villafuerte D. wrote: > Hi! > is there a way to get a list's (or any variable) name in a string? > > For example: > >>> list1 = [1, 2, 3] > I would like to do something like this: > >>> var = list1.name() > So that var contains 'list1'. You can sortof force it by going through locals() and globals(), but a better approach would probably be to look again at *why* you want this. Most of the time, if you need to refer to some variable name programmatically like this, what you're really looking for is a list or a dictionary. In other words, you typically want to refer to variables by a variable name so that you can select one object from a set of possible objects based on some runtime parameter. That's exactly the niche that dictionaries fit. For example, >>> data = {} >>> data['list1'] = [1, 2, 3] >>> data['list2'] = [4, 5, 6] >>> data {'list1': [1, 2, 3], 'list2': [4, 5, 6]} >>> key = 'list1' >>> data[key] [1, 2, 3] >>> Maybe if you explain a bit more about your intent, we can explore an easier way to accomplish your goal than mucking about in the interpreter's innards. Jeff Shannon Technician/Programmer Credit International From aschmidt at fredericksburg.com Mon Sep 29 20:32:11 2003 From: aschmidt at fredericksburg.com (Allen) Date: Mon Sep 29 20:32:47 2003 Subject: [Tutor] Pouring a list into a dictionary then into database In-Reply-To: References: Message-ID: <3F78CF0B.6050909@fredericksburg.com> Hi Danny! Thanks for the quick response! > Ah! As of Python 2.3, there's another concise way of saying this: ...but how about for 2.1.3? This resides on a Zope box and so using the Python that installed with it. > One way to do this is to move the crsr.execute() within the loop body > itself: > > ### > sql = "replace into tablename %s values (%s)" > for k, v in map(None, headings, foundData): ## we can use zip() > crsr.execute(sql, (k, v)) > ### But for the way I am using REPLACE, I need to do the whole line at one time. > you can also call the executemany() method to do this operation on your > whole list of key/value pairs. So you should be able to say: > > ### > sql = "replace into tablename %s values (%s)" > crsr.executemany(zip(headings, foundData)) > ### So where does the sql go?? Still confused. I will keep poking around. Thanks again! > Good luck to you! Thanks! I think I will need it! From dyoo at hkn.eecs.berkeley.edu Mon Sep 29 20:57:42 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 29 20:58:12 2003 Subject: [Tutor] Pouring a list into a dictionary then into database In-Reply-To: <3F78CF0B.6050909@fredericksburg.com> Message-ID: On Mon, 29 Sep 2003, Allen wrote: > > you can also call the executemany() method to do this operation on your > > whole list of key/value pairs. So you should be able to say: > > > > ### > > sql = "replace into tablename %s values (%s)" > > crsr.executemany(zip(headings, foundData)) > > ### > > So where does the sql go?? Hi Allen, ... Doh. Good question. My bad. I should have written: ### sql = "replace into tablename %s values (%s)" crsr.executemany(sql, zip(headings, foundData)) ### instead. My apologies! I do have a good defense though: ignorance! *grin* The reason I couldn't test this code is because I'm not familiar at all with REPLACE and wasn't able to run it on a test database. I'm only familiar with INSERT, UPDATE, DELETE, and SELECT. Is REPLACE part of the SQL standard? Talk to you later! From aschmidt at fredericksburg.com Mon Sep 29 21:12:04 2003 From: aschmidt at fredericksburg.com (Allen) Date: Mon Sep 29 21:12:33 2003 Subject: [Tutor] Pouring a list into a dictionary then into database In-Reply-To: References: Message-ID: <3F78D864.8030600@fredericksburg.com> REPLACE has the same syntax as INSERT. But, if it finds a duplicate based on a unique or primary key, it first deletes the row and then inserts the new row. Works great. No duplicate? Then it just does a normal insert. I jumped the gun on my response because it was obvious where it would go...duh on my part. But...what about for 'slightly' older versions... 2.1.3 to be specific? Thanks Allen Danny Yoo wrote: > > On Mon, 29 Sep 2003, Allen wrote: > > >>>you can also call the executemany() method to do this operation on your >>>whole list of key/value pairs. So you should be able to say: >>> >>>### >>>sql = "replace into tablename %s values (%s)" >>>crsr.executemany(zip(headings, foundData)) >>>### >> >>So where does the sql go?? > > > Hi Allen, > > > ... Doh. Good question. My bad. > > > I should have written: > > ### > sql = "replace into tablename %s values (%s)" > crsr.executemany(sql, zip(headings, foundData)) > ### > > instead. My apologies! > > > I do have a good defense though: ignorance! *grin* The reason I couldn't > test this code is because I'm not familiar at all with REPLACE and wasn't > able to run it on a test database. I'm only familiar with INSERT, UPDATE, > DELETE, and SELECT. Is REPLACE part of the SQL standard? > > > Talk to you later! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From bgailer at alum.rpi.edu Mon Sep 29 21:13:39 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Sep 29 21:15:56 2003 Subject: [Tutor] Pouring a list into a dictionary In-Reply-To: References: <3F78B769.3060601@fredericksburg.com> Message-ID: <6.0.0.22.0.20030929191206.0335b070@66.28.54.253> At 05:40 PM 9/29/2003, Danny Yoo wrote: >On Mon, 29 Sep 2003, Allen wrote: > > > The answer to my last inquiry worked out to be this: (thanks for the > > suggestions) > > > > I have two lists (same length) and needed field ONE from list A > > (headings) be the key to the value of field ONE of list B (foundData). > > Iterate through these to create my dictionary. > > > > dataDict={} > > for k, v in map(None, headings, foundData): > > dataDict[k]= v > >Hi Allen, > > >Ah! As of Python 2.3, there's another concise way of saying this: > >### >dataDict={} >for k, v in map(None, headings, foundData): > dataDict[k]= v >### > > > >Using some of 2.3's new features, we can now say it this way: > >### >dataDict = dict(zip(headers, foundData)) >### That even works in 2.2.3. Is this a new concept of backward compatibility?- [snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.521 / Virus Database: 319 - Release Date: 9/23/2003 From dyoo at hkn.eecs.berkeley.edu Tue Sep 30 00:04:54 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 30 00:05:25 2003 Subject: [Tutor] Pouring a list into a dictionary then into database In-Reply-To: <3F78D864.8030600@fredericksburg.com> Message-ID: On Mon, 29 Sep 2003, Allen wrote: > But...what about for 'slightly' older versions... 2.1.3 to be specific? Oh! My apologies: I forgot to reply about that part of your question. According to the Library Reference, http://www.python.org/doc/lib/built-in-funcs.html#l2h-78 the good news is that zip() should work in Python 2.0. Unfortunately, though, the nifty key-value initialization stuff with dict() is a bit more recent, so I don't think it will work in 2.1.3. Let's check the Python 2.1 library docs: http://www.python.org/doc/2.1/lib/lib.html ... Nuts. I can't find dict() in the index, and the docs for it now say that it was introduced in 2.2. So I guess we can use zip(), but not dict() for that Zope installation you're using. Anyway, hope this helps! From dyoo at hkn.eecs.berkeley.edu Tue Sep 30 00:11:58 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 30 00:12:28 2003 Subject: [Tutor] Pouring a list into a dictionary In-Reply-To: <6.0.0.22.0.20030929191206.0335b070@66.28.54.253> Message-ID: > >Using some of 2.3's new features, we can now say it this way: > > > >### > >dataDict = dict(zip(headers, foundData)) > >### > > That even works in 2.2.3. Is this a new concept of backward compatibility?- > [snip] Hi Bob, Very true! I was confused when I read the docs at: http://www.python.org/doc/lib/built-in-funcs.html For some wacky reason, I thought that: dict(zip(('one', 'two'), (2, 3))) was introduced in 2.3, but that's not right --- we had this in 2.2 too. Python 2.3 did introduce an improvement to dict(): we can now initialize it by using keyword arguments: ### >>> dict(two=2, three=3) {'three': 3, 'two': 2} ### Thanks for the correction! From idiot1 at netzero.net Tue Sep 30 00:19:46 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Tue Sep 30 00:18:55 2003 Subject: [Tutor] cgiserver update Message-ID: <3F790462.1060300@netzero.net> Having the webpages in the same folder as the python executables leads to vulnerabilities, and to confusion. It is better to have the server use a different folder as 'webroot' so that web pages are served there, and nothing else but what SHOULD be accessable on your pc's webserver- so if used on a LAN, your server/site can be accessed, but nothing further up the tree is accessable, like any executables you might have lying around in 'C:\Python 22', as one can feed commands to the interpeter which it would gleefully execute, to your sorrow. Therefore, with advice from STeve, I modified the cgi-server to serve from a different web 'root' directory and directories under it. Here is the new and improved server. #!C:\Python22\pythonw.exe # COPYRIGHT 2003 Steve Holden, free for personal use. # Please visit http://www.holdenweb.com/ to learn more! # import CGIHTTPServer, BaseHTTPServer, os os.chdir ('.\web') httpd=BaseHTTPServer.HTTPServer(('',8080), CGIHTTPServer.CGIHTTPRequestHandler) httpd.serve_forever() # It was that easy. All my webpages on the server are now in 'C:\Python22\web', and under it in cgi-bin are the scripts, and under that the wiki pages. under ~\web is ~\images, where images live. It's a server. -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From roypython at hotmail.com Tue Sep 30 01:16:28 2003 From: roypython at hotmail.com (roy ollis) Date: Tue Sep 30 01:16:32 2003 Subject: [Tutor] mailing list archive reader Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030930/4c413fa7/attachment.html From jakieabraham at yahoo.com Tue Sep 30 02:42:16 2003 From: jakieabraham at yahoo.com (Jacob Abraham) Date: Tue Sep 30 02:42:22 2003 Subject: [Tutor] Regular Expression Help Message-ID: <20030930064216.48765.qmail@web11207.mail.yahoo.com> Dear Tutor, I am having some trouble with my regular expressions. Here is my problem. 1. Find the word 'Required_Text:' 2. Find All characters till a.A new line character or b.The word 'Required_' These were my failed attempts import re reg=re.search a='''Some Text Required_Text: Some other text and (23.32) numbers Required_Field: Some more text''' b=reg('Required_Text:.*(Required_)?',a) b.group() 'Required_Text: Some other text and (23.32) numbers Required_Field: Some more text' b=reg('Required_Text:.*?(Required_)?',a) 'Required_Field:' Please help me capture 'Required_Text: Some other text and (23.32) numbers Required_' __________________________________ Do you Yahoo!? The New Yahoo! Shopping - with improved product search http://shopping.yahoo.com From guillermo.fernandez at epfl.ch Mon Sep 29 19:58:52 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez) Date: Tue Sep 30 03:47:01 2003 Subject: [Tutor] Database acces vs XML Message-ID: <3F78C73C.8030209@epfl.ch> Hi, Thanks for the answers. Everything seems to indicate that XML does not answer my problems, as I was thinking in using DOM-based model. > Perhaps the best approach would be to write some kind of parser (not > necessarily XML-based) to read through your log files in the same > fashion as a SAX parser, performing callbacks as it goes, without > actually reading everything into memory. If each entry is on a > separate line, you can use the xreadlines method of the file object to > do this. I already programed a parser that reads the file line by line with xreadlines, but the dataprocess I need implies some kind of data storage, either in a database or in memory as I do it now (and one of the problems of my disgrace ;-) > The RDBMS solution (you can use sqlite for that, there's a pysqlite > binding --- it's a file based database, very fast and requires no > maintenance work) seems better to me (but we already use databases for > other projects here)... It is also faster and can simplify a lot of > the work if it's done on the server instead of on the client As I'm working only with the log files, I've no server-client problems to take into accoount :-) I had a look to the pysqlite module, and seems to better fit my needs.In the docs they say sqlite "fully comply with the Python Database API v.2.0 specification" and give no further details about pysqlite use. I had a look into the python library reference and there seems to be no "standard" database module. All those different database modules are quite confusing! Is there any tutorial for using databases with the Database API specification? Or describing this specification? Thanks, Guille From goki75 at vsnl.net Tue Sep 30 05:44:06 2003 From: goki75 at vsnl.net (G Kiran) Date: Tue Sep 30 05:52:32 2003 Subject: [Tutor] jabber Message-ID: <001801c38738$4e339eb0$b74c41db@VULCAN> i was trying to connect to a jabber server as a client using jabber library but my id doesnot come on my other cient(miranda IM) running with a different user id whats the problem??? import jabber import re server = "jabber.org" username = "salil_one" password = "rayhelix" class myclnt(jabber.Client): def __init__(self, host, username, password, port=5222, debug=0, log=0): jabber.Client.__init__(self, host, port, debug, log) self.connect() print "Connected" self.login() self.sendInitPresence() self.requestRoster() def login(self): if self.auth(username, password, 'Test'): print "Logged in" else: raise RuntimeError("Failed to login") while (1): try: clnt = myclient(server, username, password) except Exception, e: print "There was an problem trying again" --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.521 / Virus Database: 319 - Release Date: 9/23/2003 From vadim at gym-nippes.k.nw.schule.de Tue Sep 30 07:13:30 2003 From: vadim at gym-nippes.k.nw.schule.de (Vadim Usenko) Date: Tue Sep 30 07:14:12 2003 Subject: [Tutor] Project Parallelport In-Reply-To: <20030930111030.GA6822@liposerv.bluecher>; from vadim@gym-nippes.k.nw.schule.de on Di, Sep 30, 2003 at 13:10:30 +0200 References: <20030923110358.GA17002@liposerv.bluecher> <20030930111030.GA6822@liposerv.bluecher> Message-ID: <20030930111330.GC6822@liposerv.bluecher> Hi all, I am searching for a module in python to connect a programm directly with the parallel port to build a mini-crossway with some traffic lights. Do you have some information for me, please? Thanks, Vadim From project5 at redrival.net Tue Sep 30 07:56:29 2003 From: project5 at redrival.net (Andrei) Date: Tue Sep 30 07:58:32 2003 Subject: [Tutor] Re: Regular Expression Help In-Reply-To: <20030930064216.48765.qmail@web11207.mail.yahoo.com> References: <20030930064216.48765.qmail@web11207.mail.yahoo.com> Message-ID: Jacob Abraham wrote: > Dear Tutor, Hi, > I am having some trouble with my regular > expressions. > Here is my problem. > 1. Find the word 'Required_Text:' > 2. Find All characters till > a.A new line character or > b.The word 'Required_' > > These were my failed attempts Here's a regex which matches the "Required_Text" up till the next newline or "Required_" (uses a negative lookahead assertion, that (?=...) stuff): "Required_Text: (.)*(?=\n|Required_)" Running this on: """Some Text Required_Text: Some other text and (23.32) numbers Required_Field: Some more text Required_Text: Some other text and (23.32) numbersRequired_Field: Some more text""" will return: 0: "Required_Text: Some other text and" 1: "Required_Text: Some other text and (23.22) numbers" It suits the requirements you gave (stop at either newline or Required, whichever comes first), but it seems a bit weird that you don't want both matches to be the same. You could also slightly modify the regex to: "Required_Text: ((.)*(?=\n|Required_))" This forms a group (with index 1) containing the stuff that is required. And you could build on that: "Required_Text: ((.)*(?=\n|Required_))(Required_){0,1}" which returns instead of the previous 1: 1: "Required_Text: Some other text and (23.22) numbers Required_" FWIW, Spe (http://spe.pycs.net) includes a plugin called Kiki (written by yours truly :)) which visualizes the results of regexes (groups and the likes - at least, if he's already included my latest version in the download). You could also look into the Tkinter-based recon.py (not sure where you can get it, but Vaults of Parnassus or Google are your friends) if you mind wxPython-based solutions, but it's not quite as featureful. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From hec.villafuerte at telgua.com.gt Tue Sep 30 12:50:28 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Tue Sep 30 10:50:30 2003 Subject: [Tutor] List's name in a string In-Reply-To: <3F78CEF8.4020804@ccvcorp.com> References: <3F78D18C.4090900@telgua.com.gt> <3F78CEF8.4020804@ccvcorp.com> Message-ID: <3F79B454.8020505@telgua.com.gt> Jeff Shannon wrote: > You can sortof force it by going through locals() and globals(), but a > better approach would probably be to look again at *why* you want this. > > Most of the time, if you need to refer to some variable name > programmatically like this, what you're really looking for is a list > or a dictionary. In other words, you typically want to refer to > variables by a variable name so that you can select one object from a > set of possible objects based on some runtime parameter. That's > exactly the niche that dictionaries fit. For example, > > >>> data = {} > >>> data['list1'] = [1, 2, 3] > >>> data['list2'] = [4, 5, 6] > >>> data > {'list1': [1, 2, 3], 'list2': [4, 5, 6]} > >>> key = 'list1' > >>> data[key] > [1, 2, 3] > >>> > > Maybe if you explain a bit more about your intent, we can explore an > easier way to accomplish your goal than mucking about in the > interpreter's innards. You're right, I need to briefly explain what I want to do: * There's a list (LIST) which contains filenames (as strings); i.e.: LIST = ['file1', 'file2']. * There's some processing on each file refered to by LIST. * The processed output should be stored in a file named 'LIST_proc' (producing just one output file, appending the results from 'file1', 'file2', etc.) Thanks. From pythontutor at venix.com Tue Sep 30 12:00:24 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Sep 30 12:00:48 2003 Subject: [Tutor] mailing list archive reader In-Reply-To: References: Message-ID: <3F79A898.2040600@venix.com> Your email program would hopefully do the job. With luck you can simply import the archive. If importing doesn't work, let us know. I am not sure how easy it would be to get the mailman archive management up and working on your windows pc. mailman was set up for apache and sendmail in the rpm that I used to install it on my linux server. While you wouldn't care about the mail server part, you would need to get a web server running in conjunction with mailman. Hopefully importing each archive into your email program as separate folders is feasible. roy ollis wrote: > is there a program that can read the mailing list archives from a local > flie and format them like the online options (ie date, thread, author). > i downloaded each months archies but the seem to be huge flat files with > alot of repition for threads. i looked into mailman but evidently it > requires an expert to force it into windows and if i was an expret i > wouldn't need the list so much ;) .im currently running xp on a 2.6 > pentium if that matters. and i have a glitchy dial up which is why i > want to run from the local files. by the time i get reconnected during > high traffic times i lose my train of thought, very bad for the > untrained mind. thanks for any help/pointers. i'm still at the raw > newbie stage learning python as a first comp language so make it for > dummies style if ya can. thanx. roy > > ------------------------------------------------------------------------ > Instant message in style with MSN Messenger 6.0. Download it now FREE! > > > > ------------------------------------------------------------------------ > > _______________________________________________ > 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 pythontutor at venix.com Tue Sep 30 12:09:52 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Sep 30 12:10:08 2003 Subject: [Tutor] mailing list archive reader In-Reply-To: References: Message-ID: <3F79AAD0.7050702@venix.com> As an experiment, I downloaded a small mailman archive and unzipped it. I changed the name to 2003March and copied it into my Netscape Mail directory. I started Netscape and it accepted the archive as just another email folder. The sort by thread, subject and sender functions all worked. This kind of approach can work with the email programs that simply save the emails as a text file while building a separate index (.msf in Netscape's case) file for managing the email. This won't work with Outlook. roy ollis wrote: > is there a program that can read the mailing list archives from a local > flie and format them like the online options (ie date, thread, author). > i downloaded each months archies but the seem to be huge flat files with > alot of repition for threads. i looked into mailman but evidently it > requires an expert to force it into windows and if i was an expret i > wouldn't need the list so much ;) .im currently running xp on a 2.6 > pentium if that matters. and i have a glitchy dial up which is why i > want to run from the local files. by the time i get reconnected during > high traffic times i lose my train of thought, very bad for the > untrained mind. thanks for any help/pointers. i'm still at the raw > newbie stage learning python as a first comp language so make it for > dummies style if ya can. thanx. roy > > ------------------------------------------------------------------------ > Instant message in style with MSN Messenger 6.0. Download it now FREE! > > > > ------------------------------------------------------------------------ > > _______________________________________________ > 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 vicki at thepenguin.org Tue Sep 30 12:17:19 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Tue Sep 30 12:20:00 2003 Subject: [Tutor] conversion confusion Message-ID: <35300.206.53.226.4.1064938639.squirrel@www.thepenguin.org> I am trying to OR two values. These values are the hex values minus the 0x part. If I had an ASCII 'm' for instance, I would OR the value 6D to the existing seed value. When I try this, I get an error. CRCval=ord(value2add) ^ ord(seed) because the value2add is 2 characters rather than one. Is there an established function to take a multi-character string and convert it to a numeric value that works with OR? --vicki From pythontutor at venix.com Tue Sep 30 13:04:25 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Sep 30 13:04:33 2003 Subject: [Tutor] conversion confusion In-Reply-To: <35300.206.53.226.4.1064938639.squirrel@www.thepenguin.org> References: <35300.206.53.226.4.1064938639.squirrel@www.thepenguin.org> Message-ID: <3F79B799.2010307@venix.com> >>> ord('m') 109 >>> int('6d',16) 109 So int(value2add,16) should give you the right number. I assume this relates to the serial processing that you've written about in the past. Did you create value2add by using a hex funtion on a character? Would it be feasible to simply use ord on the original character? Vicki Stanfield wrote: > I am trying to OR two values. These values are the hex values minus the 0x > part. If I had an ASCII 'm' for instance, I would OR the value 6D to the > existing seed value. When I try this, I get an error. > > CRCval=ord(value2add) ^ ord(seed) > > because the value2add is 2 characters rather than one. Is there an > established function to take a multi-character string and convert it to a > numeric value that works with OR? > > --vicki > > _______________________________________________ > 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 dyoo at hkn.eecs.berkeley.edu Tue Sep 30 13:04:37 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 30 13:04:44 2003 Subject: [Tutor] Database acces vs XML [documentation on Database API 2.0] In-Reply-To: <3F78C73C.8030209@epfl.ch> Message-ID: > I had a look to the pysqlite module, and seems to better fit my needs.In > the docs they say sqlite "fully comply with the Python Database API > v.2.0 specification" and give no further details about pysqlite use. I > had a look into the python library reference and there seems to be no > "standard" database module. All those different database modules are > quite confusing! Is there any tutorial for using databases with the > Database API specification? Or describing this specification? Hi Guillermo, Yes, there's documentation on the Database API 2.0, starting from the 'Database' topic guide: http://python.org/topics/database/ We can find the API here: http://python.org/peps/pep-0249.html (It might be nice for the Sqlite folks to directly hyperlink the Database API link into their documentation. That should reduce the confusion for anyone else who's using Sqlite for the first time.) Examples, examples... ok, Linux Journal has written an article that shows how to use the API: http://www.linuxjournal.com/article.php?sid=2605 There's another example from the Devshed folks: http://www.devshed.com/Server_Side/Python/PythonMySQL/ We can also talk about examples on the Tutor list, if you'd like. If you have some really hefty database questions, there's a dedicated Special Interest Group for Python and databases: http://mail.python.org/mailman/listinfo/db-sig From amk at amk.ca Tue Sep 30 13:07:54 2003 From: amk at amk.ca (amk@amk.ca) Date: Tue Sep 30 13:07:59 2003 Subject: [Tutor] conversion confusion In-Reply-To: <35300.206.53.226.4.1064938639.squirrel@www.thepenguin.org> References: <35300.206.53.226.4.1064938639.squirrel@www.thepenguin.org> Message-ID: <20030930170754.GA20302@rogue.amk.ca> On Tue, Sep 30, 2003 at 11:17:19AM -0500, Vicki Stanfield wrote: > CRCval=ord(value2add) ^ ord(seed) Note that ^ is XOR; | (the vertical pipe) is the symbol for OR. --amk From VICKI.STANFIELD at ROCHE.COM Tue Sep 30 13:10:26 2003 From: VICKI.STANFIELD at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis}) Date: Tue Sep 30 13:13:01 2003 Subject: [Tutor] conversion confusion Message-ID: Oh, yes, I meant to type XOR. Thanks. --vicki -----Original Message----- From: amk@amk.ca [mailto:amk@amk.ca] Sent: Tuesday, September 30, 2003 12:08 PM To: tutor@python.org Subject: Re: [Tutor] conversion confusion On Tue, Sep 30, 2003 at 11:17:19AM -0500, Vicki Stanfield wrote: > CRCval=ord(value2add) ^ ord(seed) Note that ^ is XOR; | (the vertical pipe) is the symbol for OR. --amk _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jeff at ccvcorp.com Tue Sep 30 13:22:26 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Sep 30 13:19:44 2003 Subject: [Tutor] List's name in a string References: <3F78D18C.4090900@telgua.com.gt> <3F78CEF8.4020804@ccvcorp.com> <3F79B454.8020505@telgua.com.gt> Message-ID: <3F79BBD2.8060305@ccvcorp.com> H?ctor Villafuerte D. wrote: > You're right, I need to briefly explain what I want to do: > * There's a list (LIST) which contains filenames (as strings); i.e.: > LIST = ['file1', 'file2']. > * There's some processing on each file refered to by LIST. > * The processed output should be stored in a file named 'LIST_proc' > (producing just one > output file, appending the results from 'file1', 'file2', etc.) Okay, that seems pretty straightforward. I'd do this following a rough skeleton something like this: outfile = file('LIST_proc', 'w') for filename in LIST: infile = file(filename,'r') process_file(infile, outfile) infile.close() outfile.close() where process_file() reads lines from the input file, massages them in whatever way necessary, and writes the result to outfile. To be honest, I'm not sure where the desire to get a variable by name came in; perhaps you were thinking that using names from the list was a little more complex than it really is? Jeff Shannon Technician/Programmer Credit International From hec.villafuerte at telgua.com.gt Tue Sep 30 16:39:03 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Tue Sep 30 14:38:50 2003 Subject: [Tutor] List's name in a string In-Reply-To: <3F79BBD2.8060305@ccvcorp.com> References: <3F78D18C.4090900@telgua.com.gt> <3F78CEF8.4020804@ccvcorp.com> <3F79B454.8020505@telgua.com.gt> <3F79BBD2.8060305@ccvcorp.com> Message-ID: <3F79E9E7.3060807@telgua.com.gt> Jeff Shannon wrote: > H?ctor Villafuerte D. wrote: > >> You're right, I need to briefly explain what I want to do: >> * There's a list (LIST) which contains filenames (as strings); i.e.: >> LIST = ['file1', 'file2']. >> * There's some processing on each file refered to by LIST. >> * The processed output should be stored in a file named 'LIST_proc' >> (producing just one >> output file, appending the results from 'file1', 'file2', etc.) > > > Okay, that seems pretty straightforward. I'd do this following a > rough skeleton something like this: > > outfile = file('LIST_proc', 'w') > for filename in LIST: > infile = file(filename,'r') > process_file(infile, outfile) > infile.close() > outfile.close() > > where process_file() reads lines from the input file, massages them in > whatever way necessary, and writes the result to outfile. > > To be honest, I'm not sure where the desire to get a variable by name > came in; perhaps you were thinking that using names from the list was > a little more complex than it really is? > Ok, you're right.... I should have said that I have multiple LISTs and that I want to do something like this: >>> file_w = open(LIST.name() + '_proc', 'w') at least that's the basic idea. I could write one open statement for every list in my program (there aren't that many), but I'm trying to make a function in order to generalize this my code. This function looks like this: NOTES: * traf is the expected list with filenames to process def build_basic(traf): """Creates basic processed files.""" if traf: file_w = open(traf.name() + '_proc', 'w') # THE PROBLEM IS HERE (this is pseudocode) for arch in traf: for line in fileinput.input(arch): file_w.write( line[0:8] + line[8:16] + line[16:22] + line[22:36] + line[50:56] + line[62:69] + line[69:76] + '\n') Thanks again. From pythontutor at venix.com Tue Sep 30 15:07:41 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Sep 30 15:07:48 2003 Subject: [Tutor] conversion confusion In-Reply-To: References: Message-ID: <3F79D47D.60402@venix.com> hex takes a numeric input and returns a string with the hex characters to represent that number. >>> hex(1234) '0x4d2' >>> hex(ord('m')) '0x6d' Just use: ord(input_character) ^ seed >>> seed = 1234 >>> ord('m') ^ seed 1215 Note that you probably do not need to convert the character to hex (except for display purposes. >>> ord('m') 109 >>> hex(ord('m')) '0x6d' >>> int('6d',16) 109 Stanfield, Vicki {D167~Indianapolis} wrote: > Now that I think about it, it is not really a hex value when I pass it in but a string. I pass either a number or an alpha character like 'm' that I read from the command line. I need to convert whatever it is to a hex value. For instance, 'm' would be converted to '6D' before being XOR'ed to the seed value. When I try to use hex('m'), I am told that I can't convert a hex value to a hex value. How is 'm' a hex value? > > --vicki > > -----Original Message----- > From: Lloyd Kvam [mailto:pythontutor@venix.com] > Sent: Tuesday, September 30, 2003 12:04 PM > To: Vicki Stanfield > Cc: tutor@python.org > Subject: Re: [Tutor] conversion confusion > > > >>> ord('m') > 109 > >>> int('6d',16) > 109 > > So int(value2add,16) should give you the right number. > > I assume this relates to the serial processing that you've written about in > the past. Did you create value2add by using a hex funtion on a character? > Would it be feasible to simply use ord on the original character? > > Vicki Stanfield wrote: > > >>I am trying to OR two values. These values are the hex values minus the 0x >>part. If I had an ASCII 'm' for instance, I would OR the value 6D to the >>existing seed value. When I try this, I get an error. >> >>CRCval=ord(value2add) ^ ord(seed) >> >>because the value2add is 2 characters rather than one. Is there an >>established function to take a multi-character string and convert it to a >>numeric value that works with OR? >> >>--vicki >> >>_______________________________________________ >>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 jeff at ccvcorp.com Tue Sep 30 15:09:59 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Sep 30 15:11:22 2003 Subject: [Tutor] List's name in a string References: <3F78D18C.4090900@telgua.com.gt> <3F78CEF8.4020804@ccvcorp.com> <3F79B454.8020505@telgua.com.gt> <3F79BBD2.8060305@ccvcorp.com> <3F79E9E7.3060807@telgua.com.gt> Message-ID: <3F79D507.1080700@ccvcorp.com> H?ctor Villafuerte D. wrote: > > Jeff Shannon wrote: > >> H?ctor Villafuerte D. wrote: >> >> Okay, that seems pretty straightforward. I'd do this following a >> rough skeleton something like this: >> >> outfile = file('LIST_proc', 'w') >> for filename in LIST: >> infile = file(filename,'r') >> process_file(infile, outfile) >> infile.close() >> outfile.close() > > Ok, you're right.... I should have said that I have multiple LISTs and > that I want to do something like this: > >>> file_w = open(LIST.name() + '_proc', 'w') > at least that's the basic idea. Okay, you've got multiple lists that you want to apply the above treatment to. You can keep those lists in a dictionary, like so: list_dict = { 'LIST1': ['file1', 'file2', 'file3'], 'LIST2': ['otherfile1', 'otherfile2'] } And then you can iterate over the items in the dictionary: for listname, filelist in list_dict.items(): outfile_name = "%s_proc" % listname outfile = file(outfile_name, 'w') for filename in filelist: # ... If you want to build the lists of filenames on the fly, that's fine, too. Just assemble the list of files, generate a unique name, and plug them into the dictionary -- list_dict[name] = filelist Or, say you have a long list of files that you're trying to categorize into different sublists. You can use dict.get() to make this easier -- get() will return a default value if a key isn't found in the dictionary. list_dict = {} for filename in big_filelist: key = category(filename) existing = list_dict.get(key, []) existing.append(filename) list_dict[key] = existing Hopefully this will give you some ideas on how to handle the specifics of your problem... Jeff Shannon Technician/Programmer Credit International From hec.villafuerte at telgua.com.gt Tue Sep 30 18:17:31 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Tue Sep 30 16:17:19 2003 Subject: [Tutor] List's name in a string In-Reply-To: <3F79D507.1080700@ccvcorp.com> References: <3F78D18C.4090900@telgua.com.gt> <3F78CEF8.4020804@ccvcorp.com> <3F79B454.8020505@telgua.com.gt> <3F79BBD2.8060305@ccvcorp.com> <3F79E9E7.3060807@telgua.com.gt> <3F79D507.1080700@ccvcorp.com> Message-ID: <3F7A00FB.5050804@telgua.com.gt> Jeff wrote: > Okay, you've got multiple lists that you want to apply the above > treatment to. You can keep those lists in a dictionary, like so: > > list_dict = { 'LIST1': ['file1', 'file2', 'file3'], > 'LIST2': ['otherfile1', 'otherfile2'] } > > And then you can iterate over the items in the dictionary: > > for listname, filelist in list_dict.items(): > outfile_name = "%s_proc" % listname > outfile = file(outfile_name, 'w') > for filename in filelist: > # ... > > If you want to build the lists of filenames on the fly, that's fine, > too. Just assemble the list of files, generate a unique name, and > plug them into the dictionary -- > > list_dict[name] = filelist > > Or, say you have a long list of files that you're trying to categorize > into different sublists. You can use dict.get() to make this easier > -- get() will return a default value if a key isn't found in the > dictionary. > > list_dict = {} > for filename in big_filelist: > key = category(filename) > existing = list_dict.get(key, []) > existing.append(filename) > list_dict[key] = existing > > Hopefully this will give you some ideas on how to handle the specifics > of your problem... > Great, thanks! Dictionaries will make it... I knew all those new data structures would be useful someday :) From pythontutor at venix.com Tue Sep 30 17:07:49 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Sep 30 17:08:01 2003 Subject: [Tutor] conversion confusion In-Reply-To: References: Message-ID: <3F79F0A5.90400@venix.com> XOR works on integers. The hex function takes a number and produces a string that is meant to be easy for people to read so that they can understand the underlying bits. The computer already understands the bits and doesn't need any conversion. '0x6d' represents the number 109 and allows us to recognize the bit pattern '0x67' represents the number 103 >>> 103 ^ 109 10 >>> hex(103 ^ 109) '0xa' >>> int('0a',16) 10 Hex is used for people who want an aid for understanding the underlying bits used in the computer. Generally, you only need the hex function to display to people. The computer already understands the bits just as they are. Stanfield, Vicki {D167~Indianapolis} wrote: > Now I am really confused! When I do this by hand, I put my calculator in hex mode and XOR the values 67 and 6d. It works fine there. The values I pass in are correct (67 and 6d) but I can't XOR them to save my life (Gee, I am getting old; aren't I?). If the variables value2add and seed represent 67 and 6d respectively. Why won't XOR work with them? In spite of the fact that these values are hex, the error I get is: > > TypeError: unsupported operand type(s) for ^: 'str' and 'str' > > I used binascii.hexlify to change the 'm' to 6d by the way. Why is it being seen as a string? > > --vicki > > -----Original Message----- > From: Lloyd Kvam [mailto:pythontutor@venix.com] > Sent: Tuesday, September 30, 2003 2:08 PM > To: Stanfield, Vicki {D167~Indianapolis} > Cc: Tutor Python > Subject: Re: [Tutor] conversion confusion > > > hex takes a numeric input and returns a string with the hex characters to > represent that number. > >>> hex(1234) > '0x4d2' > >>> hex(ord('m')) > '0x6d' > > Just use: > ord(input_character) ^ seed > >>> seed = 1234 > >>> ord('m') ^ seed > 1215 > > Note that you probably do not need to convert the character to hex (except > for display purposes. > >>> ord('m') > 109 > >>> hex(ord('m')) > '0x6d' > >>> int('6d',16) > 109 > > > Stanfield, Vicki {D167~Indianapolis} wrote: > > >>Now that I think about it, it is not really a hex value when I pass it in but a string. I pass either a number or an alpha character like 'm' that I read from the command line. I need to convert whatever it is to a hex value. For instance, 'm' would be converted to '6D' before being XOR'ed to the seed value. When I try to use hex('m'), I am told that I can't convert a hex value to a hex value. How is 'm' a hex value? >> >>--vicki >> >>-----Original Message----- >>From: Lloyd Kvam [mailto:pythontutor@venix.com] >>Sent: Tuesday, September 30, 2003 12:04 PM >>To: Vicki Stanfield >>Cc: tutor@python.org >>Subject: Re: [Tutor] conversion confusion >> >> >> >>> ord('m') >>109 >> >>> int('6d',16) >>109 >> >>So int(value2add,16) should give you the right number. >> >>I assume this relates to the serial processing that you've written about in >>the past. Did you create value2add by using a hex funtion on a character? >>Would it be feasible to simply use ord on the original character? >> >>Vicki Stanfield wrote: >> >> >> >>>I am trying to OR two values. These values are the hex values minus the 0x >>>part. If I had an ASCII 'm' for instance, I would OR the value 6D to the >>>existing seed value. When I try this, I get an error. >>> >>>CRCval=ord(value2add) ^ ord(seed) >>> >>>because the value2add is 2 characters rather than one. Is there an >>>established function to take a multi-character string and convert it to a >>>numeric value that works with OR? >>> >>>--vicki >>> >>>_______________________________________________ >>>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 jonathan.hayward at pobox.com Tue Sep 30 18:41:36 2003 From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com) Date: Tue Sep 30 18:41:42 2003 Subject: [Tutor] Complaint about maximum recursion Message-ID: <3F7A06A0.1040200@pobox.com> My script now gets this error on starting up. What is wrong if a 50-line stack trace complains about excessive recursion? Traceback (most recent call last): File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 3878, in ? multitasking.start_oracle() File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 2288, in start_oracle server_init() File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 3802, in server_init section.get_documents(1) File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 2614, in get_documents self.possibly_include_files_from_directory, "") File "/usr/lib/python2.2/posixpath.py", line 287, in walk walk(name, func, arg) File "/usr/lib/python2.2/posixpath.py", line 279, in walk func(arg, top, names) File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 2681, in possibly_include_files_from_directory self) File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 857, in get_document return webpage(filename, section) File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 2805, in __init__ document.__init__(self, filename, section) File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 637, in __init__ self.process() File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 808, in process self.compute_title() File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 2948, in compute_title self.title = self.get_tag_contents("title", self.get_file_contents()) File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 763, in get_tag_contents internal = self.get_tag_contents_internal(tag, file_contents) File "/home/jonathan/creations/software/inventions/datamine/fathersd", line 772, in get_tag_contents_internal return my_re.findall(file_contents) RuntimeError: maximum recursion limit exceeded TIA, -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From hec.villafuerte at telgua.com.gt Tue Sep 30 21:39:51 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Tue Sep 30 19:39:39 2003 Subject: [Tutor] Efficient way to join files Message-ID: <3F7A3067.1000409@telgua.com.gt> Hi all, I need to join multiple files. Is there a more efficient way to do it than using fileinput.input(file) and looping through those files? Thanks in advance, Hector From john at duartedailey.org Tue Sep 30 20:18:40 2003 From: john at duartedailey.org (John Duarte) Date: Tue Sep 30 20:18:50 2003 Subject: [Tutor] Cut and paste from interpreter Message-ID: <200309301718.40312.john@duartedailey.org> What is the best way to cut and paste code from the interpreter? Is there a way to print the history of an interpreter session? I am looking for an efficient way to cut and paste code after working it out within an interpreter session. For example, after working out a successful function would there be a way to print a formatted representation of that function from within the interpreter? Thanks, John From project5 at redrival.net Tue Sep 30 21:51:20 2003 From: project5 at redrival.net (Andrei) Date: Tue Sep 30 21:53:26 2003 Subject: [Tutor] Re: Cut and paste from interpreter In-Reply-To: <200309301718.40312.john@duartedailey.org> References: <200309301718.40312.john@duartedailey.org> Message-ID: John Duarte wrote: > What is the best way to cut and paste code from the interpreter? > Is there a way to print the history of an interpreter session? > > I am looking for an efficient way to cut and paste code after working it out > within an interpreter session. For example, after working out a successful > function would there be a way to print a formatted representation of that > function from within the interpreter? I'd say the selection/clipboard capabilities rather depend on the interpreter and OS. If you have wxPython, use PyCrust and go to the "Session" tab. E.g. here's a session recorded in that tab: import re 5+5 for i in range(5): print i, And here it is how it looks in the shell part of PyCrust, where it was actually typed: >>> import re >>> 5+5 10 >>> for i in range(5): ... print i, ... 0 1 2 3 4 -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From jeff at truedatapartners.com Sun Sep 21 19:13:22 2003 From: jeff at truedatapartners.com (Jeffery Chin) Date: Thu Oct 9 20:16:55 2003 Subject: [Tutor] Limit on number of characters in a string? Message-ID: Is there a limit on how many characters can be in a string? I'm using pythonwin with python 2.3 and there seems to be a limit. I'm trying to concatenate lines from a file to make one continuous string and it won't grow beyond a certain length. I think it cuts it off around 3800 characters, but this was not consistent, but looking at the screen output, it certainly would not add more to the string. script would read in the file and check whether to concatenate the line to the string: elif (record_check == ','): interim_list.append(logline_path + entry + '.txt;') looking at the screen output and what is written to a file, it will not continue to write to the string after it hits a certain length. If there isn't such a limit there must be an error elsewhere, but it seems to work fine for the shorter strings. Jeffery From vadim at gym-nippes.k.nw.schule.de Tue Sep 23 07:04:16 2003 From: vadim at gym-nippes.k.nw.schule.de (Vadim Usenko) Date: Thu Oct 9 20:17:20 2003 Subject: [Tutor] Project Parallelport Message-ID: <20030923110358.GA17002@liposerv.bluecher> Hi all, I am searching for a module in python to connect a programm directly with the parallel port to build a mini-crossway with some traffic lights. Do you have some information for me, please? Thanks, Vadim From vick1975 at intnet.mu Tue Sep 23 07:24:08 2003 From: vick1975 at intnet.mu (Vickram) Date: Thu Oct 9 20:17:29 2003 Subject: [Tutor] I need help with Python Message-ID: <001301c381c5$07328e40$d60d7bca@angel> Hello there, Python is really an excellent programming language, in terms of mathematical calculations. I have had a first hand experience of the power of python while using the Mayalib source code for python to calculate mayan dates. However, i am currently experiencing some problems in writing my own program as i am not a language programmer. I need to make calculations using very large numbers, unfortunately, i am getting a "ZeroDivisionError: float division" error. Can you please help me out? What follows is my program. Its simple and brief, yet it is actually calculating one of the best proven theories in science - special relativity. import cmath a = 186282.397 b = 1609.344 c = 365.2421987817 d = 99.9999999999999999995 e = (d*a)/100 beta = ((e*b)**2) / ((a*b)**2) gamma = 1/math.sqrt(1-beta) ty = 100000 td = ty*c print print "speed of light =",a,"mps" print "1 mile =",b,"metres" print "1 year =",c,"days" print print "% of c =",d,"%" print "gamma =",gamma print print "normal time = ",ty,"years" print " ",td,"days" print print "time dilation =",ty/round(gamma),"yrs" print " ",td/gamma,"days" Thanking you Vickram -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030923/dcbfe018/attachment-0001.html From tjd at sfu.ca Wed Sep 24 02:49:22 2003 From: tjd at sfu.ca (Toby Donaldson) Date: Thu Oct 9 20:17:38 2003 Subject: [Tutor] re-directing print statements in exec Message-ID: <000e01c38267$fab53d90$6501a8c0@bigduck> Hi all, I am wondering if there is any easy way to make a print statement in an exec statement get sent to a string instead of the console. For instance, >>> prog = """ r = 5 print 3.14 * r ** 2 """ >>> exec prog 78.5 The result gets printed to the console. But instead, I'd like it to be in a string. Any suggestions? Toby -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20030924/a5224708/attachment.html From kim.branson at csiro.au Sun Sep 28 22:48:31 2003 From: kim.branson at csiro.au (Kim Branson) Date: Thu Oct 9 20:17:46 2003 Subject: [Tutor] osx python editor In-Reply-To: <001701c3862b$64294d90$797ba8c0@rclilly.com> Message-ID: <69372ED0-F227-11D7-84A4-000A9579AE94@csiro.au> Hi all, i'm making the transition from perl to python, i'm trying to convert a lot of tools into python so they can be maintained a little better. I'm looking at doing alot of my work under osx rather than linux. I've grabbed the macpython release. its got a ide in but it seems to lack colour syntax highlighting, this is i find very useful. Either i'm dumb and its not turned on by default (and i can't see a pref to do it), or there is a better tool out there. What ide are there for osx? and are there any gotchas for developing on osx and then running production on a linux system....should be all the same right? oh one more thing....is there a python lisp interface....i've got alot of horrid lisp code i might need to call, or should i rewrite the lot in python. Python can do most lisp things i've been told, but not macros? cheers Kim Dr Kim Branson Computational Chemistry and Molecular Modelling Division of Structural Biology The Walter and Elisa Hall Institute for Medical Resarch Parkville, Victoria Australia & Diffraction and Theory CSIRO Health Sciences and Nutrition 343 Royal Parade, Parkville, Victoria Australia Ph +613 9662 7136 email kbranson@wehi.edu.au email kim.branson@csiro.au -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 1295 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20030929/022668c7/attachment.bin From sholden at holdenweb.com Mon Sep 29 07:43:35 2003 From: sholden at holdenweb.com (Steve Holden) Date: Thu Oct 9 20:17:52 2003 Subject: [Tutor] RE: path in BaseHttpServer.py module In-Reply-To: <3F770A62.8060002@netzero.net> Message-ID: > -----Original Message----- > From: Kirk Bailey [mailto:idiot1@netzero.net] > Sent: Sunday, September 28, 2003 12:21 PM > To: Steve Holden; Tutor > Subject: path in BaseHttpServer.py module > > > Apparently BaseHTTPServer.py module defines self.path as path > from the command > line. relevant exerpt: > requestline = self.raw_requestline > if requestline[-2:] == '\r\n': > requestline = requestline[:-2] > elif requestline[-1:] == '\n': > requestline = requestline[:-1] > self.requestline = requestline > words = requestline.split() > if len(words) == 3: > [command, path, version] = words > (line 224-232) > self.command, self.path, self.request_version = command, > path, version > (line 245) > Danger, danger, Will Robinson! In this statement the server is analysing the request from the client. It should have decided its working directory long before this, so you should *not* need to make any changes to the *HTTPServer modules - just set your current directory as I suggested in the previous mail (which I omitted to copy to the tutor list, sorry, maybe you can pass on the advice when you've got it worked out). > OKFINE. But I want the server script to referr to a directory > UNDER that point > on the tree, so webpages (in fact all of the web accessable > tree) is rooted in a > directory UNDER that directory. This means modifying the path > declaration in the > module- which means editing the module, OR declaring it in > the top level script. Nope. The "path" you are looking at is the path *relative to the web root* of the URI that the client is requesting - the server works this out each time it makes a request. > Now this gets back to how python works, espically how it > handles building up > it's dictionary when it imports functions in modules. If I > redefine a function > defined in an imported module, will this break other functions? > If those other functions rely on the one you changed working as it originally did, yes. You should generally resist the temptation to poke about randomly without a clear understanding of what's supposed to be happening, although that *is* one technique you can use to understand where particular things happen. > Again, the existing script is: > #!C:\Python22\pythonw.exe > # COPYRIGHT 2003 Steve Holden, free for personal use. > # Please visit http://www.holdenweb.com/ to learn more! > # > import CGIHTTPServer, BaseHTTPServer > httpd=BaseHTTPServer.HTTPServer(('',8080), > CGIHTTPServer.CGIHTTPRequestHandler) > httpd.serve_forever() > # > > Any discussion? > Well, only to reiterate that this script currently serves the directory that it's run from, plus any subdirectories. So clearly we could modify it by inserting code at the beginning to change the current directory - that's what os.chdir() is for. As I believe I suggested in my previous mail, one possible change would be to look at sys.argv - the list of command-line arguments - and if there's a second element following the program name you could use os.chdir to change to that directory. Since I don't want to spoon-feed you I've left the details for you to work out, but you know you can get back to me if you can't get it working. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Interview with GvR August 14, 2003 http://www.onlamp.com/python/ > From adamane at csir.co.za Tue Sep 30 03:52:45 2003 From: adamane at csir.co.za (Akhona Damane) Date: Thu Oct 9 20:17:57 2003 Subject: [Tutor] AVPython in arcview Message-ID: Hi I am currently trying to automate some ArcView processes using AVPython. Where can I get relevant information on this topic. I would like to automate the following tasks: 1. fetching grid and feature data 2. open and set up a ModelBuilder 3. run the Model for each feature class; filter the output grid and save the results 4. convert shapefile to coverage; clip; merge thank you in advance Mr. Akhona Damane CSIR Environmentek Spatial Technology (012) 841 3188 Fax (012) 8412689 adamane@csir.co.za -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. Mailscanner thanks transtec Computers for their support.