From missive at hotmail.com Tue Mar 1 00:36:40 2005 From: missive at hotmail.com (Lee Harr) Date: Tue Mar 1 00:37:06 2005 Subject: [Tutor] (no subject) Message-ID: >I attempting to control xfmedia, >http://spuriousinterrupt.org/projects/xfmedia/ , via it's remote from >python and I can not get a connection. > >s = socket.fromfd('/tmp/xfmedia_remote.1001.0', socket.AF_UNIX, >socket.SOCK_STREAM) > >i get this error > >Traceback (most recent call last): > File "", line 1, in ? > >f = open('/tmp/xfmedia_remote.1001.0') >Traceback (most recent call last): > File "", line 1, in ? >IOError: [Errno 6] No such device or address: >'/tmp/xfmedia_remote.1001.0' > >yet ls shows the file exists, xfmedia is working fine. > I have not done this before, but I think you need to create a _new_ socket for your end, and then connect to the other socket. Does that make more sense? _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From python.programming at gmail.com Tue Mar 1 01:35:08 2005 From: python.programming at gmail.com (Kevin) Date: Tue Mar 1 01:35:12 2005 Subject: [Tutor] printing out a box of O's Message-ID: I just started getting in to python and for taking a look at the for loop. I want to print out a box of O's 10o chars long by 10 lines long this is what I came up with. Is there a better way to do this: j = 'O' for i in j*10: print i * 100 Thanks Kevin From cyresse at gmail.com Tue Mar 1 01:45:31 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 1 01:45:36 2005 Subject: [Tutor] printing out a box of O's In-Reply-To: References: Message-ID: for y in range(10): for x in range(10): print "O", print '\n' Or - for y in range(10): print "O"*10 On Mon, 28 Feb 2005 18:35:08 -0600, Kevin wrote: > I just started getting in to python and for taking a look at the for > loop. I want to print out a box > of O's 10o chars long by 10 lines long this is what I came up with. Is > there a better way to do > this: > > j = 'O' > for i in j*10: > print i * 100 > > Thanks > > Kevin > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dyoo at hkn.eecs.berkeley.edu Tue Mar 1 02:33:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 1 02:33:38 2005 Subject: [Tutor] Python and a web image map In-Reply-To: Message-ID: > Save the above as an HTM and click, it should give you the x,y co-ords > for the browser window excluding scrolbars etc. It is possible to do this with Python, since a server-side HTML ISMAP will send its coordinates off as part of the request. There are some notes here: http://www.algonet.se/~ug/html+pycgi/img.html The coordinates we get back are in terms of the pixels of the image, so translating to a latitidue/longitude system will probably take some more work. Best of wishes! From billk at fastmail.fm Tue Mar 1 04:06:44 2005 From: billk at fastmail.fm (Bill Kranec) Date: Tue Mar 1 04:06:46 2005 Subject: [Tutor] Criticism / Suggestions Message-ID: <4223DC44.6010506@fastmail.fm> Hello, So I think that I've 'completed' my first real Python program, and I would appreciate any constructive criticism you all could offer. The program deals with a question that my Dad asked me awhile ago, which was "If twelve people want to divide into teams of two and play (golf) against each other, can a series of rounds be constructed such that each player is teammates with each other player only once, and play against each other as opponents no more then 3 times" ( that last bit might or might not be 'optimal'. My program: 1. Defines a round as a list, for example [1,2,3,4,5,6,7,8,9,10,11,12], meaning player 1 & player 2 vs. player 3 & player 4, etc. I have generated all such possible rounds ( I think ). 2. Defines a tournament iterator object, which uses two functions, checkTeammates and checkOpponents, to build a tournament satisfying the above criteria. Like I mentioned before, this is my first fairly complex program, and is also my first real use of things like exceptions, objects, and list comprehensions. Basically I would like to know weather or not I used these structures properly, weather or not my syntax is good, and if there are any places with potential for improvement. ( This version is somewhat slow, but is much faster than previous versions that I have written. ) I've tried to have as many comments as possible to help readability. Code aside, my algorithm may or may not be the best. Feel free to suggest improvements. The code is located at http://rafb.net/paste/results/lrd5DG32.html. Thanks for any thoughts! Bill From amonroe at columbus.rr.com Tue Mar 1 04:33:38 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Mar 1 04:34:22 2005 Subject: [Tutor] How to read unicode strings from a binary file and display them as plain ascii? Message-ID: <12255145785.20050228223338@columbus.rr.com> I started writing a program to parse the headers of truetype fonts to examine their family info. But I can't manage to print out the strings without the zero bytes in between each character (they display as a black block labeled 'NUL' in Scite's output pane) I tried: stuff = f.read(nlength) stuff = unicode(stuff, 'utf-8') print type(stuff), 'stuff', stuff.encode() This prints: stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] Apparently I'm missing something simple, but I don't know what. Alan From javier at ruere.com.ar Tue Mar 1 05:40:19 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Tue Mar 1 05:37:46 2005 Subject: [Tutor] Re: Edonkey Automatic Search Program?! In-Reply-To: References: Message-ID: . , wrote: > Hi, > > I just want to know whether this program can be programmed by python or > not. > > p2p program like edonkey is very very complicated (I think so..) > > but, is searching program for edonkey complicated too? > > Should the search program be connected to edonkey? (I think so..) > > > The Edonkey Automatic Search Program should be like... > > i input some words and the prgram automatically download files > > which are related to words by days, hours. > > > I'm looking forward to see your replys... P2P complicated? Please! Check http://www.freedom-to-tinker.com/tinyp2p.html out. ;) Javier From javier at ruere.com.ar Tue Mar 1 05:51:18 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Tue Mar 1 05:48:56 2005 Subject: [Tutor] Re: How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: <12255145785.20050228223338@columbus.rr.com> References: <12255145785.20050228223338@columbus.rr.com> Message-ID: R. Alan Monroe wrote: > I started writing a program to parse the headers of truetype fonts to > examine their family info. But I can't manage to print out the strings > without the zero bytes in between each character (they display as a > black block labeled 'NUL' in Scite's output pane) > > I tried: > stuff = f.read(nlength) > stuff = unicode(stuff, 'utf-8') If there are embeded 0's in the string, it won't be utf8, it could be utf16 or 32. Try: unicode(stuff, 'utf-16') or stuff.decode('utf-16') > print type(stuff), 'stuff', stuff.encode() > This prints: > > stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] I don't understand what you tried to accomplish here. > Apparently I'm missing something simple, but I don't know what. Try the other encodings. It probably is utf-16. Javier From alan.gauld at freenet.co.uk Tue Mar 1 08:35:02 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Mar 1 08:35:09 2005 Subject: [Tutor] Python and a web image map References: Message-ID: <01a201c51e31$2f0366b0$a6388651@xp> > I have been doing Python for a bit now but I am trying to make a clickable > map of the world on a web page that gives me the latitude and longitude of a > location selected. I have done little with HTML beyond forms and have done > no Java script. Is this a problem Python can solve or is this a HTML / Java > script issue. Personally I'd go with JavaScript on this one. It has a built-in knowledge of the web browser interface and document which makes extracting the mouse location etc much easier. Its possible in Python but IMHO is easier in JavaScript on the client. Alan G. From alan.gauld at freenet.co.uk Tue Mar 1 08:40:36 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Mar 1 08:40:40 2005 Subject: [Tutor] printing out a box of O's References: Message-ID: <01b101c51e31$f57d7d80$a6388651@xp> ----- Original Message ----- From: "Kevin" To: Sent: Tuesday, March 01, 2005 12:35 AM Subject: [Tutor] printing out a box of O's > there a better way to do > this: > > j = 'O' > for i in j*10: > print i * 100 Its not bad, but the for loop could be 'simplified' to: for i in range(10): print j*100 its not any shorter and probably doesn't run much faster but its a lot more readable because its the conventional Python idiom for coding fixed length loops. Alan G. From kabads at gmail.com Tue Mar 1 10:22:06 2005 From: kabads at gmail.com (Adam Cripps) Date: Tue Mar 1 10:22:10 2005 Subject: [Tutor] Saving Entry fields in Tkinter Message-ID: I'm writing an application which has rows of Entry fields (created in a loop - see previous thread; and thanks guys!). All the content of the Entry fields are accessed through self.contentlist[i].get() Now I'm trying to save the content of those fields in a friendly format. I've used pickle in the past, but experienced problems with pickling Tkinter widgets. I'm saving using this method :- for i in self.contentlist: saving = i.get() + "\n" f.write(saving) f.close() which creates a text file with each entry field separated with a "\n". What would be a good way to open this file and re-populate the entry fields with the content? I'm not sure how to parse the text according to the \n separator. Am I going down the right path here? TIA Adam -- http://www.monkeez.org PGP key: 0x7111B833 From amonroe at columbus.rr.com Tue Mar 1 12:39:22 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Mar 1 12:40:06 2005 Subject: [Tutor] Re: How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: References: <12255145785.20050228223338@columbus.rr.com> Message-ID: <8584290042.20050301063922@columbus.rr.com> > R. Alan Monroe wrote: >> I started writing a program to parse the headers of truetype fonts to >> examine their family info. But I can't manage to print out the strings >> without the zero bytes in between each character (they display as a >> black block labeled 'NUL' in Scite's output pane) >> >> I tried: >> stuff = f.read(nlength) >> stuff = unicode(stuff, 'utf-8') > If there are embeded 0's in the string, it won't be utf8, it could be > utf16 or 32. > Try: > unicode(stuff, 'utf-16') > or > stuff.decode('utf-16') >> print type(stuff), 'stuff', stuff.encode() >> This prints: >> >> stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] > I don't understand what you tried to accomplish here. That's evidence of what I failed to accomplish. My expected results was to print the word "Copyright" and whatever other strings are present in the font, with no intervening NUL characters. > Try the other encodings. It probably is utf-16. Aha, after some trial and error I see that I'm running into an endian problem. It's "\x00C" in the file, which needs to be swapped to "C\x00". I cheated temporarily by just adding 1 to the file pointer :^) Alan -------------- next part -------------- #~ 11/30/1998 03:45 PM 38,308 FUTURAB.TTF #~ 11/30/1998 03:45 PM 38,772 FUTURABI.TTF #~ 12/10/1998 06:24 PM 32,968 FUTURAK.TTF #~ 12/30/1998 05:15 AM 36,992 FUTURAL.TTF #~ 12/15/1998 11:39 PM 37,712 FUTURALI.TTF #~ 01/05/1999 03:59 AM 38,860 FUTURAXK.TTF #~ The OpenType font with the Offset Table. If the font file contains only one font, the Offset Table will begin at byte 0 of the file. If the font file is a TrueType collection, the beginning point of the Offset Table for each font is indicated in the TTCHeader. #~ Offset Table Type Name Description #~ Fixed sfnt version 0x00010000 for version 1.0. #~ USHORT numTables Number of tables. #~ USHORT searchRange (Maximum power of 2 <= numTables) x 16. #~ USHORT entrySelector Log2(maximum power of 2 <= numTables). #~ USHORT rangeShift NumTables x 16-searchRange. import struct def grabushort(): global f data = f.read(2) return int(struct.unpack('>H',data)[0]) def grabulong(): global f data = f.read(4) return int(struct.unpack('>L',data)[0]) f=open('c:/windows/fonts/futurak.ttf', 'rb') version=f.read(4) numtables = grabushort() print numtables f.read(6) #skip searchrange, entryselector, rangeshift #~ Table Directory Type Name Description #~ ULONG tag 4 -byte identifier. #~ ULONG checkSum CheckSum for this table. #~ ULONG offset Offset from beginning of TrueType font file. #~ ULONG length Length of this table. #for x in range(numtables): for x in range(numtables): tag=f.read(4) checksum =grabulong() offset = grabulong() tlength = grabulong() print 'tag', tag, 'offset', offset, 'tlength', tlength if tag=='name': nameoffset = offset namelength = tlength print 'nameoffset', nameoffset, 'namelength', namelength #The Naming Table is organized as follows: #~ Type Name Description #~ USHORT format Format selector (=0). #~ USHORT count Number of name records. #~ USHORT stringOffset Offset to start of string storage (from start of table). #~ NameRecord nameRecord[count] The name records where count is the number of records. #~ (Variable) Storage for the actual string data. #~ Each NameRecord looks like this: #~ Type Name Description #~ USHORT platformID Platform ID. #~ USHORT encodingID Platform-specific encoding ID. #~ USHORT languageID Language ID. #~ USHORT nameID Name ID. #~ USHORT length String length (in bytes). #~ USHORT offset String offset from start of storage area (in bytes). print f.seek(nameoffset) format = grabushort() count = grabushort() stringoffset = grabushort() print 'format', format, 'count', count, 'stringoffset', stringoffset for x in range(count): platformid = grabushort() encodingid = grabushort() languageid = grabushort() nameid = grabushort() nlength = grabushort() noffset = grabushort() print 'platformid', platformid, 'encodingid', encodingid, 'languageid', languageid, 'nameid', nameid, 'nlength', nlength, 'noffset', noffset if platformid==3:# microsoft bookmark = f.tell() print 'bookmark', bookmark f.seek(nameoffset+stringoffset+noffset+1) stuff = f.read(nlength) #stuff = unicode(stuff, 'utf-16') stuff = stuff.decode( 'utf-16') print type(stuff), 'stuff', stuff f.seek(bookmark) f.close() From kent37 at tds.net Tue Mar 1 12:50:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 1 12:50:06 2005 Subject: [Tutor] How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: <12255145785.20050228223338@columbus.rr.com> References: <12255145785.20050228223338@columbus.rr.com> Message-ID: <422456E9.5030707@tds.net> R. Alan Monroe wrote: > I started writing a program to parse the headers of truetype fonts to > examine their family info. But I can't manage to print out the strings > without the zero bytes in between each character (they display as a > black block labeled 'NUL' in Scite's output pane) > > I tried: > stuff = f.read(nlength) > stuff = unicode(stuff, 'utf-8') I think you need 'utf-16be', not 'utf-8'. See this page if you don't know the difference: http://www.joelonsoftware.com/articles/Unicode.html Kent > print type(stuff), 'stuff', stuff.encode() > > This prints: > > stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] > > Apparently I'm missing something simple, but I don't know what. > > Alan > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ewald.ertl at hartter.com Tue Mar 1 12:52:57 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue Mar 1 12:53:02 2005 Subject: [Tutor] Saving Entry fields in Tkinter In-Reply-To: References: Message-ID: <20050301125257.00004683@sunray2.hartter.com> Hi! Perhaps this could help you: fileContent=open( "my/file/to/read", "r").readlines() for line in fileContent: print line.strip() # remove leading and trailing whitspace's incl. \n In the loop you could perhaps populate the entry-widgets. HTH Ewald on Tue, 1 Mar 2005 09:22:06 +0000 Adam Cripps wrote : --------------------------------------------------------------------------------------------- Adam Cripps > I'm writing an application which has rows of Entry fields (created in Adam Cripps > a loop - see previous thread; and thanks guys!). All the content of Adam Cripps > the Entry fields are accessed through self.contentlist[i].get() Adam Cripps > Adam Cripps > Now I'm trying to save the content of those fields in a friendly Adam Cripps > format. I've used pickle in the past, but experienced problems with Adam Cripps > pickling Tkinter widgets. Adam Cripps > Adam Cripps > I'm saving using this method :- Adam Cripps > Adam Cripps > for i in self.contentlist: Adam Cripps > saving = i.get() + "\n" Adam Cripps > f.write(saving) Adam Cripps > f.close() Adam Cripps > Adam Cripps > which creates a text file with each entry field separated with a "\n". Adam Cripps > Adam Cripps > What would be a good way to open this file and re-populate the entry Adam Cripps > fields with the content? I'm not sure how to parse the text according Adam Cripps > to the \n separator. Adam Cripps > Adam Cripps > Am I going down the right path here? Adam Cripps > Adam Cripps > TIA Adam Cripps > Adam ------------------- end ---------------------- -- Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 Wiener Stra?e 41 mailto:ewald.ertl@trinomic.com A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl@hartter.com From amonroe at columbus.rr.com Tue Mar 1 12:59:04 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Mar 1 12:59:46 2005 Subject: [Tutor] How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: <422456E9.5030707@tds.net> References: <12255145785.20050228223338@columbus.rr.com> <422456E9.5030707@tds.net> Message-ID: <17885472022.20050301065904@columbus.rr.com> > R. Alan Monroe wrote: >> I started writing a program to parse the headers of truetype fonts to >> examine their family info. But I can't manage to print out the strings >> without the zero bytes in between each character (they display as a >> black block labeled 'NUL' in Scite's output pane) >> >> I tried: >> stuff = f.read(nlength) >> stuff = unicode(stuff, 'utf-8') > I think you need 'utf-16be', not 'utf-8'. See this page if you don't know the difference: Outstanding! Batteries included, indeed. Alan From kent37 at tds.net Tue Mar 1 14:46:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 1 14:46:33 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <4223DC44.6010506@fastmail.fm> References: <4223DC44.6010506@fastmail.fm> Message-ID: <42247232.1080409@tds.net> Bill Kranec wrote: > Hello, > > So I think that I've 'completed' my first real Python program, and I > would appreciate any constructive criticism you all could offer. The > program deals with a question that my Dad asked me awhile ago, which was > "If twelve people want to divide into teams of two and play (golf) > against each other, can a series of rounds be constructed such that each > player is teammates with each other player only once, do you mean, 'each player is teammates with each other player exactly once', or, 'each player is teammates with each other player at most once'? Is there a certain number of rounds that must be played? Comments in no particular order - Why do you have the initialization code in a comment? Wouldn't it be helpful to put that in a function or maybe Tournament.__init__()? - I have a hard time figuring out how this is supposed to work. Maybe some comments about the algorithm you are using would help? I have no idea what self.key is doing. - What is the argument to Tournament.__init__() for? - checkTeammates() and checkOpponents() should probably be part of Tournament unless they are useful elsewhere. - You might want to use sets to represent your teams and lists of teams. Sets have a built-in intersect method that should be faster than your hand coded one. In Python 2.4 you could create pairings as pairings = [set(number1, number2) for number1 in range(1,13) for number2 in range(1,13) if number1 < number2] or you could eliminate the conditional by tweaking the ranges: pairings = [(number1, number2) for number1 in range(1,12) for number2 in range(number1+1,13)] - This code repeats twice, maybe it should be in a method with a name that explains what it does: self.rounds = [ roundlist[ entry ] for entry in args ] self.flattened = [ entry for list in self.rounds for entry in list ] - The above code depends on roundlist which is not even defined anywhere in the module (just shown in the comment). This suggests again that the init code from the comment should be part of Tournament, and roundlist should be an attribute of Tournament. For a class to depend on some external variable is bad design and will break if the client code is in a different module from the class code (roundlist will be in a different namespace than Tournament). - Tournament.next() doesn't return a value, it prints it directly. It should return self.key or str( self.key ) - Your loop for key in tment: key relies on the interactive shell to print out key, it won't print anything if run from a program. for key in tment: print key would be better. OK, enough for now, I hope this is helpful and doesn't come across as too critical :-) Kent From MLists at romulo.de Tue Mar 1 15:15:08 2005 From: MLists at romulo.de (Rainer Mansfeld) Date: Tue Mar 1 15:15:14 2005 Subject: [Tutor] printing out a box of O's In-Reply-To: References: Message-ID: <422478EC.4090403@romulo.de> Kevin schrieb: > I just started getting in to python and for taking a look at the for > loop. I want to print out a box > of O's 10o chars long by 10 lines long this is what I came up with. Is > there a better way to do > this: > > j = 'O' > for i in j*10: > print i * 100 > > Thanks > > Kevin Hi Kevin, I don't know, if this is better, but at least it's shorter: >>> print ('O' * 100 + '\n') * 10 Rainer From mark.kels at gmail.com Tue Mar 1 15:51:54 2005 From: mark.kels at gmail.com (Mark Kels) Date: Tue Mar 1 15:51:58 2005 Subject: [Tutor] How to use threads ? Message-ID: Can anyone give me a very simple example on thread programming ? I looked at some tutorials but they don't really make sense... Thanks in advance -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From AKolinski at nriindustries.com Tue Mar 1 16:04:07 2005 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Tue Mar 1 16:03:15 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <42247232.1080409@tds.net> Message-ID: On my way to write my own scripts from scratch I'm still assembling bits and pieces from everywhere in the Python universe to create little programs that help me automate updating my website: - to invoke a players' ranking program, - to convert text files to php formats, - ... I would like to go even further and employ Tkinter to: - open and run a C and/or Python code (including arguments where necessary), - name and safe generated html/php files. The only thing I found is the following line of code: filemenu.add_command(label="Open...", command=askopenfile) - which obviously does not do the job. Therefore, what would be the right command within Tkinter to do what I need? _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski office 416.652.4256 cell. 416.838.7667 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050301/cd746564/attachment.html From AKolinski at nriindustries.com Tue Mar 1 16:15:18 2005 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Tue Mar 1 16:14:20 2005 Subject: [Tutor] to employ Tkinter Message-ID: My apologies for leaving Subject entry unchanged :-). _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski ----- Forwarded by Andrzej Kolinski/NRI on 01/03/2005 10:12 AM ----- Andrzej Kolinski Sent by: tutor-bounces@python.org 01/03/2005 10:04 AM To Python Tutor , tutor-bounces@python.org cc Subject Re: [Tutor] Criticism / Suggestions On my way to write my own scripts from scratch I'm still assembling bits and pieces from everywhere in the Python universe to create little programs that help me automate updating my website: - to invoke a players' ranking program, - to convert text files to php formats, - ... I would like to go even further and employ Tkinter to: - open and run a C and/or Python code (including arguments where necessary), - name and safe generated html/php files. The only thing I found is the following line of code: filemenu.add_command(label="Open...", command=askopenfile) - which obviously does not do the job. Therefore, what would be the right command within Tkinter to do what I need? _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050301/bd4df00f/attachment.html From kabads at gmail.com Tue Mar 1 16:31:10 2005 From: kabads at gmail.com (Adam Cripps) Date: Tue Mar 1 16:33:06 2005 Subject: [Tutor] Saving Entry fields in Tkinter In-Reply-To: References: <20050301125257.00004683@sunray2.hartter.com> Message-ID: On Tue, 1 Mar 2005 15:30:02 +0000, Adam Cripps wrote: > On Tue, 1 Mar 2005 12:52:57 +0100, Ewald Ertl wrote: > > Hi! > > > > Perhaps this could help you: > > > > fileContent=open( "my/file/to/read", "r").readlines() > > > > for line in fileContent: > > print line.strip() # remove leading and trailing whitspace's incl. \n > > > > In the loop you could perhaps populate the entry-widgets. > > > > HTH > > > > Ewald > > > > on Tue, 1 Mar 2005 09:22:06 +0000 Adam Cripps wrote : > > Thanks Ewald - this is what I have so far, with a far from perfect result: File=open( FileName, "r") readlines = File.readlines() intcount = 0 newcontent =[] for line in readlines: print line.strip() # remove leading and trailing whitspace's incl. \n self.contentlist[intcount].set(repr(line.strip)) intcount = intcount + 1 But all the entry fields are filled with these and not the text: I'm not sure what else to do here... any ideas? Thanks Adam -- http://www.monkeez.org PGP key: 0x7111B833 From kabads at gmail.com Tue Mar 1 16:45:50 2005 From: kabads at gmail.com (Adam Cripps) Date: Tue Mar 1 16:47:52 2005 Subject: [Tutor] Saving Entry fields in Tkinter In-Reply-To: References: <20050301125257.00004683@sunray2.hartter.com> Message-ID: On Tue, 1 Mar 2005 15:31:10 +0000, Adam Cripps wrote: > On Tue, 1 Mar 2005 15:30:02 +0000, Adam Cripps wrote: > > On Tue, 1 Mar 2005 12:52:57 +0100, Ewald Ertl wrote: > > > Hi! > > > > > > Perhaps this could help you: > > > > > > fileContent=open( "my/file/to/read", "r").readlines() > > > > > > for line in fileContent: > > > print line.strip() # remove leading and trailing whitspace's incl. \n > > > > > > In the loop you could perhaps populate the entry-widgets. > > > > > > HTH > > > > > > Ewald > > > > > > on Tue, 1 Mar 2005 09:22:06 +0000 Adam Cripps wrote : > > > > > Thanks Ewald - this is what I have so far, with a far from perfect result: > File=open( FileName, "r") > readlines = File.readlines() > intcount = 0 > newcontent =[] > for line in readlines: > print line.strip() # remove leading and trailing whitspace's incl. \n > self.contentlist[intcount].set(repr(line.strip)) > intcount = intcount + 1 > > But all the entry fields are filled with these and not the text: > > > > I'm not sure what else to do here... > > any ideas? I think I got the jist of it - readlines is a list, which holds all the text, and so I also iterate over readlines and push that content in thus: self.contentlist[intcount].set(readlines[intcount]) Adam -- http://www.monkeez.org PGP key: 0x7111B833 From ewald.ertl at hartter.com Tue Mar 1 17:40:26 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue Mar 1 17:40:30 2005 Subject: [Tutor] Saving Entry fields in Tkinter In-Reply-To: References: <20050301125257.00004683@sunray2.hartter.com> Message-ID: <20050301174026.0000134d@sunray2.hartter.com> Hi on Tue, 1 Mar 2005 15:31:10 +0000 Adam Cripps wrote : --------------------------------------------------------------------------------------------- Adam Cripps > > Adam Cripps > Thanks Ewald - this is what I have so far, with a far from perfect result: Adam Cripps > File=open( FileName, "r") Adam Cripps > readlines = File.readlines() Adam Cripps > intcount = 0 Adam Cripps > newcontent =[] Adam Cripps > for line in readlines: Adam Cripps > print line.strip() # remove leading and trailing whitspace's incl. \n Adam Cripps > self.contentlist[intcount].set(repr(line.strip)) I think, here's the call missing self.contentlist[intcount].set(repr(line.strip())) ^^ That should be the reason, why you get the reference to the method of the string and not the content. If your printing line.strip without the paranthesis you get the reference of the method. This reference can be assigned to a variable to call it later. Adam Cripps > intcount = intcount + 1 Adam Cripps > Adam Cripps > But all the entry fields are filled with these and not the text: Adam Cripps > Adam Cripps > Adam Cripps > Adam Cripps > I'm not sure what else to do here... Adam Cripps > Adam Cripps > any ideas? Adam Cripps > Adam Cripps > Thanks Adam Cripps > Adam Adam Cripps > -- Adam Cripps > http://www.monkeez.org Adam Cripps > PGP key: 0x7111B833 Adam Cripps > _______________________________________________ Adam Cripps > Tutor maillist - Tutor@python.org Adam Cripps > http://mail.python.org/mailman/listinfo/tutor Adam Cripps > ------------------- end ---------------------- From jon.papageorgiou at wachovia.com Tue Mar 1 19:29:07 2005 From: jon.papageorgiou at wachovia.com (jon.papageorgiou@wachovia.com) Date: Tue Mar 1 19:25:10 2005 Subject: [Tutor] Check if user exist in domain Message-ID: I need to check if a user is in a domain from a computer that is not in a domain. Currently, we are running an NT domain, but will be moving to ActiveDirectory2003 in the next few months. I thought if I could get user information for the user I could verify that the user account existed: #CODE STARTS HERE ###################################################### import win32net import win32netcon domain = "domain" login = "userid" try: #get the server for the domain -- it has to be a primary dc server = str(win32net.NetGetDCName("",domain)) print server #info returns a dictionary of information info = win32net.NetUserGetInfo(server, login, 1) print info#['full_name'] except win32net.error: print "Error: " + login + " not found in " + domain + "." #CODE ENDS HERE ###################################################### The problem is that the following code only works when one is logged in locally with a UserID and password that is the SAME as a UserID and password on the Domain. Example: Domain : Berlin Stand-alone <<- Different User : Frank Frank <<- Same Password: frank'spassword frank'spassword <<- Same So I then attempted to authenticate with alternate credentials. The following code did not work.It blew up on line 20. #CODE STARTS HERE ###################################################### import sys import win32api import win32net import win32netcon import win32security import win32con domain = "berlin" login = "hans" userwithrights = "frank" userwithrightspassword = "frank'spassword" #code blows up on next line hUser = win32security.LogonUser( userwithrights, domain, userwithrightspassword, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT ) win32security.ImpersonateLoggedOnUser(hUser) print win32api.GetUserName() # Should display "frank" #code to be run with alternate credentials try: #get the server for the domain -- it has to be a primary dc server = str(win32net.NetGetDCName("",domain)) print server #info returns a dictionary of information info = win32net.NetUserGetInfo(server, login, 1) print info#['full_name'] except win32net.error: print "Error: " + login + " not found in " + domain + "." win32security.RevertToSelf() hUser.Close() #CODE ENDS HERE ###################################################### The output I receive is as follows: Traceback (most recent call last): File "C:\Documents and Settings\Administrator\Desktop\python-components\getuser2.py", line 20, in ? win32con.LOGON32_PROVIDER_DEFAULT pywintypes.error: (1326, 'LogonUser', 'Logon failure: unknown user name or bad password.') The account being checked and the account that I am impersonating are both domain admins and the password I am using is correct. Can anybody point me in the right direction as to what I am missing? Jon Papageorgiou From klappnase at freenet.de Tue Mar 1 20:52:44 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue Mar 1 20:49:47 2005 Subject: [Tutor] Saving Entry fields in Tkinter In-Reply-To: <20050301125257.00004683@sunray2.hartter.com> References: <20050301125257.00004683@sunray2.hartter.com> Message-ID: <20050301205244.2a9648a3.klappnase@freenet.de> On Tue, 1 Mar 2005 12:52:57 +0100 Ewald Ertl wrote: > Hi! > > Perhaps this could help you: > > fileContent=open( "my/file/to/read", "r").readlines() > > for line in fileContent: > print line.strip() # remove leading and trailing whitspace's incl. \n > > > In the loop you could perhaps populate the entry-widgets. > > HTH > > Ewald Or use the fileinput module: var_list = [] for line in fileinput.input(filename): var = Tkinter.StringVar() var.set(line) var_list.append(var) Best regards Michael > > on Tue, 1 Mar 2005 09:22:06 +0000 Adam Cripps wrote : > --------------------------------------------------------------------------------------------- > > Adam Cripps > I'm writing an application which has rows of Entry fields (created in > Adam Cripps > a loop - see previous thread; and thanks guys!). All the content of > Adam Cripps > the Entry fields are accessed through self.contentlist[i].get() > Adam Cripps > > Adam Cripps > Now I'm trying to save the content of those fields in a friendly > Adam Cripps > format. I've used pickle in the past, but experienced problems with > Adam Cripps > pickling Tkinter widgets. > Adam Cripps > > Adam Cripps > I'm saving using this method :- > Adam Cripps > > Adam Cripps > for i in self.contentlist: > Adam Cripps > saving = i.get() + "\n" > Adam Cripps > f.write(saving) > Adam Cripps > f.close() > Adam Cripps > > Adam Cripps > which creates a text file with each entry field separated with a "\n". > Adam Cripps > > Adam Cripps > What would be a good way to open this file and re-populate the entry > Adam Cripps > fields with the content? I'm not sure how to parse the text according > Adam Cripps > to the \n separator. > Adam Cripps > > Adam Cripps > Am I going down the right path here? > Adam Cripps > > Adam Cripps > TIA > Adam Cripps > Adam > > > ------------------- end ---------------------- > > > -- > Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 > trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 > Wiener Stra?e 41 mailto:ewald.ertl@trinomic.com > A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl@hartter.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jfouhy at paradise.net.nz Tue Mar 1 21:03:14 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: Tue Mar 1 21:03:55 2005 Subject: [Tutor] to employ Tkinter In-Reply-To: References: Message-ID: <4224CA82.5030601@paradise.net.nz> Andrzej Kolinski wrote: > I would like to go even further and employ Tkinter to: > - open and run a C and/or Python code (including arguments where > necessary), > - name and save generated html/php files. > > The only thing I found is the following line of code: > filemenu.add_command(label="Open...", command=askopenfile) > - which obviously does not do the job. Tkinter is a GUI framework ... Basically, with Tkinter, you attach the code you want to run to GUI events. eg: from Tkinter import * import tkMessageBox import tkFileDialog import os # This will hold the entry widgets, for later reference. entries = {} tk = Tk() Label(tk, text='Program:').grid(row=0, column=0) entries['program'] = Entry(tk) entries['program'].grid(row=0, column=1) Label(tk, text='Arg 1:').grid(row=1, column=0) entries['arg1'] = Entry(tk) entries['arg1'].grid(row=1, column=1) Label(tk, text='Arg 2:').grid(row=2, column=0) entries['arg2'] = Entry(tk) entries['arg2'].grid(row=2, column=1) Label(tk, text='Arg 3:').grid(row=3, column=0) entries['arg3'] = Entry(tk) entries['arg3'].grid(row=3, column=1) # Build a 'Browse' button for the program field. def browseProg(self): prog = tkFileDialog.askopenfilename() if prog: entries['program'].delete(0, END) entries['program'].insert(END, prog) Button(tk, text='Browse', command=browseProg).grid(row=0, column=2) # Callback to run the program specified. def runProgram(): prog = entries['program'].get() arg1 = entries['arg1'].get() arg2 = entries['arg2'].get() arg3 = entries['arg3'].get() if not os.path.exists(prog): tkMessageBox.showerror('Error', '%s: File not found!' % prog) return args = filter(None, [arg1, arg2, arg3]) os.system(' '.join([prog] + args)) Button(tk, text='Run', command=runProgram).grid() tk.mainloop() --------------------------------------------------------- It should go without saying that there are security concerns when you are allowing users to run arbitrary programs! -- John. From shitizb at yahoo.com Tue Mar 1 21:25:56 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Tue Mar 1 21:26:01 2005 Subject: [Tutor] How to use threads ? In-Reply-To: Message-ID: <20050301202557.2424.qmail@web53803.mail.yahoo.com> --- Mark Kels wrote: > Can anyone give me a very simple example on thread > programming ? > I looked at some tutorials but they don't really > make sense... > > > Thanks in advance > -- > 1. The day Microsoft makes something that doesn't > suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about > it's friends. > 3. Documentation is like sex: when it is good, it is > very, very good. > And when it is bad, it is better than nothing. - > Dick Brandon > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Tue Mar 1 22:15:20 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Mar 1 22:15:47 2005 Subject: [Tutor] Criticism / Suggestions References: Message-ID: <004301c51ea3$ca474ca0$07b78851@xp> > programs that help me automate updating my website: > - to invoke a players' ranking program, > - to convert text files to php formats, > - ... > > I would like to go even further and employ Tkinter to: If you want to put Tkinter on your web site then you probably will be dissapointed. If you want to use a Tkinter GUI to create HTML/PHP content then thats OK. > - open and run a C and/or Python code (including arguments where > necessary), > - name and safe generated html/php files. > > The only thing I found is the following line of code: > filemenu.add_command(label="Open...", command=askopenfile) If thats all you found you were probably looking in the wrong place. There is a Tkinter section on the Python website with links to Tkinter tutorials. Or you can try my ultra basic level intro to GUI programming with Tkinter. I think you need a Frame containing an Entry widget for the command(or a drop down list or menu) and another Entry for the filename, which could be populated via the standard dialogs. Finally you need a button to execute the command and that will call the commands module or os.popen or somesuch mechanism to do the work. Have a look at the Tkinter tuitorials. If you don;t understand them try doing a command line version first, making sure to separate the function that does the work from the code that gets user input and displays output. See how you get on... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From nick at javacat.f2s.com Tue Mar 1 23:08:00 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Mar 1 23:06:42 2005 Subject: [Tutor] reading from stdin Message-ID: <1109714880.10412.5.camel@fuzzbox.local> Hi folks, I've been pondering how to get python to read from a pipe outside of itself, sort of. For example I tried a simple python prog to do a grep, eg # ps -e | myprog.py cron would give this output 3778 ? 00:00:00 crond same as # ps -e | grep cron The way I did this was to use sys.stdin.readlines() to get the output from the pipe. Here is the program: [code] import sys, glob args = sys.stdin.readlines() # found on the net pat = sys.argv[1] for i in args: if (i.find(pat) != -1): print i, [/code] My question is am I getting the output from the pipe in the correct way ? The way Im doing it works (so far) but should I be doing it another way ? Many thanks Nick . From shaleh at speakeasy.net Tue Mar 1 23:14:39 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Tue Mar 1 23:15:54 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109714880.10412.5.camel@fuzzbox.local> References: <1109714880.10412.5.camel@fuzzbox.local> Message-ID: <4224E94F.7070403@speakeasy.net> Nick Lunt wrote: > The way I did this was to use sys.stdin.readlines() to get the output > from the pipe. > > Here is the program: > > [code] > import sys, glob > args = sys.stdin.readlines() # found on the net > pat = sys.argv[1] > for i in args: > if (i.find(pat) != -1): > print i, > [/code] > > My question is am I getting the output from the pipe in the correct > way ? The way Im doing it works (so far) but should I be doing it > another way ? > unless you want the output for some other reason, a more idiomatic way is: for line in sys.stdin.readlines(): # handle the line I tend to use xreadlines() which does not read the entire input at once. For stdin this make sense, you have no idea how much data will be piped in. From maxnoel_fr at yahoo.fr Tue Mar 1 23:20:14 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Mar 1 23:20:18 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109714880.10412.5.camel@fuzzbox.local> References: <1109714880.10412.5.camel@fuzzbox.local> Message-ID: <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> On Mar 1, 2005, at 22:08, Nick Lunt wrote: > The way I did this was to use sys.stdin.readlines() to get the output > from the pipe. > > Here is the program: > > [code] > import sys, glob > args = sys.stdin.readlines() # found on the net > pat = sys.argv[1] > for i in args: > if (i.find(pat) != -1): > print i, > [/code] > > My question is am I getting the output from the pipe in the correct > way ? The way Im doing it works (so far) but should I be doing it > another way ? I don't think you are. You're using readlines(), which means your program won't execute until ps terminates. UNIX philosophy is to have programs start acting as soon as possible -- in that case, as soon as the first line is available. You should be reading sys.stdin as an iterator (same thing you'd do for a file): import sys for line in sys.stdin: # do stuff with that line of input -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From nick at javacat.f2s.com Tue Mar 1 23:23:12 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Mar 1 23:21:55 2005 Subject: [Tutor] reading from stdin In-Reply-To: <4224E94F.7070403@speakeasy.net> References: <1109714880.10412.5.camel@fuzzbox.local> <4224E94F.7070403@speakeasy.net> Message-ID: <1109715792.10412.11.camel@fuzzbox.local> On Tue, 2005-03-01 at 14:14 -0800, Sean Perry wrote: > > unless you want the output for some other reason, a more idiomatic way > is: > > for line in sys.stdin.readlines(): > # handle the line > > I tend to use xreadlines() which does not read the entire input at once. > For stdin this make sense, you have no idea how much data will be > piped in. Thanks Sean, I agree with you on both accounts there. Cheers Nick . From srini_iyyer_bio at yahoo.com Tue Mar 1 23:21:58 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Tue Mar 1 23:22:01 2005 Subject: [Tutor] Tab delim file In-Reply-To: <1109714880.10412.5.camel@fuzzbox.local> Message-ID: <20050301222158.42380.qmail@web53503.mail.yahoo.com> Hello: I have a nasty file where I have 165 column and 140K lines. For every 12 columns, a new dataset is written. 0-12 - File A's data is there 13-24 - File B's data is there. My task is to write data in each 12 columns to a file. I have a rough idea, but when I try I am unable to proceed further. f1 = open('my_file.txt','r') aml = f1.read().split('\n') fLine = aml[0] k = len(fLine)/12 # k = 162/12 #So I want to jump k blocks and get the text. for line in aml: cols = line.split('\t') while i > 13: ...... I am lost from here... Every 4 line(row) contains the file name on which I have to write the file. can any one plese help, i am really stuck in a problem. thanks srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jfouhy at paradise.net.nz Tue Mar 1 23:22:54 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue Mar 1 23:22:59 2005 Subject: [Tutor] reading from stdin In-Reply-To: <4224E94F.7070403@speakeasy.net> References: <1109714880.10412.5.camel@fuzzbox.local> <4224E94F.7070403@speakeasy.net> Message-ID: <1109715774.4224eb3e7dc38@www.paradise.net.nz> Quoting Sean Perry : > for line in sys.stdin.readlines(): > # handle the line > > I tend to use xreadlines() which does not read the entire input at once. xreadlines() these days just does 'return self', I believe. File objects are their own iterators; you can just do: for line in sys.stdin: # do stuff -- John. From nick at javacat.f2s.com Tue Mar 1 23:26:29 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Mar 1 23:25:10 2005 Subject: [Tutor] reading from stdin In-Reply-To: <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> References: <1109714880.10412.5.camel@fuzzbox.local> <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> Message-ID: <1109715989.10412.14.camel@fuzzbox.local> On Tue, 2005-03-01 at 22:20 +0000, Max Noel wrote: > I don't think you are. You're using readlines(), which means your > program won't execute until ps terminates. > UNIX philosophy is to have programs start acting as soon as possible > -- in that case, as soon as the first line is available. You should be > reading sys.stdin as an iterator (same thing you'd do for a file): > > import sys > for line in sys.stdin: > # do stuff with that line of input Aha, that makes sense. Thanks very much. Nick . From nick at javacat.f2s.com Tue Mar 1 23:28:02 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Mar 1 23:26:45 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109715774.4224eb3e7dc38@www.paradise.net.nz> References: <1109714880.10412.5.camel@fuzzbox.local> <4224E94F.7070403@speakeasy.net> <1109715774.4224eb3e7dc38@www.paradise.net.nz> Message-ID: <1109716082.10412.17.camel@fuzzbox.local> On Wed, 2005-03-02 at 11:22 +1300, jfouhy@paradise.net.nz wrote: > Quoting Sean Perry : > > > for line in sys.stdin.readlines(): > > # handle the line > > > > I tend to use xreadlines() which does not read the entire input at once. > > xreadlines() these days just does 'return self', I believe. File objects are > their own iterators; you can just do: > > for line in sys.stdin: > # do stuff > Same as Max Noel said, must be a good idea ;) Thankyou Nick . From jfouhy at paradise.net.nz Tue Mar 1 23:28:37 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue Mar 1 23:28:41 2005 Subject: [Tutor] reading from stdin In-Reply-To: <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> References: <1109714880.10412.5.camel@fuzzbox.local> <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> Message-ID: <1109716117.4224ec95cedec@www.paradise.net.nz> Quoting Max Noel : > UNIX philosophy is to have programs start acting as soon as possible > -- in that case, as soon as the first line is available. You should be > reading sys.stdin as an iterator (same thing you'd do for a file): > > import sys > for line in sys.stdin: > # do stuff with that line of input Is this sufficient? I tried to write a test program to get that behaviour.. ----- produce.py ----- #!/usr/bin/python import time for i in xrange(10): time.sleep(1) print i ----- read.py ----- #!/usr/bin/python import sys for line in sys.stdin: print line.strip() -------------------- If I do: $ ./produce.py | ./read.py I get nothing for ten seconds, then I get the numbers 0 through 9, one per line. What am I missing? -- John. From shaleh at speakeasy.net Wed Mar 2 00:01:53 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Wed Mar 2 00:03:11 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109716117.4224ec95cedec@www.paradise.net.nz> References: <1109714880.10412.5.camel@fuzzbox.local> <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> <1109716117.4224ec95cedec@www.paradise.net.nz> Message-ID: <4224F461.6070307@speakeasy.net> jfouhy@paradise.net.nz wrote: > If I do: > > $ ./produce.py | ./read.py > > I get nothing for ten seconds, then I get the numbers 0 through 9, one per line. > > What am I missing? > From the python man page: -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop. From peterm at ccs.neu.edu Wed Mar 2 00:15:19 2005 From: peterm at ccs.neu.edu (Peter Markowsky) Date: Wed Mar 2 00:15:32 2005 Subject: [Tutor] reading from stdin In-Reply-To: <4224F461.6070307@speakeasy.net> References: <1109714880.10412.5.camel@fuzzbox.local> <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> <1109716117.4224ec95cedec@www.paradise.net.nz> <4224F461.6070307@speakeasy.net> Message-ID: <0e6638a7b01ece43210021cdcdf32345@ccs.neu.edu> Hi, On Mar 1, 2005, at 6:01 PM, Sean Perry wrote: > jfouhy@paradise.net.nz wrote: >> If I do: >> $ ./produce.py | ./read.py >> I get nothing for ten seconds, then I get the numbers 0 through 9, >> one per line. >> What am I missing? > > From the python man page: > -u > Force stdin, stdout and stderr to be totally unbuffered. On > systems where it matters, also put stdin, stdout and stderr in binary > mode. Note that there is internal buffering in xreadlines(), > readlines() and file-object iterators ("for line in sys.stdin") which > is not influenced by this option. To work around this, you will want > to use "sys.stdin.readline()" inside a "while 1:" loop. > What exactly is the "right" way to put sys.stdin in unbuffered mode? in another program I've tried to accomplish that by doing something like this import os import fcntl <...> stdinfd = sys.stdin.fileno() fcntl.fcntl(stdinfd, fcntl.F_SETFL, os.O_NONBLOCK) ... and then calling later data = sys.stdin.read(numbytes) is this correct? -Pete From james.sweeney at ieee.org Wed Mar 2 00:22:08 2005 From: james.sweeney at ieee.org (James O. Sweeney) Date: Wed Mar 2 00:17:35 2005 Subject: [Tutor] Setting up a database Message-ID: <0ICP00KVS4P83TO1@vms040.mailsrvcs.net> Hello, I have an assignment that entails entering cash transactions as records. The significant record fields are a date/time stamp, the amount, and whether the transaction is a deposit or withdrawal. My question is about setting up the database file. In Python there is a dictionary function but it looks as if only one value can be assigned to the key (I intend to make the key the timestamp). The file has to be searchable so that reports can be pulled regarding amount, date range, etc. - the usual things one would do with a database. I can't figure if I can make a query on a multi-field record in Python without engaging a dependency such a storing the record in a mySQL database and querying it from Python. I'm having real burnout with this and would appreciate a point in the right direction. Much Thanks, James -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050301/4c47f2b1/attachment.htm From hugonz-lists at h-lab.net Wed Mar 2 00:35:55 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed Mar 2 00:35:57 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109714880.10412.5.camel@fuzzbox.local> References: <1109714880.10412.5.camel@fuzzbox.local> Message-ID: <4224FC5B.9040204@h-lab.net> Everypne else has answered pretty muh about this. I just want to add that if you want to read noncanonically (less thana line ending in "\n" you'll have to do it char by char =( AFAIK, there's no way to redefine a separator por readlines() (other than \n..) Hugo Nick Lunt wrote: > Hi folks, > > I've been pondering how to get python to read from a pipe outside of > itself, sort of. > > For example I tried a simple python prog to do a grep, eg > > # ps -e | myprog.py cron > > would give this output > > 3778 ? 00:00:00 crond > > same as > # ps -e | grep cron > > The way I did this was to use sys.stdin.readlines() to get the output > from the pipe. > > Here is the program: > > [code] > import sys, glob > args = sys.stdin.readlines() # found on the net > pat = sys.argv[1] > for i in args: > if (i.find(pat) != -1): > print i, > [/code] > > My question is am I getting the output from the pipe in the correct > way ? The way Im doing it works (so far) but should I be doing it > another way ? > > Many thanks > Nick . > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Wed Mar 2 01:27:19 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 2 01:27:24 2005 Subject: [Tutor] Tab delim file In-Reply-To: <20050301222158.42380.qmail@web53503.mail.yahoo.com> References: <1109714880.10412.5.camel@fuzzbox.local> <20050301222158.42380.qmail@web53503.mail.yahoo.com> Message-ID: Hi Srinivas, You want to use the csv module, it's designed for this kind of stuff. http://docs.python.org/lib/module-csv.html So, I think for your thing you'd want = import csv f1 = open('my_file.txt','r') reader = csv.reader(f1) reader.delimiter = '\t' fileA = [] fileB = [] for row in reader: toA = [] toB = [] for i in range(len(row)): if i <= 12: toA.append(row[i]) else: toB.append(row[i]) fileA.append(toA) fileB.append(toB) You may want to play with this, I'm not sure if I set the reader's delimiter right. But \t is tab. Good luck, Liam Clarke On Tue, 1 Mar 2005 14:21:58 -0800 (PST), Srinivas Iyyer wrote: > Hello: > > I have a nasty file where I have 165 column and 140K > lines. > > For every 12 columns, a new dataset is written. > > 0-12 - File A's data is there > 13-24 - File B's data is there. > > My task is to write data in each 12 columns to a file. > > I have a rough idea, but when I try I am unable to > proceed further. > > f1 = open('my_file.txt','r') > aml = f1.read().split('\n') > > fLine = aml[0] > > k = len(fLine)/12 # k = 162/12 > > #So I want to jump k blocks and get the text. > > for line in aml: > cols = line.split('\t') > while i > 13: > ...... > I am lost from here... > > Every 4 line(row) contains the file name on which I > have to write the file. > > can any one plese help, i am really stuck in a > problem. > > thanks > srini > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dyoo at hkn.eecs.berkeley.edu Wed Mar 2 01:35:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 2 01:40:28 2005 Subject: [Tutor] Setting up a database In-Reply-To: <0ICP00KVS4P83TO1@vms040.mailsrvcs.net> Message-ID: On Tue, 1 Mar 2005, James O. Sweeney wrote: > I have an assignment that entails entering cash transactions as records. Hi James, Just to make it clear: we are prohibited from doing homework questions. Since it's an assignment, we'll try to stay clear of direct solutions. > My question is about setting up the database file. In Python there is a > dictionary function but it looks as if only one value can be assigned to > the key (I intend to make the key the timestamp). A dictionary can be used to associate a single key with multiple values. If we let each value be a list, then we can do a 'key' to 'records' mapping: ### >>> d = {} >>> def addTally(name): ... d.setdefault(name[0], []).append(name) ... >>> addTally('john') >>> addTally('brian') >>> addTally('jane') >>> addTally('alice') >>> addTally('bob') >>> d {'a': ['alice'], 'j': ['john', 'jane'], 'b': ['brian', 'bob']} ### Here, we can see that the key 'john' can be associated with multiple values. The body above: ###### d.setdefault(name[0], []).append(name) ###### is shorthand for: ###### if name not in d: d[name[0]] = [] d[name[0]].append(name) ###### > The file has to be searchable so that reports can be pulled regarding > amount, date range, etc. - the usual things one would do with a > database. The direct solution would be to use a database here. > I can't figure if I can make a query on a multi-field record in Python You can. Conceptually, if you can make a query into a predicate, then you can always do a linear scan: ### Pseudocode def doQuerySearch(): resultSet = [] for record in allRecordsInDatabase: if satisfiesQuery(record): resultSet.append(record) return resultSet ### And satisfiesQuery() can do whatever it needs to do to see if the record is a good one or not. The problem here is one of efficiency: this is a linear scan. For small databases, this is fine. For larger ones, it might not be so good. Databases use indices and other optimization strategies to avoid a linear scan across the entire database. Dictionaries are one tool at our disposal that allow us to avoid linear scans. If we use several dictionaries, then we might even be able to do quick lookup on different fields. But a lot of the work behind databases involves figuring out which field constraint will cut down on the number of candidates most effectively, and that's hard work. That's why, if you can, you probably should use a real database. Best of wishes to you. From cyresse at gmail.com Wed Mar 2 01:40:31 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 2 01:40:34 2005 Subject: [Tutor] Setting up a database In-Reply-To: <0ICP00KVS4P83TO1@vms040.mailsrvcs.net> References: <0ICP00KVS4P83TO1@vms040.mailsrvcs.net> Message-ID: While we generally don't get too specific with assignments and/or homework - For a traditional database, you'd have to go the mySQL route. A dictionary is good, but for only one discreet key. That said, you could do it with objects like this - dictOfTransactionObjects = {} class CashTransaction: def __init__(self, amount, depOrWith): self.amount=float(amount) self.transactionType = depOrWith #...do various things which get the various values dateStamp, amount, transType dictOfTransactionObjects[dateStamp] = CashTransaction(amount, transType) So, now your dictionary will be {'01/05/2004-22:00:00' : } And you could search either by the dictionary key which is acting like a primary key, (the timestamp) or like this - isWith = [] for (key, item) in dictOfTransactionObjects.items(): if item.transactionType == 'Withdrawal': isWith.append(key) And isWith becomes a list of primary keys of withdrawals. That said, I would use SQL queries instead, it's a lot more straightforward, you'll end up reinventing several wheels this way. Regards, Liam Clarke On Tue, 01 Mar 2005 18:22:08 -0500, James O. Sweeney wrote: > > > > Hello, > > I have an assignment that entails entering cash transactions as records. The > significant record fields are a date/time stamp, the amount, and whether the > transaction is a deposit or withdrawal. My question is about setting up the > database file. In Python there is a dictionary function but it looks as if > only one value can be assigned to the key (I intend to make the key the > timestamp). The file has to be searchable so that reports can be pulled > regarding amount, date range, etc. ? the usual things one would do with a > database. I can't figure if I can make a query on a multi-field record in > Python without engaging a dependency such a storing the record in a mySQL > database and querying it from Python. I'm having real burnout with this and > would appreciate a point in the right direction. > > Much Thanks, > > James > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dyoo at hkn.eecs.berkeley.edu Wed Mar 2 01:37:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 2 01:42:28 2005 Subject: [Tutor] Setting up a database In-Reply-To: Message-ID: > ### > >>> d = {} > >>> def addTally(name): > ... d.setdefault(name[0], []).append(name) > ... > >>> addTally('john') > >>> addTally('brian') > >>> addTally('jane') > >>> addTally('alice') > >>> addTally('bob') > >>> d > {'a': ['alice'], 'j': ['john', 'jane'], 'b': ['brian', 'bob']} > ### > > > Here, we can see that the key 'john' can be associated with multiple > values. Hi James, Quick typo correction. I meant to write: """Here, we can see that the key 'j' can be associated with multiple values.""" My apologies! From missive at hotmail.com Wed Mar 2 02:26:20 2005 From: missive at hotmail.com (Lee Harr) Date: Wed Mar 2 02:27:04 2005 Subject: [Tutor] Re: open a socket from a named file on linux Message-ID: Sorry. I sent this yesterday but forgot the subject. Hope this helps point you in the right direction ... >I attempting to control xfmedia, >http://spuriousinterrupt.org/projects/xfmedia/ , via it's remote from >python and I can not get a connection. > >s = socket.fromfd('/tmp/xfmedia_remote.1001.0', socket.AF_UNIX, >socket.SOCK_STREAM) > >i get this error > >Traceback (most recent call last): > File "", line 1, in ? > >f = open('/tmp/xfmedia_remote.1001.0') >Traceback (most recent call last): > File "", line 1, in ? >IOError: [Errno 6] No such device or address: >'/tmp/xfmedia_remote.1001.0' > >yet ls shows the file exists, xfmedia is working fine. > I have not done this before, but I think you need to create a _new_ socket for your end, and then connect to the other socket. Does that make more sense? _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar - get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From david at graniteweb.com Wed Mar 2 06:13:35 2005 From: david at graniteweb.com (David Rock) Date: Wed Mar 2 06:17:31 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109715792.10412.11.camel@fuzzbox.local> References: <1109714880.10412.5.camel@fuzzbox.local> <4224E94F.7070403@speakeasy.net> <1109715792.10412.11.camel@fuzzbox.local> Message-ID: <20050302051335.GB1056@wdfs.graniteweb.com> * Nick Lunt [2005-03-01 22:23]: > On Tue, 2005-03-01 at 14:14 -0800, Sean Perry wrote: > > > > > unless you want the output for some other reason, a more idiomatic way > > is: > > > > for line in sys.stdin.readlines(): > > # handle the line > > > > I tend to use xreadlines() which does not read the entire input at once. > > For stdin this make sense, you have no idea how much data will be > > piped in. > > Thanks Sean, I agree with you on both accounts there. For another approach to this, I like to use the fileinput module. In the case of the original example of mimicing grep, it allows you to easily handle both a list of files passed to the command or use it as a pipe. The default action if there are no files given is to use stdin. http://www.python.org/doc/2.4/lib/module-fileinput.html -- 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/20050301/66fafd35/attachment.pgp From billk at fastmail.fm Wed Mar 2 07:17:28 2005 From: billk at fastmail.fm (Bill Kranec) Date: Wed Mar 2 07:17:29 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <42247232.1080409@tds.net> References: <4223DC44.6010506@fastmail.fm> <42247232.1080409@tds.net> Message-ID: <42255A78.6040909@fastmail.fm> Hi Kent, First off, thank you so much for the suggestions! They have helped clarify some of the concepts I've been struggling with lately ( mostly object - related ones ). I have been teaching myself Python in my spare time for the last few months, and have no previous programming experience, so any feedback I get really helps me improve as a programmer. I have implemented some of the changes you talked about, and posted an updated version of my program here: http://rafb.net/paste/results/SicsjJ23.html I hope this new version is a bit better, and that my answers to your questions help you understand what I'm doing. > do you mean, 'each player is teammates with each other player exactly > once', or, 'each player is teammates with each other player at most > once'? Is there a certain number of rounds that must be played? Each player is teammates with each other player exactly once. > - Why do you have the initialization code in a comment? Wouldn't it be > helpful to put that in a function or maybe Tournament.__init__()? The initialization code is commented because I don't run it every time the script runs ( it takes awhile to run ). I usually load the list from a file, this is reflected in my updated code. > - I have a hard time figuring out how this is supposed to work. Maybe > some comments about the algorithm you are using would help? I have no > idea what self.key is doing. My algorithm works something like this: Fact: roundlist partitions into 11 slices of length 113400, and self.key keeps track of which round in each of those slices I am currently using. Starting with the first tournament ( Tournament(0) ), I do the following: 1. Construct the tournament. 2. Test to see if two players are on the same team twice ( checkTeammates ) 3. Test to see if two players match up against each other too often (checkOpponents ) 4a. If everything is ok, I'll append another round from the next slice. 4b. If not, I'll try the next round in the most recent slice. If none of the rounds in the slice work, I'll move back and try the next round in the previous slice, etc. 5. Whenever I manage to build an 11 round tournament, I'm done. It's an attempt at a recursive algorithm, and I'm not sure how well it is implemented. > - What is the argument to Tournament.__init__() for? The argument lets you specify a starting tournament, to avoid having to start the search from the beginning, you can instead pick up from some point where you last left off. Example: Tournament(0,113460) gives a two round tournament using elements 0, 113460 from roundlist. > - The above code depends on roundlist which is not even defined > anywhere in the module (just shown in the comment). This suggests > again that the init code from the comment should be part of > Tournament, and roundlist should be an attribute of Tournament. For a > class to depend on some external variable is bad design and will break > if the client code is in a different module from the class code > (roundlist will be in a different namespace than Tournament). I have always been uneasy about this, but I wanted to be able to define multiple tournament objects off of the same roundlist, to avoid generating the list every time a new object is created. I think what I really want to do is have a separate Round class, from which Tournament inherits the list of rounds. I have started to implement something like this in my most recent version, but haven't finished it yet. ( I need to understand class inheritance better. ) > - Tournament.next() doesn't return a value, it prints it directly. It > should return self.key or str( self.key ) Does the next() call in an iterator object need to return a value, and if so, why? ( My reasoning was that next() only needs to increment the iterator. ) Thanks again for any additional suggestions! Bill From jeffshannon at gmail.com Wed Mar 2 08:44:43 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Wed Mar 2 08:44:47 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <42255A78.6040909@fastmail.fm> References: <4223DC44.6010506@fastmail.fm> <42247232.1080409@tds.net> <42255A78.6040909@fastmail.fm> Message-ID: <5d0204a1050301234415bcccd4@mail.gmail.com> On Wed, 02 Mar 2005 01:17:28 -0500, Bill Kranec wrote: > [...] I wanted to be able to define > multiple tournament objects off of the same roundlist, to avoid > generating the list every time a new object is created. I think what I > really want to do is have a separate Round class, from which Tournament > inherits the list of rounds. I have started to implement something like > this in my most recent version, but haven't finished it yet. ( I need > to understand class inheritance better. ) This sounds like a good idea, but inheritance is probably not the right way to solve it. Every Tournament contains a list of Rounds, but it's probably not accurate to say that a Tournament is a type of Round. (Inheritance works best when it describes an "is-a" relationship, not a "has-a" relationship.) It's probably better to have Tournament and Round be independent classes, but have Tournament instances hold a list of Rounds (which may be passed in during initialization, or may be added later). This is called "composition", and is just as important (or perhaps more important) of an idea as inheritance, even though inheritance gets all the press. ;) Jeff Shannon From nick at javacat.f2s.com Wed Mar 2 08:59:33 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed Mar 2 08:58:14 2005 Subject: [Tutor] reading from stdin In-Reply-To: <20050302051335.GB1056@wdfs.graniteweb.com> References: <1109714880.10412.5.camel@fuzzbox.local> <4224E94F.7070403@speakeasy.net> <1109715792.10412.11.camel@fuzzbox.local> <20050302051335.GB1056@wdfs.graniteweb.com> Message-ID: <1109750373.5012.0.camel@fuzzbox.local> Thanks to everyone who helped me with this. It's certainly given me something to think about :) Cheers Nick . On Tue, 2005-03-01 at 23:13 -0600, David Rock wrote: > * Nick Lunt [2005-03-01 22:23]: > > On Tue, 2005-03-01 at 14:14 -0800, Sean Perry wrote: > > > > > > > > unless you want the output for some other reason, a more idiomatic way > > > is: > > > > > > for line in sys.stdin.readlines(): > > > # handle the line > > > > > > I tend to use xreadlines() which does not read the entire input at once. > > > For stdin this make sense, you have no idea how much data will be > > > piped in. > > > > Thanks Sean, I agree with you on both accounts there. > > For another approach to this, I like to use the fileinput module. In the > case of the original example of mimicing grep, it allows you to easily > handle both a list of files passed to the command or use it as a pipe. > The default action if there are no files given is to use stdin. > > http://www.python.org/doc/2.4/lib/module-fileinput.html > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From nick at javacat.f2s.com Wed Mar 2 09:19:51 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed Mar 2 09:18:34 2005 Subject: [Tutor] reading from stdin In-Reply-To: <4224FC5B.9040204@h-lab.net> References: <1109714880.10412.5.camel@fuzzbox.local> <4224FC5B.9040204@h-lab.net> Message-ID: <1109751591.5278.0.camel@fuzzbox.local> Hi Hugo, many thanks for pointing that out. It all helps :) Thanks again, Nick . On Tue, 2005-03-01 at 17:35 -0600, Hugo Gonz?lez Monteverde wrote: > Everypne else has answered pretty muh about this. I just want to add > that if you want to read noncanonically (less thana line ending in "\n" > you'll have to do it char by char =( AFAIK, there's no way to redefine a > separator por readlines() (other than \n..) > > Hugo > > Nick Lunt wrote: > > Hi folks, > > > > I've been pondering how to get python to read from a pipe outside of > > itself, sort of. > > > > For example I tried a simple python prog to do a grep, eg > > > > # ps -e | myprog.py cron > > > > would give this output > > > > 3778 ? 00:00:00 crond > > > > same as > > # ps -e | grep cron > > > > The way I did this was to use sys.stdin.readlines() to get the output > > from the pipe. > > > > Here is the program: > > > > [code] > > import sys, glob > > args = sys.stdin.readlines() # found on the net > > pat = sys.argv[1] > > for i in args: > > if (i.find(pat) != -1): > > print i, > > [/code] > > > > My question is am I getting the output from the pipe in the correct > > way ? The way Im doing it works (so far) but should I be doing it > > another way ? > > > > Many thanks > > Nick . > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > From carroll at tjc.com Wed Mar 2 10:02:22 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed Mar 2 10:02:31 2005 Subject: [Tutor] How to use threads ? In-Reply-To: Message-ID: On Tue, 1 Mar 2005, Mark Kels wrote: > Can anyone give me a very simple example on thread programming ? I don't think a simple example is possible, given that threads are inherently for slightly more complex processing than you ordinarily do. That being said, here's an example. This is a made-up process. It shows both queuing and an arbitrary number of threads. First, the imports: ########################### import random, os, time, sys import threading, Queue ########################### No, I'll define a class for the "work" to be performed. Basically, each work unit just specifies how much time the system is supposed to wait, in second; pretend that it's doing some amount of work that takes some number of seconds to be performed: ########################### class workunit(object): """ Sample object to be put on a queue similating work to be done. variables: counter: a serial number just for identification purposes. waittime: the time in second it uses up. Done: a flag used for a special-purpose end-of-queue sentinel, in which case waittime is ignored. """ counter = 1 def __init__(self, waittime=0, Done=False): self.counter = workunit.counter self.waittime = waittime self.Done = Done workunit.counter += 1 ########################### This will be called in one of two ways: w = workunit(waittime=20) # to indicate wait for 20 seconds; or w = workunit(Done=True) # to add a "dummy" work unit to the queue so # everyone know the queue is empty and finished. Okay, imagine a queue (or just a list) full of work units like the above. Here's a plain old sequential NON-THREAD way of processing this: ########################### def ProcessQueue(work_queue): """ Method to process an element from the queue (Non-Threaded implementation). All it does is loop, doing the following: pull an element from the queue (break out if it's a "Done" marker) print a starting message; wait for the specified amount of time; print an ending message """ while True: queue_entry = work_queue.get() if queue_entry.Done: break print "%s starting on workunit %d, %d secs" % \ (time.asctime(), queue_entry.counter, queue_entry.waittime) time.sleep(queue_entry.waittime) print "%s ending for workunit %d" % \ (time.asctime(), queue_entry.counter) ############################ Okay, understand that, first See what it's doing? It's just popping things off the work_queue, printing a message, waiting for the indicated amount of time in the work unit, and printing another message; then starting over. Now, let's try the same approach with threads. Firrst, the class declaration: ############################# class ThreadProcessQueue(threading.Thread): """ This is a Threaded equivalent to ProcessQueue(). """ ############################# Now, here's the ThreadProcessQueue.__init__: ############################# def __init__(self, threadname, work_queue, **kwds): self.tname = threadname self.work_queue = work_queue threading.Thread.__init__(self, **kwds) print "%s Thread %s started" % (time.asctime(), self.tname) ############################# The parameters here are an arbitrary name for the thread, and the queue it will process. All __init__ does is print a message that the thread started. Here's the guts of it, the ThreadProcessQueue.__run__ method. NOte how similar it is to the non-Threaded version: ############################# def run(self): while True: queue_entry = work_queue.get() if queue_entry.Done: break print "%s Thread %s starting on workunit %d, %d secs" % \ (time.asctime(), self.tname, queue_entry.counter, queue_entry.waittime) time.sleep(queue_entry.waittime) print "%s Thread %s ending for workunit %d" % \ (time.asctime(), self.tname, queue_entry.counter) print "%s %s thead ending." % (time.asctime(), self.tname) self.work_queue.put(queue_entry) ############################# The only real difference is that the messages produced include an identifier so you can see which thread is generating which message; and also there's that self.work_queue.put(queue_entry) at the end. I'll discuss that at the end of this message. Now, here's the main program that uses these. First some setup: ############################ print "MAIN: %s starting..." % (time.asctime()) work_queue = Queue.Queue() NumWorkUnits=8 NumThreads=3 WaitTimes = [3,6,9,12,1,5,5,1] lenWaitTimes = len(WaitTimes) # WaitTimes is just a list of some arbitrary times representing work # A particular WorkUnit will wait for one of these times. ThreadList=[] ########################### Queue is s specialized type of FIFO list, which is made to be shared among concurrently running threads. We use that instead of a plain list. NumWorkUnits and NumThreads are just constants, for the number of work units that we'll put in the queue, and the number of threads that will read from them. WaitTimes is just an arbitrary list of numbers that we'll randomly select from later. Every work unit will get a random one of these, which indicates how long it should take to be processed (e.g., 1 for a 1-second workunit, 12 for a 12-second workunit, etc. ThreadList is a list that will contain all the threads. Let's get those threads going: ################################# # make up a list of threads (not started yet) for i in range(1,NumThreads+1): ThreadName = "T%03d" % i ThreadList.append(ThreadProcessQueue(ThreadName, work_queue)) ################################# Okay, this has created three threads (NumThreads = 3), with names T001, T002 and T003. Each has been passed the work_queue (which is still empty), and all three threads have been added to the ThreadList. The threads all exist at this point, but have not yet been started. That's next: ############################### # start the Threads for t in ThreadList: t.start() print "%s MAIN: all threads started" % (time.asctime()) ############################### This just starts the threads. The __run__ method in each thread starts running. The problem is, with the work queue empty, they'll just sit there. So, let's start putting stuff into the work queue: ############################### # Start putting things on the queue for i in range(NumWorkUnits): random_wait = WaitTimes[int(random.uniform(0,len(WaitTimes)))] w = workunit(random_wait) work_queue.put(w) ############################### This just selects a random amount of time to wait from the WaitTimes list, creates a work unit specifying that amount of time, and puts the workunit on the queue. At this point, the threads should start waking up; they were all sitting on a queue.get for an empty queue. NOw that they can start pulling things off of it, they will. I also want to put an end-of-queue element here: ############################### # Put a shutdown indicator work_queue.put(workunit(Done=True)) ############################### That's it! Just for grins, we can add a "final" shutdown message: ############################ print "%s MAIN: all done." % (time.asctime()) ############################ But you'll see that doesn't work very well. Here's what I see as output on one run: Wed Mar 02 00:40:05 2005 MAIN starting... Wed Mar 02 00:40:05 2005 Thread T001 started Wed Mar 02 00:40:05 2005 Thread T002 started Wed Mar 02 00:40:05 2005 Thread T003 started Wed Mar 02 00:40:05 2005 MAIN: all threads started Wed Mar 02 00:40:05 2005 Thread T001 starting on workunit 1, 5 secs Wed Mar 02 00:40:05 2005 Thread T002 starting on workunit 2, 12 secs Wed Mar 02 00:40:05 2005 Thread T003 starting on workunit 3, 9 secs Wed Mar 02 00:40:05 2005 MAIN: all done. Wed Mar 02 00:40:10 2005 Thread T001 ending for workunit 1 Wed Mar 02 00:40:10 2005 Thread T001 starting on workunit 4, 6 secs Wed Mar 02 00:40:14 2005 Thread T003 ending for workunit 3 Wed Mar 02 00:40:14 2005 Thread T003 starting on workunit 5, 12 secs Wed Mar 02 00:40:16 2005 Thread T001 ending for workunit 4 Wed Mar 02 00:40:16 2005 Thread T001 starting on workunit 6, 12 secs Wed Mar 02 00:40:17 2005 Thread T002 ending for workunit 2 Wed Mar 02 00:40:17 2005 Thread T002 starting on workunit 7, 1 secs Wed Mar 02 00:40:18 2005 Thread T002 ending for workunit 7 Wed Mar 02 00:40:18 2005 Thread T002 starting on workunit 8, 1 secs Wed Mar 02 00:40:19 2005 Thread T002 ending for workunit 8 Wed Mar 02 00:40:19 2005 T002 thead ending. Wed Mar 02 00:40:26 2005 Thread T003 ending for workunit 5 Wed Mar 02 00:40:26 2005 T003 thead ending. Wed Mar 02 00:40:28 2005 Thread T001 ending for workunit 6 Wed Mar 02 00:40:28 2005 T001 thead ending. >From the queue's point of view, here is how the work got parcelled out among threads: Work units: 1: 5 sec (T001) 2: 12 sec (T002) 3: 9 sec (T003) 4: 6 sec (T001) 5: 12 sec (T003) 6: 12 sec (T001) 7: 1 sec (T002) 8: 1 sec (T002) Here's a graphical view of what the threads were doing: T001: 11111444444666666666666 T002: 22222222222278 T003: 333333333555555555555 You can see that T002 ended first, followed by T003 and then T001 (which matches the timestamps). Okay, a couple oddities. First, that self.work_queue.put(queue_entry) line. This is so that when the first thread to see the Done marker sees it, it puts it back on the queue before it exits. That way, each of the other threads sees it, puts it back on for the next and exits. (I could have instead written this just to exeit when the queue was empty, but there are some ugly issues with that, too, for example, if the thing that loads up the queue pauses, the queue empties and all the threads quit, and then the queue loader adds more, with the threads already gone.) The other oddity: Note that the MAIN "final message" issued long before the threads were done. I wanted this example to nicely wait for all the threads to end before putting out that message, but couldn't figure out how to do that. For those familiar with threads: calls to t.isAlive() returned True long after the thread referred to had finished up and put out its final shitdown message. Anyway, I hope this helps as a bit of a tutorial. From linux236r4 at hotpop.com Wed Mar 2 11:48:19 2005 From: linux236r4 at hotpop.com (dm) Date: Wed Mar 2 11:48:26 2005 Subject: [Tutor] open a socket from a named file on linux In-Reply-To: <1109546297.14526.9.camel@bioblue> References: <1109546297.14526.9.camel@bioblue> Message-ID: <1109760499.14594.1.camel@bioblue> On Sun, 2005-02-27 at 17:18 -0600, dm wrote: > Hello, I am trying to open a socket connection to a named file on my > computer and can not seem to get it working. Any help or advice would > be great. solution use what are called unix domain sockets, in python they are accessed like this s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect('/tmp/xfmedia_remote.1001.0') now s is a normal socket object. From kent37 at tds.net Wed Mar 2 13:23:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 2 13:23:06 2005 Subject: [Tutor] Re: Help- Simple recursive function to build a list In-Reply-To: <4225455D.6030808@elemental-systems.com> References: <42252a53_2@newspeer2.tds.net> <4225455D.6030808@elemental-systems.com> Message-ID: <4225B024.2000605@tds.net> actuary77 wrote: > Kent Johnson wrote: >> >>> def rec(n,alist=[]): >> ... _nl=alist[:] >> ... print n,_nl >> ... if n == 0: >> ... print n,_nl >> ... return _nl >> ... else: >> ... _nl=_nl+[n] >> ... return rec(n-1,_nl) >> ... >> >>> _nl = rec(4) >> 4 [] >> 3 [4] >> 2 [4, 3] >> 1 [4, 3, 2] >> 0 [4, 3, 2, 1] >> 0 [4, 3, 2, 1] >> >>> print _nl >> [4, 3, 2, 1] >> >> Kent > > Kent, thank you for the answer. > > I just don't understand why. > > I only have one return at the point at the test of the end of the > recursion, n == 0. You have to return a result from each level of recursion. You have rec(4) <- this returns nothing to its caller rec(3, [4]) <- this returns nothing to its caller rec(2, [4,3]) <- this returns nothing to its caller rec(1, [4,3,2]) <- this returns nothing to its caller rec(0, [4,3,2,1]) <- this returns [4,3,2,1] to the call above By adding the missing 'return', you make all the intermediate invocations return the final result up the chain to their caller. This version shows what is happening: >>> def rec(n,alist=[]): ... _nl=alist[:] ... if n == 0: ... print n,_nl ... return _nl ... else: ... _nl=_nl+[n] ... print 'calling rec(', n-1, _nl, ')' ... val = rec(n-1,_nl) ... print 'rec(', n-1, _nl, ') returned', val ... return val ... >>> rec(4) calling rec( 3 [4] ) calling rec( 2 [4, 3] ) calling rec( 1 [4, 3, 2] ) calling rec( 0 [4, 3, 2, 1] ) 0 [4, 3, 2, 1] rec( 0 [4, 3, 2, 1] ) returned [4, 3, 2, 1] rec( 1 [4, 3, 2] ) returned [4, 3, 2, 1] rec( 2 [4, 3] ) returned [4, 3, 2, 1] rec( 3 [4] ) returned [4, 3, 2, 1] [4, 3, 2, 1] Kent PS Please send followups to the Tutor list so all may benefit from the discussion. > > I see from the output that the list is being built, up to the point of > the one and only return, > > if n == 0: > print n,_nl # 0 [4, 3, 2, 1] > return _nl # None, Why doesn't this return _nl = [4, 3, 2, 1]? > > I can see that the list is being built without the second return. > And even at the point where the end of the recursion is tested, n == 0, > the value to be returned, _nl is equal to the desired result? > The second return is never used! > The list being built is passed as an argument. > > Scope? > > Why is the second return required? > > Most confused ;( > > From shitizb at yahoo.com Wed Mar 2 18:03:43 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Mar 2 18:03:47 2005 Subject: [Tutor] Re: Online Programming Contest (Python solutions accepted) In-Reply-To: <1109765080.931561.250290@g14g2000cwa.googlegroups.com> Message-ID: <20050302170343.60015.qmail@web53802.mail.yahoo.com> Hi, some questions need to be addressed. First, is execution time a factor, bcos admittedly python sols r much slowere than c/c++. second, wats the exact conf of python installed on machines checking our sols. i.e. which modules r allowed n which r not. shitiz --- Sridhar wrote: > Hi, > > We, the students of CEG, Anna University [1] are > organizing an online > programming contest as part of aBaCus [2] 2005. The > contest itself > will start on 6th March 2005 at 1:00 pm IST [3] and > will end after 5 > hours. You have to solve the problems posted at the > start of the > contest. Teams ranking high will be awarded the > prizes. > > As a special note, inspite of C,C++ and Java we also > allow Python [4] > this time. So we hope a lot of Pythonistas also > could attend the > contest for fun. :-) > > For more details about the contest, visit the > contest page > > -- http://203.197.138.181/OPC -- > > [1] http://en.wikipedia.org/wiki/Anna_University > [2] http://www.annauniv.edu/abacus/ > [3] Indian Standard Time (IST) is the time zone for > India. It is 5 > hours and 30 minutes ahead of GMT/UTC. > [4] http://www.python.org > > -- > Sridhar Ratna - http://srid.bsdnerds.org > > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From s.varun at gmail.com Wed Mar 2 19:20:42 2005 From: s.varun at gmail.com (Varun Soundararajan) Date: Wed Mar 2 19:20:46 2005 Subject: [Tutor] Re: Python Online Programming Contest In-Reply-To: <32b5ee76050224114510c9cd5e@mail.gmail.com> References: <32b5ee76050224114510c9cd5e@mail.gmail.com> Message-ID: <32b5ee760503021020557ea67a@mail.gmail.com> Hi, The results of OPC (online programming contest) is out. The statistics of python usage is available at http://www.samhita.info/opc/status.php. Regards, -OPC Team From mark.kels at gmail.com Wed Mar 2 20:35:56 2005 From: mark.kels at gmail.com (Mark Kels) Date: Wed Mar 2 20:36:00 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <20050301202537.62490.qmail@web53804.mail.yahoo.com> References: <20050301202537.62490.qmail@web53804.mail.yahoo.com> Message-ID: On Tue, 1 Mar 2005 12:25:37 -0800 (PST), Shitiz Bansal wrote: > > Here is a simple program > > class abc(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > self.x=1 etc. etc..... > self.cont_flag=1 > def run(self): > while self.cont_flag: > print self.x > (you can set the self.cont_falg to zero > whenever you wish to end the loop(and > hence > the thread., either > here, or even from outside the thread. > of course, it isnt necessary that your > thread is a loop, it can be a finite > function.) > Thanks alot !! I think I got it ths time. The only problem is that when I try to do it my thread doesnt closes. When does a thread closes ? Thanks again. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From gwyn.evans at gmail.com Wed Mar 2 21:34:18 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Wed Mar 2 21:34:22 2005 Subject: [Tutor] Threaded persistance? Message-ID: Hi, New to Python, but with Java background I'm interested in comments/suggestions for something I'm trying... I've got a series of events (basically a dictionary of a few key:value pairs) which I'd like to forward onto a web service. That should be no problem, but I'm investigating what I can do when the web service is down for a bit. What I'm considering is to persist the event and trigger a seperate thread to retry the forwarding. What I'm wondering about is if there's a storage method that allows 1 thread writing to the storage while the other thread reads and then deletes from the storage... I had a look at using ZODB but hit problems when trying to have two connections to the same FileStorage DB, but a second look at things suggested that dbm might well do what I need, if I ensure only one thread at a time can access it. /Gwyn From kent37 at tds.net Wed Mar 2 21:53:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 2 21:53:15 2005 Subject: [Tutor] Threaded persistance? In-Reply-To: References: Message-ID: <422627BD.6020304@tds.net> Gwyn Evans wrote: > Hi, > New to Python, but with Java background I'm interested in > comments/suggestions for something I'm trying... > > I've got a series of events (basically a dictionary of a few > key:value pairs) which I'd like to forward onto a web service. That > should be no problem, but I'm investigating what I can do when the web > service is down for a bit. > What I'm considering is to persist the event and trigger a seperate > thread to retry the forwarding. What I'm wondering about is if > there's a storage method that allows 1 thread writing to the storage > while the other thread reads and then deletes from the storage... Do you need to allow for the sending thread to be restarted as well? In other words, does the queue have to be persistent? If not, you could use Queue.Queue which is intended for this kind of inter-thread communication. Kent From nixonron at yahoo.com Wed Mar 2 21:54:04 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Wed Mar 2 21:54:07 2005 Subject: [Tutor] Better Search and replace method Message-ID: <20050302205404.33444.qmail@web20326.mail.yahoo.com> I'm trying to figure out a better solution to do multiple search and replaces in a text file without having to type: import re s = open('filename') re.sub('vaule1','value2',s) re.sub('vaule3','value4',s) etc I've tried putting all the vaules in a list and doing the replace, but came up short. Any suggestions? Thanks in advance Ron __________________________________ Celebrate Yahoo!'s 10th Birthday! Yahoo! Netrospective: 100 Moments of the Web http://birthday.yahoo.com/netrospective/ From gwyn.evans at gmail.com Wed Mar 2 21:59:35 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Wed Mar 2 21:59:44 2005 Subject: [Tutor] Threaded persistance? In-Reply-To: <422627BD.6020304@tds.net> References: <422627BD.6020304@tds.net> Message-ID: On Wed, 02 Mar 2005 15:53:17 -0500, Kent Johnson wrote: > Gwyn Evans wrote: > > Hi, > > New to Python, but with Java background I'm interested in > > comments/suggestions for something I'm trying... > > > > I've got a series of events (basically a dictionary of a few > > key:value pairs) which I'd like to forward onto a web service. That > > should be no problem, but I'm investigating what I can do when the web > > service is down for a bit. > > What I'm considering is to persist the event and trigger a seperate > > thread to retry the forwarding. What I'm wondering about is if > > there's a storage method that allows 1 thread writing to the storage > > while the other thread reads and then deletes from the storage... > > Do you need to allow for the sending thread to be restarted as well? In other words, does the queue > have to be persistent? If not, you could use Queue.Queue which is intended for this kind of > inter-thread communication. Ideally, yes, although the main issue I was concerned about with Queue.Queue was that I didn't want to be be limited by memory size... I guess the final fallback would be going straight to a full-blown DB with a connection from each thread, but I'm not sure if it's a bit over the top... /Gwyn From gwyn.evans at gmail.com Wed Mar 2 22:15:50 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Wed Mar 2 22:15:53 2005 Subject: [Tutor] Re: Threaded persistance? In-Reply-To: References: Message-ID: On Wed, 2 Mar 2005 20:34:18 +0000, Gwyn Evans wrote: > I had a look at using ZODB but hit problems when trying to have two > connections to the same FileStorage DB, but a second look at things > suggested that dbm might well do what I need, if I ensure only one > thread at a time can access it. When I found I had the same sort of issue with dbm I had a closer look and realised that my test code was tidying up too quickly and closing the DB before the test had actually finished, so it looks as if ZODB's still in the picture! /Gwyn From carroll at tjc.com Wed Mar 2 22:48:51 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed Mar 2 22:48:54 2005 Subject: [Tutor] How to use threads ? In-Reply-To: Message-ID: On Wed, 2 Mar 2005, Mark Kels wrote: > The only problem is that when I try to do it my thread doesnt closes. > When does a thread closes ? You got me. That's what I meant when I wrote "calls to t.isAlive() returned True long after the thread referred to had finished up and put out its final [shutdown] message." I don't know what it would take to have a t.isAlive() call ever come back as False. I may experiment a bit. That tutorial and program was put together on the fly late last night, and I didn't have the opportunity to look into that issue. From alan.gauld at freenet.co.uk Wed Mar 2 23:19:45 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Mar 2 23:19:48 2005 Subject: [Tutor] Better Search and replace method References: <20050302205404.33444.qmail@web20326.mail.yahoo.com> Message-ID: <004601c51f75$f12b7940$1cd28751@xp> > I'm trying to figure out a better solution to do > multiple search and replaces in a text file without > having to type: > import re > s = open('filename') s = open(...).read() # I assume? > re.sub('vaule1','value2',s) > re.sub('vaule3','value4',s) > I've tried putting all the vaules in a list and doing > the replace, but came up short. Any suggestions? Without seeing what you tried or what the results were I can only guess... But did you try storing the values as a list of tuples, or as a dictionary? values = [ (vaule1, value2), (vaule3,value4),...] for target,replace in values: re.sub(target,replace,s) OR values = { 'vaule1' : 'value2', 'vaule3' : 'value4', .....} for target in values.keys(): re,sub(target,values[target],s) Finally do you need re? Or could the simple string methods work? They'd be slightly faster... Alan G. From kent37 at tds.net Wed Mar 2 23:44:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 2 23:44:06 2005 Subject: [Tutor] Better Search and replace method In-Reply-To: <20050302205404.33444.qmail@web20326.mail.yahoo.com> References: <20050302205404.33444.qmail@web20326.mail.yahoo.com> Message-ID: <422641B1.1040709@tds.net> Ron Nixon wrote: > I'm trying to figure out a better solution to do > multiple search and replaces in a text file without > having to type: > import re > s = open('filename') > re.sub('vaule1','value2',s) > re.sub('vaule3','value4',s) > etc > > I've tried putting all the vaules in a list and doing > the replace, but came up short. Any suggestions? See this recipe which uses the ability of re.sub() to take a callable as the substitution parameter to do what you want. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 Kent From shitizb at yahoo.com Wed Mar 2 23:48:11 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Mar 2 23:48:16 2005 Subject: [Tutor] How to use threads ? In-Reply-To: Message-ID: <20050302224811.80682.qmail@web53804.mail.yahoo.com> The thread finishes when: 1.The run method finishes. 2.In case of the loop- you may - >>> import threading >>> class abc(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.cont_flag=1 def run(self): while self.cont_flag: pass >>> abcd=abc() >>> abcd >>> abcd.start() >>> abcd >>> abcd.cont_flag=0 >>> abcd Also, you may >>> del abcd >>> abcd Traceback (most recent call last): File "", line 1, in -toplevel- abcd NameError: name 'abcd' is not defined I am not very sure about the CPU usage of a stopped thread.Perhaps someone from the group can enlighten us. Hope this makes it clear. Cheers, Shitiz --- Mark Kels wrote: > On Tue, 1 Mar 2005 12:25:37 -0800 (PST), Shitiz > Bansal > wrote: > > > > Here is a simple program > > > > class abc(threading.Thread): > > def __init__(self): > > threading.Thread.__init__(self) > > self.x=1 etc. etc..... > > self.cont_flag=1 > > def run(self): > > while self.cont_flag: > > print self.x > > (you can set the self.cont_falg to zero > > whenever you wish to end the loop(and > > hence > > the thread., either > > here, or even from outside the thread. > > of course, it isnt necessary that your > > thread is a loop, it can be a finite > > function.) > > > Thanks alot !! > I think I got it ths time. > The only problem is that when I try to do it my > thread doesnt closes. > When does a thread closes ? > > Thanks again. > > -- > 1. The day Microsoft makes something that doesn't > suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about > it's friends. > 3. Documentation is like sex: when it is good, it is > very, very good. > And when it is bad, it is better than nothing. - > Dick Brandon > __________________________________ Celebrate Yahoo!'s 10th Birthday! Yahoo! Netrospective: 100 Moments of the Web http://birthday.yahoo.com/netrospective/ From tegmine at gmail.com Thu Mar 3 00:59:58 2005 From: tegmine at gmail.com (Luis N) Date: Thu Mar 3 01:00:02 2005 Subject: [Tutor] slow html generation code Message-ID: <77bfa81a05030215596064b8fd@mail.gmail.com> This code seems a little slow, is there anything in particular that jumps out as being not quite right. The idea is that a file is opened that contains path names to other files, that are appended and outputed into a directory of choice. I plan to move this off the filesystem into a database when the concept is worked out, maybe that will help. #!/usr/local/bin/python import sys import os from string import Template from textile import textile def main(files): if len(files) < 1: print 'Feed me with XHTML, String Templates, and Textile' else: path = os.path.expanduser('~/') publish = os.path.join(path, 'publish') pages = os.path.join(publish, 'pages') write = os.path.join(path, 'public_html/write') try: for i in files: page = os.path.join(write, i) f = open(os.path.join(pages, i), 'r') tmp = "" for line in f.readlines(): line = line.rstrip() structure = open(os.path.join(publish, line)) clean = structure.read() tmp = tmp + clean.rstrip() txt = textile(tmp) + '' t = Template(txt) s = t.safe_substitute(title='Web-siter: %s' % i[:-5]) output = open(page, 'w') output.write('') output.write(s) except: pass if __name__ == '__main__': main(sys.argv[1:]) From shaleh at speakeasy.net Thu Mar 3 01:12:45 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Thu Mar 3 01:14:03 2005 Subject: [Tutor] slow html generation code In-Reply-To: <77bfa81a05030215596064b8fd@mail.gmail.com> References: <77bfa81a05030215596064b8fd@mail.gmail.com> Message-ID: <4226567D.1020806@speakeasy.net> Luis N wrote: > This code seems a little slow, is there anything in particular that > jumps out as being not quite right. > > The idea is that a file is opened that contains path names to other > files, that are appended and outputed into a directory of choice. > > I plan to move this off the filesystem into a database when the > concept is worked out, maybe that will help. > You are reading entire file contents into memory. Once with f.readlines() and then again with structure.read(). If these are somewhat large files that could definitely be a place for slowness. If nothing else, Python promises garbage collection to be done, but not when. So many of your files could be sitting in memory. From dyoo at hkn.eecs.berkeley.edu Thu Mar 3 01:37:38 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 3 01:37:43 2005 Subject: [Tutor] slow html generation code In-Reply-To: <77bfa81a05030215596064b8fd@mail.gmail.com> Message-ID: On Wed, 2 Mar 2005, Luis N wrote: > This code seems a little slow, is there anything in particular that > jumps out as being not quite right. Hi Luis, Some comments: You have an empty 'except' exception-handling block in the code: ###### try: for i in files: page = os.path.join(write, i) ## ... code cut output.write(s) except: pass ###### Try not to do that. *grin* Having 'except: pass' is almost always a bad idea because it really makes it hard to debug problems. Make sure your exception handler does something useful: as it is, the code can disguise all sorts of bugs without giving any feedback to you. It's not clear at all what the benefit of the custom exception handler is in your code, so I'd recommend just dropping the try/except. Another thing is that the code is a big long: it might be worthwhile to break: > page = os.path.join(write, i) > f = open(os.path.join(pages, i), 'r') > tmp = "" > for line in f.readlines(): > line = line.rstrip() > structure = open(os.path.join(publish, line)) > clean = structure.read() > tmp = tmp + clean.rstrip() > txt = textile(tmp) + '' > t = Template(txt) > s = t.safe_substitute(title='Web-siter: %s' % i[:-5]) > output = open(page, 'w') > output.write('') > output.write(s) off into its own helper function. Let's pretend that we call this function 'writePage()': ###### def writePage(): ## FIXME: the argument list here isn't quite right yet page = os.path.join(write, i) f = open(os.path.join(pages, i), 'r') tmp = "" for line in f.readlines(): line = line.rstrip() structure = open(os.path.join(publish, line)) clean = structure.read() tmp = tmp + clean.rstrip() txt = textile(tmp) + '' t = Template(txt) s = t.safe_substitute(title='Web-siter: %s' % i[:-5]) output = open(page, 'w') output.write('') output.write(s) ###### This breakup isn't quite right yet, and this needs to take in some parameters. So it needs a little work. But this improves the code by allowing you to concentrate on what it means to write a single page. It also makes it easier to see a possible bug in the code: the last few lines in the 'for' loop look suspicious: ###### txt = textile(tmp) + '' t = Template(txt) s = t.safe_substitute(title='Web-siter: %s' % i[:-5]) output = open(page, 'w') output.write('') output.write(s) ###### It does look strange that the file is being open and rewritten over and over, for each line in the file. Are you sure you want to put that in the body of the loop? Best of wishes to you! From javier at ruere.com.ar Thu Mar 3 05:42:33 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Thu Mar 3 05:39:55 2005 Subject: [Tutor] Re: How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: <8584290042.20050301063922@columbus.rr.com> References: <12255145785.20050228223338@columbus.rr.com> <8584290042.20050301063922@columbus.rr.com> Message-ID: R. Alan Monroe wrote: >>R. Alan Monroe wrote: >> >>>I started writing a program to parse the headers of truetype fonts to >>>examine their family info. But I can't manage to print out the strings >>>without the zero bytes in between each character (they display as a >>>black block labeled 'NUL' in Scite's output pane) >>> >>>I tried: >>> stuff = f.read(nlength) >>> stuff = unicode(stuff, 'utf-8') > > >> If there are embeded 0's in the string, it won't be utf8, it could be >>utf16 or 32. >> Try: >> unicode(stuff, 'utf-16') >>or >> stuff.decode('utf-16') > > >>> print type(stuff), 'stuff', stuff.encode() >>>This prints: >>> >>> stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] > > >> I don't understand what you tried to accomplish here. > > > That's evidence of what I failed to accomplish. My expected results > was to print the word "Copyright" and whatever other strings are > present in the font, with no intervening NUL characters. Oh but why print type(stuff) or 'stuff'? > Aha, after some trial and error I see that I'm running into an endian > problem. It's "\x00C" in the file, which needs to be swapped to > "C\x00". I cheated temporarily by just adding 1 to the file pointer > :^) Ah! Endianness! I completely overlook this issue! I have lost several hours of my life to endian problems. Glad to see (on another post) there is an encoding which handles explicitly the endianness or the encoded string. Javier From kent37 at tds.net Thu Mar 3 05:48:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 3 05:48:59 2005 Subject: [Tutor] slow html generation code In-Reply-To: References: Message-ID: <42269736.3060006@tds.net> Danny Yoo wrote: > It also makes it easier to see a possible bug in the code: the last few > lines in the 'for' loop look suspicious: > > ###### > txt = textile(tmp) + '' > t = Template(txt) > s = t.safe_substitute(title='Web-siter: %s' % i[:-5]) > output = open(page, 'w') > output.write('') > output.write(s) > ###### > > It does look strange that the file is being open and rewritten over and > over, for each line in the file. Are you sure you want to put that in the > body of the loop? You are also passing the text through textile / Template / safe_substitute repeatedly. You probably want to accumulate all the text, process it once and write it to the file. Kent From gwyn.evans at gmail.com Thu Mar 3 12:08:59 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Thu Mar 3 12:09:46 2005 Subject: [Tutor] Re: Threaded persistance? In-Reply-To: References: Message-ID: On Wed, 2 Mar 2005 21:15:50 +0000, Gwyn Evans wrote: > On Wed, 2 Mar 2005 20:34:18 +0000, Gwyn Evans wrote: > > I had a look at using ZODB but hit problems when trying to have two > > connections to the same FileStorage DB, but a second look at things > > suggested that dbm might well do what I need, if I ensure only one > > thread at a time can access it. > > When I found I had the same sort of issue with dbm I had a closer > look and realised that my test code was tidying up too quickly and > closing the DB before the test had actually finished, so it looks as > if ZODB's still in the picture! I've put the code I've come up with at http://www.javaguy.co.uk/Python/TestCEH.html but as I'm new to Python, I'd appreciate any comments, if anyone have time to take a look. /Gwyn From kent37 at tds.net Thu Mar 3 12:50:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 3 12:50:28 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <42255A78.6040909@fastmail.fm> References: <4223DC44.6010506@fastmail.fm> <42247232.1080409@tds.net> <42255A78.6040909@fastmail.fm> Message-ID: <4226F9FF.4020008@tds.net> Bill Kranec wrote: > Hi Kent, >> - The above code depends on roundlist which is not even defined >> anywhere in the module (just shown in the comment). This suggests >> again that the init code from the comment should be part of >> Tournament, and roundlist should be an attribute of Tournament. For a >> class to depend on some external variable is bad design and will break >> if the client code is in a different module from the class code >> (roundlist will be in a different namespace than Tournament). > > > I have always been uneasy about this, but I wanted to be able to define > multiple tournament objects off of the same roundlist, to avoid > generating the list every time a new object is created. I think what I > really want to do is have a separate Round class, from which Tournament > inherits the list of rounds. I have started to implement something like > this in my most recent version, but haven't finished it yet. ( I need > to understand class inheritance better. ) Composition is a better solution than inheritance. You can have a separate Round class and pass an instance of Round to the constructor for Tournament. Tournament can save the instance and refer to it as needed. > >> - Tournament.next() doesn't return a value, it prints it directly. It >> should return self.key or str( self.key ) > > > Does the next() call in an iterator object need to return a value, and > if so, why? ( My reasoning was that next() only needs to increment the > iterator. ) To be an iterator it needs to return a value. This is the value that will be assigned to the loop variable. For example, this class looks like an iterator but it doesn't return any value from next(): class not_an_iterator: def __init__(self): self.i = 0 def __iter__(self): return self def next(self): if self.i < 5: print 'In next - i =', self.i self.i += 1 else: raise StopIteration If I use the class in a loop, the loop variable doesn't receive any value: for i in not_an_iterator(): print 'In loop - i =', i prints: In next - i = 0 In loop - i = None In next - i = 1 In loop - i = None In next - i = 2 In loop - i = None In next - i = 3 In loop - i = None In next - i = 4 In loop - i = None For the loop variable to get the values from next(), I have to return it: class is_an_iterator: def __init__(self): self.i = 0 def __iter__(self): return self def next(self): if self.i < 5: print 'In next - i =', self.i old_i = self.i self.i += 1 return old_i else: raise StopIteration for i in is_an_iterator(): print 'In loop - i =', i prints: In next - i = 0 In loop - i = 0 In next - i = 1 In loop - i = 1 In next - i = 2 In loop - i = 2 In next - i = 3 In loop - i = 3 In next - i = 4 In loop - i = 4 Incidentally, generator functions make it much easier to do this because they maintain state between calls automatically. I could write is_an_iterator as a generator like this: def is_a_generator(): i = 0 while i < 5: yield i i += 1 for i in is_a_generator(): print 'In loop - i =', i Kent From kent37 at tds.net Thu Mar 3 13:01:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 3 13:01:39 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <42255A78.6040909@fastmail.fm> References: <4223DC44.6010506@fastmail.fm> <42247232.1080409@tds.net> <42255A78.6040909@fastmail.fm> Message-ID: <4226FC9D.8020202@tds.net> Bill Kranec wrote: > Hi Kent, > > First off, thank you so much for the suggestions! They have helped > clarify some of the concepts I've been struggling with lately ( mostly > object - related ones ). I have been teaching myself Python in my spare > time for the last few months, and have no previous programming > experience, so any feedback I get really helps me improve as a programmer. > > I have implemented some of the changes you talked about, and posted an > updated version of my program here: > > http://rafb.net/paste/results/SicsjJ23.html > > I hope this new version is a bit better, and that my answers to your > questions help you understand what I'm doing. OK, some comments on the code. - I would make checkTeammates() and checkOpponents() return a boolean value rather than raising an exception. Then next() would have code like if self.checkTeammates( self.flattened ) and self.checkOpponents( self.flattened ): # add the round to the tournament else: # handle a bad round - You are (ab)using the iterator protocol essentially to implement a while loop. I would rename next() to something like makeTournament() and put the code in a loop like while len(self.rounds) < 11: ... You can return the final tournament if you want or just have the output from makeTournament() be the only result. - Instead of stdout.write( str( self.key ) + '\n' ) just use print self.key BTW what is magic about 113400? Kent From mark.kels at gmail.com Thu Mar 3 15:04:28 2005 From: mark.kels at gmail.com (Mark Kels) Date: Thu Mar 3 15:04:33 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <20050302224811.80682.qmail@web53804.mail.yahoo.com> References: <20050302224811.80682.qmail@web53804.mail.yahoo.com> Message-ID: On Wed, 2 Mar 2005 14:48:11 -0800 (PST), Shitiz Bansal wrote: > The thread finishes when: > 1.The run method finishes. > 2.In case of the loop- you may - > > >>> import threading > >>> class abc(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > self.cont_flag=1 > def run(self): > while self.cont_flag: > pass > > >>> abcd=abc() > >>> abcd > > >>> abcd.start() > >>> abcd > > >>> abcd.cont_flag=0 > >>> abcd > But for some reason it keeps working after its job is done in my app... Here is the class: (the app itself got some Entrys to get the input and a Button to start the go() and stop() functions) class scan(threading.Thread): def _init_(self): threading.thread._init_(self) def scanner(self): self.open_counter=0 self.flag='scan' try: host=host_e.get() start_port=int(start_port_e.get()) end_port=int(end_port_e.get()) except ValueError: tkMessageBox.showerror("Bad input","You must enter a vaild host IP and port numbers.") pass else: start.config(text="Stop",command=stop) root.update() result.insert(END,"Scanning "+str(host)+"...\n\n") root.update() while start_port<=end_port and self.flag=='scan': self.sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sk.settimeout(0.01) try: self.sk.connect((host,start_port)) except: pass else: result.insert(END,str(start_port)+"\n") root.update() self.open_counter=self.open_counter+1 self.sk.close() start_port=start_port+1 if self.flag=='scan': result.insert(END,"\nDone !!\nFound "+str(self.open_counter)+" opened ports") root.update() start.config(text="Scan",command=go) root.update() elif self.flag=='stop': result.insert(END,"\n Scan stopped.") start.config(text="Scan",command=go) root.update() app=scan() Here is the go() function, which starts the thread: def go(): app.start() app.scanner() And here is the stop() function that should end the thread and the scan (and for some reason it ends only the scan loop): def stop(): app.flag='stop' You got any Idea whats wrong here ?? Thanks allot. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From gwyn.evans at gmail.com Thu Mar 3 15:31:55 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Thu Mar 3 15:32:17 2005 Subject: [Tutor] How to use threads ? In-Reply-To: References: <20050302224811.80682.qmail@web53804.mail.yahoo.com> Message-ID: On Thu, 3 Mar 2005 16:04:28 +0200, Mark Kels wrote: > On Wed, 2 Mar 2005 14:48:11 -0800 (PST), Shitiz Bansal > wrote: > > The thread finishes when: > > 1.The run method finishes. > > 2.In case of the loop- you may - > > > > >>> import threading > > >>> class abc(threading.Thread): > > def __init__(self): > > threading.Thread.__init__(self) > > self.cont_flag=1 > > def run(self): > > while self.cont_flag: > > pass > > > > >>> abcd=abc() > > >>> abcd > > > > >>> abcd.start() > > >>> abcd > > > > >>> abcd.cont_flag=0 > > >>> abcd > > > > But for some reason it keeps working after its job is done in my app... > Here is the class: > (the app itself got some Entrys to get the input and a Button to start > the go() and stop() functions) > > class scan(threading.Thread): > def _init_(self): > threading.thread._init_(self) > def scanner(self): > self.open_counter=0 > self.flag='scan' > try: > host=host_e.get() > start_port=int(start_port_e.get()) > end_port=int(end_port_e.get()) > except ValueError: > tkMessageBox.showerror("Bad input","You must enter a vaild > host IP and port numbers.") > pass > else: > start.config(text="Stop",command=stop) > root.update() > result.insert(END,"Scanning "+str(host)+"...\n\n") > root.update() > while start_port<=end_port and self.flag=='scan': > self.sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > self.sk.settimeout(0.01) > try: > self.sk.connect((host,start_port)) > except: > pass > else: > result.insert(END,str(start_port)+"\n") > root.update() > self.open_counter=self.open_counter+1 > self.sk.close() > start_port=start_port+1 > if self.flag=='scan': > result.insert(END,"\nDone !!\nFound > "+str(self.open_counter)+" opened ports") > root.update() > start.config(text="Scan",command=go) > root.update() > elif self.flag=='stop': > result.insert(END,"\n Scan stopped.") > start.config(text="Scan",command=go) > root.update() > app=scan() > > Here is the go() function, which starts the thread: > def go(): > app.start() > app.scanner() > > And here is the stop() function that should end the thread and the > scan (and for some reason it ends only the scan loop): > def stop(): > app.flag='stop' > > You got any Idea whats wrong here ?? Hi, The one thing that stands out is that when you subclass Thread as you do, you need to override the 'run' method, which will get called as a result of you calling 'start()'. You're calling start(), but you've not got a run method, so the new thread doesn't call your code. Instead you've got your own call to 'scanner()', that is running under the main thread. Rename 'scanner()' to 'run()', remove the call to 'scanner()' and see how that looks. /Gwyn From mark.kels at gmail.com Thu Mar 3 16:53:11 2005 From: mark.kels at gmail.com (Mark Kels) Date: Thu Mar 3 16:53:15 2005 Subject: [Tutor] How to use threads ? In-Reply-To: References: <20050302224811.80682.qmail@web53804.mail.yahoo.com> Message-ID: On Thu, 3 Mar 2005 14:31:55 +0000, Gwyn Evans wrote: > Hi, > The one thing that stands out is that when you subclass Thread as > you do, you need to override the 'run' method, which will get called > as a result of you calling 'start()'. > You're calling start(), but you've not got a run method, so the new > thread doesn't call your code. Instead you've got your own call to > 'scanner()', that is running under the main thread. > > Rename 'scanner()' to 'run()', remove the call to 'scanner()' and > see how that looks. It looks the same, but with 1 line less... The thread is still working after the loop is done, so after I stop the scan I cant start another one. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From gwyn.evans at gmail.com Thu Mar 3 17:36:05 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Thu Mar 3 17:36:40 2005 Subject: [Tutor] How to use threads ? In-Reply-To: References: <20050302224811.80682.qmail@web53804.mail.yahoo.com> Message-ID: On Thu, 3 Mar 2005 17:53:11 +0200, Mark Kels wrote: > On Thu, 3 Mar 2005 14:31:55 +0000, Gwyn Evans wrote: > > Hi, > > The one thing that stands out is that when you subclass Thread as > > you do, you need to override the 'run' method, which will get called > > as a result of you calling 'start()'. > > You're calling start(), but you've not got a run method, so the new > > thread doesn't call your code. Instead you've got your own call to > > 'scanner()', that is running under the main thread. > > > > Rename 'scanner()' to 'run()', remove the call to 'scanner()' and > > see how that looks. > > It looks the same, but with 1 line less... > The thread is still working after the loop is done, so after I stop > the scan I cant start another one. Hmm, at this point I'd be either firing up a debugger or adding a print/msg box to check that it's exiting run() as expected... How are you trying to start another scan? You'd have to create a new instance, you can't just call app.start() again. /Gwyn From mark.kels at gmail.com Thu Mar 3 19:02:05 2005 From: mark.kels at gmail.com (Mark Kels) Date: Thu Mar 3 19:02:10 2005 Subject: [Tutor] How to use threads ? In-Reply-To: References: <20050302224811.80682.qmail@web53804.mail.yahoo.com> Message-ID: On Thu, 3 Mar 2005 16:36:05 +0000, Gwyn Evans wrote: > How are you trying to start another scan? You'd have to create a > new instance, you can't just call app.start() again. Thanks allot !! This is exactly what I was doing wrong. Now it works :) -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From amonroe at columbus.rr.com Fri Mar 4 00:10:37 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri Mar 4 00:11:21 2005 Subject: [Tutor] Re: How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: References: <12255145785.20050228223338@columbus.rr.com> <8584290042.20050301063922@columbus.rr.com> Message-ID: <152298565474.20050303181037@columbus.rr.com> >>>> print type(stuff), 'stuff', stuff.encode() >>>>This prints: >>>> >>>> stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] >> >> >>> I don't understand what you tried to accomplish here. >> >> >> That's evidence of what I failed to accomplish. My expected results >> was to print the word "Copyright" and whatever other strings are >> present in the font, with no intervening NUL characters. > Oh but why print type(stuff) To make sure it really came back as , as opposed to . > or 'stuff'? Personal tradition :^) The outcome of the project was this: Firefox would not display bold text correctly when I selected "Futura Lt BT" as my font (it would display a stretched version of the Light font, even though I also had "Futura Bold BT" in my fonts folder). After some googling, I figured out that (if I understand it right) Windows groups plain fonts and bold fonts together based on their internal family name, which turned out to be different between the two fonts. futural.ttf Font Family name : Futura Lt BT Font Subfamily name : Light futurab.ttf Font Family name : Futura Md BT Font Subfamily name : Bold So as best I can tell, the d*mb*asses that made Word Perfect Office 2002 (pre-loaded on my computer when I bought it) failed to give me the entire font family. Alan From dyoo at hkn.eecs.berkeley.edu Fri Mar 4 07:58:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 4 07:58:34 2005 Subject: [Tutor] Re: Q & A In-Reply-To: <20050226062509.47947.qmail@web51603.mail.yahoo.com> Message-ID: [Meta note to other folks on the list: I'm sorry for letting this post through; I was rushing, and I should have been more careful when going through my moderation queue.] On Fri, 25 Feb 2005, liew choon chui wrote: > Here are two question to need some solution. Hi Lieu Choon Chui, I do not want to be rude, but, bluntly speaking, you have to do your own work. Asking us to do it for you is a bit insulting, and I hope you understand you've just made a terrible netiquette blunder. Your homework is yours to solve. Please read: http://www.catb.org/~esr/faqs/smart-questions.html If you have questions about Python, we will be happy to help you. But don't dump homework questions on us and expect a useful response. From cyresse at gmail.com Fri Mar 4 08:59:33 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Mar 4 08:59:36 2005 Subject: [Tutor] Programming challenge (C++ and Python) In-Reply-To: <20050201082017.44023.qmail@web61002.mail.yahoo.com> References: <20050201082017.44023.qmail@web61002.mail.yahoo.com> Message-ID: ??? Why am I getting this one as new again? On Tue, 1 Feb 2005 00:20:17 -0800 (PST), Ali Polatel wrote: > Dear Python friends, > I need a favor.I play chess at a chess server with the name > ICC(www.chessclub.com). I want to write a plugin for their interface using > Python. > I don't have any idea about how to write a plugin but I found out that > the server administrator has written a Plugin Development Kit in C++ for > those who wish to write plugins for the interface.I don't know C++ so I > cannot convert this kit into python scripts.Can anyone do this for me? or > can anyone examine those scripts and tell me a way how to write those with > python?The development kit is avaliable at the site > ftp://ftp.chessclub.com/pub/icc/interface/blitzin2/plugins/ > under the name PluginDevkit.zip > Any kind of help is appreciated. > Regards, > Ali Polatel > > ________________________________ > Do you Yahoo!? > Yahoo! Search presents - Jib Jab's 'Second Term' > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From davholla2002 at yahoo.co.uk Fri Mar 4 10:26:40 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri Mar 4 10:26:43 2005 Subject: [Tutor] Make a .exe Message-ID: <20050304092641.55708.qmail@web25406.mail.ukl.yahoo.com> I have a game I wrote using python and pygame that I am trying to change into a .exe I created the script setup.py which has this code :- setup.py from distutils.core import setup import py2exe setup(console=["Gamename.py"]) In a dos prompt with all the files there I ran :- python setup.py py2exe It Completed with these errors :- The following modules appear to be missing {'AppKit', 'Foundation', 'objc'] but the game.exe was created However when I try to run it I get &nb sp; File "livewires3\games.pyc", line 585 in init_text File "livewires3\games.pyc", line 585 in init_text Fatal Python error: Segmentation Fault. Livewires3 is a modified version of a pygame wrapper. http://www.livewires.org.uk/python/ is where the original is. The book I used to learn python "python programming for the absolute beginner" has a modified version of this with some functionality added and taken away. I modified the wrapper so that has the functionality of both wrappers. Any ideas about how to fix it ? Thanks in advance David Send instant messages to your online friends http://uk.messenger.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050304/990ecfa0/attachment.html From gwyn.evans at gmail.com Fri Mar 4 10:37:21 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Fri Mar 4 10:37:24 2005 Subject: [Tutor] Newbie question. In-Reply-To: <001601c5050c$de90dfb0$0408a8c0@Client98> References: <001601c5050c$de90dfb0$0408a8c0@Client98> Message-ID: On Fri, 28 Jan 2005 09:42:07 +0200, Adriaan Louw wrote: > I want to learn python as quick as possible, for web programming at first, > and applications later on. Any leads? Hi, I'd start with the basic python tutorials, then have a look at something like CherryPy (http://www.cherrypy.org/) or Quixote (http://www.quixote.ca/) for the initial web stuff - there are others, too. Try & read around each a bit, e.g. web site/mailing lists, then download & give ones you fancy a try. > I have an xp windows and ms office machine. (I'm considering linux, but it's > a bit daunting?) No need to in most cases. > How do I run python scripts? Nothing happens when I double-click the > filename, in IDLE I only get the code, and not what it does. Command line is one way. Make sure your PATH (My Computer/Propeties/Advanced/Environment, or similar) has the Python folder in it then try "python " You can also try Explorer/Tools/Folder Options/File Types/.PY to associate .py files with the python.exe file. Gwyn From gwyn.evans at gmail.com Fri Mar 4 10:43:08 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Fri Mar 4 10:43:11 2005 Subject: [Tutor] Proxy In-Reply-To: <20050130002329.4200.qmail@web61003.mail.yahoo.com> References: <20050130002329.4200.qmail@web61003.mail.yahoo.com> Message-ID: On Sat, 29 Jan 2005 16:23:29 -0800 (PST), Ali Polatel wrote: > is it possible to connect to somewhere through a proxy while using sockets > module of Python to connect? If yes can you show me some basic examples? Yes, but not auto-magically. If you want to stay at the sockets level, you'll have to handle all the proxy interaction yourself. I'd suggest instead looking at the urllib2 module, as I believe that you can use that (via a Request object?) to handle the proxy for you. /Gwyn From maxnoel_fr at yahoo.fr Fri Mar 4 11:11:51 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Mar 4 11:11:55 2005 Subject: [Tutor] Make a .exe In-Reply-To: <20050304092641.55708.qmail@web25406.mail.ukl.yahoo.com> References: <20050304092641.55708.qmail@web25406.mail.ukl.yahoo.com> Message-ID: <1c69aad8c67d4430e7ae3e410e42ed61@yahoo.fr> On Mar 4, 2005, at 09:26, David Holland wrote: > It Completed with these errors :- > The following modules appear to be missing {'AppKit', > 'Foundation', 'objc'] Now that's really weird. AppKit and Foundation are Mac OS X frameworks, and objc stands for Objective-C, the language in which they're written and which you're supposed to use to develop applications that use them. However, since you're on a Windows box, I have no idea why Python is trying to involve them. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Fri Mar 4 12:16:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 4 12:16:43 2005 Subject: [Tutor] Newbie question. In-Reply-To: <001601c5050c$de90dfb0$0408a8c0@Client98> References: <001601c5050c$de90dfb0$0408a8c0@Client98> Message-ID: <42284398.4060402@tds.net> Adriaan Louw wrote: > I want to learn python as quick as possible, for web programming at > first, and applications later on. Any leads? There are many tutorials available, see http://www.python.org/doc/Intros.html for one list. > > I have an xp windows and ms office machine. (I'm considering linux, but > it's a bit daunting?) > > How do I run python scripts? Nothing happens when I double-click the > filename, in IDLE I only get the code, and not what it does. You can run the program in IDLE using Run / Run Module (F5). > I know that cgi-scripts must be called from html. I want to to use a > python server for testing. Which is thebest, and how? There are many options for web programming, one list is here: http://www.python.org/moin/WebProgramming In addition to CherryPy and Quixote, Snakelets is a complete web solution that is intended to be easy to learn. Twisted and Zope are perhaps the most comprehensive solutions. Kent From davholla2002 at yahoo.co.uk Fri Mar 4 13:12:02 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri Mar 4 13:12:03 2005 Subject: [Tutor] make an .exe In-Reply-To: <20050304110113.E3BD81E4005@bag.python.org> Message-ID: <20050304121202.16666.qmail@web25405.mail.ukl.yahoo.com> Noel Thanks for that info, I did do a search for that but I could not find anything useful Message: 3 Date: Fri, 4 Mar 2005 10:11:51 +0000 From: Max Noel Subject: Re: [Tutor] Make a .exe To: David Holland Cc: tutor@python.org Message-ID: <1c69aad8c67d4430e7ae3e410e42ed61@yahoo.fr> Content-Type: text/plain; charset=US-ASCII; format=flowed On Mar 4, 2005, at 09:26, David Holland wrote: > It Completed with these errors :- > The following modules appear to be missing {'AppKit', > 'Foundation', 'objc'] Now that's really weird. AppKit and Foundation are Mac OS X frameworks, and objc stands for Objective-C, the language in which they're written and which you're supposed to use to develop applications that use them. However, since you're on a Windows box, I have no idea why Python is trying to involve them. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ------------------------------ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 13, Issue 13 ************************************* Send instant messages to your online friends http://uk.messenger.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050304/282cfe49/attachment.htm From mhansen at cso.atmel.com Fri Mar 4 15:00:03 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri Mar 4 15:00:03 2005 Subject: [Tutor] Re: Newbie question. In-Reply-To: <20050304110113.4F10E1E4016@bag.python.org> References: <20050304110113.4F10E1E4016@bag.python.org> Message-ID: <422869E3.20702@cso.atmel.com> > Subject: > Re: [Tutor] Newbie question. > From: > Gwyn Evans > Date: > Fri, 4 Mar 2005 09:37:21 +0000 > To: > tutor@python.org > > To: > tutor@python.org > > >On Fri, 28 Jan 2005 09:42:07 +0200, Adriaan Louw > wrote: > > >>I want to learn python as quick as possible, for web programming at first, >>and applications later on. Any leads? >> >> > >Hi, > I'd start with the basic python tutorials, then have a look at >something like CherryPy (http://www.cherrypy.org/) or Quixote >(http://www.quixote.ca/) for the initial web stuff - there are others, >too. Try & read around each a bit, e.g. web site/mailing lists, then >download & give ones you fancy a try. > > > I would politely disagree here. You need to walk before you can run. If you haven't done _any_ web programming before, it's probably best to do a small web app using just python's cgi module. I would think that CherryPy and Quixote are complex web tools/frameworks that I wouldn't recommend to someone new to web programming until they got their feet wet doing some basic web programming. After that, then explore more advanced web programming with CherryPy or Quixote. If you have done some basic web programming in other languages, then ignore this message. Mike From python.programming at gmail.com Fri Mar 4 16:43:46 2005 From: python.programming at gmail.com (Kevin) Date: Fri Mar 4 16:43:51 2005 Subject: [Tutor] (no subject) Message-ID: Hello all. I have just completed my very first python program just a simple number guessing. I would like for someone to try it out if they could and let me know how I did with it and where I could have improved apon it. There are t files main.py and defs.py Thanks ############################################################################## #!/usr/bin/python #main.py ########################### from defs import * import sys ########################### choice() #Lets call the main menu up for the user #This is used to ask if you would like to keep playing# while 1: play = raw_input("What is your choice? ") #Aks use to enter a choice from the menu if play == '3': #If user picks 3 print "\nHave a nice day!\n" #Tell them to have a nice day sys.exit() #Then exit the entire thing elif play == '2': #If user picks 2 instruct() #Then lets call the instructions function elif play == '1': #If user picks 1 game() #Then lets call the game function for the user to play elif play == '': #This is used is the menu leaves the screen so the user can get it back choice() #Bring back the menu else: print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" #Let the user know that they can only pick 1, 2, 3 or just hit enter and nothing else. ########################################################################### #defs.py ######### import random import sys ####################################################### #This is not used in the game yet def yesno(question): """Asks the use a yes or no question""" answer = None while answer not in ('y','ye','yes','n','no'): answer = raw_input(question).lower() if answer not in ('y','ye','yes','n','no'): print "Please enter Y or N" return answer ######################################################## #This is the guessing game# def game(): """This is the main part of the guessing game""" tries = 5 #Set the number of tries to 5 guess = random.randrange(2)+1 #Computer picks a number from 1 to 20 while 1: try: answer = int(raw_input("What is your guess? ")) #Ask the user to guess the number if answer != guess: #Check to see if answer is not equal to guessed number tries -= 1 #if answer is wrong reduce the number of tries by 1 print "Thats not it, you only have %d tries left" %tries #Tell user not right answer if tries == 0: #Check to see if user has run out of tries print "\nYou lost this round!" #If no tries left let the user know raw_input("\n[Hit Enter to Continue]\n") #Wait for user to go back to main menu choice() #Show main menu for user break #Then break out of the loop if answer == guess: #If the answer is equal to the guessed number print "\nCongrats you just Won this round!!" #Tell the user he just one in so many tries raw_input("[Hit Enter to Continue]") #Wait for user to go back to main menu choice() #Show main menu for user break #Break out of the loop except ValueError: #Lets make sure that the user is only typeing in numbers and nothing else print "\nYou can only use numbers\n" #Let user know they can only use numbers #This is the main menu for the game def choice(): """The main menu of the game""" print """ ######################################## # # # NUMBER GUESSING GAME # # # # - Created by Kevin J # # - python.programming@gmail.com # # ------------------------------------ # # 1 - Play # # 2 - instructions # # 3 - Quit # ########################################\n""" #This is the instuctions on how to play the game that can be called from the main menu def instruct(): """Instructions on how to play the guessing game""" print"""\n HOW TO PLAY THE NUMBER GUESSING GAME ######################################################################## # To play this game all you need to do is guess a number from 1 to 20. # # You will only have 5 tries to beat the game. Once you have beat the # # game or you have used up all of your 5 tries you will be sent back # # to the main screen were you can quit or start over again. # ######################################################################## [HIT ENTER FOR MAIN MENU]\n""" From bvande at po-box.mcgill.ca Fri Mar 4 18:14:28 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Mar 4 18:16:08 2005 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <42289774.6010607@po-box.mcgill.ca> Kevin said unto the world upon 2005-03-04 10:43: > Hello all. I have just completed my very first python program just a > simple number guessing. I would like for someone to try it out if they > could and let me know how I did with it and where I could have > improved apon it. There are t files main.py and defs.py > > Thanks Hi Kevin, Though I am a learner, too, I have a few comments. They are more about style than substance. 1) A lot of your code comments get in the way of my reading and easily understanding the code. Consider: .# leading `.'s to foil google groups and other whitespace stripping readers .if play == '3': #If user picks 3 . print "\nHave a nice day!\n" #Tell them to have a nice day . sys.exit() #Then exit the entire thing I think this would be much easier to read if it were like: .if play == '3': # If user picks 3 . print "\nHave a nice day!\n" # Tell them to have a nice day . sys.exit() # Then exit the entire thing (Note that some people hate the comments along the side and would prefer them the precede the line(s) they comment on. I like the 2 column approach, but that's just one duffer's view.) But, even better would be: .if play == '3': . print "\nHave a nice day!\n" . sys.exit() Your comments are close to the canonical example of 'bad comments': count += 1 # increment count by 1 Comments like this add nothing except squiggles to read on the screen or page. They just repeat the code; so, instead of helping, they are just noise. Comments are good for tricky bits, to explain just why some non-obvious chunk of code is there, or to remind the reader (who could well be you) why some particular approach was taken. (Neatness counts ;-) 2) Whitespace is a good thing. Python needs it horizontally, but you can (and, IMHO, should) employ vertical whitespace to chunk up the code. Your code had this chunk: . if play == '3': #If user picks 3 . print "\nHave a nice day!\n" #Tell them to have a nice day . sys.exit() #Then exit the entire thing . elif play == '2': #If user picks 2 . instruct() #Then lets call the instructions function . elif play == '1': #If user picks 1 . game() #Then lets call the game function for the user to play . elif play == '': #This is used is the menu leaves the screen so the user can get it back . choice() #Bring back the menu . else: . print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" Try reading that and then this: . if play == '3': . print "\nHave a nice day!\n" . sys.exit() . . elif play == '2': . instruct() . . elif play == '1': . game() . . elif play == '': # I might have put a comment here but . choice() # the else clause below explains it. . . else: . print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" Which one is easier to read? :-) The separation between blocks doesn't matter too much when the blocks are short, but I still like it. Different strokes, though. But, if each block had, say 4 or 5 lines, it would be much easier for me to parse with the separation. 3) I've come to like informative dosctrings a lot. When you start using tools like pydoc on your own code, you will be glad you used them. (Plus, they cut down on the need for inline comments.) and, 4) I'd make the yesno() function do a bit more work. So, combining these two points, where you have: .def yesno(question): . """Asks the use a yes or no question""" . answer = None . while answer not in ('y','ye','yes','n','no'): . answer = raw_input(question).lower() . if answer not in ('y','ye','yes','n','no'): . print "Please enter Y or N" . return answer I have a utility function: def yes_or_no(question): . '''Asks the user the question; returns True for yes, False for no. . . question is used to prompt the user for raw_input. That input is . put in lower case and compared to the values ['y', 'yes', 'n', . 'no']. If it matches a `yes' value, True is returned; if it . matches a `no' value False is returned. If it matches none of . these values, a report of what was entered and of valid inputs . is printed and the user is reprompted until an acceptable value . is entered. . ''' . response = raw_input(question) . while True: . . lresp = response.lower() . . if lresp == 'y' or lresp == 'yes': . # adjust matching values to your tastes . return True . if lresp == 'n' or lresp == 'no': . return False . . response = raw_input(''' . You entered: %s . Valid inputs are `n', 'no', `y', and `yes' (any case). . Please try again. . %s . ''' %(response, question)) My code is a lot longer, but 1) it does a little bit more, and 2) it has a much more useful docstring. If you wanted to reuse your function elsewhere (and you will), you might have to actually look at the code to see how it works. Mine is much easier to use with help() or the web browser version of pydoc. 5) I don't see why you broke your program up the way you did. I would have everything but the yesno() in one file. The yesno I would put in something like the inpututils.py file I have where I've got other standard user input routines, too. (Examples would be code to ask for a number between n and m, any number, a file path, etc.) Anyway, I hope that helps some and that the more experienced list members will swoop in (they always do :-) to fix anything I said that is goofy. Best, Brian vdB > > ############################################################################## > > #!/usr/bin/python > #main.py > ########################### > from defs import * > import sys > ########################### > > choice() #Lets call the main menu up for the user > #This is used to ask if you would like to keep playing# > while 1: > play = raw_input("What is your choice? ") #Aks use to enter a choice > from the menu > if play == '3': #If user picks 3 > print "\nHave a nice day!\n" #Tell them to have a nice day > sys.exit() #Then exit the entire thing > elif play == '2': #If user picks 2 > instruct() #Then lets call the instructions function > elif play == '1': #If user picks 1 > game() #Then lets call the game function for the user to play > elif play == '': #This is used is the menu leaves the screen so the > user can get it back > choice() #Bring back the menu > else: > print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" > #Let the user know that they can only pick 1, 2, 3 or just hit enter > and nothing else. > > ########################################################################### > #defs.py > ######### > import random > import sys > ####################################################### > #This is not used in the game yet > def yesno(question): > """Asks the use a yes or no question""" > answer = None > while answer not in ('y','ye','yes','n','no'): > answer = raw_input(question).lower() > if answer not in ('y','ye','yes','n','no'): > print "Please enter Y or N" > return answer > ######################################################## > #This is the guessing game# > def game(): > """This is the main part of the guessing game""" > tries = 5 #Set the number of tries to 5 > guess = random.randrange(2)+1 #Computer picks a number from 1 to 20 > while 1: > try: > answer = int(raw_input("What is your guess? ")) #Ask the user to > guess the number > if answer != guess: #Check to see if answer is not equal to guessed number > tries -= 1 #if answer is wrong reduce the number of tries by 1 > print "Thats not it, you only have %d tries left" %tries #Tell > user not right answer > if tries == 0: #Check to see if user has run out of tries > print "\nYou lost this round!" #If no tries left let the user know > raw_input("\n[Hit Enter to Continue]\n") #Wait for user to go > back to main menu > choice() #Show main menu for user > break #Then break out of the loop > if answer == guess: #If the answer is equal to the guessed number > print "\nCongrats you just Won this round!!" #Tell the user he > just one in so many tries > raw_input("[Hit Enter to Continue]") #Wait for user to go back to main menu > choice() #Show main menu for user > break #Break out of the loop > except ValueError: #Lets make sure that the user is only typeing in > numbers and nothing else > print "\nYou can only use numbers\n" #Let user know they can only > use numbers > > #This is the main menu for the game > def choice(): > """The main menu of the game""" > print """ > ######################################## > # # > # NUMBER GUESSING GAME # > # # > # - Created by Kevin J # > # - python.programming@gmail.com # > # ------------------------------------ # > # 1 - Play # > # 2 - instructions # > # 3 - Quit # > ########################################\n""" > > #This is the instuctions on how to play the game that can be called > from the main menu > def instruct(): > """Instructions on how to play the > guessing game""" > print"""\n > HOW TO PLAY THE NUMBER GUESSING GAME > ######################################################################## > # To play this game all you need to do is guess a number from 1 to 20. # > # You will only have 5 tries to beat the game. Once you have beat the # > # game or you have used up all of your 5 tries you will be sent back # > # to the main screen were you can quit or start over again. # > ######################################################################## > [HIT ENTER FOR MAIN MENU]\n""" > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From shitizb at yahoo.com Fri Mar 4 18:19:41 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Fri Mar 4 18:19:44 2005 Subject: [Tutor] Linked List Message-ID: <20050304171941.53337.qmail@web53806.mail.yahoo.com> Hi, Any body has any idea on how to implement a linked list in python? Ordinary python lists are not quite the same. what i need is a list i can traverse through sequentially without bothering about the indices, as another process is continuously editing this list, by inserting and deleting elements even as the list is being traversed. Shitiz __________________________________ Celebrate Yahoo!'s 10th Birthday! Yahoo! Netrospective: 100 Moments of the Web http://birthday.yahoo.com/netrospective/ From project5 at redrival.net Fri Mar 4 19:17:06 2005 From: project5 at redrival.net (Andrei) Date: Fri Mar 4 19:24:52 2005 Subject: [Tutor] Re: Linked List References: <20050304171941.53337.qmail@web53806.mail.yahoo.com> Message-ID: Shitiz Bansal wrote on Fri, 4 Mar 2005 09:19:41 -0800 (PST): > Any body has any idea on how to implement a linked > list in python? Perhaps like this: >>> class node(object): ... def __init__(self, item, next=None): ... self.item = item ... self.next = next >>> a = node('item a') >>> b = node(3) >>> c = node((3,4)) >>> d = node('last item') >>> a.next = b >>> b.next = c >>> c.next = d >>> mynode = a >>> while mynode: ... print mynode.item ... mynode = mynode.next item a 3 (3, 4) last item -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From chelan.farsight at gmail.com Fri Mar 4 19:37:58 2005 From: chelan.farsight at gmail.com (Chelan Farsight) Date: Fri Mar 4 19:38:54 2005 Subject: [Tutor] Re: Q & A In-Reply-To: References: <20050226062509.47947.qmail@web51603.mail.yahoo.com> Message-ID: <661da26c05030410371eba7b4b@mail.gmail.com> Okay this is a real question I have and I am not trying to defend the actions of Mr. Chui. I simply wanted to make sure that I have joined the right list. Are we allowed to ask total n00b questions on this list? If not what level of understanding is presumed before someone should post a question? Again, please do not misunderstand, I have no qualms with *refusing* to do someone's homework for them. I just want to make sure that total newbies are welcome here. If not then a reccomendation for another list would be greatly appreciated. Thanks for your patience and help, chelan On Thu, 3 Mar 2005 22:58:31 -0800 (PST), Danny Yoo wrote: > > [Meta note to other folks on the list: I'm sorry for letting this post > through; I was rushing, and I should have been more careful when going > through my moderation queue.] > > > On Fri, 25 Feb 2005, liew choon chui wrote: > > > Here are two question to need some solution. > > Hi Lieu Choon Chui, > > I do not want to be rude, but, bluntly speaking, you have to do your own > work. Asking us to do it for you is a bit insulting, and I hope you > understand you've just made a terrible netiquette blunder. Your homework > is yours to solve. > > Please read: > > http://www.catb.org/~esr/faqs/smart-questions.html > > If you have questions about Python, we will be happy to help you. But > don't dump homework questions on us and expect a useful response. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Fri Mar 4 19:45:54 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 4 19:45:58 2005 Subject: [Tutor] Programming challenge (C++ and Python) In-Reply-To: Message-ID: On Fri, 4 Mar 2005, Liam Clarke wrote: > ??? Why am I getting this one as new again? Hi Liam, This one is my fault. As a mailing list administrator, I have to go through stuff that's sitting in a moderation queue. I'd been a little derelict in my responsibility lately, and hadn't looked at the queue since January. I looked at it yesterday and started allowing some messages to come in , but I was careless enough not to notice some the questions that were already posted to this list from back in January. I apologize for this; I'll try to do a less careless job next time. From dyoo at hkn.eecs.berkeley.edu Fri Mar 4 19:49:33 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 4 19:49:44 2005 Subject: [Tutor] Re: Linked List In-Reply-To: Message-ID: On Fri, 4 Mar 2005, Andrei wrote: > Shitiz Bansal wrote on Fri, 4 Mar 2005 09:19:41 -0800 (PST): > > > Any body has any idea on how to implement a linked list in python? There's a chapter on Linked Lists in "How to Think Like a Computer Scientist": http://www.ibiblio.org/obp/thinkCSpy/chap17.htm You might also enjoy this post from a few years back: http://mail.python.org/pipermail/tutor/2002-April/014073.html From kent37 at tds.net Fri Mar 4 19:52:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 4 19:52:23 2005 Subject: [Tutor] Re: Q & A In-Reply-To: <661da26c05030410371eba7b4b@mail.gmail.com> References: <20050226062509.47947.qmail@web51603.mail.yahoo.com> <661da26c05030410371eba7b4b@mail.gmail.com> Message-ID: <4228AE6D.4050609@tds.net> Chelan Farsight wrote: > Okay this is a real question I have and I am not trying to defend the > actions of Mr. Chui. I simply wanted to make sure that I have joined > the right list. Are we allowed to ask total n00b questions on this > list? Yes, this list is specifically for total n00bs and other beginners (and people who like to answer beginners' questions :-) If not what level of understanding is presumed before someone > should post a question? None. A reasonable level of *effort* is appreciated. You will get better results if you try something and ask for help when you get stuck, and if you take the time to write a clear question. > Again, please do not misunderstand, I have no qualms with *refusing* > to do someone's homework for them. I just want to make sure that > total newbies are welcome here. Yes, definitely. Kent From dyoo at hkn.eecs.berkeley.edu Fri Mar 4 20:05:53 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 4 20:06:05 2005 Subject: [Tutor] Re: Q & A In-Reply-To: <661da26c05030410371eba7b4b@mail.gmail.com> Message-ID: On Fri, 4 Mar 2005, Chelan Farsight wrote: > Okay this is a real question I have and I am not trying to defend the > actions of Mr. Chui. I simply wanted to make sure that I have joined > the right list. Are we allowed to ask total n00b questions on this > list? Hi Chelan, Yikes! Newcomer questions are perfectly fine. I'm sorry for the exasperated tone I used in my last message, and will try to explain myself. Let me clarify: if it's obvious that the questioner doesn't even care about the question they are asking --- if someone is just trying to get us to do homework so they can copy and paste it into some word processor --- then I get annoyed. (But I should have posted my rant off-list, so that it didn't disrupt anyone else.) If it looks like the questioner cares about the answer, and is doing other things to learn more about the subject, then that's ok. > If not what level of understanding is presumed before someone should > post a question? Any level of understanding is actually fine. Personally, it's the human intent of the questions that matters to me. Neither of Chui's questions had anything to do with Python. If there's any real requirement about questions, it's that it should at least have something to do with learning how to program in Python. > I just want to make sure that total newbies are welcome here. If not > then a reccomendation for another list would be greatly appreciated. This list is for beginners and newcomers to Python and programming. If you have any questions, please feel free to ask them. And, again, I apologize about the earlier rant; I get emotional very easily. *grin* From chelan.farsight at gmail.com Fri Mar 4 20:31:08 2005 From: chelan.farsight at gmail.com (Chelan Farsight) Date: Fri Mar 4 20:31:13 2005 Subject: [Tutor] Re: Q & A In-Reply-To: References: <661da26c05030410371eba7b4b@mail.gmail.com> Message-ID: <661da26c050304113158291c82@mail.gmail.com> Kent and Danny, Thanks so much for the quick and warmhearted reply. /whew Just wanted to make sure. I know there are lists specifically aimed at advanced users and wanted to watch my p's and q's. Well as I work my way through I am certain I will have questions and I am glad I have found a place to help out. Oh and rant away it can be kinda fun at times =) Thanks again, Chelan From bill at celestial.net Fri Mar 4 22:02:11 2005 From: bill at celestial.net (Bill Campbell) Date: Fri Mar 4 22:02:04 2005 Subject: [Tutor] Berkeley db incompatibility Message-ID: <20050304210211.GC96069@alexis.mi.celestial.com> I don't know that this is a tutor topic, but since I'm a python newbie, I'll try. Building python-2.4 with db-4.3.27 fails on an undefined enum, DB_LSTAT_ERR resulting in no bsddb module. It looks like the sleepycat folks decided to break backwards compatibility by dropping this out of the enum. I've tried google to find a fix, but haven't found anything yet. Is there a recommended fix for this? Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ The Constitution is a written instrument. As such, its meaning does not alter. That which it meant when it was adopted, it means now. -- SOUTH CAROLINA v. US, 199 U.S. 437, 448 (1905) From project5 at redrival.net Fri Mar 4 21:55:31 2005 From: project5 at redrival.net (Andrei) Date: Fri Mar 4 22:02:32 2005 Subject: [Tutor] Re: Re: Q & A References: <20050226062509.47947.qmail@web51603.mail.yahoo.com> <661da26c05030410371eba7b4b@mail.gmail.com> Message-ID: Chelan Farsight wrote on Fri, 4 Mar 2005 12:37:58 -0600: > actions of Mr. Chui. I simply wanted to make sure that I have joined > the right list. Are we allowed to ask total n00b questions on this > list? If not what level of understanding is presumed before someone > should post a question? The Tutor list is for beginners, which includes people who haven't programmed before. I'd say it even includes homework where the student in question has actually tried doing something and ran into a snag, but not in the case where the student just posts a "solve this homework for me". -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From kent37 at tds.net Sat Mar 5 01:50:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 01:50:59 2005 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4229026D.10002@tds.net> Kevin wrote: > Hello all. I have just completed my very first python program just a > simple number guessing. I would like for someone to try it out if they > could and let me know how I did with it and where I could have > improved apon it. There are t files main.py and defs.py I second Brian's comments about comments and white space. The comments make it very hard to pick out the actual code. Better if you can let the code speak for itself. Kent From keridee at jayco.net Sat Mar 5 02:07:49 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Mar 5 02:07:21 2005 Subject: [Tutor] Linked List References: <20050304171941.53337.qmail@web53806.mail.yahoo.com> Message-ID: <002201c5211f$cb9660e0$a95428cf@JSLAPTOP> I'm taking a shot in the dark and answering here. Have you tried making a copy of the list, iterating over the copy, and changing the original based on the copy? Jacob > Hi, > Any body has any idea on how to implement a linked > list in python? > Ordinary python lists are not quite the same. what i > need is a list i can traverse through sequentially > without bothering about the indices, as another > process is continuously editing this list, by > inserting and deleting elements even as the list is > being traversed. > > Shitiz > > > > > __________________________________ > Celebrate Yahoo!'s 10th Birthday! > Yahoo! Netrospective: 100 Moments of the Web > http://birthday.yahoo.com/netrospective/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From ron at frenchmerchants.net Sat Mar 5 03:39:44 2005 From: ron at frenchmerchants.net (Ronnie Betzen) Date: Sat Mar 5 03:39:59 2005 Subject: [Tutor] Problem with IntVar() Message-ID: <200503042039.46191.ron@frenchmerchants.net> I've been trying to use IntVar() to update checkboxes using the Tkinter toolkit. To date I haven't been successful getting it to work. Evidently I'm missing some concept with regards to setting up my interface. I've successfully run scripts by other people using IntVar() so I know my personal system is ok. Here is some code that causes me problems with IntVar(). Can someone enlighten this total newbie (python and programming both.) as to what I'm missing here? Thanks, Ron From ron at frenchmerchants.net Sat Mar 5 03:52:02 2005 From: ron at frenchmerchants.net (Ronnie Betzen) Date: Sat Mar 5 03:52:06 2005 Subject: [Tutor] Problem with IntVar() - Oops! Here's the code. In-Reply-To: <200503042039.46191.ron@frenchmerchants.net> References: <200503042039.46191.ron@frenchmerchants.net> Message-ID: <200503042052.02275.ron@frenchmerchants.net> #! /usr/bin/env python import Tkinter class timer: def __init__(self): # initialize global variables self.ckbuttonstatus = IntVar() # set up main window self.top = Tk() self.top.geometry('355x125') self.top.title(appname) self.top.resizable(width='no', height='no') # set up menubar self.menubar = menu(self.top) self.top.config(menu = self.menubar) # set up file menu self.filemenu = Menu(self.menubar, tearoff = 0) self.filemenu.add_cascade(label="File", menu=self.filemenu) self.filemenu.add_checkbutton(label = "Click Me!", command = self.labelUpdate) self.filemenu.add_command(label = "Quit", command=self.top.quit) # set up main display area self.frame = Frame(self.top) self.frame.pack(fill=x) self.displaylabel=Label(self.frame, text=" ", font="Times 36 bold", relief="sunken") self.displaylabel.pack(side=BOTTOM, fill=X) def labelUpdate(self): self.status = self.ckbuttonstatus.get() self.labeltext = "Chekbutton status is: " + self.status self.displaylabel.config(text=labeltext) self.top.update() if __name__ == '__main__': mainApp = timer() mainloop() On Friday 04 March 2005 08:39 pm, Ronnie Betzen wrote: > I've been trying to use IntVar() to update checkboxes using the Tkinter > toolkit. To date I haven't been successful getting it to work. Evidently > I'm missing some concept with regards to setting up my interface. I've > successfully run scripts by other people using IntVar() so I know my > personal system is ok. > > Here is some code that causes me problems with IntVar(). Can someone > enlighten this total newbie (python and programming both.) as to what I'm > missing here? > > Thanks, > > Ron > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From billk at fastmail.fm Sat Mar 5 05:05:53 2005 From: billk at fastmail.fm (Bill Kranec) Date: Sat Mar 5 05:05:48 2005 Subject: [Tutor] returning table elements with Beautiful Soup Message-ID: <42293021.1030309@fastmail.fm> Hi, I'm trying to use Beautiful Soup to scrape some data out of an HTML table. I can do this using table = soup("td", {'class' : 'yfnc_tabledata1' }) table[0].string.strip() However, if I try for entry in table: entry.string.strip() I get: AttributeError: Tag instance has no attribute 'string' Clearly Python is now treating the cell as a list element, not as a Beautiful Soup class, so it cannot find the method that I want to use. But I can't seem to find a way to do what I meant to do. Is there an easy way to have Beautiful Soup return each data element in the table, preferably into a list? Any help is greatly appreciated. Bill From kent37 at tds.net Sat Mar 5 05:48:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 05:48:06 2005 Subject: [Tutor] Problem with IntVar() - Oops! Here's the code. In-Reply-To: <200503042052.02275.ron@frenchmerchants.net> References: <200503042039.46191.ron@frenchmerchants.net> <200503042052.02275.ron@frenchmerchants.net> Message-ID: <42293A01.4070507@tds.net> There seem to be quite a few problems with this code... Ronnie Betzen wrote: > #! /usr/bin/env python > import Tkinter should be from Tkinter import * > > class timer: > def __init__(self): > The next line needs to be after the line 'self.top = Tk()' so Tkinter is initialized when the variable is created. > # initialize global variables > self.ckbuttonstatus = IntVar() > > # set up main window > self.top = Tk() > self.top.geometry('355x125') appname is not defined... > self.top.title(appname) etc... I think you have bitten off too much here. Try starting with a very small, working program that has a little of what you want in it. Then add another little piece and get that working. Repeat until you get to where you want to be. Ask questions when you don't understand the next step. Here is a very simple program that links a checkbox and a label through a variable. Maybe this is a step in the right direction for you: from Tkinter import * root = Tk() var = IntVar() Label(textvariable=var).pack() c = Checkbutton(text="Click Me", variable=var) c.pack() root.mainloop() Kent > self.top.resizable(width='no', height='no') > > # set up menubar > self.menubar = menu(self.top) > self.top.config(menu = self.menubar) > > # set up file menu > self.filemenu = Menu(self.menubar, tearoff = 0) > self.filemenu.add_cascade(label="File", menu=self.filemenu) > self.filemenu.add_checkbutton(label = "Click Me!", command = > self.labelUpdate) > self.filemenu.add_command(label = "Quit", command=self.top.quit) > > # set up main display area > self.frame = Frame(self.top) > self.frame.pack(fill=x) > self.displaylabel=Label(self.frame, text=" ", font="Times 36 bold", > relief="sunken") > self.displaylabel.pack(side=BOTTOM, fill=X) > > def labelUpdate(self): > self.status = self.ckbuttonstatus.get() > self.labeltext = "Chekbutton status is: " + self.status > self.displaylabel.config(text=labeltext) > self.top.update() > > if __name__ == '__main__': > mainApp = timer() > mainloop() > > > On Friday 04 March 2005 08:39 pm, Ronnie Betzen wrote: > >>I've been trying to use IntVar() to update checkboxes using the Tkinter >>toolkit. To date I haven't been successful getting it to work. Evidently >>I'm missing some concept with regards to setting up my interface. I've >>successfully run scripts by other people using IntVar() so I know my >>personal system is ok. >> >>Here is some code that causes me problems with IntVar(). Can someone >>enlighten this total newbie (python and programming both.) as to what I'm >>missing here? >> >>Thanks, >> >>Ron >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ron at frenchmerchants.net Sat Mar 5 06:20:29 2005 From: ron at frenchmerchants.net (Ronnie Betzen) Date: Sat Mar 5 06:20:37 2005 Subject: [Tutor] Problem with IntVar() (SOLVED!) In-Reply-To: <42293A01.4070507@tds.net> References: <200503042039.46191.ron@frenchmerchants.net> <200503042052.02275.ron@frenchmerchants.net> <42293A01.4070507@tds.net> Message-ID: <200503042320.29917.ron@frenchmerchants.net> Thanks, Kent! Moving self.top=Tk() up solved the IntVar() problem. *sigh* Man, learning curves can be a royal pain.... ;-) Also, thanks for the advice about starting off with little bits at a time. Kinda seems like an obvious way to do things when you think about it. :-/ From kent37 at tds.net Sat Mar 5 06:22:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 06:22:12 2005 Subject: [Tutor] returning table elements with Beautiful Soup In-Reply-To: <42293021.1030309@fastmail.fm> References: <42293021.1030309@fastmail.fm> Message-ID: <422941FF.9070205@tds.net> Bill Kranec wrote: > Hi, > > I'm trying to use Beautiful Soup to scrape some data out of an HTML > table. I can do this using > > table = soup("td", {'class' : 'yfnc_tabledata1' }) > table[0].string.strip() OK, table is a list of Tags, the first one has a 'string' attribute. > > However, if I try > > for entry in table: > entry.string.strip() > > I get: AttributeError: Tag instance has no attribute 'string' Because not every Tag in table has a 'string' attribute, only the ones that have a single string child somewhere. Try this and you will see better what is going on: import urllib2 from BeautifulSoup import BeautifulSoup data = urllib2.urlopen('http://finance.yahoo.com/q?s=IBM').read() soup = BeautifulSoup(data) table = soup("td", {'class' : 'yfnc_tabledata1' }) for entry in table: print entry try: print entry.string except AttributeError: print 'No string' ## prints 92.37 92.37 Mar 4 Mar 4 Down 0.04 (0.04%) No string ...etc Notice the third element has two string children - ' ' and '0.04 (0.04%)'. You will have to do a little more work if you want the text from that one. > Is there an easy way to have Beautiful Soup return each data element in > the table, preferably into a list? allStrings = [entry.string for entry in table if hasattr(entry, 'string')] print allStrings ## prints ['92.37', 'Mar 4', '92.41', '92.94', 'N/A', 'N/A', '107.33', '92.36 - 93.18', '81.90 - 99.10', '4,754,000', '4,619,454', '150.81B', '18.65', '4.95', '0.72 (0.78%)', '15.02', '1.57', '10-Mar-05', ' 8-Feb-05', '5.62', '1.04', '2.1', '1.64'] Kent From osagie at gmail.com Sat Mar 5 06:25:18 2005 From: osagie at gmail.com (Anderson) Date: Sat Mar 5 06:25:21 2005 Subject: [Tutor] Cataloging Web Page Information Message-ID: <56defa170503042125689d98dc@mail.gmail.com> Hello, I currently have access to a webpage that has information that I'd like to put into a CSV (comma seperated value) spreadsheet. Its frontend is a form; you fill the form out by entering some text and selecting the appropriate option from a drop down menu, and then you press the submit form button. The webpage subsequently displays links to every entry it can find and when you click on the link you get the full info of that entry. I want to automate the whole process with a python script. I figured out that the csv module(s) would be best for storing the received information but what module should I use to access the website, fill out the form, enter each resulting link and retrieve the information? Thanks for your time, Anderson From kent37 at tds.net Sat Mar 5 06:50:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 06:50:40 2005 Subject: [Tutor] Cataloging Web Page Information In-Reply-To: <56defa170503042125689d98dc@mail.gmail.com> References: <56defa170503042125689d98dc@mail.gmail.com> Message-ID: <422948AA.4000707@tds.net> Anderson wrote: > Hello, > > I currently have access to a webpage that has information that I'd > like to put into a CSV (comma seperated value) spreadsheet. Its > frontend is a form; you fill the form out by entering some text and > selecting the appropriate option from a drop down menu, and then you > press the submit form button. You may be able just to send the same data as the form without having to actually read the form from the web site. If the form uses GET, you can see the data it sends in the URL bar of the browser after you submit the form. If the form uses POST, you will have to look at the actual form to see how the data is formatted. Alternatively you can use ClientForm to fill out the actual form and submit it. http://wwwsearch.sourceforge.net/ClientForm/ > > The webpage subsequently displays links to every entry it can find and > when you click on the link you get the full info of that entry. BeautifulSoup can help you pull the links out of the reply. http://www.crummy.com/software/BeautifulSoup/ urllib2 (in the standard library) can retrieve the final web page, if you need to parse it use BeautifulSoup again. Kent > > I want to automate the whole process with a python script. I figured > out that the csv module(s) would be best for storing the received > information but what module should I use to access the website, fill > out the form, enter each resulting link and retrieve the information? > > Thanks for your time, > Anderson > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Sat Mar 5 15:01:48 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Mar 5 15:01:29 2005 Subject: [Tutor] (no subject) References: Message-ID: <000901c5218b$e8e3c860$735428cf@JSLAPTOP> I want to third the whitespace and comments. Also, looking at your code I notice that each of your > while 1: > play = raw_input("What is your choice? ") #Aks use to enter a choice > from the menu > if play == '3': #If user picks 3 > print "\nHave a nice day!\n" #Tell them to have a nice day > sys.exit() #Then exit the entire thing > elif play == '2': #If user picks 2 > instruct() #Then lets call the instructions function > elif play == '1': #If user picks 1 > game() #Then lets call the game function for the user to play > elif play == '': #This is used is the menu leaves the screen so the > user can get it back > choice() #Bring back the menu > else: > print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" results from the choice are basically functions and functions are objects, so.... (I got this idea from Danny and Kent - I like it...) def exit(): print "\nHave a nice day!\n" # You might want to make this a raw_input so the sys.exit() # user can catch it before the screen disappears... def altexit(): # Alternative exit raw_input("\nHave a nice day!\nPress enter to exit.") # This stops the exit just long enough for the user to press enter and leave sys.exit() def instruct(): ## Whatever instruct is, goes here def game(): ## The game function is here def choice(): ## The choice definition is here ## Now the fun part ## ## We define a dictionary options that stores the strings that the user would input as keys. The values ## are the functions that we just defined options = {"3":altexit, # Notice no parenthesis--we don't want to call the functions when putting them in the dicionary! "2":instruct, "1":game, "":choice} while 1: play = raw_input("What is your choice? ") if play in options.keys(): ## This makes sure that the user input is one of our options options[play]() ## Call the function that is the value of the key that is the choice the user made else: ## Say that the user input is not one of your choices... print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" HTH, Jacob From alan.gauld at freenet.co.uk Sat Mar 5 15:20:25 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Mar 5 15:19:48 2005 Subject: [Tutor] returning table elements with Beautiful Soup References: <42293021.1030309@fastmail.fm> <422941FF.9070205@tds.net> Message-ID: <014c01c5218e$7a6291c0$1cd28751@xp> > > I'm trying to use Beautiful Soup to scrape some data out of an HTML > > table. I can do this using A new one on me, but Beautiful Soup looks very interesting. I've just downloaded it. Thanks for pointing it out. Alan G. From shitizb at yahoo.com Sat Mar 5 15:20:40 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sat Mar 5 15:20:43 2005 Subject: [Tutor] Linked List In-Reply-To: <002201c5211f$cb9660e0$a95428cf@JSLAPTOP> Message-ID: <20050305142041.7620.qmail@web53807.mail.yahoo.com> I could not understand what you exactly mean. In order to explain wat my problem is, here is an example code. Its not exactly what I am doing, I am using multiple threads and a rather complicated code so try and understand the sense rather than the code itself. >>> myls=range(50) >>> for i in myls: print i if i==20: myls.insert(5,5) The point is, the list(both size and elements) is changing even as it is being operated upon. This particular case goes into infinite loop at i=20. Interestingly, I can freely edit the list yet to be traversed, without any ill effects, which would not have been possible if a python list was a pure array(due to immutable length of an array in c). Shitiz --- "Jacob S." wrote: > I'm taking a shot in the dark and answering here. > > Have you tried making a copy of the list, iterating > over the copy, and > changing the original based on the copy? > > Jacob > > > Hi, > > Any body has any idea on how to implement a linked > > list in python? > > Ordinary python lists are not quite the same. what > i > > need is a list i can traverse through > sequentially > > without bothering about the indices, as another > > process is continuously editing this list, by > > inserting and deleting elements even as the list > is > > being traversed. > > > > Shitiz > > > > > > > > > > __________________________________ > > Celebrate Yahoo!'s 10th Birthday! > > Yahoo! Netrospective: 100 Moments of the Web > > http://birthday.yahoo.com/netrospective/ > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Sat Mar 5 15:53:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 15:54:01 2005 Subject: [Tutor] (no subject) In-Reply-To: <000901c5218b$e8e3c860$735428cf@JSLAPTOP> References: <000901c5218b$e8e3c860$735428cf@JSLAPTOP> Message-ID: <4229C804.3030208@tds.net> Jacob S. wrote: > while 1: > play = raw_input("What is your choice? ") > if play in options.keys(): ## This makes sure that the user > input is one of our options 'if play in options' is preferable. options.keys() returns a list of keys that will be searched sequentially. options is a dict which supports fast direct lookup. So when you say 'if play in options.keys()' not only do you type more but you generate an intermediate list and use a slower form of search! > options[play]() ## Call the function that is the > value of the key that is the choice the user made > else: ## Say that the user input > is not one of your choices... > print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" But even better is to make the error message a default option: def bad_choice(): print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" Then the lookup becomes just options.get(play, bad_choice)() Kent From python at venix.com Sat Mar 5 17:32:01 2005 From: python at venix.com (Lloyd Kvam) Date: Sat Mar 5 17:32:05 2005 Subject: [Tutor] cataloging web Page Information Message-ID: <1110040320.5848.10.camel@laptop.venix.com> A minor addition to Kent's advice: urllib2 can be used to post form data to a web site. This is very convenient if the expected data format is stable. You will still need the urlencode from urllib to encode the data to be posted. -- Lloyd Kvam Venix Corp From kent37 at tds.net Sat Mar 5 19:21:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 19:21:18 2005 Subject: [Tutor] Linked List In-Reply-To: <20050305142041.7620.qmail@web53807.mail.yahoo.com> References: <20050305142041.7620.qmail@web53807.mail.yahoo.com> Message-ID: <4229F89A.9030705@tds.net> Shitiz Bansal wrote: > I could not understand what you exactly mean. > > In order to explain wat my problem is, here is an > example code. Its not exactly what I am doing, I am > using multiple threads and a rather complicated code > so try and understand the sense rather than the code > itself. > > >>>>myls=range(50) >>>>for i in myls: > > print i > if i==20: > myls.insert(5,5) > > The point is, the list(both size and elements) is > changing even as it is being operated upon. What Jacob is saying is, one common way to deal with this is to make a copy of the list and iterate over that while changing the original list. Your sample would look like this: myls=range(50) for i in myls[:]: # <-- Note: makes a copy of myls print i if i==20: myls.insert(5,5) Kent > > This particular case goes into infinite loop at i=20. > > Interestingly, I can freely edit the list yet to be > traversed, without any ill effects, which would not > have been possible if a python list was a pure > array(due to immutable length of an array in c). > > Shitiz > > --- "Jacob S." wrote: > > >>I'm taking a shot in the dark and answering here. >> >>Have you tried making a copy of the list, iterating >>over the copy, and >>changing the original based on the copy? >> >>Jacob From amonroe at columbus.rr.com Sat Mar 5 23:11:29 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Mar 5 23:12:16 2005 Subject: [Tutor] Anyone know of a window utility to reverse engineer unknown binary graphic file format? Message-ID: <24467817445.20050305171129@columbus.rr.com> I know it's a long shot but... I have some graphics files from an old DOS game that I want to convert to a normal .png or whatever. Anyone know of a program that can load binary data and view it multiple different ways? Like treating the raw data as 1 bit, 4 bit, 8 bit, planar, linear, adjust the pitch and offset, etc. in some kind of GUI until you get a recognizable image? The game reads its graphic files in 512 byte increments at runtime, judging by sysinterals filemon. This gave me a little hope that the graphics are uncompressed even multiples of 512 bytes each. I used python to read the 1st 512 bytes of the file and output it to another file, for experimentation. I wrote a script to read that in and output the high 4 bits as a byte, and the low 4 bits as a subsequent byte, but that image didn't really look like anything recognizable, loading it as raw into Photoshop. Alan From dyoo at hkn.eecs.berkeley.edu Sat Mar 5 23:31:50 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 5 23:31:59 2005 Subject: [Tutor] Anyone know of a window utility to reverse engineer unknown binary graphic file format? In-Reply-To: <24467817445.20050305171129@columbus.rr.com> Message-ID: On Sat, 5 Mar 2005, R. Alan Monroe wrote: > I have some graphics files from an old DOS game that I want to convert > to a normal .png or whatever. Anyone know of a program that can load > binary data and view it multiple different ways? Like treating the raw > data as 1 bit, 4 bit, 8 bit, planar, linear, adjust the pitch and > offset, etc. in some kind of GUI until you get a recognizable image? Hi Alan, A lot of image types contain a recognizable header that you might be able to use. Python comes with a library that tries its best to recognize certain image file types: http://www.python.org/doc/lib/module-imghdr.html You may want to do a quick check with imghdr to see if it's something standard that 'imghdr' can recognize. Another possibility is to use the 'file' Unix utility, which also recognizes a surprising variety of file formats. Otherwise, I'm out of ideas at the moment. *grin* You may want to ask your question on comp.lang.python, since it is slightly unusual to get a file and have to infer the file type. From shitizb at yahoo.com Sun Mar 6 00:01:34 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sun Mar 6 00:01:37 2005 Subject: [Tutor] Linked List In-Reply-To: <4229F89A.9030705@tds.net> Message-ID: <20050305230134.24036.qmail@web53809.mail.yahoo.com> Got ya, it doesnt however help in my case as inside the for loop also i intend to change the list elements. --- Kent Johnson wrote: > Shitiz Bansal wrote: > > I could not understand what you exactly mean. > > > > In order to explain wat my problem is, here is an > > example code. Its not exactly what I am doing, I > am > > using multiple threads and a rather complicated > code > > so try and understand the sense rather than the > code > > itself. > > > > > >>>>myls=range(50) > >>>>for i in myls: > > > > print i > > if i==20: > > myls.insert(5,5) > > > > The point is, the list(both size and elements) is > > changing even as it is being operated upon. > > What Jacob is saying is, one common way to deal with > this is to make a copy of the list and iterate > over that while changing the original list. Your > sample would look like this: > > myls=range(50) > for i in myls[:]: # <-- Note: makes a copy of myls > print i > if i==20: > myls.insert(5,5) > > Kent > > > > > This particular case goes into infinite loop at > i=20. > > > > Interestingly, I can freely edit the list yet to > be > > traversed, without any ill effects, which would > not > > have been possible if a python list was a pure > > array(due to immutable length of an array in c). > > > > Shitiz > > > > --- "Jacob S." wrote: > > > > > >>I'm taking a shot in the dark and answering here. > >> > >>Have you tried making a copy of the list, > iterating > >>over the copy, and > >>changing the original based on the copy? > >> > >>Jacob > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Celebrate Yahoo!'s 10th Birthday! Yahoo! Netrospective: 100 Moments of the Web http://birthday.yahoo.com/netrospective/ From cyresse at gmail.com Sun Mar 6 00:11:45 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Mar 6 00:11:50 2005 Subject: [Tutor] Anyone know of a window utility to reverse engineer unknown binary graphic file format? In-Reply-To: References: <24467817445.20050305171129@columbus.rr.com> Message-ID: Slightly OT, but I'd recommend Irfanview, a wonderful piece of freeware. If it can't open it, it's probably not in a standard graphics file format. On Sat, 5 Mar 2005 14:31:50 -0800 (PST), Danny Yoo wrote: > > > On Sat, 5 Mar 2005, R. Alan Monroe wrote: > > > I have some graphics files from an old DOS game that I want to convert > > to a normal .png or whatever. Anyone know of a program that can load > > binary data and view it multiple different ways? Like treating the raw > > data as 1 bit, 4 bit, 8 bit, planar, linear, adjust the pitch and > > offset, etc. in some kind of GUI until you get a recognizable image? > > Hi Alan, > > A lot of image types contain a recognizable header that you might be able > to use. Python comes with a library that tries its best to recognize > certain image file types: > > http://www.python.org/doc/lib/module-imghdr.html > > You may want to do a quick check with imghdr to see if it's something > standard that 'imghdr' can recognize. Another possibility is to use the > 'file' Unix utility, which also recognizes a surprising variety of file > formats. > > Otherwise, I'm out of ideas at the moment. *grin* You may want to ask > your question on comp.lang.python, since it is slightly unusual to get a > file and have to infer the file type. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From stbru at teksavvy.com Sun Mar 6 00:28:41 2005 From: stbru at teksavvy.com (=?ISO-8859-1?Q?St=E9phane_Brunet?=) Date: Sun Mar 6 00:28:17 2005 Subject: [Tutor] Linked List In-Reply-To: <4229F89A.9030705@tds.net> References: <20050305142041.7620.qmail@web53807.mail.yahoo.com> <4229F89A.9030705@tds.net> Message-ID: <422A40A9.2000808@teksavvy.com> Kent Johnson wrote: > > What Jacob is saying is, one common way to deal with this is to make a > copy of the list and iterate over that while changing the original > list. Your sample would look like this: Hi, And what if the list is *really* big ? Don't you loose much speed/memory while making a copy ? St?phane From alan.gauld at freenet.co.uk Sun Mar 6 00:56:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 6 00:56:07 2005 Subject: [Tutor] (no subject) References: <000901c5218b$e8e3c860$735428cf@JSLAPTOP> Message-ID: <016701c521df$023bbc20$1cd28751@xp> > ## Now the fun part ## > ## We define a dictionary options that stores the strings that the user > would input as keys. The values > ## are the functions that we just defined > > options = {"3":altexit, # Notice no parenthesis--we don't want to > call the functions when putting them in the dicionary! > "2":instruct, > "1":game, > "":choice} > > while 1: > play = raw_input("What is your choice? ") > if play in options.keys(): > options[play]() > else: > print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" Or more pythonically: while 1: play = raw_input(... try: options[play]() except KeyError: print "\nYou need...." Avoids the search of keys each time, and follows the idiom of "its better to ask forgiveness" Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Mar 6 01:04:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 6 01:04:13 2005 Subject: [Tutor] Linked List References: <20050305142041.7620.qmail@web53807.mail.yahoo.com> Message-ID: <016e01c521e0$21f59260$1cd28751@xp> > >>> myls=range(50) > >>> for i in myls: > print i > if i==20: > myls.insert(5,5) > > The point is, the list(both size and elements) is > changing even as it is being operated upon. You are quite right it is, in general a bad idea to alter the thing you are iterating over. > This particular case goes into infinite loop at i=20. For obvious reasons: you insert something before 20 which moves up one position, the next element in the list is now 20 again. Better to use a while loop over the indices if you must do this kind of thing, then increment the index as well as insert the item. myls = range(50) index = 0 while index < len(myls): print myls[index] if myls[index] == 20: myls.insert(5,5) index += 1 index += 1 But if the changes are being made outside your loop (eg by another thread - dangerous practice anyway!) you need the linked list approach and you also need to treat our list as a protected resource in your threads. ie lock it before using otherwise you may wind up deleting the thing you are working on! HTH, Alan G. From alan.gauld at freenet.co.uk Sun Mar 6 01:08:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 6 01:08:23 2005 Subject: [Tutor] Anyone know of a window utility to reverse engineer unknownbinary graphic file format? References: <24467817445.20050305171129@columbus.rr.com> Message-ID: <017901c521e0$ada59cb0$1cd28751@xp> > I have some graphics files from an old DOS game that I want to convert to > a normal .png or whatever. Anyone know of a program that can load > binary data and view it multiple different ways? Like treating the raw > data as 1 bit, 4 bit, 8 bit, planar, linear, adjust the pitch and > offset, etc. in some kind of GUI until you get a recognizable image? I usually just rename the file by changing the extension till something succeeeds in opening it! There are some graphics format convertors around however so it might be worth googling for them and see if any do auto format detection. Alan G. From kent37 at tds.net Sun Mar 6 01:29:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 6 01:29:26 2005 Subject: [Tutor] Linked List In-Reply-To: <422A40A9.2000808@teksavvy.com> References: <20050305142041.7620.qmail@web53807.mail.yahoo.com> <4229F89A.9030705@tds.net> <422A40A9.2000808@teksavvy.com> Message-ID: <422A4EE2.3020800@tds.net> St?phane Brunet wrote: > Kent Johnson wrote: > >> >> What Jacob is saying is, one common way to deal with this is to make a >> copy of the list and iterate over that while changing the original >> list. Your sample would look like this: > > > Hi, > > And what if the list is *really* big ? Don't you loose much speed/memory > while making a copy ? Well, you do need double the memory and it does take time to copy the list. Whether it is too much will depend on the specific requirements. If you use a linked list instead of a built-in list you will more than double the memory requirements immediately. In a linked list, for each data item you store a reference to the data, a reference to the next node and the overhead of the node class instance. The built-in list just has a single reference for each item and a single instance overhead. The time to traverse a linked list may well be much greater than for a builtin list. Builtins are fast, often faster than anything you can write yourself in Python. In Python often the simple solution works best. Don't dismiss it until you try it :-) Alternatives for filtering a list are - use a list comprehension to build a new list. This is often the best solution. It copies the elements being kept, but it avoids having to shift list elements when one element is deleted. - work from the back of the list - it is safe to iterate a list in reverse and delete elements as you go. I don't think either of these meet the OP's requirements, though. As I understand it, he wants to iterate a list, changing the list as he goes, while the list is also being modified by another thread. A naive linked list will not satisfy these requirements either - some sort of synchronization will be needed to avoid, for example, one thread linking a new item onto an item that is being deleted by the other thread. Kent From kabads at gmail.com Sun Mar 6 08:41:30 2005 From: kabads at gmail.com (Adam Cripps) Date: Sun Mar 6 08:41:35 2005 Subject: [Tutor] (no subject) In-Reply-To: References: <42289774.6010607@po-box.mcgill.ca> Message-ID: On Sun, 6 Mar 2005 07:38:54 +0000, Adam Cripps wrote: > On Fri, 04 Mar 2005 12:14:28 -0500, Brian van den Broek > wrote: > Kevin said unto the world upon 2005-03-04 10:43: > > Hello all. I have just completed my very first python program just a > > simple number guessing. I would like for someone to try it out if they > > could and let me know how I did with it and where I could have > > improved apon it. There are t files main.py and defs.py > > > > Thanks > > Hi Kevin, > > Though I am a learner, too, I have a few comments. They are more about > style than substance. > > 1) A lot of your code comments get in the way of my reading and easily > understanding the code. Consider: > > .# leading `.'s to foil google groups and other whitespace stripping > readers > .if play == '3': #If user picks 3 > . print "\nHave a nice day!\n" #Tell them to have a nice day > . sys.exit() #Then exit the entire thing > > I think this would be much easier to read if it were like: > > .if play == '3': # If user picks 3 > . print "\nHave a nice day!\n" # Tell them to have a nice day > . sys.exit() # Then exit the entire thing > > (Note that some people hate the comments along the side and would > prefer them the precede the line(s) they comment on. I like the 2 > column approach, but that's just one duffer's view.) > > But, even better would be: > > .if play == '3': > . print "\nHave a nice day!\n" > . sys.exit() > Is the tutor list mirrored on usenet such as google groups? I've searched and not found it. I think it's a bit harsh to blame the style on a client that strips white-space, where he has no control over it. Are we not better off using another client? I use gmail [1] to collect this kind of email and using the recent thread entitle "Reading Tutor with gmail: monospace fonts" have managed to make my mail monospace, which makes it a lot easier to read. None of the whitespace was stripped in my mail, and the style looked fine. In fact, by littering it with '.' you are making it more of a task to run this script, as you have to strip all the '.' out first - a real pain. Adam [1] Although gmail is far from perfect. From cyresse at gmail.com Sun Mar 6 08:44:34 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Mar 6 08:44:37 2005 Subject: [Tutor] (no subject) In-Reply-To: References: <42289774.6010607@po-box.mcgill.ca> Message-ID: How about everyone uses www.rafb.net/paste for long bits of code? I know I do, as it colours functions, classes differently, etc, and it respects tabs. On Sun, 6 Mar 2005 07:41:30 +0000, Adam Cripps wrote: > On Sun, 6 Mar 2005 07:38:54 +0000, Adam Cripps wrote: > > On Fri, 04 Mar 2005 12:14:28 -0500, Brian van den Broek > > wrote: > > Kevin said unto the world upon 2005-03-04 10:43: > > > Hello all. I have just completed my very first python program just a > > > simple number guessing. I would like for someone to try it out if they > > > could and let me know how I did with it and where I could have > > > improved apon it. There are t files main.py and defs.py > > > > > > Thanks > > > > Hi Kevin, > > > > Though I am a learner, too, I have a few comments. They are more about > > style than substance. > > > > 1) A lot of your code comments get in the way of my reading and easily > > understanding the code. Consider: > > > > .# leading `.'s to foil google groups and other whitespace stripping > > readers > > .if play == '3': #If user picks 3 > > . print "\nHave a nice day!\n" #Tell them to have a nice day > > . sys.exit() #Then exit the entire thing > > > > I think this would be much easier to read if it were like: > > > > .if play == '3': # If user picks 3 > > . print "\nHave a nice day!\n" # Tell them to have a nice day > > . sys.exit() # Then exit the entire thing > > > > (Note that some people hate the comments along the side and would > > prefer them the precede the line(s) they comment on. I like the 2 > > column approach, but that's just one duffer's view.) > > > > But, even better would be: > > > > .if play == '3': > > . print "\nHave a nice day!\n" > > . sys.exit() > > > > > Is the tutor list mirrored on usenet such as google groups? I've > searched and not found it. I think it's a bit harsh to blame the style > on a client that strips white-space, where he has no control over it. > Are we not better off using another client? > > I use gmail [1] to collect this kind of email and using the recent thread > entitle "Reading Tutor with gmail: monospace fonts" have managed to > make my mail monospace, which makes it a lot easier to read. None of > the whitespace was stripped in my mail, and the style looked fine. In > fact, by littering it with '.' you are making it more of a task to run > this script, as you have to strip all the '.' out first - a real pain. > > Adam > > [1] Although gmail is far from perfect. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From bvande at po-box.mcgill.ca Sun Mar 6 09:40:25 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Mar 6 09:42:16 2005 Subject: [Tutor] (no subject) In-Reply-To: References: <42289774.6010607@po-box.mcgill.ca> Message-ID: <422AC1F9.9030403@po-box.mcgill.ca> Adam Cripps said unto the world upon 2005-03-06 02:38: > On Fri, 04 Mar 2005 12:14:28 -0500, Brian van den Broek > wrote: > >>Kevin said unto the world upon 2005-03-04 10:43: >> >>>Hello all. I have just completed my very first python program just a >>>simple number guessing. I would like for someone to try it out if they >>>could and let me know how I did with it and where I could have >>>improved apon it. There are t files main.py and defs.py >>> >>>Thanks >> >>Hi Kevin, >> >>Though I am a learner, too, I have a few comments. They are more about >>style than substance. >> >>1) A lot of your code comments get in the way of my reading and easily >>understanding the code. Consider: >> >>.# leading `.'s to foil google groups and other whitespace stripping >>readers > > > Is the tutor list mirrored on usenet such as google groups? I've > searched and not found it. I think it's a bit harsh to blame the style > on a client that strips white-space, where he has no control over it. > Are we not better off using another client? Hi Adam, I don't know if tutor is viewable through google groups or not. However, it has proved a problem on comp.lang.python, where I picked up the leading '.' trick. Noting that Kevin (the OP) was using a gmail account and not knowing if the google groups' leading whitespace stripping `feature' was also a gmail feature, I figured it would be better to be safe and put the possibly needless '.'s in. It would indeed have been harsh to complain about his whitespace if it were google-striped whitespace at issue. But, when I commented upon the lack of whitespace in his code, I said B> Whitespace is a good thing. Python needs it horizontally, but B> you can (and, IMHO, should) employ vertical whitespace to chunk B> up the code. So, it is a different issue. > I use gmail to collect this kind of email and using the recent thread > entitle "Reading Tutor with gmail: monospace fonts" have managed to > make my mail monospace, which makes it a lot easier to read. None of > the whitespace was stripped in my mail, and the style looked fine. That is good to know; I won't worry next time. > In fact, by littering it with '.' you are making it more of a task to run > this script, as you have to strip all the '.' out first - a real pain. A bummer, yes. And one to blame on google groups -- it is much less of a pain than loosing all leading whitespace. But, not too much a pain, either (we are programming here, right ;-) : # assuming the code has been saved to a .py file whose lines # are available for iteration in python_file stripped_lines = [] for line in python_file: if line.startswith('.'): line = line[1:] stripped_lines.append(line) # write the stripped_line to the original .py file, and you're # good to go. Best, Brian vdB From jeffshannon at gmail.com Sun Mar 6 10:42:11 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Sun Mar 6 10:42:16 2005 Subject: [Tutor] Linked List In-Reply-To: <20050305142041.7620.qmail@web53807.mail.yahoo.com> References: <002201c5211f$cb9660e0$a95428cf@JSLAPTOP> <20050305142041.7620.qmail@web53807.mail.yahoo.com> Message-ID: <5d0204a1050306014228206a09@mail.gmail.com> On Sat, 5 Mar 2005 06:20:40 -0800 (PST), Shitiz Bansal wrote: > In order to explain wat my problem is, here is an > example code. Its not exactly what I am doing, I am > using multiple threads and a rather complicated code > so try and understand the sense rather than the code > itself. > > >>> myls=range(50) > >>> for i in myls: > print i > if i==20: > myls.insert(5,5) > > The point is, the list(both size and elements) is > changing even as it is being operated upon. My first thought was to say, "Use a queue.Queue." But it appears that you need to be able to do more than just add items at the end of the queue. I suspect that what you need is along the lines of a "priority queue". That is, something that works approximately like a queue, but when you add items to it, you also specify a priority for them. Then, when you retrieve an item from the queue, what you get is not necessarily the first-inserted item, but rather the item with highest priority. You might want to check the Cookbook to see if there's a priority queue recipe there. If not, I suspect that Google can be convinced to yield something... Jeff Shannon From pythontut at pusspaws.net Sun Mar 6 10:49:43 2005 From: pythontut at pusspaws.net (Dave S) Date: Sun Mar 6 10:49:51 2005 Subject: [Tutor] 2d list matrix 7 x 75 problem Message-ID: <422AD237.5030205@pusspaws.net> Hello, I need to generate a list 2d matrix of the kind ... [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '']] except its dimensions need to be 7 x 75. I thought I had it sorted with map2 = [ [''] *7 ] *75 until the coding screwed up & I realised I had 75 references to the same list :-( so I thought I would be clever with ... >>> a=[0]*5 >>> a [0, 0, 0, 0, 0] >>> b=[a[:]]*5 same problem. It seems realy simple but how do I generate a 7 x 75 list matrix ? Dave Oh PS Is there a more elegant solution to if string == 'sun' or string == 'mon' or string == 'tue' or string == 'wed' or string == 'thu' or string == 'fri' or string == 'sat': the above works but any suggestions would be welcome :-) From jeffshannon at gmail.com Sun Mar 6 11:00:52 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Sun Mar 6 11:00:55 2005 Subject: [Tutor] 2d list matrix 7 x 75 problem In-Reply-To: <422AD237.5030205@pusspaws.net> References: <422AD237.5030205@pusspaws.net> Message-ID: <5d0204a1050306020033cae2e5@mail.gmail.com> On Sun, 06 Mar 2005 09:49:43 +0000, Dave S wrote: > I need to generate a list 2d matrix of the kind ... > > [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', > '', '', '', ''], ['', '', '', '', '']] > > except its dimensions need to be 7 x 75. I thought I had it sorted with > > map2 = [ [''] *7 ] *75 > > until the coding screwed up & I realised I had 75 references to the same > list :-( Try: map2 = [['']*7 for n in range(75)] The list comprehension will execute ['']*7 each iteration, creating a new list instead of just creating new references to the same list. > Oh PS > > Is there a more elegant solution to > > if string == 'sun' or string == 'mon' or string == 'tue' or string == > 'wed' or string == 'thu' or string == 'fri' or string == 'sat': Try: if string in ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']: (Or perhaps look into using the datetime module, depending on how detailed your needs are.) Jeff Shannon From pythontut at pusspaws.net Sun Mar 6 11:37:13 2005 From: pythontut at pusspaws.net (Dave S) Date: Sun Mar 6 11:37:22 2005 Subject: [Tutor] 2d list matrix 7 x 75 problem In-Reply-To: <5d0204a1050306020033cae2e5@mail.gmail.com> References: <422AD237.5030205@pusspaws.net> <5d0204a1050306020033cae2e5@mail.gmail.com> Message-ID: <422ADD59.6030001@pusspaws.net> Jeff Shannon wrote: >On Sun, 06 Mar 2005 09:49:43 +0000, Dave S wrote: > > > >>I need to generate a list 2d matrix of the kind ... >> >>[['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', >>'', '', '', ''], ['', '', '', '', '']] >> >>except its dimensions need to be 7 x 75. I thought I had it sorted with >> >>map2 = [ [''] *7 ] *75 >> >>until the coding screwed up & I realised I had 75 references to the same >>list :-( >> >> > >Try: > >map2 = [['']*7 for n in range(75)] > >The list comprehension will execute ['']*7 each iteration, creating a >new list instead of just creating new references to the same list. > > > > >>Oh PS >> >>Is there a more elegant solution to >> >>if string == 'sun' or string == 'mon' or string == 'tue' or string == >>'wed' or string == 'thu' or string == 'fri' or string == 'sat': >> >> > >Try: > >if string in ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']: > >(Or perhaps look into using the datetime module, depending on how >detailed your needs are.) > >Jeff Shannon >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > Many thanks Dave :-) :-) :-) :-) From maxnoel_fr at yahoo.fr Sun Mar 6 13:42:35 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Mar 6 13:42:43 2005 Subject: [Tutor] 2d list matrix 7 x 75 problem In-Reply-To: <422AD237.5030205@pusspaws.net> References: <422AD237.5030205@pusspaws.net> Message-ID: <7fdc8d047bf956e1c0b6c8fb4d43a1c8@yahoo.fr> On Mar 6, 2005, at 09:49, Dave S wrote: > so I thought I would be clever with ... > >>> a=[0]*5 > >>> a > [0, 0, 0, 0, 0] > >>> b=[a[:]]*5 > > same problem. > > It seems realy simple but how do I generate a 7 x 75 list matrix ? > > Dave Try this: >>> a = [''] * 5 >>> b = [a[:] for i in range(5)] >>> b [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '']] >>> b[0] is b[1] False List comprehensions. Gotta love 'em... ^^ > Is there a more elegant solution to > > if string == 'sun' or string == 'mon' or string == 'tue' or string == > 'wed' or string == 'thu' or string == 'fri' or string == 'sat': Yes, there is. if a in ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'): (also works with a list or a dictionary) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From alan.gauld at freenet.co.uk Sun Mar 6 16:54:02 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 6 16:53:05 2005 Subject: [Tutor] (no subject) References: <42289774.6010607@po-box.mcgill.ca> Message-ID: <019b01c52264$b89d2eb0$1cd28751@xp> > Is the tutor list mirrored on usenet such as google groups? I've > searched and not found it. Nope, the archives are available but there is no usenet mirroe. > I think it's a bit harsh to blame the style > on a client that strips white-space, where he has no control over it. > Are we not better off using another client? Unfortunately there seem to be several clients that do this. And in fat even clients that don;t do it can be configured to do so! It seems to be particularly true of HTML based mail tools, yet another reason to avoid HTML mail!. > the whitespace was stripped in my mail, and the style looked fine. In > fact, by littering it with '.' you are making it more of a task to run > this script, as you have to strip all the '.' out first - a real pain. Most decent text editors can do a search/replace on the start of line, :.,%s/^\.// in vim for example... But you are right, it does clutter it up, but rather that than lose the all important formatting due to some rogue email client (or even server in some cases!) Alan G. From jfouhy at paradise.net.nz Sun Mar 6 19:07:45 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: Sun Mar 6 19:07:42 2005 Subject: [Tutor] Linked List In-Reply-To: <5d0204a1050306014228206a09@mail.gmail.com> References: <002201c5211f$cb9660e0$a95428cf@JSLAPTOP> <20050305142041.7620.qmail@web53807.mail.yahoo.com> <5d0204a1050306014228206a09@mail.gmail.com> Message-ID: <422B46F1.9040404@paradise.net.nz> Jeff Shannon wrote: > You might want to check the Cookbook to see if there's a priority > queue recipe there. If not, I suspect that Google can be convinced to > yield something... From the bisect module docs: import Queue, bisect class PriorityQueue(Queue.Queue): def _put(self, item): bisect.insort(self.queue, item) # usage queue = PriorityQueue(0) queue.put((2, "second")) queue.put((1, "first")) queue.put((3, "third")) priority, value = queue.get() -- John. From amonroe at columbus.rr.com Sun Mar 6 19:39:32 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun Mar 6 19:40:16 2005 Subject: [Tutor] (no subject) In-Reply-To: <019b01c52264$b89d2eb0$1cd28751@xp> References: <42289774.6010607@po-box.mcgill.ca> <019b01c52264$b89d2eb0$1cd28751@xp> Message-ID: <7541500466.20050306133932@columbus.rr.com> >> Is the tutor list mirrored on usenet such as google groups? I've >> searched and not found it. > Nope, the archives are available but there is no usenet mirroe. What about this: http://dir.gmane.org/gmane.comp.python.tutor Alan From apple_py at biz-experts.net Sun Mar 6 20:28:43 2005 From: apple_py at biz-experts.net (Victor Bouffier) Date: Sun Mar 6 20:28:45 2005 Subject: [Tutor] MySQLdb error while inserting records Message-ID: <422B59EB.2030907@biz-experts.net> Hi all, I consider myself fairly proficient with SQL, but I'm still getting the hang of the MySQL API. I am working through the examples in "Open Source Web Development with LAMP: Using Linux, Apache, MySQL, Perl, and PHP" by James Lee and Brent Ware, and trying to make the third "P" to be Python. :) There is an example in the book which is written in Perl, used to insert new records to MySQL. I tried it as it is written and it works fine. I have migrated to Python another example that gets all of the records in the age_information table (SELECT query), and it is getting the data successfully. However, I am having problems with the program to insert records. The following is my modified code in Python: ------------------------------ 1 #!/usr/bin/python 2 # connect.py 3 4 import sys 5 import MySQLdb 6 7 if len(sys.argv) != 4: 8 print "You have to enter lastname, firstname and age\n" 9 sys.exit(1) 10 11 # This is to change the age type from str to int 12 last, first, strAge = sys.argv[1:] 13 age = int(strAge) 14 15 # Some debugging lines 16 print last, first, age 17 print type(last), type(first), type(age) 18 print 19 #sys.exit() 20 21 22 try: 23 conn = MySQLdb.connect(host='localhost', 24 user='apache', passwd='LampIsCool', db='people') 25 except: 26 print "Could not connect\n" 27 sys.exit(1) 28 29 c = conn.cursor() 30 31 # prepare the SQL, exit() if the preparation fails 32 query = ''' 33 INSERT INTO age_information 34 (lastname, firstname, age) 35 VALUES (?, ?, ?) 36 ''' 37 38 # execute the SQL 39 records = c.execute(query, (last, first, age)) 40 if records >= 1: 41 print "Succesfully inserted %d records" % records 42 else: 43 print "Could not insert anything, sorry." 44 45 c.commit() 46 c.close() 47 conn.close() 48 ------------------------------ Executing the script from the command line, I get the following output: ------------------------------ $ ./insert.py Cool Joe 13 Cool Joe 13 Traceback (most recent call last): File "./insert.py", line 39, in ? records = c.execute(query, (last, first, age)) File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py", line 95, in execute return self._execute(query, args) File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py", line 110, in _execute self.errorhandler(self, TypeError, m) File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue TypeError: not all arguments converted during string formatting ------------------------------ I was getting this same error so I entered lines 12 and 13 to change the age from type string to integer. No change. Do you know what am I missing? Thanks to all. -- Victor Bouffier Finance Manager www.grupoandersons.com From kent37 at tds.net Sun Mar 6 20:40:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 6 20:40:53 2005 Subject: [Tutor] MySQLdb error while inserting records In-Reply-To: <422B59EB.2030907@biz-experts.net> References: <422B59EB.2030907@biz-experts.net> Message-ID: <422B5CBC.10907@tds.net> Victor Bouffier wrote: > > Hi all, > > I consider myself fairly proficient with SQL, but I'm still getting the > hang of the MySQL API. I am working through the examples in "Open Source > Web Development with LAMP: Using Linux, Apache, MySQL, Perl, and PHP" by > James Lee and Brent Ware, and trying to make the third "P" to be Python. :) > > There is an example in the book which is written in Perl, used to insert > new records to MySQL. I tried it as it is written and it works fine. I > have migrated to Python another example that gets all of the records in > the age_information table (SELECT query), and it is getting the data > successfully. However, I am having problems with the program to insert > records. According to this page http://sourceforge.net/docman/display_doc.php?docid=26238&group_id=22307 MySQLdb uses the 'format' style of passing parameters to SQL, not the questionmark style you have used below. So change query to > 32 query = ''' > 33 INSERT INTO age_information > 34 (lastname, firstname, age) > 35 VALUES (%s, %s, %s) > 36 ''' Kent > > The following is my modified code in Python: > > ------------------------------ > 1 #!/usr/bin/python > 2 # connect.py > 3 > 4 import sys > 5 import MySQLdb > 6 > 7 if len(sys.argv) != 4: > 8 print "You have to enter lastname, firstname and age\n" > 9 sys.exit(1) > 10 > 11 # This is to change the age type from str to int > 12 last, first, strAge = sys.argv[1:] > 13 age = int(strAge) > 14 > 15 # Some debugging lines > 16 print last, first, age > 17 print type(last), type(first), type(age) > 18 print > 19 #sys.exit() > 20 > 21 > 22 try: > 23 conn = MySQLdb.connect(host='localhost', > 24 user='apache', passwd='LampIsCool', db='people') > 25 except: > 26 print "Could not connect\n" > 27 sys.exit(1) > 28 > 29 c = conn.cursor() > 30 > 31 # prepare the SQL, exit() if the preparation fails > 32 query = ''' > 33 INSERT INTO age_information > 34 (lastname, firstname, age) > 35 VALUES (?, ?, ?) > 36 ''' > 37 > 38 # execute the SQL > 39 records = c.execute(query, (last, first, age)) > 40 if records >= 1: > 41 print "Succesfully inserted %d records" % records > 42 else: > 43 print "Could not insert anything, sorry." > 44 > 45 c.commit() > 46 c.close() > 47 conn.close() > 48 > ------------------------------ > > Executing the script from the command line, I get the following output: > > > ------------------------------ > $ ./insert.py Cool Joe 13 > Cool Joe 13 > > > Traceback (most recent call last): > File "./insert.py", line 39, in ? > records = c.execute(query, (last, first, age)) > File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py", line 95, in > execute > return self._execute(query, args) > File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py", line 110, > in _execute > self.errorhandler(self, TypeError, m) > File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line > 33, in defaulterrorhandler > raise errorclass, errorvalue > TypeError: not all arguments converted during string formatting > ------------------------------ > > I was getting this same error so I entered lines 12 and 13 to change the > age from type string to integer. No change. > Do you know what am I missing? > > Thanks to all. > From apple_py at biz-experts.net Mon Mar 7 01:09:53 2005 From: apple_py at biz-experts.net (Victor Bouffier) Date: Mon Mar 7 01:10:07 2005 Subject: [Tutor] MySQLdb error while inserting records In-Reply-To: <422B5CBC.10907@tds.net> References: <422B59EB.2030907@biz-experts.net> <422B5CBC.10907@tds.net> Message-ID: <422B9BD1.4000701@biz-experts.net> Yes! That did it. I got confused since Programming Python mentions the '?' for arguments, although I failed to notice it was just used as an example. Actual identifiers could vary depending on the database. Thanks a lot Kent. Kent Johnson wrote: > Victor Bouffier wrote: > >> >> Hi all, >> >> I consider myself fairly proficient with SQL, but I'm still getting >> the hang of the MySQL API. I am working through the examples in "Open >> Source Web Development with LAMP: Using Linux, Apache, MySQL, Perl, >> and PHP" by James Lee and Brent Ware, and trying to make the third >> "P" to be Python. :) >> >> There is an example in the book which is written in Perl, used to >> insert new records to MySQL. I tried it as it is written and it works >> fine. I have migrated to Python another example that gets all of the >> records in the age_information table (SELECT query), and it is >> getting the data successfully. However, I am having problems with the >> program to insert records. > > > According to this page > http://sourceforge.net/docman/display_doc.php?docid=26238&group_id=22307 > MySQLdb uses the 'format' style of passing parameters to SQL, not the > questionmark style you have used below. So change query to > > 32 query = ''' > > 33 INSERT INTO age_information > > 34 (lastname, firstname, age) > > 35 VALUES (%s, %s, %s) > > 36 ''' > > Kent > -- Victor Bouffier Finance Manager www.grupoandersons.com From tameyer at ihug.co.nz Mon Mar 7 01:18:55 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Mon Mar 7 01:19:08 2005 Subject: [Tutor] Intro for interfacing with Microsoft Access? In-Reply-To: Message-ID: > Does anyone know of any online resource that explains how to > interface to Microsoft Access via Python, where the intended > audience is someone who knows Python, but not the Microsoft innards? These two pages are quite good: =Tony.Meyer From kent37 at tds.net Mon Mar 7 01:29:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 7 01:29:50 2005 Subject: [Tutor] Intro for interfacing with Microsoft Access? In-Reply-To: References: Message-ID: <422BA07A.30106@tds.net> Tony Meyer wrote: >>Does anyone know of any online resource that explains how to >>interface to Microsoft Access via Python, where the intended >>audience is someone who knows Python, but not the Microsoft innards? > > > These two pages are quite good: > > > adodbapi gives a Python DB-API interface to ADO. It seems to work with Access. http://sourceforge.net/projects/adodbapi Kent > > =Tony.Meyer > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From tameyer at ihug.co.nz Mon Mar 7 01:53:02 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Mon Mar 7 01:53:11 2005 Subject: [Tutor] Intro for interfacing with Microsoft Access? In-Reply-To: Message-ID: [Terry Carroll] >>> Does anyone know of any online resource that explains how to >>> interface to Microsoft Access via Python, where the intended >>> audience is someone who knows Python, but not the Microsoft innards? [Tony Meyer] >> These two pages are quite good: >> >> >> [Terry Carroll] > Thanks. Unfortunately, both of those seem to assume you know > Python and the Win APIs, but not how to connect the, For > someone who doesn't know the APIs, they're actually not very helpful. The second link has very simple steps - you basically just retype the code from steps 1 to 3 and you're all connected. Then pick one of the following steps, depending on what you want to (read, insert, etc), and retype the code from there. Once you have the recordset object (steps 1-3), you can easily modify the existing examples to do whatever you want just by referencing the reference material in Access itself (I forget what it's called - the object reference material that you get to via the macro stuff). When I first needed to work with Access, I knew nothing about ADO or coding Access, but something about writing Python, and this got me up and running very easily. > But I do appreciate you taking the time to point them out. No worries. =Tony.Meyer From GLS33782 at msn.com Sat Mar 5 19:16:57 2005 From: GLS33782 at msn.com (Gregory Sexton) Date: Mon Mar 7 02:27:14 2005 Subject: [Tutor] help Message-ID: Is there a forum for the complete beginning Python student? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050305/c305c807/attachment.html From GLS33782 at msn.com Sun Mar 6 02:50:22 2005 From: GLS33782 at msn.com (Gregory Sexton) Date: Mon Mar 7 02:27:16 2005 Subject: [Tutor] help Message-ID: Does sp1 and sp2 in Wwindows XP block certain python commands? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050305/26c130ab/attachment.htm From dyoo at hkn.eecs.berkeley.edu Mon Mar 7 02:48:04 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 7 02:48:07 2005 Subject: [Tutor] Linked List In-Reply-To: <5d0204a1050306014228206a09@mail.gmail.com> Message-ID: > > >>> myls=range(50) > > >>> for i in myls: > > print i > > if i==20: > > myls.insert(5,5) > > > > The point is, the list(both size and elements) is > > changing even as it is being operated upon. > > My first thought was to say, "Use a queue.Queue." But it appears that > you need to be able to do more than just add items at the end of the > queue. > > I suspect that what you need is along the lines of a "priority queue". > That is, something that works approximately like a queue, but when you > add items to it, you also specify a priority for them. Then, when you > retrieve an item from the queue, what you get is not necessarily the > first-inserted item, but rather the item with highest priority. Priority queues are already a part of the Standard Library in the 'heapq' module: http://www.python.org/doc/lib/module-heapq.html We used this as part of a program that showed an example of a discrete simulation: http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2503815 Best of wishes! From kent37 at tds.net Mon Mar 7 03:19:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 7 03:19:50 2005 Subject: [Tutor] help In-Reply-To: References: Message-ID: <422BBA3F.3020909@tds.net> Gregory Sexton wrote: > Is there a forum for the complete beginning Python student? Yes, this is it. Kent From kent37 at tds.net Mon Mar 7 03:20:31 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 7 03:20:35 2005 Subject: [Tutor] help In-Reply-To: References: Message-ID: <422BBA6F.6020304@tds.net> Gregory Sexton wrote: > Does sp1 and sp2 in Wwindows XP block certain python commands? I haven't heard of any; is there a command you are having trouble with? Kent From ravikishants at yahoo.com Mon Mar 7 06:35:16 2005 From: ravikishants at yahoo.com (Ravi Kishan T.S) Date: Mon Mar 7 06:35:23 2005 Subject: [Tutor] How to get graphical representation in Excel file In-Reply-To: 6667 Message-ID: <20050307053516.48114.qmail@web50402.mail.yahoo.com> Hi! I am working on Python on Windows XP, Iam being able to create or generate an Excel file using python, but unable to write the excel file with the graphs in it. I want to represent some data in the form of Graph (Gant chart, Pie chart and all), Can somebody help me with this. Regards Ravi __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050306/9e324331/attachment.htm From ravikishants at yahoo.com Mon Mar 7 06:35:16 2005 From: ravikishants at yahoo.com (Ravi Kishan T.S) Date: Mon Mar 7 06:35:24 2005 Subject: [Tutor] How to get graphical representation in Excel file In-Reply-To: 6667 Message-ID: <20050307053516.48114.qmail@web50402.mail.yahoo.com> Hi! I am working on Python on Windows XP, Iam being able to create or generate an Excel file using python, but unable to write the excel file with the graphs in it. I want to represent some data in the form of Graph (Gant chart, Pie chart and all), Can somebody help me with this. Regards Ravi __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050306/9e324331/attachment.html From cyresse at gmail.com Mon Mar 7 11:48:07 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Mar 7 11:48:12 2005 Subject: [Tutor] How to get graphical representation in Excel file In-Reply-To: <20050307053516.48114.qmail@web50402.mail.yahoo.com> References: <20050307053516.48114.qmail@web50402.mail.yahoo.com> Message-ID: Erm.... win32api? On Sun, 6 Mar 2005 21:35:16 -0800 (PST), Ravi Kishan T.S wrote: > Hi! > > I am working on Python on Windows XP, Iam being able to create or generate > an Excel file using python, but unable to write the excel file with the > graphs in it. I want to represent some data in the form of Graph (Gant > chart, Pie chart and all), > > Can somebody help me with this. > > Regards > Ravi > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Mon Mar 7 17:46:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 7 17:46:52 2005 Subject: [Tutor] help In-Reply-To: References: <422BBA6F.6020304@tds.net> Message-ID: <422C8572.5030605@tds.net> Gregory Sexton wrote: > Thanks for the help! Sorry for the trivial questions, but I guess we all > have to start somewhere. Beginning python student, OS Windows XP,using > Python 2.4. Also novice to programming. I cant get the "/a" command to > work. I don't know what the "/a" command is, please give more details. I get an elongated 0 in my Python interpreter, but no sound. I don't know what you mean by that either. Some tips for getting help from this list: - post actual code. It's OK if it's broken, we will help fix it - post actual error messages including the entire stack trace (everything from the line that says "Traceback (most recent call last)"). Python error messages have a lot of useful content that can help someone else diagnose a problem. - please send replies to the list so everyone can benefit and help Kent By > the way I am learning from a book entitled "Python Programming for the > absolute beginner" by Michael Dawson. Thanks again. > From maxnoel_fr at yahoo.fr Mon Mar 7 17:52:54 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon Mar 7 17:53:00 2005 Subject: [Tutor] help In-Reply-To: <422C8572.5030605@tds.net> References: <422BBA6F.6020304@tds.net> <422C8572.5030605@tds.net> Message-ID: On Mar 7, 2005, at 16:46, Kent Johnson wrote: > Gregory Sexton wrote: >> Thanks for the help! Sorry for the trivial questions, but I guess we >> all have to start somewhere. Beginning python student, OS Windows >> XP,using Python 2.4. Also novice to programming. I cant get the >> "/a" command to work. > > I don't know what the "/a" command is, please give more details. I find it extremely unlikely that Python, even in its Windows incarnation, support a "/a" switch, or any slash switch for that matter. Python is a UNIX program -- its switches start with one or two dashes, as the slash is the directory separator. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From klappnase at freenet.de Mon Mar 7 18:33:45 2005 From: klappnase at freenet.de (Michael Lange) Date: Mon Mar 7 18:30:37 2005 Subject: [Tutor] help In-Reply-To: <422C8572.5030605@tds.net> References: <422BBA6F.6020304@tds.net> <422C8572.5030605@tds.net> Message-ID: <20050307183345.1bfc23bf.klappnase@freenet.de> On Mon, 07 Mar 2005 11:46:42 -0500 Kent Johnson wrote: > Gregory Sexton wrote: > > Thanks for the help! Sorry for the trivial questions, but I guess we all > > have to start somewhere. Beginning python student, OS Windows XP,using > > Python 2.4. Also novice to programming. I cant get the "/a" command to > > work. > > I don't know what the "/a" command is, please give more details. > > I get an elongated 0 in my Python interpreter, but no sound. > Sound? Maybe you meant print "\a" ? Michael From stygian at tesco.net Mon Mar 7 18:44:30 2005 From: stygian at tesco.net (glen) Date: Mon Mar 7 18:43:12 2005 Subject: [Tutor] help Message-ID: <1110217470.2915.18.camel@localhost> Gregory Sexton wrote: > Thanks for the help! Sorry for the trivial questions, but I guess we all > have to start somewhere. Beginning python student, OS Windows XP,using > Python 2.4. Also novice to programming. I cant get the "/a" command to > work. Shouldn't it be "\a", and it won't work from IDLE. You can save the file with the .py extension, and double click it from the file manager and it works fine. I booted XP JUST to test it :) > the way I am learning from a book entitled "Python Programming for the > absolute beginner" by Michael Dawson. Thanks again. On page 25 there is a paragraph called 'trap' that warns about this. Hope this has helped, a little. Glen From dyoo at hkn.eecs.berkeley.edu Mon Mar 7 19:11:18 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 7 19:11:24 2005 Subject: [Tutor] How to get graphical representation in Excel file In-Reply-To: Message-ID: [Ravi] > > I am working on Python on Windows XP, Iam being able to create or > > generate an Excel file using python, but unable to write the excel > > file with the graphs in it. I want to represent some data in the form > > of Graph (Gant chart, Pie chart and all), [Liam] > Erm.... win32api? Hi Ravi, As Liam mentions, your question is really specific to win32api material; I'm not sure if we at Tutor will be as expert about this topic as the folks on the win32api list. Try asking your question on the win32api list: http://mail.python.org/mailman/listinfo/python-win32 Best of wishes to you! From alan.gauld at freenet.co.uk Mon Mar 7 19:14:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Mar 7 19:14:42 2005 Subject: [Tutor] help References: Message-ID: <002b01c52341$91aba9c0$dbc98751@xp> > Is there a forum for the complete beginning Python student? Yes, this is it! Welcome. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Mar 7 19:15:59 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Mar 7 19:15:43 2005 Subject: [Tutor] help References: Message-ID: <003901c52341$b7511d40$dbc98751@xp> > Does sp1 and sp2 in Wwindows XP block certain python commands? Nope. Although SP2 does various strange things that could cause some bits of Python to behave strangely but there are plenty people using SP2 and Python suvccessfully. Alan G. From alan.gauld at freenet.co.uk Mon Mar 7 19:18:52 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Mar 7 19:18:48 2005 Subject: [Tutor] How to get graphical representation in Excel file References: <20050307053516.48114.qmail@web50402.mail.yahoo.com> Message-ID: <004d01c52342$1e91c310$dbc98751@xp> > I am working on Python on Windows XP, Iam being able to create or > generate an Excel file using python, but unable to write the excel > file with the graphs in it. I want to represent some data in the > form of Graph (Gant chart, Pie chart and all), Creating graphs in Excel is best done within Excel! You can do it using the COM inteface and the Python winall package but its not simple unless you are very familiar with COM. Does it have to be in Excel? It might be easier to draw the graphs direct from the data in Python? Alan G. From amonroe at columbus.rr.com Tue Mar 8 00:47:38 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Mar 8 00:48:25 2005 Subject: [Tutor] Can you get python to force a number to remain 32 bit instead of autoconverting to type 'long'? Message-ID: <30646386554.20050307184738@columbus.rr.com> I tried to convert this pseudocode function IntNoise(32-bit integer: x) x = (x<<13) ^ x; return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0); end IntNoise function from this website http://freespace.virgin.net/hugo.elias/models/m_perlin.htm to python. But it seems to rely on wraparound within the 32 bit int. Can you duplicate this behavior in python? Alan From apple_py at biz-experts.net Tue Mar 8 02:30:19 2005 From: apple_py at biz-experts.net (Victor Bouffier) Date: Tue Mar 8 02:30:27 2005 Subject: [Tutor] Paradox database files Message-ID: <422D002B.6030403@biz-experts.net> Hi all. Does anybody know of a Python module to read from Paradox database files? I don't need to write back to the files. These files are being exported using a proprietary application and I need to parse them to extract transaction information. I found something about ODBC being able to connect to several database types, but I am not even sure how this would work with Paradox. Any OS solution you suggest works fine for me, since I have access to both a unix (linux) box and Python on Windows too. Thanks. -- Victor Bouffier Finance Manager www.grupoandersons.com From dyoo at hkn.eecs.berkeley.edu Tue Mar 8 02:51:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 8 02:51:49 2005 Subject: [Tutor] Paradox database files In-Reply-To: <422D002B.6030403@biz-experts.net> Message-ID: On Mon, 7 Mar 2005, Victor Bouffier wrote: > Does anybody know of a Python module to read from Paradox database > files? I don't need to write back to the files. These files are being > exported using a proprietary application and I need to parse them to > extract transaction information. Hi Victor, You might be interested in 'pxview': http://pxlib.sourceforge.net/pxview.html which can extract CSV-formatted files out of Paradox Database files. Once you have your data in CSV format, then Python's "csv" module can come into play: http://www.python.org/doc/lib/module-csv.html Alternatively, you might be able to use the pxlib Python bindings directly. According to: http://pxlib.sourceforge.net/documentation.php?manpage=pxlib a Python binding exists somewhere out there, though I haven't been able to find it yet... ok, found it, but it appears you might need to check it out of CVS: http://cvs.sourceforge.net/viewcvs.py/pxlib/bindings/ so this might not be as easy to use right out of the box. From bgailer at alum.rpi.edu Mon Mar 7 19:31:26 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Mar 8 03:51:56 2005 Subject: ****SPAM(11.8)**** Re: [Tutor] returning table elements with Beautiful Soup In-Reply-To: <014c01c5218e$7a6291c0$1cd28751@xp> References: <42293021.1030309@fastmail.fm> <422941FF.9070205@tds.net> <014c01c5218e$7a6291c0$1cd28751@xp> Message-ID: <6.1.2.0.0.20050307103102.0357d7a8@mail.mric.net> At 06:20 AM 3/5/2005, Alan Gauld wrote: > > > I'm trying to use Beautiful Soup to scrape some data out of an >HTML > > > table. I can do this using > >A new one on me, but Beautiful Soup looks very interesting. I've just >downloaded it. From where? My Google search does not help. >Thanks for pointing it out. > >Alan G. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer@alum.rpi.edu 510 558 3275 home 303 442 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050307/14d8722f/attachment-0001.html From kent37 at tds.net Tue Mar 8 04:06:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 8 04:06:19 2005 Subject: ****SPAM(11.8)**** Re: [Tutor] returning table elements with Beautiful Soup In-Reply-To: <6.1.2.0.0.20050307103102.0357d7a8@mail.mric.net> References: <42293021.1030309@fastmail.fm> <422941FF.9070205@tds.net> <014c01c5218e$7a6291c0$1cd28751@xp> <6.1.2.0.0.20050307103102.0357d7a8@mail.mric.net> Message-ID: <422D16A5.4040609@tds.net> Bob Gailer wrote: > At 06:20 AM 3/5/2005, Alan Gauld wrote: > >> > > I'm trying to use Beautiful Soup to scrape some data out of an >> HTML >> > > table. I can do this using >> >> A new one on me, but Beautiful Soup looks very interesting. I've just >> downloaded it. > > > From where? My Google search does not help. Actually it's the second listing if you Google 'Beautiful Soup'. http://www.crummy.com/software/BeautifulSoup/ Kent From apple_py at biz-experts.net Tue Mar 8 03:53:07 2005 From: apple_py at biz-experts.net (apple_py) Date: Tue Mar 8 04:53:12 2005 Subject: [Tutor] Paradox database files Message-ID: <20050308035307.8666.qmail@thehosting123.com> Hi Danny, Thanks a lot for your help. I have not been able to try it out, but I will first thing tomorrow. It seems that this is just what I need. I love this forum. Thanks to all. Victor -------Original Message------- > From: "Danny Yoo" > Subject: Re: [Tutor] Paradox database files > Sent: 08 Mar 2005 01:51:35 > > On Mon, 7 Mar 2005, Victor Bouffier wrote: > > > Does anybody know of a Python module to read from Paradox database > > files? I don't need to write back to the files. These files are being > > exported using a proprietary application and I need to parse them to > > extract transaction information. > > > Hi Victor, > > You might be interested in 'pxview': > > http://pxlib.sourceforge.net/pxview.html > > which can extract CSV-formatted files out of Paradox Database files. Once > you have your data in CSV format, then Python's "csv" module can come into > play: > > http://www.python.org/doc/lib/module-csv.html > > > Alternatively, you might be able to use the pxlib Python bindings > directly. According to: > > http://pxlib.sourceforge.net/documentation.php?manpage=pxlib > > a Python binding exists somewhere out there, though I haven't been able to > find it yet... ok, found it, but it appears you might need to check it out > of CVS: > > http://cvs.sourceforge.net/viewcvs.py/pxlib/bindings/ > > so this might not be as easy to use right out of the box. -------Original Message------- From apple_py at biz-experts.net Tue Mar 8 17:06:50 2005 From: apple_py at biz-experts.net (Victor Bouffier) Date: Tue Mar 8 17:07:06 2005 Subject: [Tutor] Paradox database files In-Reply-To: <20050308035307.8666.qmail@thehosting123.com> References: <20050308035307.8666.qmail@thehosting123.com> Message-ID: <422DCD9A.4060608@biz-experts.net> Hi all, I know this is OT from Python, but does anybody know how to fix my library issues. I get some awkward dependencies issues from these pylib libraries. # rpm -Uvh pxlib-0.4.3-1.i386.rpm error: Failed dependencies: libbz2.so.1.0 is needed by pxlib-0.4.3-1.i386 but when I look into my libraries I find the necessary ones under /usr/lib: # ll /usr/lib/libbz2* -rwxr-xr-x 1 root root 67594 Jun 15 2004 /usr/lib/libbz2.a lrwxrwxrwx 1 root root 11 Feb 6 11:02 /usr/lib/libbz2.so -> libbz2.so.1 lrwxrwxrwx 1 root root 15 Feb 6 10:10 /usr/lib/libbz2.so.1 -> libbz2.so.1.0.2 lrwxrwxrwx 1 root root 24 Mar 8 09:41 /usr/lib/libbz2.so.1.0 -> /usr/lib/libbz2.so.1.0.2 -rwxr-xr-x 1 root root 71724 Jun 15 2004 /usr/lib/libbz2.so.1.0.2 I created the second-to-last symlink with no success. I also added '/usr/lib' to /etc/ld.so.conf as suggested in a newsgroup. I've got a Fedora Core3 with both apt and yum installed, and both tell me I've got the latest libraries (bzip2-libs). If you believe I should post my question elsewhere, please let me know. Thanks. Victor apple_py wrote: >-------Original Message------- > > >>From: "Danny Yoo" >>Subject: Re: [Tutor] Paradox database files >>Sent: 08 Mar 2005 01:51:35 >> >> On Mon, 7 Mar 2005, Victor Bouffier wrote: >> >> > Does anybody know of a Python module to read from Paradox database >> > files? I don't need to write back to the files. These files are being >> > exported using a proprietary application and I need to parse them to >> > extract transaction information. >> >> >> Hi Victor, >> >> You might be interested in 'pxview': >> >> http://pxlib.sourceforge.net/pxview.html >> >> which can extract CSV-formatted files out of Paradox Database files. Once >> you have your data in CSV format, then Python's "csv" module can come into >> play: >> >> http://www.python.org/doc/lib/module-csv.html >> >> >> Alternatively, you might be able to use the pxlib Python bindings >> directly. According to: >> >> http://pxlib.sourceforge.net/documentation.php?manpage=pxlib >> >> a Python binding exists somewhere out there, though I haven't been able to >> find it yet... ok, found it, but it appears you might need to check it out >> of CVS: >> >> http://cvs.sourceforge.net/viewcvs.py/pxlib/bindings/ >> >> so this might not be as easy to use right out of the box. >> >> >-------Original Message------- >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > -- Victor Bouffier Finance Manager www.grupoandersons.com From phthenry at iglou.com Tue Mar 8 17:21:29 2005 From: phthenry at iglou.com (Paul Tremblay) Date: Tue Mar 8 17:20:14 2005 Subject: [Tutor] getting a webpage via python Message-ID: <20050308162129.GE2055@localhost.localdomain> Is there a simple way to get a web page with python? I have done no network programming with python before. My router (a Linksys 54G model) stores the IP/MAC addresss in a web page. There is no way for me to access them except through the web. Righ now, I am using this code: command = 'lynx -reload -auth %s:%s -source http://%s/DHCPTable.asp > %s' % ( self.__log_name, self.__log_password, self.__router_address, temp_out1) (exit_status, out_text) = commands.getstatusoutput(command) The lynx terminal browser dumps the raw HTML page to the out_text, and I can then parse it. I would like to make the code independent of lynx, if possible. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@iglou.com * ************************ From ewald.ertl at hartter.com Tue Mar 8 17:28:46 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue Mar 8 17:28:50 2005 Subject: [Tutor] Paradox database files In-Reply-To: <422DCD9A.4060608@biz-experts.net> References: <20050308035307.8666.qmail@thehosting123.com> <422DCD9A.4060608@biz-experts.net> Message-ID: <20050308172846.00004032@sunray1> Hi Victor on Tue, 08 Mar 2005 10:06:50 -0600 Victor Bouffier wrote : --------------------------------------------------------------------------------------------- Victor Bouffier > Hi all, Victor Bouffier > I know this is OT from Python, but does anybody know how to fix my Victor Bouffier > library issues. I get some awkward dependencies issues from these pylib Victor Bouffier > libraries. Victor Bouffier > Victor Bouffier > # rpm -Uvh pxlib-0.4.3-1.i386.rpm Victor Bouffier > error: Failed dependencies: Victor Bouffier > libbz2.so.1.0 is needed by pxlib-0.4.3-1.i386 Victor Bouffier > Victor Bouffier > but when I look into my libraries I find the necessary ones under /usr/lib: Victor Bouffier > Victor Bouffier > # ll /usr/lib/libbz2* Victor Bouffier > -rwxr-xr-x 1 root root 67594 Jun 15 2004 /usr/lib/libbz2.a Victor Bouffier > lrwxrwxrwx 1 root root 11 Feb 6 11:02 /usr/lib/libbz2.so -> libbz2.so.1 Victor Bouffier > lrwxrwxrwx 1 root root 15 Feb 6 10:10 /usr/lib/libbz2.so.1 -> Victor Bouffier > libbz2.so.1.0.2 Victor Bouffier > lrwxrwxrwx 1 root root 24 Mar 8 09:41 /usr/lib/libbz2.so.1.0 -> Victor Bouffier > /usr/lib/libbz2.so.1.0.2 Victor Bouffier > -rwxr-xr-x 1 root root 71724 Jun 15 2004 /usr/lib/libbz2.so.1.0.2 Victor Bouffier > Perhap's there is a problem with the RPM-Database. I don't know how rpm works internaly, but it controls somewhere in a "database", which packages are installed on the system. On an old SuSE-System I can search, to which package a file belongs rpm -q -f /usr/lib/libbz2.so bzip2-1.0.2-103 Here I see, that libbz2.so belongs to the bzip2-Package. The other way is to list the files belonging to a package: rpm -q -l bzip2-1.0.2-103 /usr/bin/bunzip2 /usr/bin/bzcat /usr/bin/bzip2 /usr/bin/bzip2recover /usr/include/bzlib.h /usr/lib/libbz2.a /usr/lib/libbz2.la /usr/lib/libbz2.so /usr/lib/libbz2.so.1 /usr/lib/libbz2.so.1.0.0 During the installation/update-Process, I think, rpm looks up, all dependencys mentioned in the rpm if they are installed on the system via the "database" where it logs, what is installed. Try if you can get a package to which your /usr/lib/libbz2.so.1 belongs. The other way is, to install the rpm-Package without depdency-check's, but this could result in the availability of the pxlib-Package, but it perhaps does not work. You've to test this, before you keep the package. "rpm -Uvh --nodeps" This should ignore the dependencies and install the package. ------------------- end ---------------------- HTH Ewald From eculpepper at hcc-care.com Tue Mar 8 17:30:49 2005 From: eculpepper at hcc-care.com (Eric Culpepper) Date: Tue Mar 8 17:29:31 2005 Subject: [Tutor] getting a webpage via python Message-ID: <48CA63C679F03D4187762B7CE066AAD202D0AAB0@hccexchange.hcccorp.hcc-care.com> You could use the builtin modules like urllib2, httplib, or you could use John Lee's spifftastic module "mechanize". I use mechanize a lot for automating downloading files from various partner websites my company has relations with. http://docs.python.org/lib/module-httplib.html http://docs.python.org/lib/module-urllib2.html http://wwwsearch.sourceforge.net/mechanize/ Good luck. Eric Culpepper eculpepper@hcc-care.com -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Paul Tremblay Sent: Tuesday, March 08, 2005 10:21 AM To: python tutor Subject: [Tutor] getting a webpage via python Is there a simple way to get a web page with python? I have done no network programming with python before. My router (a Linksys 54G model) stores the IP/MAC addresss in a web page. There is no way for me to access them except through the web. Righ now, I am using this code: command = 'lynx -reload -auth %s:%s -source http://%s/DHCPTable.asp > %s' % ( self.__log_name, self.__log_password, self.__router_address, temp_out1) (exit_status, out_text) = commands.getstatusoutput(command) The lynx terminal browser dumps the raw HTML page to the out_text, and I can then parse it. I would like to make the code independent of lynx, if possible. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@iglou.com * ************************ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From ewald.ertl at hartter.com Tue Mar 8 17:33:56 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue Mar 8 17:34:01 2005 Subject: [Tutor] getting a webpage via python In-Reply-To: <20050308162129.GE2055@localhost.localdomain> References: <20050308162129.GE2055@localhost.localdomain> Message-ID: <20050308173356.000000b0@sunray1> Hi Paul! As mentioned earlier by Kent in this group under the subject: Subject: Re: [Tutor] Downloading from http Mark Kels wrote: > On Sat, 12 Feb 2005 09:25:10 -0500, Jacob S. wrote: > >>urllib or urllib2 or maybe httplib maybe? >> >> urlopen( url[, data]) > I'm sorry, but I didn't understood a thing (maybe its because of my > bad english, and mybe its because I'm just dumb :). Anyway, can you > give me a code example or a link to a tutorial that talks about this ? >>> from urllib import urlopen >>> u=urlopen('http://www.google.com') >>> d=u.read() >>> print d[:200] Google