From marilyn at deliberate.com Mon Nov 1 00:06:56 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Nov 1 00:06:59 2004 Subject: [Tutor] escape-quoting strings In-Reply-To: <20041031220522.GK31976@niof.net> Message-ID: I got it!! This works: ad0 = address.replace('\\', '\\\\') ad0 = ad0.replace('\"','\\"') db_style0 = '''%%%s%%''' % ad0 print "0:", db_style0 On Sun, 31 Oct 2004, Rick Pasotto wrote: > On Sun, Oct 31, 2004 at 01:53:42PM -0800, Marilyn Davis wrote: > > Hi Python Tutors, > > > > I'm having a devil of a time quoting strings properly for MySql. > > You example did not include any MySql statements. How are you sending > the string to MySql? I didn't want to complicate my question with MySql stuff. Here is a successful call that depended on the quoting scheme above: insert ignore into doorman (in_id, msg_id, out_address, status, start) values (60, "1COOZD-0003KN-2z", "\"Toys \\\"R\\\" Us Gift Card Giveaway\" ", "NO_MESSAGE", "0") Thank you. Marilyn From rick at niof.net Mon Nov 1 00:23:32 2004 From: rick at niof.net (Rick Pasotto) Date: Mon Nov 1 00:23:36 2004 Subject: [Tutor] escape-quoting strings In-Reply-To: References: <20041031220522.GK31976@niof.net> Message-ID: <20041031232332.GL31976@niof.net> On Sun, Oct 31, 2004 at 03:06:56PM -0800, Marilyn Davis wrote: > I got it!! > > This works: > > ad0 = address.replace('\\', '\\\\') > ad0 = ad0.replace('\"','\\"') > db_style0 = '''%%%s%%''' % ad0 > print "0:", db_style0 > > On Sun, 31 Oct 2004, Rick Pasotto wrote: > > > On Sun, Oct 31, 2004 at 01:53:42PM -0800, Marilyn Davis wrote: > > > Hi Python Tutors, > > > > > > I'm having a devil of a time quoting strings properly for MySql. > > > > You example did not include any MySql statements. How are you sending > > the string to MySql? > > I didn't want to complicate my question with MySql stuff. But that part is important. Python's MySQLdb module takes care of and simplifies the quoting. I suspect you're doing a lot of unnecessary work. > Here is a successful call that depended on the quoting scheme above: > > insert ignore into doorman (in_id, msg_id, out_address, status, start) > values (60, "1COOZD-0003KN-2z", "\"Toys \\\"R\\\" Us Gift Card Giveaway\" > ", "NO_MESSAGE", "0") You're *hard* *coding* the values? I thought you were working with a string variable. -- "And the fox said to the little prince: men have forgotten this truth, but you must not forget it. You become responsible, forever, for what you have tamed." -- Antoine de Saint-Exupery [The Little Prince] Rick Pasotto rick@niof.net http://www.niof.net From flaxeater at yahoo.com Mon Nov 1 02:45:04 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Mon Nov 1 02:45:07 2004 Subject: [Tutor] Python on handhelds Message-ID: <20041101014505.92124.qmail@web54301.mail.yahoo.com> Anthony P. wrote: >Hello Everyone, > > > >I've been asked to develop a simple application that will run on the > >Dell Axiom handheld computer. Does anyone know how to get Python to > >run on this little device? > > > >Thanks, > >Anthony > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > Looking at things about this I ran over a reference to using jython on wince. perhaps you should look at that. __________________________________ Do you Yahoo!? Take Yahoo! Mail with you! Get it on your mobile phone. http://mobile.yahoo.com/maildemo From flaxeater at yahoo.com Mon Nov 1 03:04:00 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Mon Nov 1 03:04:03 2004 Subject: [Tutor] escape-quoting strings Message-ID: <20041101020400.96810.qmail@web54301.mail.yahoo.com> Marilyn Davis wrote: >I got it!! > >This works: > >ad0 = address.replace('\\', '\\\\') >ad0 = ad0.replace('\"','\\"') >db_style0 = '''%%%s%%''' % ad0 >print "0:", db_style0 > I thought I should tell you about raw strings eg. r'\new' out puts \new not ew the r at the front automaticly escapes special characters. __________________________________ Do you Yahoo!? Y! Messenger - Communicate in real time. Download now. http://messenger.yahoo.com From pythonTutor at venix.com Mon Nov 1 04:34:34 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Nov 1 04:35:28 2004 Subject: [Tutor] escape-quoting strings In-Reply-To: References: Message-ID: <1099280074.16476.14.camel@laptop.venix.com> On Sun, 2004-10-31 at 18:06, Marilyn Davis wrote: > I got it!! > > This works: > > ad0 = address.replace('\\', '\\\\') > ad0 = ad0.replace('\"','\\"') > db_style0 = '''%%%s%%''' % ad0 > print "0:", db_style0 > > On Sun, 31 Oct 2004, Rick Pasotto wrote: > > > On Sun, Oct 31, 2004 at 01:53:42PM -0800, Marilyn Davis wrote: > > > Hi Python Tutors, > > > > > > I'm having a devil of a time quoting strings properly for MySql. > > > > You example did not include any MySql statements. How are you sending > > the string to MySql? > > I didn't want to complicate my question with MySql stuff. > > Here is a successful call that depended on the quoting scheme above: > > insert ignore into doorman (in_id, msg_id, out_address, status, start) values (60, "1COOZD-0003KN-2z", "\"Toys \\\"R\\\" Us Gift Card Giveaway\" ", "NO_MESSAGE", "0") Your real MySQL code was omitted. I'll assume a cursor named curs. curs.execute(sql_cmd, parameters) is the general format for executing an SQL statement. With MySQL the parameter positions are marked with %s - so it looks like string interpolation. Parameters is a tuple of variables that need to be inserted into the sql_cmd at the positions marked by %s. DO NOT USE PYTHON string interpolation. Let the MySQLdb module do it. For your situation: sql_cmd = '''insert ignore into doorman (in_id, msg_id, out_address, status, start) values (60, "1COOZD-0003KN-2z", %s, "NO_MESSAGE", "0")''' parameters = (address, ) There is no need to change the incoming string value to be able to feed it into the database. The Python DBI documentation does not discuss this clearly enough. I made the same mistake in some of my first DBI programs. > > > > Thank you. > > Marilyn > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From marilyn at deliberate.com Mon Nov 1 06:32:47 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Nov 1 06:33:09 2004 Subject: [Tutor] escape-quoting strings In-Reply-To: <1099280074.16476.14.camel@laptop.venix.com> Message-ID: On Sun, 31 Oct 2004, Lloyd Kvam wrote: > On Sun, 2004-10-31 at 18:06, Marilyn Davis wrote: > > I got it!! > > > > This works: > > > > ad0 = address.replace('\\', '\\\\') > > ad0 = ad0.replace('\"','\\"') > > db_style0 = '''%%%s%%''' % ad0 > > print "0:", db_style0 > > > > On Sun, 31 Oct 2004, Rick Pasotto wrote: > > > > > On Sun, Oct 31, 2004 at 01:53:42PM -0800, Marilyn Davis wrote: > > > > Hi Python Tutors, > > > > > > > > I'm having a devil of a time quoting strings properly for MySql. > > > > > > You example did not include any MySql statements. How are you sending > > > the string to MySql? > > > > I didn't want to complicate my question with MySql stuff. > > > > Here is a successful call that depended on the quoting scheme above: > > > > insert ignore into doorman (in_id, msg_id, out_address, status, start) values (60, "1COOZD-0003KN-2z", "\"Toys \\\"R\\\" Us Gift Card Giveaway\" ", "NO_MESSAGE", "0") > > Your real MySQL code was omitted. I'll assume a cursor named curs. > > curs.execute(sql_cmd, parameters) Oh, I have a method wrapped around it to throw meaningful exceptions, and then that's in a class that maintains the connection. > > is the general format for executing an SQL statement. With MySQL the > parameter positions are marked with %s - so it looks like string > interpolation. Parameters is a tuple of variables that need to be > inserted into the sql_cmd at the positions marked by %s. DO NOT USE > PYTHON string interpolation. Let the MySQLdb module do it. Wow. I had no idea that this was available. I did it all wrong. I just did a little test and it is totally cool. > > For your situation: > sql_cmd = '''insert ignore into doorman (in_id, msg_id, out_address, > status, start) values (60, "1COOZD-0003KN-2z", %s, "NO_MESSAGE", "0")''' > > parameters = (address, ) > > There is no need to change the incoming string value to be able to feed > it into the database. > > The Python DBI documentation does not discuss this clearly enough. I > made the same mistake in some of my first DBI programs. I don't see it in the documentation for MySQLdb at all! Should I be looking somewhere else? How did you learn this? I wish I knew this a few months ago. Where have you been?? ;^) Marilyn > > > > > > > > > Thank you. > > > > Marilyn > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > -- From pythonTutor at venix.com Mon Nov 1 14:54:55 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Nov 1 14:55:42 2004 Subject: [Tutor] escape-quoting strings In-Reply-To: References: Message-ID: <1099317295.17067.8.camel@laptop.venix.com> http://python.org/topics/database/ Read the DB-API spec version 2 All of the module documentation assumes you are already familiar with the DB-API (DBI) and only deals with other issues. The ability of the module to map your data into the query becomes critical when dealing with binary data. On Mon, 2004-11-01 at 00:32, Marilyn Davis wrote: > I don't see it in the documentation for MySQLdb at all! Should I be > looking somewhere else? > > How did you learn this? > > I wish I knew this a few months ago. Where have you been?? ;^) > > Marilyn > > > > > > > > > > > > > > > Thank you. > > > > > > Marilyn > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp From tigershark at morganmeader.com Mon Nov 1 17:33:33 2004 From: tigershark at morganmeader.com (Morgan Meader) Date: Mon Nov 1 17:35:25 2004 Subject: [Tutor] redundant function ( or, I need advice about cleaning up my code ) In-Reply-To: <6.1.0.6.0.20041030230021.02aed1c8@mail4.skillsoft.com> References: <416D8491.7040101@insightmill.com> <672E3FEE-2ACE-11D9-A933-000393CBC88E@yahoo.fr> <41844C87.4040303@insightmill.com> <3A5B61FA-2AE7-11D9-A933-000393CBC88E@yahoo.fr> <6.1.0.6.0.20041030230021.02aed1c8@mail4.skillsoft.com> Message-ID: <4186655D.5000004@morganmeader.com> Thanks folks, Great ideas for making my code smaller and more readable. I will use enumerate() when I need to access more than one list by index. When zip and/or oop make more sense to me I will try that definitely. So many great hints on this list. Thanks, Morgan From klappnase at freenet.de Mon Nov 1 17:49:27 2004 From: klappnase at freenet.de (Michael Lange) Date: Mon Nov 1 17:49:14 2004 Subject: [Tutor] Does anyone know if IDLE has a maximized setting? In-Reply-To: <000201c4bf49$c32d4be0$d05328cf@JSLAPTOP> References: <000201c4bf49$c32d4be0$d05328cf@JSLAPTOP> Message-ID: <20041101174927.560287dc.klappnase@freenet.de> On Fri, 29 Oct 2004 10:50:29 -0500 "Jacob S." wrote: > Hello again. > > I am using IDLE for editing my scripts and I was wondering if there was > a way to default the IDLE windows to come up maximized every time. As it is, > I have to maximize the window every time I right click on a file and click > edit with IDLE. This gets annoying very quickly. Does anyone know what file > in the idlelib directory might contain the TK script for the editor and > shell windows so that I might change that setting myself? > > It's in EditorWindow.py, line 79 (at least my version, the line might vary); the magic line is: self.top = top = self.Toplevel(root, menu=self.menubar) this creates the new window. You can use the Toplevel's geometry method to do what you want; simply add a line: top.geometry('1024x740+0+0') this will draw a window of 1024 x 740 pixels into the upper left corner of your screen (the argument passed to geometry() is generally of the form: 'widthxheight+x-offset+y-offset'); If you don't want to deal too much with the secrets of Tkinter it's probably the easiest to just try the appropriate values you need. I hope this helps Michael From elh at outreachnetworks.com Mon Nov 1 18:19:53 2004 From: elh at outreachnetworks.com (Eric L. Howard) Date: Mon Nov 1 18:20:49 2004 Subject: [Tutor] Does anyone know if IDLE has a maximized setting? In-Reply-To: <20041101174927.560287dc.klappnase@freenet.de> References: <000201c4bf49$c32d4be0$d05328cf@JSLAPTOP> <20041101174927.560287dc.klappnase@freenet.de> Message-ID: <20041101171951.GA4561@outreachnetworks.com> At a certain time, now past [Nov.01.2004-05:49:27PM +0100], klappnase@freenet.de spake thusly: > On Fri, 29 Oct 2004 10:50:29 -0500 > "Jacob S." wrote: > > > Hello again. > > > > I am using IDLE for editing my scripts and I was wondering if there was > > a way to default the IDLE windows to come up maximized every time. As it is, > > I have to maximize the window every time I right click on a file and click > > edit with IDLE. This gets annoying very quickly. Does anyone know what file > > in the idlelib directory might contain the TK script for the editor and > > shell windows so that I might change that setting myself? > > > > > > It's in EditorWindow.py, line 79 (at least my version, the line might vary); the magic line is: > > self.top = top = self.Toplevel(root, menu=self.menubar) > > this creates the new window. > > You can use the Toplevel's geometry method to do what you want; simply > add a line: > > top.geometry('1024x740+0+0') I adjust the EditorWindow properties by added the following to ~/.idlerc/config-main.cfg [EditorWindow] font= -windows-profontwindows-medium-r-normal--11-110-72-72-c-60-microsoft-cp1252 font-size= 10 font-bold=0 width= 120 height= 50 If you can figure out the width and height needed to fill the screen, this setup wouldn't get overwritten by updates to idle... ~elh -- Eric L. Howard e l h @ o u t r e a c h n e t w o r k s . c o m ------------------------------------------------------------------------ www.OutreachNetworks.com 313.297.9900 ------------------------------------------------------------------------ JabberID: elh@jabber.org Advocate of the Theocratic Rule From kapiladhanvi at gmail.com Mon Nov 1 18:35:36 2004 From: kapiladhanvi at gmail.com (Mr. Dhanvi Kapila) Date: Mon Nov 1 18:35:43 2004 Subject: [Tutor] [OT] Part time job openings ? Message-ID: <35ccaa99041101093514005a2b@mail.gmail.com> Hi Guys, I am a computer science student doin my masters in Texas A & M University at Kingsville , TX . I was wondering whether anyone know of any part time software / web development job openings ? I have over 2.5 years exp in India and would like to earn some extra cash :) Please can anybody forward me any details about any openings or projects ? i am proficient in PERL, C, C++ , Python, HTML , Javascript, DHTML. I can send my resume on request to interested parties. Awaiting your replies . Thanks Sincerely, Dhanvi Kapila -- ?v? kapila * .dhanvi 2.0.0 /(_)\ http://kapiladhanvi.myensim.net ^ ^ the good ones may be taken.. but the best are still waiting for me LinUX powered From dyoo at hkn.eecs.berkeley.edu Mon Nov 1 18:49:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 1 18:49:09 2004 Subject: [Tutor] [OT] Part time job openings ? In-Reply-To: <35ccaa99041101093514005a2b@mail.gmail.com> Message-ID: On Mon, 1 Nov 2004, Mr. Dhanvi Kapila wrote: > I am a computer science student doin my masters in Texas A & M > University at Kingsville , TX . [job posting cut] You're right. This is completely off topic from helping people learn about programming Python. Please use a more relevant forum. The Python Job Board: http://python.org/Jobs.html recommends using something like Mojolin: http://www.mojolin.com/ From mhansen at cso.atmel.com Mon Nov 1 21:09:48 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Mon Nov 1 21:09:36 2004 Subject: [Tutor] Re: programming theology questions In-Reply-To: <20041030191545.D33D31E4009@bag.python.org> References: <20041030191545.D33D31E4009@bag.python.org> Message-ID: <4186980C.6010501@cso.atmel.com> I know you posted this on Saturday, but I get digest mode and the list sends to my work address, so I just read your message. Anyway, the book The Pragmatic Programmer suggests that you learn a new language every year. I haven't done that, but I think learning different languages is a good thing. Someday I'd like to try Smalltalk or Lisp. I think those two are different enough from what I know(VB/VBA, VBScript, Perl, Python, COBOL, DCL) that they'd warp my brain exposing me to new and different ways of doing things. Sometimes I get concerned about learning another language. I worry about mixing them up when I'm coding.(Vthon or PyBOL =) ) But that really hasn't happened. You'll manage to keep it straight. I just try to make sure I get over the initial learning curve of one before learning another. Mike > > Subject: > [Tutor] programming theology questions > From: > Rene Lopez > Date: > Sat, 30 Oct 2004 12:21:09 -0400 > To: > Python Tutor > > To: > Python Tutor > > >How many programming languages can safely fit in your head before you >get confused, or think it's not worth it? :-) > >Is there any programming language blasphemy? Like learning C++ and >then VB? Is that a sin or a exercise in insanity? > >Just curious as to what languages you keep in your mental toolboxes :) > > > > From dyoo at hkn.eecs.berkeley.edu Mon Nov 1 21:51:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 1 21:51:34 2004 Subject: [Tutor] escape-quoting strings In-Reply-To: <1099317295.17067.8.camel@laptop.venix.com> Message-ID: On Mon, 1 Nov 2004, Lloyd Kvam wrote: > http://python.org/topics/database/ > > Read the DB-API spec version 2 > > All of the module documentation assumes you are already familiar with > the DB-API (DBI) and only deals with other issues. The ability of the > module to map your data into the query becomes critical when dealing > with binary data. > > On Mon, 2004-11-01 at 00:32, Marilyn Davis wrote: > > I don't see it in the documentation for MySQLdb at all! Should I be > > looking somewhere else? > > > > How did you learn this? > > > > I wish I knew this a few months ago. Where have you been?? ;^) Hi Marylyn, All the SQL bindings in the programming languages I've seen provide some kind of "prepared statement" syntax, since quotation is tricky to deal with. Java does it with its 'java.sql.PreparedStatement' class, and Perl also supports it with its DBI::bind_param stuff. But you're right, though: using a prepared statement is not obvious. It's like one of those trial-by-fire sort of things. It does seem to be a very frequently asked question that is not well addressed by the current documentation. I'd love to see this addressed directly in the Python-SQL tutorials out there. For example: http://www.amk.ca/python/writing/DB-API.html just sneaks the prepared syntax stuff in near the end, in the section about Transactions, and doesn't highlight the reasons for using it. The other tutorial I often point folks to is the on by Devshed: http://www.devshed.com/index2.php?option=content&task=view&id=210&pop=1&page=0&hide_js=1 and it does use the prepared statement syntax... but, again, doesn't explain what makes it better than direct interpolation. And since MySQLdb's prepared statement syntax looks almost like String Formatting, it's not really obvious why using it is any better than just doing the interpolation directly. Does anyone want a crack at writing a tutorial about this? *grin* Maybe someone on the Tutor list can write something up and get it linked to the Database Topics page: http://www.python.org/topics/database/docs.html From jeffpeery at yahoo.com Mon Nov 1 22:14:31 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon Nov 1 22:14:35 2004 Subject: [Tutor] end of file symbol? Message-ID: <20041101211431.18831.qmail@web60102.mail.yahoo.com> is there an end of file symbol? or an end of line symbol? usually I look for '\n' when I am filtering though text to find the end of a line, but I am wondering if there is a better end of line character. thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041101/205af1d2/attachment.html From bill.mill at gmail.com Mon Nov 1 22:29:19 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Nov 1 22:29:27 2004 Subject: [Tutor] end of file symbol? In-Reply-To: <20041101211431.18831.qmail@web60102.mail.yahoo.com> References: <20041101211431.18831.qmail@web60102.mail.yahoo.com> Message-ID: <797fe3d404110113296573b75a@mail.gmail.com> Jeff, Windows-style text file lines end in "/r/n". Unix-style text file lines end in "/n". I believe that Mac-style text file lines end in "/r" . You can use the variable os.linesep to see what the current platform's line separator is. There is no end of file character. Peace Bill Mill On Mon, 1 Nov 2004 13:14:31 -0800 (PST), Jeff Peery wrote: > > is there an end of file symbol? or an end of line symbol? usually I look for > '\n' when I am filtering though text to find the end of a line, but I am > wondering if there is a better end of line character. thanks. > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kent_johnson at skillsoft.com Mon Nov 1 22:35:21 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Nov 1 22:35:30 2004 Subject: [Tutor] end of file symbol? In-Reply-To: <20041101211431.18831.qmail@web60102.mail.yahoo.com> References: <20041101211431.18831.qmail@web60102.mail.yahoo.com> Message-ID: <6.1.0.6.0.20041101162735.029359e0@mail4.skillsoft.com> Jeff, end-of-line is platform-dependent. On Unix / Linux / Mac OSX it is \n. On Windows it is usually \r\n. On MacOS 9 it is \r. If you open a file with the mode 'U' or 'rU' you get "universal newline support" which converts any of these newline types to \n. (See http://docs.python.org/whatsnew/node7.html) If you are processing text line-by-line, there might be a better way to do it than searching for \n. You can read a file by lines like this: f = open('myfile.txt', 'rU') for line in f: # do something with line If you have the text in a string already you can use for line in s.splitlines(): # do something with line or just lines = s.splitlines() to get a list of all the lines. There is no end-of-file character, you just run out of data. Kent At 01:14 PM 11/1/2004 -0800, Jeff Peery wrote: >is there an end of file symbol? or an end of line symbol? usually I look >for '\n' when I am filtering though text to find the end of a line, but I >am wondering if there is a better end of line character. thanks. > >Jeff >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From marilyn at deliberate.com Mon Nov 1 22:36:20 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Nov 1 22:36:24 2004 Subject: [Tutor] escape-quoting strings In-Reply-To: Message-ID: Thank you Danny. Another wonderful thing that isn't well-documented as far as I can tell, although it is mentioned in the reference manual, is using a dictionary to fill in the %(key)s slots in a format string. I learned this by studying Mailman code. It's a huge feature IMHO. And another thing, when, in Python code, can I hit the return key mid-statement? After a ',', and when else? I've sort of given up trying to break up statements. Thank you tutors. This list is soooooo helpful. Marilyn On Mon, 1 Nov 2004, Danny Yoo wrote: > > > On Mon, 1 Nov 2004, Lloyd Kvam wrote: > > > http://python.org/topics/database/ > > > > Read the DB-API spec version 2 > > > > All of the module documentation assumes you are already familiar with > > the DB-API (DBI) and only deals with other issues. The ability of the > > module to map your data into the query becomes critical when dealing > > with binary data. > > > > On Mon, 2004-11-01 at 00:32, Marilyn Davis wrote: > > > I don't see it in the documentation for MySQLdb at all! Should I be > > > looking somewhere else? > > > > > > How did you learn this? > > > > > > I wish I knew this a few months ago. Where have you been?? ;^) > > > Hi Marylyn, > > All the SQL bindings in the programming languages I've seen provide some > kind of "prepared statement" syntax, since quotation is tricky to deal > with. Java does it with its 'java.sql.PreparedStatement' class, and Perl > also supports it with its DBI::bind_param stuff. > > But you're right, though: using a prepared statement is not obvious. > It's like one of those trial-by-fire sort of things. It does seem to be a > very frequently asked question that is not well addressed by the current > documentation. > > > I'd love to see this addressed directly in the Python-SQL tutorials out > there. For example: > > http://www.amk.ca/python/writing/DB-API.html > > just sneaks the prepared syntax stuff in near the end, in the section > about Transactions, and doesn't highlight the reasons for using it. The > other tutorial I often point folks to is the on by Devshed: > > http://www.devshed.com/index2.php?option=content&task=view&id=210&pop=1&page=0&hide_js=1 > > and it does use the prepared statement syntax... but, again, doesn't > explain what makes it better than direct interpolation. And since > MySQLdb's prepared statement syntax looks almost like String Formatting, > it's not really obvious why using it is any better than just doing the > interpolation directly. > > > Does anyone want a crack at writing a tutorial about this? *grin* Maybe > someone on the Tutor list can write something up and get it linked to the > Database Topics page: > > http://www.python.org/topics/database/docs.html > > > -- From bill.mill at gmail.com Mon Nov 1 22:53:37 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Nov 1 22:53:46 2004 Subject: [Tutor] end of file symbol? In-Reply-To: <797fe3d404110113296573b75a@mail.gmail.com> References: <20041101211431.18831.qmail@web60102.mail.yahoo.com> <797fe3d404110113296573b75a@mail.gmail.com> Message-ID: <797fe3d4041101135369785c56@mail.gmail.com> Ummm, yeah, so I meant "\r\n" on windows, "\n" on *nix, and "\r" on Mac pre-OS X. All of my "/" should be "\". Thanks to the person who pointed that out. Peace Bill Mill bill.mill at gmail.com On Mon, 1 Nov 2004 16:29:19 -0500, Bill Mill wrote: > Jeff, > > Windows-style text file lines end in "/r/n". Unix-style text file > lines end in "/n". I believe that Mac-style text file lines end in > > > "/r" . You can use the variable os.linesep to see what the current > platform's line separator is. > > There is no end of file character. > > Peace > Bill Mill > > On Mon, 1 Nov 2004 13:14:31 -0800 (PST), Jeff Peery wrote: > > > > is there an end of file symbol? or an end of line symbol? usually I look for > > '\n' when I am filtering though text to find the end of a line, but I am > > wondering if there is a better end of line character. thanks. > > > > Jeff > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > From marilyn at deliberate.com Mon Nov 1 23:08:48 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Nov 1 23:08:52 2004 Subject: [Tutor] escape-quoting strings In-Reply-To: <20041101020400.96810.qmail@web54301.mail.yahoo.com> Message-ID: On Sun, 31 Oct 2004, Chad Crabtree wrote: > Marilyn Davis wrote: > > >I got it!! > > > >This works: > > > >ad0 = address.replace('\\', '\\\\') > >ad0 = ad0.replace('\"','\\"') > >db_style0 = '''%%%s%%''' % ad0 > >print "0:", db_style0 > > > I thought I should tell you about raw strings eg. > > r'\new' Thank you Chad. This might be helpful in another circumstance. It goes to show that I'm clueless without the help here! Marilyn > > out puts > \new > > not > > ew > > the r at the front automaticly escapes special characters. > > > > __________________________________ > Do you Yahoo!? > Y! Messenger - Communicate in real time. Download now. > http://messenger.yahoo.com > -- From kent_johnson at skillsoft.com Mon Nov 1 23:19:27 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Nov 1 23:19:32 2004 Subject: [Tutor] continuation lines In-Reply-To: References: Message-ID: <6.1.0.6.0.20041101171440.02af6670@mail4.skillsoft.com> At 01:36 PM 11/1/2004 -0800, Marilyn Davis wrote: >And another thing, when, in Python code, can I hit the return key >mid-statement? After a ',', and when else? I've sort of given up >trying to break up statements. You can break a line whenever you have an open parenthesis (, brace { or bracket [ eg lst = [ 'stuff', 'morestuff' ] myDict = { 'a' : 1, 'b' : 2 } callOfFunctionWithVeryManyArguments('arg1', 'arg2', 'arg3', 'arg4') You can explicitly continue a line by ending it with a \ x = a + \ b You can include line breaks inside triple-quoted strings: s = '''Here is some text that spans two lines''' Kent From mlist-python at dideas.com Tue Nov 2 00:05:09 2004 From: mlist-python at dideas.com (Chris Barnhart) Date: Tue Nov 2 00:05:51 2004 Subject: [Tutor] Problem modify windows registry (desktop wallpaper) Message-ID: <5.0.2.1.2.20041101170023.022b8da8@qmail.dideas.com> Hi, I'm attempting to write a python (2.3.3) program that will update the wallpaper under Windows 2000. I found an example delphi program : (http://www.latiumsoftware.com/en/delphi/00020.php) which suggest that I need to change a registry variable, and then execute a system parameters changed statement. The following program attempts to change the desktop wallpaper by changing a key in the HKEY_CURRENT_USER. This fails due to access denied? I'm using methods from _winreg. What weird, is that by using OpenKey I've been able to create new registry sub folders, and then using SetValue, change the value of the "default" key. I've also looked modifying the registry from WMI, and also looked at using windll - but obsolete. Any ideas? Thank you, Chris -------------- import _winreg as wreg key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Control Panel\\Desktop") v = wreg.QueryValueEx(key,"WallPaper") print "Key value is : ", v wreg.SetValueEx(key, "WallPaper", 0, wreg.REG_SZ, v[0]) C:\src\python>python r3.py Key value is : (u'C:\\WINNT\\Mozilla Wallpaper.bmp', 1) Traceback (most recent call last): File "r3.py", line 6, in ? wreg.SetValueEx(key, "WallPaper", 0, wreg.REG_SZ, v[0]) WindowsError: [Errno 5] Access is denied From marilyn at deliberate.com Tue Nov 2 00:21:46 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Tue Nov 2 00:21:49 2004 Subject: [Tutor] continuation lines In-Reply-To: <6.1.0.6.0.20041101171440.02af6670@mail4.skillsoft.com> Message-ID: Thank you! On Mon, 1 Nov 2004, Kent Johnson wrote: > At 01:36 PM 11/1/2004 -0800, Marilyn Davis wrote: > >And another thing, when, in Python code, can I hit the return key > >mid-statement? After a ',', and when else? I've sort of given up > >trying to break up statements. > > You can break a line whenever you have an open parenthesis (, brace { or > bracket [ > eg > > lst = [ > 'stuff', > 'morestuff' > ] > > myDict = { > 'a' : 1, > 'b' : 2 > } > > callOfFunctionWithVeryManyArguments('arg1', 'arg2', > 'arg3', 'arg4') > > You can explicitly continue a line by ending it with a \ > x = a + \ > b > > You can include line breaks inside triple-quoted strings: > s = '''Here is some text > that spans two lines''' > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From justinstraube at charter.net Tue Nov 2 08:17:11 2004 From: justinstraube at charter.net (justin) Date: Tue Nov 2 06:18:35 2004 Subject: [Tutor] os.rename error problem Message-ID: Hello, I know os.rename is pretty easy and straight forward to use but Im trippin up on something here. In the interactive prompt I have no problem renaming a file. Even the file used below. But in a project im working on Im having a some problems. #### Start Code def reName(): new = fileEntry.get() # Entry widget with the file name if new.lower().endswith('.mp3') == False: new = new + '.mp3' old = main_display.get(ACTIVE) # gets the orig file name from the listbox for item in pathList: # Adds the file names to the path if os.path.isfile(item + '/' + old) == True: old = item + '/' + old new = item + '/' + new else: pass print 'Source Exits? ' + str(os.path.isfile(old)) print old print 'Destination Exists? ' + str(os.path.isfile(new)) print new os.rename(old, new) #### End Code >>> Source Exits? True E:/Phosphorescent/Phosphorescent - ocean_of_storms.mp3 Destination Exists? False E:/Phosphorescent/Phosphorescent - Ocean of Storms.mp3 Exception in Tkinter callback Traceback (most recent call last): File "D:\PYTHON23\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "E:\work\Python\ID3edit\v2.0\ID3edit.py", line 71, in reName os.rename(old, new) OSError: [Errno 13] Permission denied >>> Im using Win2k and have checked to see if the file is read-only. Its not and I have been able to edit the MP3 ID3 tag information without problem. Ive read the bit in the 2.3 reference about OSError being raised if the destination exists, but os.path.isfile(new) says False. Can anyone give me a hint as to what Im missing here? Regards, Justin From kent_johnson at skillsoft.com Tue Nov 2 11:43:29 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Nov 2 11:43:34 2004 Subject: [Tutor] os.rename error problem In-Reply-To: References: Message-ID: <6.1.0.6.0.20041102053451.02976a68@mail4.skillsoft.com> Justin, Is the old file open? Maybe you changed the ID tag and didn't close the file? PS a few stylistic notes: You don't need to compare to True and False in your conditionals: > if new.lower().endswith('.mp3') == False: could be if not new.lower().endswith('.mp3'): and > if os.path.isfile(item + '/' + old) == True: could be if os.path.isfile(item + '/' + old): Actually these are not quite equivalent - any Python value can be used in a conditional, not just True and False. Generally this is the behavior you want: >>> if 2: print 'True' ... True >>> if 2 == True: print 'True' ... >>> if not []: print 'False' ... False >>> if [] == False: print 'False' ... >>> > else: pass You don't need this empty else at all. Maybe you left it in as a placeholder, that's fine, but in general if the else clause is empty you can just leave it out. Kent At 11:17 PM 11/1/2004 -0800, justin wrote: >Hello, > >I know os.rename is pretty easy and straight forward to use but Im trippin >up on >something here. In the interactive prompt I have no problem renaming a file. >Even the file used below. But in a project im working on Im having a some >problems. > >#### Start Code > >def reName(): > > new = fileEntry.get() # Entry widget with the file name > if new.lower().endswith('.mp3') == False: > new = new + '.mp3' > > old = main_display.get(ACTIVE) # gets the orig file name from the > listbox > > for item in pathList: # Adds the file names to the path > if os.path.isfile(item + '/' + old) == True: > old = item + '/' + old > new = item + '/' + new > else: pass > > print 'Source Exits? ' + str(os.path.isfile(old)) > print old > print 'Destination Exists? ' + str(os.path.isfile(new)) > print new > os.rename(old, new) > >#### End Code > > >>> >Source Exits? True >E:/Phosphorescent/Phosphorescent - ocean_of_storms.mp3 >Destination Exists? False >E:/Phosphorescent/Phosphorescent - Ocean of Storms.mp3 >Exception in Tkinter callback >Traceback (most recent call last): > File "D:\PYTHON23\lib\lib-tk\Tkinter.py", line 1345, in __call__ > return self.func(*args) > File "E:\work\Python\ID3edit\v2.0\ID3edit.py", line 71, in reName > os.rename(old, new) >OSError: [Errno 13] Permission denied > >>> > >Im using Win2k and have checked to see if the file is read-only. Its not and I >have been able to edit the MP3 ID3 tag information without problem. > >Ive read the bit in the 2.3 reference about OSError being raised if the >destination exists, but os.path.isfile(new) says False. > >Can anyone give me a hint as to what Im missing here? > >Regards, >Justin > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From jerimed at myrealbox.com Tue Nov 2 13:18:15 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Tue Nov 2 13:18:18 2004 Subject: [Tutor] IndexError: string index out of range Message-ID: <1099397895.8c57be3cjerimed@myrealbox.com> Hello all, I'm geting IndexError when iterating over a string in reverse. What exactly does this mean? help(IndexError) in the interpreter isnt very helpful. I'm a beginner trying to follow examples in the online tutorial How To Think Like Computer Scientist (Python). I understand slicing of strings, lists and tuples but a bit confused with indexing. Kindly enlighten me on this part. Fortunately i have the online tutorials printed out for reference but i agree the best way to learn is to practice and practice coding. Time is liability on my side due to my day job but im trying to squeeze time in the night for python the best i can. My goal of learning python is to learn it to help with system administration of Linux/Windows. Maybe it can be of help to me one day. >>> fruit = 'banana' >>> index = 0 >>> while index < len(fruit): ... print [index], '\t', fruit[index] ... index = index + 1 ... [0] b [1] a [2] n [3] a [4] n [5] a >>> >>> index = -1 >>> while index < len(fruit): ... print [index], '\t', fruit[index] ... index = index - 1 ... [-1] a [-2] n [-3] a [-4] n [-5] a [-6] b [-7] Traceback (most recent call last): File "", line 2, in ? IndexError: string index out of range -- Regards, erimendz -- This message was sent with an unlicensed evaluation version of Novell NetMail. Please see http://www.netmail.com/ for details. From mi.janssen at gmail.com Tue Nov 2 14:06:19 2004 From: mi.janssen at gmail.com (Michael Janssen) Date: Tue Nov 2 14:06:29 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: <1099397895.8c57be3cjerimed@myrealbox.com> References: <1099397895.8c57be3cjerimed@myrealbox.com> Message-ID: <1ff2dfbf04110205061d732c82@mail.gmail.com> On Tue, 02 Nov 2004 15:18:15 +0300, Eri Mendz wrote: > I'm geting IndexError when iterating over a string in reverse. What > exactly does this mean? help(IndexError) in the interpreter isnt very > helpful. > >>> fruit = 'banana' > >>> index = 0 > >>> while index < len(fruit): > ... print [index], '\t', fruit[index] > ... index = index + 1 > ... > [0] b > [1] a > [2] n > [3] a > [4] n > [5] a > >>> > >>> index = -1 > >>> while index < len(fruit): > ... print [index], '\t', fruit[index] > ... index = index - 1 > ... > [-1] a > [-2] n > [-3] a > [-4] n > [-5] a > [-6] b > [-7] Traceback (most recent call last): > File "", line 2, in ? > IndexError: string index out of range This means: string index "banana"[-7] is out of range. Quite obviously ;-) Perhaps you're confused why the loopcondition "while indey > len(fruit)" was fine in the former example but lends to an IndexError with the second example. Reason is that you *decrement* index in the second example and thus index will be smaller than len(fruit) until the end of time. index will be decremented without boundaries. Without the IndexError, you would while loop forever ("for a long time"). Your while condition should have read "while index >= -1 * len(fruits)", which would terminate when index = -7 which is smaller than -1 * 6. These handmade indexing is allways hard to code. Better to use a for-loop: for char in fruit: print char for index,char in enumerate(fruit): print [index], char (but while this is fine coding style, it's not such a challenging learning example ;-) Things like IndexError are described in lib/module-exceptions.html (when you want to know relationship and generall usage). Michael From cyresse at gmail.com Tue Nov 2 14:07:06 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Nov 2 14:07:10 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: <1099397895.8c57be3cjerimed@myrealbox.com> References: <1099397895.8c57be3cjerimed@myrealbox.com> Message-ID: Hi Eri, I started learning 4 weeks ago, so good luck. Python is great. I'm gonig to do what I do nearly every reply, and plug Alan Gauld's tutorial. http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/index.htm Check it out, it's quite indepth as to specifics and quirks. The tutorial you're doing is good also, but I find that while it teaches good method, it's a little sparse in explaining how to implement that method, or why it is implemented that way. So yeah, the above tutorial is really good. I used it, and I'm halfway my first GUI app, so it helps. : ) Now, onto your problem. Index error means that for say, a five value index, a=[1,2,3,4,5] you tried to access the 6th value or more. This is what's getting you - index = -1 > >>> while index < len(fruit): [-1] a > [-2] n > [-3] a > [-4] n > [-5] a > [-6] b > [-7] Traceback (most recent call last): > File "", line 2, in ? > IndexError: string index out of range Ok, so the length of fruit is 6. -1 to -99999999999999999999999999999 is always going to be less than 6. So yeah, while index < len(fruit) becomes while (-1, -2, -3.. -999) < 6: Your while condition is always true. I would change it to lengthFruit = len(fruit) (Just to make the below examples easier to read) while index > -lengthFruit OK, so while -1 to -6 is greater than -6, do the following. On the 6th loop through, it will do the last slice and then subtract 1 from index, at which point index will become -6, and your loop will end. or while index != -(lengthFruit+1) This one would work as well, != means 'does not equal' So while index does not equal -7, do the following. Personally, I think that the way you're indexing in reverse is a bit awkward and confusing(Unless you're counting position from line end or something.) The computer always counts from 0 up, and I generally tend to stick with convention unless I've got a real good reason to blaze my own trail. So, another way would be - >>>for index in range(lengthFruit-1, -1, -1): ... print [ndex], '\t', fruit[index] Have you used a for loop before? So basically, for x in range(10) will increment x from 0 to 9 each loop. for x in range(5,10) will increment from 5 to 9. for x in range(0, 10, 2): print x would produce 0, 2, 4, 6, 8, it's counting by 2. But range defaults to is range(0(start), yourValue(stop), 1(step)) so when you tell it range(10) it counts from 0 to 9, 1 at a time. Notice how it counts up to 10, but not including it? This works well with a list. List x has an index of x[0] to x[9], ten values, so len(x) will be 10. And if you did q=0 while q != len(x): print x[q] q= q + 1 (a short hand way to write this is ' q += 1' subtract use -=) You would get an IndexError, because x[len(x)] which is x[10] doesn't exist. x goes from x[0] to x[9]. Anyway, digression over, So this statement 'for index in range(lengthFruit-1, -1, -1):' says start at 5, count to, but not including -1, and count by -1 each loop. lengthFruit for 'banana' will be 6, but x[5] is the last letter of 'banana' And we count to -1, to ensure that fruit[0] is printed also. So you would get >>>for index in range(lengthFruit-1, -1, -1): ... print [index], '\t', fruit[index] [5] a [4] n [3] a [2] n [1] a [0] b which is an upside down version of yours > [0] b > [1] a > [2] n > [3] a > [4] n > [5] a I hope my long winded reply helps, and now my standard disclaimer - There is no doubt an easier, more elegant way to do it, and someone more knowledgeable than me will post it shortly. But, my way works. Regards, Liam Clarke On Tue, 02 Nov 2004 15:18:15 +0300, Eri Mendz wrote: > > Hello all, > > I'm geting IndexError when iterating over a string in reverse. What > exactly does this mean? help(IndexError) in the interpreter isnt very > helpful. I'm a beginner trying to follow examples in the online tutorial > How To Think Like Computer Scientist (Python). > > I understand slicing of strings, lists and tuples but a bit confused > with indexing. Kindly enlighten me on this part. Fortunately i have the > online tutorials printed out for reference but i agree the best way to > learn is to practice and practice coding. Time is liability on my side > due to my day job but im trying to squeeze time in the night for python > the best i can. > > My goal of learning python is to learn it to help with system > administration of Linux/Windows. Maybe it can be of help to me one day. > > >>> fruit = 'banana' > >>> index = 0 > >>> while index < len(fruit): > ... print [index], '\t', fruit[index] > ... index = index + 1 > ... > [0] b > [1] a > [2] n > [3] a > [4] n > [5] a > >>> > >>> index = -1 > >>> while index < len(fruit): > ... print [index], '\t', fruit[index] > ... index = index - 1 > ... > [-1] a > [-2] n > [-3] a > [-4] n > [-5] a > [-6] b > [-7] Traceback (most recent call last): > File "", line 2, in ? > IndexError: string index out of range > > -- > Regards, > erimendz > > -- > This message was sent with an unlicensed evaluation version of > Novell NetMail. Please see http://www.netmail.com/ for details. > > _______________________________________________ > 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 orbitz at ezabel.com Tue Nov 2 14:32:27 2004 From: orbitz at ezabel.com (orbitz) Date: Tue Nov 2 14:32:35 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: <1099397895.8c57be3cjerimed@myrealbox.com> References: <1099397895.8c57be3cjerimed@myrealbox.com> Message-ID: <41878C6B.5080605@ezabel.com> 0 is both positive and negative. Eri Mendz wrote: >Hello all, > >I'm geting IndexError when iterating over a string in reverse. What >exactly does this mean? help(IndexError) in the interpreter isnt very >helpful. I'm a beginner trying to follow examples in the online tutorial >How To Think Like Computer Scientist (Python). > >I understand slicing of strings, lists and tuples but a bit confused >with indexing. Kindly enlighten me on this part. Fortunately i have the >online tutorials printed out for reference but i agree the best way to >learn is to practice and practice coding. Time is liability on my side >due to my day job but im trying to squeeze time in the night for python >the best i can. > >My goal of learning python is to learn it to help with system >administration of Linux/Windows. Maybe it can be of help to me one day. > > > > >>>>fruit = 'banana' >>>>index = 0 >>>>while index < len(fruit): >>>> >>>> >... print [index], '\t', fruit[index] >... index = index + 1 >... >[0] b >[1] a >[2] n >[3] a >[4] n >[5] a > > >>>>index = -1 >>>>while index < len(fruit): >>>> >>>> >... print [index], '\t', fruit[index] >... index = index - 1 >... >[-1] a >[-2] n >[-3] a >[-4] n >[-5] a >[-6] b >[-7] Traceback (most recent call last): > File "", line 2, in ? >IndexError: string index out of range > > >-- >Regards, >erimendz > > > > > >-- >This message was sent with an unlicensed evaluation version of >Novell NetMail. Please see http://www.netmail.com/ for details. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From Dragonfirebane at aol.com Tue Nov 2 15:03:49 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Tue Nov 2 15:03:59 2004 Subject: [Tutor] IndexError: string index out of range Message-ID: <1f6.1f01d37.2eb8edc5@aol.com> >>>>index = -1 >>>>while index < len(fruit): >>>> >>>> >... print [index], '\t', fruit[index] >... index = index - 1 >... >[-1] a >[-2] n >[-3] a >[-4] n >[-5] a >[-6] b >[-7] Traceback (most recent call last): > File "", line 2, in ? >IndexError: string index out of range len(fruit) is positive and index is negative, so index will always be smaller than len(fruit) . . . you want >>> index = -1 >>> while abs(index) <= len(fruit): print [index], '\t', fruit[index] index -= 1 [-1] a [-2] n [-3] a [-4] n [-5] a [-6] b that way, you're comparing the absolute value of index with the length of fruit and the loop will end w/o reaching an error Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041102/6c74cf6e/attachment.html From pythonTutor at venix.com Tue Nov 2 15:33:31 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue Nov 2 15:33:42 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: <1f6.1f01d37.2eb8edc5@aol.com> References: <1f6.1f01d37.2eb8edc5@aol.com> Message-ID: <1099406010.18468.21.camel@laptop.venix.com> Somewhat nit-picking but it is really while -len(fruit) <= index < len(fruit): # valid index values On Tue, 2004-11-02 at 09:03, Dragonfirebane@aol.com wrote: > >>>>index = -1 > >>>>while index < len(fruit): > >>>> > >>>> > >... print [index], '\t', fruit[index] > >... index = index - 1 > >... > >[-1] a > >[-2] n > >[-3] a > >[-4] n > >[-5] a > >[-6] b > >[-7] Traceback (most recent call last): > > File "", line 2, in ? > >IndexError: string index out of range > > len(fruit) is positive and index is negative, so index will always be > smaller than len(fruit) . . . you want > > >>> index = -1 > >>> while abs(index) <= len(fruit): > print [index], '\t', fruit[index] > index -= 1 > > [-1] a > [-2] n > [-3] a > [-4] n > [-5] a > [-6] b > > that way, you're comparing the absolute value of index with the length > of fruit and the loop will end w/o reaching an error > > > Email: dragonfirebane@aol.com > AIM: singingxduck > Programming Python for the fun of it. > > ______________________________________________________________________ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From renx99 at gmail.com Tue Nov 2 17:28:24 2004 From: renx99 at gmail.com (Rene Lopez) Date: Tue Nov 2 17:28:34 2004 Subject: [Tutor] Re: Cookie not reading first time through... In-Reply-To: <555128ce04103009057466ef3c@mail.gmail.com> References: <555128ce04103009057466ef3c@mail.gmail.com> Message-ID: <57edb4ce0411020828fdf04a0@mail.gmail.com> Nobody replied to this, so I figure nobody does cgi scripts in python ;-) but in regardless, I figured out the problem.... it was basically faulty logic and not paying attention to variable scope... so it's working now... woohoo! On Sat, 30 Oct 2004 12:05:36 -0400, Rene Lopez wrote: > I'm trying to learn how to use python for cgi scripts... > > I created a form that submits some info that I put in a cookie. Then > the script calls itself and reads the cookie, and displays a different > form to get more information. > > The problem I'm running into is the script is setting the cookie... > but it doesn't read it the first time through for some reason, if I > immediately try it again it works fine. So for some reason it's not > picking up the cookie the first time. > > Would it be a better idea to break the script into two different > scripts to accomplish this? > > Any advise would be appreciated, please be gentle, I'm still a newbie ;-) > > here is the script: > > #!/usr/bin/python > > import cgi,os,Cookie > import cgitb; cgitb.enable() > > def name_race(): > print "Content-Type: text/html\n\n" > print " \"http://www.w3.org/TR/html4/strict.dtd\">" > print "" > print "" > print "
" > print "" > print "" > print "
Name:
" > print "

" > print "" > print "" > print "" > print "" > print "" > print "" > print "" > print "
Race:
Human value=\"1\">
Elf value=\"2\">
" > print "

" > print "" > print "" > > def pick_class(): > mycookie = Cookie.SmartCookie(os.environ.get("HTTP_COOKIE", "")) > race = mycookie["race"].value > name = mycookie["name"].value > print "Content-Type: text/html\n\n" > print "" > print "" > print name > print race > print "\n" > > def print_sheet(): > pass > > def main(): > form = cgi.FieldStorage() > mycookie = Cookie.SmartCookie() > if form.has_key("name") and form.has_key("race"): > if (form["action"].value == "getclass"): > mycookie["name"] = form["name"].value > mycookie["name"]["max-age"] = 60 > mycookie["race"] = form["race"].value > mycookie["race"]["max-age"] = 60 > print mycookie > > pick_class() > else: name_race() > > main() > -- > > Rene > -- Rene From ps_python at yahoo.com Tue Nov 2 18:29:07 2004 From: ps_python at yahoo.com (kumar s) Date: Tue Nov 2 18:29:10 2004 Subject: [Tutor] Tab delimited file Message-ID: <20041102172907.43004.qmail@web53706.mail.yahoo.com> Dear Group, I have a tab-delimited text file with 100 columns. I wanted to write every first column and every alternative column starting from 2-100 in to a file. For example: Column 1 is names of my genes. Column 2 - 100 are experiments done to check those genes in various samples. Now I want to write column 1 and column 2 as file1. Column1 and column3 as file2. Col. 1 and col. 4 as file 3 ..so on and so forth. import string from string import strip f1 = open('file1.txt','r') f2 = open('sub_file2.txt','w') list = f1.read() list1 = split(list,'\n') for all lines in range(len(list1)): columns = split(list1[i],'\t') >From now on It proved difficult for me to progress ahead. How can I ask column 1 and column 2 to be written to sub_file2.txt. Can any one please help. What I do not know is: 1.how can I ask python to choose specific data only in column2, 3 4 ....like that. 2. I do not know I can ask python to iterate over each row and asking it to write only column 1 and column 2 and nothing else. Please help me and this is a stumblick block for me. Thanks Kumar __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From pythonTutor at venix.com Tue Nov 2 19:25:15 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue Nov 2 19:25:20 2004 Subject: [Tutor] Tab delimited file In-Reply-To: <20041102172907.43004.qmail@web53706.mail.yahoo.com> References: <20041102172907.43004.qmail@web53706.mail.yahoo.com> Message-ID: <1099419914.18683.29.camel@laptop.venix.com> Assuming the input file is small enough to manipulate in memory: rows = [ line.split('\t') for line in f1 ] # nested lists ~= 2d array columns = zip(*rows) # transposes rows and columns (thanks Peter Norvig) Now your data is organized the way you want it. The hard part is knowing how to do the transpose. I learned it from Peter Norvig's web site. http://www.norvig.com/python-iaq.html Let us know if you have questions getting the data written out. On Tue, 2004-11-02 at 12:29, kumar s wrote: > Dear Group, > I have a tab-delimited text file with 100 columns. > > I wanted to write every first column and every > alternative column starting from 2-100 in to a file. > > For example: > Column 1 is names of my genes. > Column 2 - 100 are experiments done to check those > genes in various samples. > > Now I want to write column 1 and column 2 as file1. > Column1 and column3 as file2. > Col. 1 and col. 4 as file 3 ..so on and so forth. > > > import string > from string import strip > > f1 = open('file1.txt','r') > f2 = open('sub_file2.txt','w') > list = f1.read() > list1 = split(list,'\n') > for all lines in range(len(list1)): > columns = split(list1[i],'\t') > > > >From now on It proved difficult for me to progress > ahead. How can I ask column 1 and column 2 to be > written to sub_file2.txt. > > Can any one please help. > > What I do not know is: > 1.how can I ask python to choose specific data only in > column2, 3 4 ....like that. > > 2. I do not know I can ask python to iterate over each > row and asking it to write only column 1 and column 2 > and nothing else. > > Please help me and this is a stumblick block for me. > > > Thanks > > Kumar > > __________________________________________________ > 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 -- Lloyd Kvam Venix Corp From carroll at tjc.com Tue Nov 2 20:04:20 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Nov 2 20:04:23 2004 Subject: [Tutor] os.rename error problem In-Reply-To: Message-ID: On Mon, 1 Nov 2004, justin wrote: > Exception in Tkinter callback > Traceback (most recent call last): > File "D:\PYTHON23\lib\lib-tk\Tkinter.py", line 1345, in __call__ > return self.func(*args) > File "E:\work\Python\ID3edit\v2.0\ID3edit.py", line 71, in reName > os.rename(old, new) > OSError: [Errno 13] Permission denied > >>> > > Im using Win2k and have checked to see if the file is read-only. Its not and I > have been able to edit the MP3 ID3 tag information without problem. It's not in use, is it? Still open by a tag editor or being played back? From shitizb at yahoo.com Tue Nov 2 22:39:43 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Tue Nov 2 22:39:47 2004 Subject: [Tutor] Problem modify windows registry (desktop wallpaper) In-Reply-To: <5.0.2.1.2.20041101170023.022b8da8@qmail.dideas.com> Message-ID: <20041102213943.55726.qmail@web53805.mail.yahoo.com> Hi, you could do either of the following: 1. replace the wallpaper file itself without touching the registry , by using commands from os module. 2. What i gather is that as a non-adminstrative user you dont have permission to change the registry. So u could use the LogonUser and ImpersonateLoggedonUser functions from win32security module to impersonate as the administrator before editing the registry. tell me if it helps. shitiz Chris Barnhart wrote: Hi, I'm attempting to write a python (2.3.3) program that will update the wallpaper under Windows 2000. I found an example delphi program : (http://www.latiumsoftware.com/en/delphi/00020.php) which suggest that I need to change a registry variable, and then execute a system parameters changed statement. The following program attempts to change the desktop wallpaper by changing a key in the HKEY_CURRENT_USER. This fails due to access denied? I'm using methods from _winreg. What weird, is that by using OpenKey I've been able to create new registry sub folders, and then using SetValue, change the value of the "default" key. I've also looked modifying the registry from WMI, and also looked at using windll - but obsolete. Any ideas? Thank you, Chris -------------- import _winreg as wreg key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Control Panel\\Desktop") v = wreg.QueryValueEx(key,"WallPaper") print "Key value is : ", v wreg.SetValueEx(key, "WallPaper", 0, wreg.REG_SZ, v[0]) C:\src\python>python r3.py Key value is : (u'C:\\WINNT\\Mozilla Wallpaper.bmp', 1) Traceback (most recent call last): File "r3.py", line 6, in ? wreg.SetValueEx(key, "WallPaper", 0, wreg.REG_SZ, v[0]) WindowsError: [Errno 5] Access is denied _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com/a -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041102/b50a0652/attachment.htm From jeff at ccvcorp.com Tue Nov 2 23:14:18 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Nov 2 23:12:16 2004 Subject: [Tutor] os.rename error problem In-Reply-To: References: Message-ID: <418806BA.4080009@ccvcorp.com> justin wrote: >Hello, > >I know os.rename is pretty easy and straight forward to use but Im trippin up on >something here. In the interactive prompt I have no problem renaming a file. > > As others have suggested, check whether the source file is already open elsewhere in your program. But I'm a bit puzzled about this segment: > for item in pathList: # Adds the file names to the path > if os.path.isfile(item + '/' + old) == True: > old = item + '/' + old > new = item + '/' + new > else: pass > > It's not clear where your pathList is coming from (presumably it's a global variable, which (like all globals) is probably a poor design choice, but that's another story), but this is *not* an optimal way to build your paths. Instead of manually adding together path elements with a character that you think should work as path separator, you should be using os.path.join() to assemble the elements. An equivalent segment using os.path.join() might look like this: for item in pathList: if os.path.isfile(os.path.join(item, old)): old = os.path.join(item, old) new = os.path.join(item, new) However, notice that if you've got more than one item in pathList, you're overwriting old and new on each iteration. This is effectively equivalent to: if os.path.isfile(os.path.join(pathList[-1], old)): old = os.path.join(pathList[-1], old) new = os.path.join(pathList[-1], new) Since we don't know what's in pathList, it's hard to say for certain whether this is a sensible thing to do or not, but my gut feeling is that you might want to reconsider how you're creating/using pathList. Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Tue Nov 2 23:20:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 2 23:20:25 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: <1099397895.8c57be3cjerimed@myrealbox.com> Message-ID: On Tue, 2 Nov 2004, Eri Mendz wrote: > I understand slicing of strings, lists and tuples but a bit confused > with indexing. Kindly enlighten me on this part. Fortunately i have the > online tutorials printed out for reference but i agree the best way to > learn is to practice and practice coding. Hi Eri, And make sure you're talking to other folks who are programming too --- many of us can offer good advice about the kind of conventions that books sometimes forget to mention... *grin* There are still some programming pitfalls out there, even with the best of tutorials, so it's invaluable that you talk to a group like this Python-Tutor mailing list. > >>> index = -1 > >>> while index < len(fruit): > ... print [index], '\t', fruit[index] > ... index = index - 1 > ... > [-1] a > [-2] n > [-3] a > [-4] n > [-5] a > [-6] b > [-7] Traceback (most recent call last): > File "", line 2, in ? > IndexError: string index out of range People have already given reasons why this is sending out an IndexError, so I'll try to avoid repeating them. But another useful technique, when debugging something like this, is to ask ourselves: what did we expect to happen instead? By getting those assumptions out there in the open, we might be able to figure out what was causing the confusion. For example, maybe we might have wanted it to continue cycling over and over, like: ### [-1] a [-2] n [-3] a [-4] n [-5] a [-6] b [-7] a [-8] n [-9] a [-10] n ... ### Or maybe we wanted something else. It's really a good technique to try to show what the expected result should be, since we can then start asking questions like, "Why didn't it do *this* at this point, instead?" Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Tue Nov 2 23:28:46 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 2 23:28:50 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: <1ff2dfbf04110205061d732c82@mail.gmail.com> Message-ID: > These handmade indexing is allways hard to code. Better to use a for-loop: > > for char in fruit: > print char > > for index,char in enumerate(fruit): > print [index], char > > (but while this is fine coding style, it's not such a challenging > learning example ;-) Hi Michael, For this particular example, I'd actually recommend using a backwards slice. Here's an example: ### >>> message = 'this is a test of the emergency broadcast system' ### We're already familiar with slicing whole sections of a list: ### >>> message[3:7] 's is' ### But it turns out that slicing is even more versatile: we can ask Python to give us every other letter, for example: ### >>> message[::1] 'this is a test of the emergency broadcast system' >>> >>> message[::2] 'ti sats fteeegnybodatsse' >>> >>> message[::3] 'tss sot eeyrdsst' ### The third component of the slice is the "step" between elements. By default, we "step" consecutive elements, but we can easily use a larger step to jump through our sequence. And it turns out that we can select a negative step: ### >>> message[::-1] 'metsys tsacdaorb ycnegreme eht fo tset a si siht' >>> >>> message[3:7:-1] '' >>> >>> message[7:3:-1] ' si ' ### Hope this helps! From marilyn at deliberate.com Wed Nov 3 00:46:05 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Nov 3 00:46:09 2004 Subject: [Tutor] mysql formatting Message-ID: Can you folks please help me some more? I'm having a trouble, now that I'm really trying to implement what I learned yesterday. Here's the error: _mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'\'doorman\' set status = "\'MOVED\'" where in_id = \'60\' and out_address like "%\'wrgf\' at line 1') Here's my code: def execute_mysql(self, this, *args): if log.level & log.sql: log.it('About to execute:' + this + '<-->' + repr(args)) try: self.cursor.execute(this, args) except _mysql_exceptions.Warning, msg: log.it('Mysql Warning: ' + str(msg)) except _mysql_exceptions.OperationalError, msg: print "Are you using the right data base? Try changing /b/local/doorman/configure.py TESTING = 0" raise And from my log: About to execute:update %s set status = "%s" where in_id = %s and out_address like "%%%s%%"<-->('doorman', 'MOVED', '60', 'wrgfgtfdpmrwe@hewpwbpsk.rashpie.com') Why am I getting those extra \' thingies? Thank you so much! Marilyn From pythonTutor at venix.com Wed Nov 3 01:12:16 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Wed Nov 3 01:13:03 2004 Subject: [Tutor] mysql formatting In-Reply-To: References: Message-ID: <1099440736.18683.85.camel@laptop.venix.com> On Tue, 2004-11-02 at 18:46, Marilyn Davis wrote: > Can you folks please help me some more? > > I'm having a trouble, now that I'm really trying to implement what I > learned yesterday. > > Here's the error: > > _mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'\'doorman\' set status = "\'MOVED\'" where in_id = \'60\' and out_address like "%\'wrgf\' at line 1') > > > Here's my code: > > def execute_mysql(self, this, *args): > if log.level & log.sql: > log.it('About to execute:' + this + '<-->' + repr(args)) > try: > self.cursor.execute(this, args) > except _mysql_exceptions.Warning, msg: > log.it('Mysql Warning: ' + str(msg)) > except _mysql_exceptions.OperationalError, msg: > print "Are you using the right data base? Try changing /b/local/doorman/configure.py TESTING = 0" > raise > > And from my log: > > About to execute:update %s set status = "%s" where in_id = %s and out_address like "%%%s%%"<-->('doorman', 'MOVED', '60', 'wrgfgtfdpmrwe@hewpwbpsk.rashpie.com') I am pretty sure it is the quotes. Simply use %s where the data is supposed to go and the module will quote it as necessary. They make it so easy on us that it is hard not to do too much. About to execute:update %s set status = %s where in_id = %s and out_address like %%%s%% <-->('doorman', 'MOVED', '60', 'wrgfgtfdpmrwe@hewpwbpsk.rashpie.com') > > > Why am I getting those extra \' thingies? > > Thank you so much! > > Marilyn > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Wed Nov 3 01:27:25 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 3 01:27:29 2004 Subject: [Tutor] mysql formatting In-Reply-To: Message-ID: On Tue, 2 Nov 2004, Marilyn Davis wrote: > Can you folks please help me some more? > > I'm having a trouble, now that I'm really trying to implement what I > learned yesterday. > [some text cut] > And from my log: > > About to execute:update %s set status = "%s" where in_id = %s and > out_address like "%%%s%%"<-->('doorman', 'MOVED', '60', > 'wrgfgtfdpmrwe@hewpwbpsk.rashpie.com') Hi Marilyn, Unfortunately, I don't think the table name can be plugged into there using the prepared statement syntax. I think only column values can be "plugged into". For example, I have a database with a 'pipeline' table, but doing something like: ### >>> conn = MySQLdb.connect(db='testdb') >>> cursor = conn.cursor() >>> cursor.execute('select * from %s', 'pipeline') Traceback (most recent call last): File "", line 1, in ? 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 114, in _execute self.errorhandler(self, exc, value) File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near ''pipeline'' at line 1") ### That brings up an ugly error, even though this will work: ### >>> cursor.execute('select * from pipeline') 1L ### So I'm pretty sure that your code needs some adjustment so that the table name itself is not a parameter. > Why am I getting those extra \' thingies? Those are there to make it clear that the quote isn't closing off the string, but is a literal quote in the content of the string. A simpler example might help: ### >>> weird_string = "This is 'a string \"with literal quotes" >>> weird_string 'This is \'a string "with literal quotes' ### When we ask Python for the representation of 'weird_string', it responds with: 'This is \'a string "with literal quotes' This tells us that it's a string, by the surrounding single quotes. And this string has the following character content: This is \'a string "with literal quotes The leading backspace in there tells us that the inner single quote doesn't close off the string, but is part of its content. The double quote here doesn't have to be escaped, since the string as a whole was displayed with single quotes. But imagine if Python had responded to our request without the backslash: ### ### Imaginary Python: Python does NOT respond this way. ### >>> weird_string = "This is 'a string \"with literal quotes" >>> weird_string 'This is 'a string "with literal quotes' ### Then this would be harder to us to understand what's happening, since it looks like the result is some kind of unbalanced value. We have 'This is' as some string. But then, there's a freestanding a string thing there, followed by some unbalanced string value "with literal quotes' which is wrong, since strings have to end with the same quote character that they begin with. So this is potentially very confusing. So although the backslashes are confusing at first, once you understand why they show up, it's not so bad. The backslashes are there to save us from being completely confused. *grin* Hope this helps! From cyresse at gmail.com Wed Nov 3 01:35:59 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Nov 3 01:36:05 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: References: <1ff2dfbf04110205061d732c82@mail.gmail.com> Message-ID: And that would be the simpler, more elegant way I mentioned in my disclaimer. : ) On Tue, 2 Nov 2004 14:28:46 -0800 (PST), Danny Yoo wrote: > > > These handmade indexing is allways hard to code. Better to use a for-loop: > > > > for char in fruit: > > print char > > > > for index,char in enumerate(fruit): > > print [index], char > > > > (but while this is fine coding style, it's not such a challenging > > learning example ;-) > > Hi Michael, > > For this particular example, I'd actually recommend using a backwards > slice. Here's an example: > > ### > >>> message = 'this is a test of the emergency broadcast system' > ### > > We're already familiar with slicing whole sections of a list: > > ### > >>> message[3:7] > 's is' > ### > > But it turns out that slicing is even more versatile: we can ask Python to > give us every other letter, for example: > > ### > >>> message[::1] > 'this is a test of the emergency broadcast system' > >>> > >>> message[::2] > 'ti sats fteeegnybodatsse' > >>> > >>> message[::3] > 'tss sot eeyrdsst' > ### > > The third component of the slice is the "step" between elements. By > default, we "step" consecutive elements, but we can easily use a larger > step to jump through our sequence. > > And it turns out that we can select a negative step: > > ### > >>> message[::-1] > 'metsys tsacdaorb ycnegreme eht fo tset a si siht' > >>> > >>> message[3:7:-1] > '' > >>> > >>> message[7:3:-1] > ' si ' > ### > > Hope this helps! > > > > _______________________________________________ > 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 keridee at jayco.net Wed Nov 3 03:07:56 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Nov 3 03:41:10 2004 Subject: [Tutor] Does anyone know if IDLE has a maximized setting? References: <000201c4bf49$c32d4be0$d05328cf@JSLAPTOP> <20041101174841.6c9386a5.klappnase@freenet.de> Message-ID: <008501c4c14e$7d223460$4c5428cf@JSLAPTOP> Okay, I thank you very much for your help!!! Unfortunately, it does not completely solve the problem. I have a little trouble with my laptop thingy. My mouse pad on my laptop does not like "restored" windows. The scroll thingy on the side of the pad will not work unless the window is actually "maximized." I am overjoyed at the change in dimensions, but I wish to set my sights a little higher. I thank you if you can find an actual maximize setting for Tkinter. Thanks, Jacob Schmidt From keridee at jayco.net Wed Nov 3 03:12:39 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Nov 3 03:41:24 2004 Subject: [Tutor] Does anyone know if IDLE has a maximized setting? References: <000201c4bf49$c32d4be0$d05328cf@JSLAPTOP><20041101174927.560287dc.klappnase@freenet.de> <20041101171951.GA4561@outreachnetworks.com> Message-ID: <008601c4c14e$7e418710$4c5428cf@JSLAPTOP> I appreciate your help too, but I tend not to mess with the .idlerc files. I have a very neat python directory where I store all of my scripts. The .idlerc directory is put on os.getcwd() if your using Windows 98, and I don't like that. So I changed it somehow, (I don't remember how) and it doesn't do that anymore. I don't really know where it rights the config file at anymore, so that rules out your very kind suggestion. I also ask you if there's a way to maximize the window--really maximize the window so the scroll on my laptop's mouse pad will work. I thank you for your suggestion, Jacob Schmidt From keridee at jayco.net Wed Nov 3 04:19:40 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Nov 3 04:20:13 2004 Subject: [Tutor] Feeling really stupid now Message-ID: <00a001c4c153$f67fbf30$4c5428cf@JSLAPTOP> Hello. I read the conversation on calculating pi, and I noticed the advantages of decimal. Could anyone give me a direct link to the source of the decimal module (released in python 2.4)? Thanks. Jacob Schmidt From keridee at jayco.net Wed Nov 3 04:36:40 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Nov 3 04:37:21 2004 Subject: [Tutor] IndexError: string index out of range References: <1099397895.8c57be3cjerimed@myrealbox.com> Message-ID: <00d701c4c156$59312e00$4c5428cf@JSLAPTOP> >q=0 >while q != len(x): > print x[q] > q= q + 1 (a short hand way to write this is ' q += 1' subtract use -=) Just a quick note. A little while ago, I believe there was a squirmish about not getting too nit-picky about optimizing the code... but... I would like to point out that the short hand way of stepping was about 1.5 times slower when I tested it for all arithmetic operations. :-) Just pointing it out. Jacob Schmidt From keridee at jayco.net Wed Nov 3 04:23:50 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Nov 3 04:51:52 2004 Subject: [Tutor] Now I feel really stupid Message-ID: <00ae01c4c154$8b829120$4c5428cf@JSLAPTOP> Duh, I'm dumb. I look at the next message or so that says how to calculate another pi formula and it has a link to decimal.py in it! Sorry. Jacob Schmidt From bill.mill at gmail.com Wed Nov 3 04:59:41 2004 From: bill.mill at gmail.com (Bill Mill) Date: Wed Nov 3 04:59:46 2004 Subject: [Tutor] Feeling really stupid now In-Reply-To: <00a001c4c153$f67fbf30$4c5428cf@JSLAPTOP> References: <00a001c4c153$f67fbf30$4c5428cf@JSLAPTOP> Message-ID: <797fe3d404110219596fdd41dc@mail.gmail.com> Jacob, You can read instructions at http://mail.python.org/pipermail/python-list/2004-September/242293.html . Peace Bill Mill On Tue, 2 Nov 2004 22:19:40 -0500, Jacob S. wrote: > Hello. > > I read the conversation on calculating pi, and I noticed the advantages > of decimal. Could anyone give me a direct link to the source of the decimal > module (released in python 2.4)? Thanks. > > Jacob Schmidt > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Dragonfirebane at aol.com Wed Nov 3 06:06:07 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Wed Nov 3 06:06:14 2004 Subject: [Tutor] Classes . . . Message-ID: <46.5c97ad07.2eb9c13f@aol.com> Hello all, I was just wondering if it was possible, within a class, to import a module without importing it in every method. I'm trying to write an OOP for tictactoe that uses random to select the computer's move when no obvious moves are available, and since I separated the program into two files, one for user interface, the other for the actual work, importing random in the user interface doesn't do squat, nor does importing it before the __init__ of the class, or within it . . . any ideas? Thanks in advance, Orri Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041103/af108f68/attachment.htm From bill.mill at gmail.com Wed Nov 3 06:12:38 2004 From: bill.mill at gmail.com (Bill Mill) Date: Wed Nov 3 06:12:42 2004 Subject: [Tutor] Classes . . . In-Reply-To: <46.5c97ad07.2eb9c13f@aol.com> References: <46.5c97ad07.2eb9c13f@aol.com> Message-ID: <797fe3d40411022112f8818b4@mail.gmail.com> Orri, Why do you import random into the file containing the UI? Why don't you just not import it there? Peace Bill Mill bill.mill at gmail.com On Wed, 3 Nov 2004 00:06:07 EST, dragonfirebane@aol.com wrote: > > Hello all, > > I was just wondering if it was possible, within a class, to import a module > without importing it in every method. I'm trying to write an OOP for > tictactoe that uses random to select the computer's move when no obvious > moves are available, and since I separated the program into two files, one > for user interface, the other for the actual work, importing random in the > user interface doesn't do squat, nor does importing it before the __init__ > of the class, or within it . . . any ideas? > > Thanks in advance, > Orri > > > Email: dragonfirebane@aol.com > AIM: singingxduck > Programming Python for the fun of it. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From jerimed at myrealbox.com Wed Nov 3 06:17:56 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Wed Nov 3 06:18:02 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: References: Message-ID: <41886A04.6060100@myrealbox.com> Dear All, Thanks a lot for the good advise and tips given to me. Will get back here if i have question on the subject issue. -- Regards, erimendz ** use firefox/thunderbird ** http://www.spreadfirefox.com/?q=affiliates&id=6670&t=58 Danny Yoo wrote: >>These handmade indexing is allways hard to code. Better to use a for-loop: >> >>for char in fruit: >> print char >> >>for index,char in enumerate(fruit): >> print [index], char >> >>(but while this is fine coding style, it's not such a challenging >>learning example ;-) > > > Hi Michael, > > > For this particular example, I'd actually recommend using a backwards > slice. Here's an example: > > ### > >>>>message = 'this is a test of the emergency broadcast system' > > ### > > > We're already familiar with slicing whole sections of a list: > > ### > >>>>message[3:7] > > 's is' > ### > > > > But it turns out that slicing is even more versatile: we can ask Python to > give us every other letter, for example: > > ### > >>>>message[::1] > > 'this is a test of the emergency broadcast system' > >>>>message[::2] > > 'ti sats fteeegnybodatsse' > >>>>message[::3] > > 'tss sot eeyrdsst' > ### > > The third component of the slice is the "step" between elements. By > default, we "step" consecutive elements, but we can easily use a larger > step to jump through our sequence. > > > > And it turns out that we can select a negative step: > > ### > >>>>message[::-1] > > 'metsys tsacdaorb ycnegreme eht fo tset a si siht' > >>>>message[3:7:-1] > > '' > >>>>message[7:3:-1] > > ' si ' > ### > > > Hope this helps! > > > > > From jerimed at myrealbox.com Wed Nov 3 09:01:14 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Wed Nov 3 09:01:15 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: References: Message-ID: On Tue, 2 Nov 2004, Danny Yoo wrote: [snip] > And it turns out that we can select a negative step: > > ### >>>> message[::-1] > 'metsys tsacdaorb ycnegreme eht fo tset a si siht' i have seen this syntax before in one of my study guides, and is awesome: >>> for i in fruit[::-1]: .... print [index], '\t', i .... index = index - 1 .... [-1] a [-2] n [-3] a [-4] n [-5] a [-6] b so now i realize in python "TIMTOWDI"... very nice, thanks guys! now back to my tutorial; i will encapsulate this in a function and generalize, e.g., to ask for user input and reverse the input. From cyresse at gmail.com Wed Nov 3 13:24:49 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Nov 3 13:24:59 2004 Subject: [Tutor] Classes . . . In-Reply-To: <797fe3d40411022112f8818b4@mail.gmail.com> References: <46.5c97ad07.2eb9c13f@aol.com> <797fe3d40411022112f8818b4@mail.gmail.com> Message-ID: >the other for the actual work, importing random in the user interface doesn't do squat, Why are you importing random into yourt UI??? -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only bsic human duty, to take the consequences. From cyresse at gmail.com Wed Nov 3 13:30:22 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Nov 3 13:30:25 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: References: Message-ID: Danny, you wouldn't want to clarify a syntax thing would you? > >>>> message[::-1] >>> message[3:7:-1] In the above, the[ ::-1] just defaults to [0:end of string:step]? Regards, Liam Clarke -- '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 maxnoel_fr at yahoo.fr Wed Nov 3 14:35:58 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Nov 3 14:42:32 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: References: Message-ID: <4B467718-2D9D-11D9-A282-000393CBC88E@yahoo.fr> On Nov 3, 2004, at 12:30, Liam Clarke wrote: >>>>>> message[::-1] >>>> message[3:7:-1] > > In the above, the[ ::-1] just defaults to [0:end of string:step]? Yup, it does. Beautiful, isn't it? -- 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 mi.janssen at gmail.com Wed Nov 3 15:00:05 2004 From: mi.janssen at gmail.com (Michael Janssen) Date: Wed Nov 3 15:00:11 2004 Subject: [Tutor] IndexError: string index out of range In-Reply-To: References: <1ff2dfbf04110205061d732c82@mail.gmail.com> Message-ID: <1ff2dfbf04110306007375eefb@mail.gmail.com> On Tue, 2 Nov 2004 14:28:46 -0800 (PST), Danny Yoo wrote: > For this particular example, I'd actually recommend using a backwards > slice. Here's an example: > >>> message = 'this is a test of the emergency broadcast system' > >>> message[::-1] > 'metsys tsacdaorb ycnegreme eht fo tset a si siht' indeed reversing via extended slice is handy sometimes. Nevertheless I allways feel like adding a comment that reads "now comes silly extended slice syntax, which means I reverse the string - sorry for that, dear reader". Not to talk about all the time I have spend / wasted while figuring out the right syntax (my first try was [-1:0:-1] ;-). A little bit it seems like line noise... Michael From ps_python at yahoo.com Wed Nov 3 17:12:48 2004 From: ps_python at yahoo.com (kumar s) Date: Wed Nov 3 17:13:26 2004 Subject: [Tutor] IndexError: list index out of range : f2.write(col[0] + '\t' + col[1] + '\n') Message-ID: <20041103161248.91728.qmail@web53704.mail.yahoo.com> Dear Group, This is a new question about IndexError and thats the reason I pasterd f2.write(col[0] + '\t' + col[1] + '\n') in the subject line. I wrote a function to parse coluns in a tab delimited text file. def cutter (f1,f2): file = open(f1,'r') file2 = open(f2,'w') fopen = file.read() flist = split(fopen,'\n') for i in range(len(flist)): col = split(flist[i],'\t') file2.write(col[0] + '\t' + col[1] + '\t' + col[3] + '\n' ) file2.close() >>> cutter('gene_data.txt','test1.txt') Traceback (most recent call last): File "", line 1, in -toplevel- cutter('gene_data.txt','test1.txt') File "", line 8, in cutter file2.write(col[0] + '\t' + col[1] + '\t' + col[3] + '\n' ) ValueError: I/O operation on closed file Why am I getting ValueError and I/O. Why shouldnt I close file2.close()? 2nd Question: I removed file2.close() line in the code. It is now like this: >>> def cutter (f1,f2): file = open(f1,'r') file2 = open(f2,'w') fopen = file.read() flist = split(fopen,'\n') for i in range(len(flist)): col = split(flist[i],'\t') file2.write(col[0] + '\t' + col[1] + '\t' + col[3] + '\n' ) >>> cutter('gene_data.txt','test1.txt') Traceback (most recent call last): File "", line 1, in -toplevel- cutter('gene_data.txt','test1.txt') File "", line 8, in cutter file2.write(col[0] + '\t' + col[1] + '\t' + col[3] + '\n' ) IndexError: list index out of range >>> Now, why am I getting IndexError: list out of range. What is the problem. I got the result but an error is not so good. Can any one help me explaing the situation. Thanks. Kumar. __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From maxnoel_fr at yahoo.fr Wed Nov 3 18:02:22 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Nov 3 18:02:31 2004 Subject: [Tutor] IndexError: list index out of range : f2.write(col[0] + '\t' + col[1] + '\n') In-Reply-To: <20041103161248.91728.qmail@web53704.mail.yahoo.com> References: <20041103161248.91728.qmail@web53704.mail.yahoo.com> Message-ID: <20C5B3ED-2DBA-11D9-A282-000393CBC88E@yahoo.fr> On Nov 3, 2004, at 16:12, kumar s wrote: > def cutter (f1,f2): > file = open(f1,'r') > file2 = open(f2,'w') > fopen = file.read() > flist = split(fopen,'\n') > for i in range(len(flist)): > col = split(flist[i],'\t') > file2.write(col[0] + '\t' + col[1] + '\t' + col[3] + > '\n' ) > file2.close() > > >>>> cutter('gene_data.txt','test1.txt') > > Traceback (most recent call last): > File "", line 1, in -toplevel- > cutter('gene_data.txt','test1.txt') > File "", line 8, in cutter > file2.write(col[0] + '\t' + col[1] + '\t' + col[3] > + '\n' ) > ValueError: I/O operation on closed file > > > Why am I getting ValueError and I/O. Why shouldnt I > close file2.close()? That's because you're closing the file after each line. You should close it after the for loop instead. Also, you're using C-style for loops. A more elegant and memory-efficient (the way you're doing it, you load the whole file in memory, which is a Bad Thing if it's a big file) way to write your function using the file iterator: def cutter(sourceName, destName): source = open(sourceName) # Read-only is the default mode dest = open(destName, 'w') for line in source: col = split(line, '\t') dest.write('\t'.join(col) + '\n') dest.close() One last thing: you're naming your source file stream 'file', which is not a good idea given that file is a Python built-in class (for which open is an alias). > > > 2nd Question: > >>>> cutter('gene_data.txt','test1.txt') > > Traceback (most recent call last): > File "", line 1, in -toplevel- > cutter('gene_data.txt','test1.txt') > File "", line 8, in cutter > file2.write(col[0] + '\t' + col[1] + '\t' + col[3] > + '\n' ) > IndexError: list index out of range >>>> > > > > Now, why am I getting IndexError: list out of range. > What is the problem. I got the result but an error is > not so good. Can any one help me explaing the > situation. That probably means that on the line for which you're getting the error, len(col) < 4. -- 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 barry at angleinc.com Wed Nov 3 18:07:55 2004 From: barry at angleinc.com (Barry Sperling) Date: Wed Nov 3 18:07:49 2004 Subject: [Tutor] Forbidden HTML, or not? In-Reply-To: <20041103161248.91728.qmail@web53704.mail.yahoo.com> References: <20041103161248.91728.qmail@web53704.mail.yahoo.com> Message-ID: <4189106B.1020505@angleinc.com> I used urlopen to get the HTML of a webpage on the net and it worked for the first few that I tried but not for Google News: http://news.google.com/nwshp?hl=en&gl=us This site gave me an error in the Interactive Window section of PythonWin, the last part of which was: line 306, in _call_chain result = func(*args) File "D:\Python23\lib\urllib2.py", line 412, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden So I interpreted that to mean that some flag was set on the site to prevent reading of the HTML. However, in Mozilla, when I read the page source with ctrl-U the HTML did show up in its entirety. What do I need to do to get the same result with my code, part of which is below: import urllib2 # OPENING AND READING HTML import re # SEARCHING THE HTML # THIS GIVES "FORBIDDEN" WITH AND WITHOUT THE "?hl=en&gl=us" ATTACHED source = urllib2.urlopen('http://news.google.com/nwshp') html_text = source.read() Barry From ejp at zomething.com Wed Nov 3 18:27:41 2004 From: ejp at zomething.com (EJP) Date: Wed Nov 3 18:27:36 2004 Subject: [Tutor] Forbidden HTML, or not? In-Reply-To: <4189106B.1020505@angleinc.com> References: <20041103161248.91728.qmail@web53704.mail.yahoo.com> <4189106B.1020505@angleinc.com> Message-ID: <20041103092741.940866015.ejp@zomething.com> > > What do I need to do to get the same result with my code, part of which > > is below: > > import urllib2 # OPENING AND READING HTML > import re # SEARCHING THE HTML > > # THIS GIVES "FORBIDDEN" WITH AND WITHOUT THE "?hl=en&gl=us" ATTACHED > source = urllib2.urlopen('http://news.google.com/nwshp') > > html_text = source.read() Note in the returned HTML: "

Forbidden

Your client does not have permission to get URL / from this server." Google may not allow the "client" or USER_AGENT named by the urllib2 to access the webpage content. You can try imitating IE, to see if that makes a difference, by declaring the USER_AGENT with the same declaration IE uses. In a quick try, I got results similar to your using urllib: IDLE 1.0.3 >>> url1="http://news.google.com/" >>> import urllib >>> page=urllib.urlopen(url1).read() >>> len(page) 2224 >>> page '403 Forbidden
Google   
Error
 

Forbidden

Your client does not have permission to get URL / from this server.

' From mlist-python at dideas.com Wed Nov 3 18:29:35 2004 From: mlist-python at dideas.com (Chris Barnhart) Date: Wed Nov 3 18:30:16 2004 Subject: [Tutor] Problem modify windows registry (desktop wallpaper) In-Reply-To: <20041102213943.55726.qmail@web53805.mail.yahoo.com> References: <5.0.2.1.2.20041101170023.022b8da8@qmail.dideas.com> Message-ID: <5.0.2.1.2.20041103121943.02315c18@qmail.dideas.com> Shitiz, Thank you for your help, I was a little rushed in my first post and left out some important details. Although the application is to change the wallpaper, the lesson I want to learn is the modification of the registry. Because the key-value I'm trying to change is in HKEY_CURRENT_USER shouldn't a non-privileged user be able to change it? I also happen to be running as ADMINISTRATOR which I should mentioned. Chris PS : Simply changing the wallpaper file won't actually change the wallpaper immediately. Possibly if I ran a "system parameters changed" function afterward, it would then update the desktop. I even have to do this after changing the registry value. At 04:39 PM 11/2/2004, Shitiz Bansal wrote: >Hi, > >you could do either of the following: > >1. replace the wallpaper file itself without touching the registry , by >using commands from os module. >2. What i gather is that as a non-adminstrative user you dont have >permission to change the registry. So u could use the LogonUser and >ImpersonateLoggedonUser functions from win32security module to impersonate >as the administrator before editing the registry. > >tell me if it helps. > >shitiz > > >Chris Barnhart wrote: >Hi, > >I'm attempting to write a python (2.3.3) program that will update the >wallpaper under Windows 2000. I found an example delphi program : >(http://www.latiumsoftware.com/en/delphi/00020.php) which suggest that I >need to change a registry variable, and then execute a system parameters >changed statement. > >The following program attempts to change the desktop wallpaper by changing >a key in the HKEY_CURRENT_USER. This fails due to access denied? I'm >using methods from _winreg. > >What weird, is that by using OpenKey I've been able to create new registry >sub folders, and then using SetValue, change the value of the "default" key. > >I've also looked modifying the registry from WMI, and also looked at using >windll - but obsolete. > >Any ideas? > >Thank you, >Chris > >-------------- > > > >import _winreg as wreg > >key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Control Panel\\Desktop") >v = wreg.QueryValueEx(key,"WallPaper") >print "Key value is : ", v >wreg.SetValueEx(key, "WallPaper", 0, wreg.REG_SZ, v[0]) > >C:\src\python>python r3.py >Key value is : (u'C:\\WINNT\\Mozilla Wallpaper.bmp', 1) >Traceback (most recent call last): >File "r3.py", line 6, in ? >wreg.SetValueEx(key, "WallPaper", 0, wreg.REG_SZ, v[0]) >WindowsError: [Errno 5] Access is denied From mark.kels at gmail.com Wed Nov 3 18:58:10 2004 From: mark.kels at gmail.com (Mark Kels) Date: Wed Nov 3 18:58:14 2004 Subject: [Tutor] Input from CGI ? Message-ID: Hi all, How can I get input (string) from the user in CGI ? Thanks! From kent_johnson at skillsoft.com Wed Nov 3 20:21:37 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Nov 3 20:21:43 2004 Subject: [Tutor] Classes . . . In-Reply-To: <46.5c97ad07.2eb9c13f@aol.com> References: <46.5c97ad07.2eb9c13f@aol.com> Message-ID: <6.1.0.6.0.20041103142045.0294a5b8@mail4.skillsoft.com> Put the import at the top of each file that uses functions from the module. Kent At 12:06 AM 11/3/2004 -0500, Dragonfirebane@aol.com wrote: >Hello all, > >I was just wondering if it was possible, within a class, to import a >module without importing it in every method. I'm trying to write an OOP >for tictactoe that uses random to select the computer's move when no >obvious moves are available, and since I separated the program into two >files, one for user interface, the other for the actual work, importing >random in the user interface doesn't do squat, nor does importing it >before the __init__ of the class, or within it . . . any ideas? > >Thanks in advance, >Orri > > >Email: dragonfirebane@aol.com >AIM: singingxduck >Programming Python for the fun of it. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From marilyn at deliberate.com Wed Nov 3 20:30:37 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Nov 3 20:30:40 2004 Subject: [Tutor] mysql formatting In-Reply-To: Message-ID: Darn me. I still don't have it right. As a reminder, here's my method: def execute_mysql(self, this, *args): if log.level & log.sql: log.it('About to execute:' + this + '<-->' + repr(args)) try: self.cursor.execute(this, args) except _mysql_exceptions.Warning, msg: log.it('Mysql Warning: ' + str(msg)) except _mysql_exceptions.OperationalError, msg: print "Are you using the right data base? Try changing /b/local/doorman/configure.py TESTING = 0" raise Yes, Danny is right that the database name must be hard-coded: s = 'update doorman set status = "%s" where in_id = %s and out_address like "%%%s%%"' my_connection.execute_mysql(s, new_status, inside_id, out_address) Doing that eliminates the traceback. But the update doesn't happen and in mysql's log I see: update doorman set status = "'MOVED'" where in_id = '60' and out_address like "%'courier-imap-admin@lists.sourceforge.net'%"; So I still have too many 's. Here I try Lloyd's idea and take all the quotes out of my format: s = 'update doorman set status = %s where in_id = %d and out_address like %%%s%%' my_connection.execute_mysql(s, new_status, int(inside_id), out_address) inside_id is "60", as a string. I figured I have better luck passing int(inside_id). But: File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue TypeError: int argument required That sure stumps me. So I try %s: s = 'update doorman set status = %s where in_id = %s and out_address like %%%s%%' my_connection.execute_mysql(s, new_status, inside_id, out_address) Gets me: _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%'courier-imap-admin@lists.sourceforge.net'%' at line 1") Maybe it has something to do with unpacking the tuple? So I give a fancy version a try, back to fiddling with escapes: def execute_mysql(self, this, *args): caller = 'self.cursor.execute(\"%s\"' % this for each in args: caller += ", " + each caller += ')' print caller try: exec(caller) # self.cursor.execute(this, args) except _mysql_exceptions.Warning, msg: log.it('Mysql Warning: ' + str(msg)) except _mysql_exceptions.OperationalError, msg: print "Are you using the right data base? Try changing /b/local/doorman/configure.py TESTING = 0" raise and I go back to this call, afterall, it has "%s", %s, and "%%%s%%", trying everything: s = 'update doorman set status = "%s" where in_id = %s and out_address like "%%%s%%"' my_connection.execute_mysql(s, new_status, inside_id, out_address) self.cursor.execute("update doorman set status = "%s" where in_id = %s and out_address like "%%%s%%"", MOVED, 60, courier-imap-admin@lists.sourceforge.net) ^ SyntaxError: invalid syntax I don't know. This is very hard! Maybe I should use MySQLdb.escape_string on my addresses and be happy with that? Maybe this is why it's not documented, maybe it's not so robust. Thank you for your help and thought. Marilyn -- From rick at niof.net Wed Nov 3 21:16:10 2004 From: rick at niof.net (Rick Pasotto) Date: Wed Nov 3 21:16:15 2004 Subject: [Tutor] mysql formatting In-Reply-To: References: Message-ID: <20041103201610.GZ31976@niof.net> On Wed, Nov 03, 2004 at 11:30:37AM -0800, Marilyn Davis wrote: > > Yes, Danny is right that the database name must be hard-coded: > > s = 'update doorman set status = "%s" where in_id = %s and out_address like "%%%s%%"' > my_connection.execute_mysql(s, new_status, inside_id, out_address) s = """ update %s set status = "%s" where in_id = %s and out_address like %s """ % ('doorman','%s','%s','%%%s%%') > s = 'update doorman set status = "%s" where in_id = %s and out_address like "%%%s%%"' > my_connection.execute_mysql(s, new_status, inside_id, out_address) > > > self.cursor.execute("update doorman set status = "%s" where in_id = %s and > out_address like "%%%s%%"", MOVED, 60, courier-imap-admin@lists.sourceforge.net) > ^ > SyntaxError: invalid syntax Of course. .execute(operation[,parameters]) Prepare and execute a database operation (query or command). Parameters may be provided as sequence or mapping and will be bound to variables in the operation. Variables are specified in a database-specific notation (see the module's paramstyle attribute for details). [5] 'parameters' must be a *sequence* (list or tuple) or *mapping* (dictionary). You used three individual items. This should work: my_connection.execute_mysql(s, (new_status, inside_id, out_address)) Note the extra parentheses to make a tuple. -- "Yes, there is Nirvanah; it is in leading your sheep to a green pasture, and in putting your child to sleep, and in writing the last line of your poem." -- Kahlil Gibran (1883-1931) [Sand and Foam] Rick Pasotto rick@niof.net http://www.niof.net From pythonTutor at venix.com Wed Nov 3 21:41:52 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Wed Nov 3 21:42:39 2004 Subject: [Tutor] mysql formatting In-Reply-To: References: Message-ID: <1099514511.19711.45.camel@laptop.venix.com> I checked our programming. We add the % for like to the parameter! s = 'update doorman set status = %s where in_id = %s and out_address like %s' cursor.execute(s, (new_status, inside_id, '%'+out_address+'%')) On Wed, 2004-11-03 at 14:30, Marilyn Davis wrote: > Darn me. > > I still don't have it right. > > As a reminder, here's my method: > > def execute_mysql(self, this, *args): > if log.level & log.sql: > log.it('About to execute:' + this + '<-->' + repr(args)) > try: > self.cursor.execute(this, args) > except _mysql_exceptions.Warning, msg: > log.it('Mysql Warning: ' + str(msg)) > except _mysql_exceptions.OperationalError, msg: > print "Are you using the right data base? Try changing > /b/local/doorman/configure.py TESTING = 0" > raise > > > Yes, Danny is right that the database name must be hard-coded: > > > s = 'update doorman set status = "%s" where in_id = %s and out_address like > "%%%s%%"' > my_connection.execute_mysql(s, new_status, inside_id, out_address) > > > Doing that eliminates the traceback. But the update doesn't happen > and in mysql's log I see: > > update doorman set status = "'MOVED'" where in_id = '60' and > out_address like "%'courier-imap-admin@lists.sourceforge.net'%"; > > So I still have too many 's. > > Here I try Lloyd's idea and take all the quotes out of my format: > > s = 'update doorman set status = %s where in_id = %d and out_address like > %%%s%%' > my_connection.execute_mysql(s, new_status, int(inside_id), out_address) > > > inside_id is "60", as a string. I figured I have better luck passing > int(inside_id). But: > > File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line 33, in > defaulterrorhandler > raise errorclass, errorvalue > TypeError: int argument required > > That sure stumps me. > > So I try %s: > > s = 'update doorman set status = %s where in_id = %s and out_address like > %%%s%%' > my_connection.execute_mysql(s, new_status, inside_id, out_address) > > Gets me: > > _mysql_exceptions.ProgrammingError: (1064, "You have an error in your > SQL syntax; check the manual that corresponds to your MySQL server > version for the right syntax to use near > '%'courier-imap-admin@lists.sourceforge.net'%' at line 1") > > Maybe it has something to do with unpacking the tuple? So I give a > fancy version a try, back to fiddling with escapes: > > def execute_mysql(self, this, *args): > caller = 'self.cursor.execute(\"%s\"' % this > for each in args: > caller += ", " + each > caller += ')' > print caller > try: > exec(caller) > # self.cursor.execute(this, args) > except _mysql_exceptions.Warning, msg: > log.it('Mysql Warning: ' + str(msg)) > except _mysql_exceptions.OperationalError, msg: > print "Are you using the right data base? Try changing > /b/local/doorman/configure.py TESTING = 0" > raise > > and I go back to this call, afterall, it has "%s", %s, and "%%%s%%", > trying everything: > > s = 'update doorman set status = "%s" where in_id = %s and out_address like > "%%%s%%"' > my_connection.execute_mysql(s, new_status, inside_id, out_address) > > > self.cursor.execute("update doorman set status = "%s" where in_id = %s and > out_address like "%%%s%%"", MOVED, 60, courier-imap-admin@lists.sourceforge.net) > ^ > SyntaxError: invalid syntax > > > I don't know. This is very hard! > > Maybe I should use MySQLdb.escape_string on my addresses and be happy > with that? Maybe this is why it's not documented, maybe it's not so > robust. > > Thank you for your help and thought. > > Marilyn > -- Lloyd Kvam Venix Corp From shitizb at yahoo.com Wed Nov 3 21:58:47 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Nov 3 21:58:51 2004 Subject: [Tutor] Problem modify windows registry (desktop wallpaper) In-Reply-To: <5.0.2.1.2.20041103121943.02315c18@qmail.dideas.com> Message-ID: <20041103205847.74540.qmail@web53807.mail.yahoo.com> Hi, Sorry for jumping to conclusions in my earlier reply. Contrary to my earlier belief a non-administrative user can change the registry values under HKEY_CURRENT_USER. The problem was in code itself. While using the SetValueEx function the key identified by the key parameter must have been opened with KEY_SET_VALUE access. The default is KEY_READ access. Hence this should ( and in fact does) work: >import _winreg as wreg > >key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, KEY_SET_VALUE ) >v = wreg.QueryValueEx(key,"WallPaper") >print "Key value is : ", v >wreg.SetValueEx(key, "WallPaper", 0, wreg.REG_SZ, v[0]) Shitiz Chris Barnhart wrote: Shitiz, Thank you for your help, I was a little rushed in my first post and left out some important details. Although the application is to change the wallpaper, the lesson I want to learn is the modification of the registry. Because the key-value I'm trying to change is in HKEY_CURRENT_USER shouldn't a non-privileged user be able to change it? I also happen to be running as ADMINISTRATOR which I should mentioned. Chris PS : Simply changing the wallpaper file won't actually change the wallpaper immediately. Possibly if I ran a "system parameters changed" function afterward, it would then update the desktop. I even have to do this after changing the registry value. At 04:39 PM 11/2/2004, Shitiz Bansal wrote: >Hi, > >you could do either of the following: > >1. replace the wallpaper file itself without touching the registry , by >using commands from os module. >2. What i gather is that as a non-adminstrative user you dont have >permission to change the registry. So u could use the LogonUser and >ImpersonateLoggedonUser functions from win32security module to impersonate >as the administrator before editing the registry. > >tell me if it helps. > >shitiz > > >Chris Barnhart wrote: >Hi, > >I'm attempting to write a python (2.3.3) program that will update the >wallpaper under Windows 2000. I found an example delphi program : >(http://www.latiumsoftware.com/en/delphi/00020.php) which suggest that I >need to change a registry variable, and then execute a system parameters >changed statement. > >The following program attempts to change the desktop wallpaper by changing >a key in the HKEY_CURRENT_USER. This fails due to access denied? I'm >using methods from _winreg. > >What weird, is that by using OpenKey I've been able to create new registry >sub folders, and then using SetValue, change the value of the "default" key. > >I've also looked modifying the registry from WMI, and also looked at using >windll - but obsolete. > >Any ideas? > >Thank you, >Chris > >-------------- > > > >import _winreg as wreg > >key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Control Panel\\Desktop") >v = wreg.QueryValueEx(key,"WallPaper") >print "Key value is : ", v >wreg.SetValueEx(key, "WallPaper", 0, wreg.REG_SZ, v[0]) > >C:\src\python>python r3.py >Key value is : (u'C:\\WINNT\\Mozilla Wallpaper.bmp', 1) >Traceback (most recent call last): >File "r3.py", line 6, in ? >wreg.SetValueEx(key, "WallPaper", 0, wreg.REG_SZ, v[0]) >WindowsError: [Errno 5] Access is denied _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com/a -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041103/96a78c9c/attachment.htm From justinstraube at charter.net Thu Nov 4 00:16:05 2004 From: justinstraube at charter.net (justin) Date: Wed Nov 3 22:17:33 2004 Subject: [Tutor] os.rename error problem Message-ID: <9roio0da1gv6csk57eiavj6ltcig03sl77@4ax.com> >> OSError: [Errno 13] Permission denied >> >>> >> >> Im using Win2k and have checked to see if the file is read-only. Its not and I >> have been able to edit the MP3 ID3 tag information without problem. > >It's not in use, is it? Still open by a tag editor or being played back? Thanks for the replies. And also the other pointers for my code. The Tutor list is a invaluable resource. Regards, Justin From marilyn at deliberate.com Wed Nov 3 22:23:05 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Nov 3 22:23:13 2004 Subject: [Tutor] mysql formatting In-Reply-To: <20041103201610.GZ31976@niof.net> Message-ID: On Wed, 3 Nov 2004, Rick Pasotto wrote: > update %s set status = "%s" where in_id = %s and out_address like %s > """ % ('doorman','%s','%s','%%%s%%') I see. But I'm happy hardcoding the name. That was a silly thing anyway. > > .execute(operation[,parameters]) > > Prepare and execute a database operation (query or > command). Parameters may be provided as sequence or > mapping and will be bound to variables in the operation. > Variables are specified in a database-specific notation > (see the module's paramstyle attribute for details). [5] Rick! Where did you get this from? help(MySQLdb) doesn't tell me this. What's [5]? What's "paramstyle attribute"? I'm missing something big about documentation, and that's for sure! Ok. Not unpacking the tuple means that my method is now: def execute_mysql(self, this, args): try: self.cursor.execute(this, args) And this call works! s = """update doorman set status = %s where in_id = %s and out_address like %s""" my_connection.execute_mysql(s, (new_status, inside_id, '%'+ out_address+'%')) It produces: update doorman set status = 'MOVED' where in_id = '60' and out_address like '%courier-imap-admin@lists.sourceforge.net%'; I wouldn't have guessed that in_id = '60' would work since it is an integer, but it does. It all works! Whew! "Yes, there is Nirvanah; it is in leading your sheep to a green pasture, and in putting your child to sleep, and in writing the last line of your poem." -- Kahlil Gibran (1883-1931) [Sand and Foam] I guess he didn't know about getting a line of code to work. :^) Thank you soooo much. I just love it when things make sense. Marilyn From dyoo at hkn.eecs.berkeley.edu Wed Nov 3 22:34:46 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 3 22:34:52 2004 Subject: [Tutor] Input from CGI ? In-Reply-To: Message-ID: On Wed, 3 Nov 2004, Mark Kels wrote: > How can I get input (string) from the user in CGI ? Hi Mark, There are examples of doing this in the Standard Library documentation. Here's a link to the documentation on the 'cgi' module: http://www.python.org/doc/lib/module-cgi.html The idea is to use the cgi module to grab form values. There are several methods we can use, but the easiest one is probably FieldStorage.getfirst(). Here's a quick example CGI program that takes in a number and prints out its square: ### #!/usr/bin/python """A small program to demonstrate simple CGIish stuff.""" import cgi import cgitb; cgitb.enable() def main(): form = cgi.FieldStorage() if form.getfirst("number"): doComputationAndPrintResult(form) else: printStartPage() def printStartPage(): printHtmlHeader() print """ """ def doComputationAndPrintResult(form): computedResult = square(int(form.getfirst("number"))) printHtmlHeader() print """ %s """ % computedResult def printHtmlHeader(): """Prints out the standard HTML header line.""" print "Content-type: text/html\n\n" def square(x): """Returns the square of x.""" return x * x if __name__ == '__main__': main() ### You might also like to browse through the Web Programming topic guide here: http://www.python.org/topics/web/ Good luck to you! From rick at niof.net Wed Nov 3 22:49:21 2004 From: rick at niof.net (Rick Pasotto) Date: Wed Nov 3 22:49:28 2004 Subject: [Tutor] mysql formatting In-Reply-To: References: <20041103201610.GZ31976@niof.net> Message-ID: <20041103214921.GA31976@niof.net> On Wed, Nov 03, 2004 at 01:23:05PM -0800, Marilyn Davis wrote: > On Wed, 3 Nov 2004, Rick Pasotto wrote: > > > .execute(operation[,parameters]) > > > > Prepare and execute a database operation (query or > > command). Parameters may be provided as sequence or > > mapping and will be bound to variables in the operation. > > Variables are specified in a database-specific notation > > (see the module's paramstyle attribute for details). [5] > > Rick! Where did you get this from? help(MySQLdb) doesn't tell me > this. What's [5]? What's "paramstyle attribute"? I'm missing > something big about documentation, and that's for sure! It's not easy to find. Goto: Select: Topic Guides (under 'Documentation Links') Select: Databases Select: DB-API spec v2.0 You should probably have documentation (not python's internal help) for the MySQLdb module somewhere. On my debian linux system it's in: /usr/share/doc/python-mysqldb/html Those docs also contain a pointer to the DB-API spec. -- There are two kinds of fool. One says, "This is old, and therefore good." And one says, "This is new, and therefore better." -- John Brunner, science fiction writer (1934-1995) Rick Pasotto rick@niof.net http://www.niof.net From kbond at free.fr Thu Nov 4 04:50:26 2004 From: kbond at free.fr (kbond) Date: Wed Nov 3 22:50:32 2004 Subject: [Tutor] formClient or how to login to a web site? In-Reply-To: References: Message-ID: <4189A702.8070309@free.fr> Hello all of you, I am starting a project that has a simple objectif logon into a web site (https://interactif.creditlyonnais.fr/), access a protected area and then save a web page on my computer. The idea is to be able to do this daily and then process the files collection to do some statistic. After googling, I found out that there is a python module called: clientForm (http://wwwsearch.sourceforge.net/ClientForm/) here it is what the author wrote about it:"ClientForm is a Python module for handling HTML forms on the client side, useful for parsing HTML forms, filling them in and returning the completed forms to the server. " The problem is that I am not able to validate my form and send it back to the server. My goal is then to be able to get the following web page. you will find below my code : +++++++++++++++++++++++++++ import urllib2 from urllib2 import urlopen from ClientForm import ParseResponse forms = ParseResponse(urlopen("https://interactif.creditlyonnais.fr")) form = forms[0] print form form["agenceId"]="XXXXX" form["compteId"]="XXXXXX" form["CodeId"]="XXXXX" print form request= form.click() ##My guess is that I am missing something there print request response= urlopen(request) print response.geturl() ##Unfortunatly I am getting there the original URL. print response.read() response.close() +++++++++++++++++++++++++++ Any help with clientForm or another solution would be more than welcome. Thank you for your help From marilyn at deliberate.com Wed Nov 3 23:47:11 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Nov 3 23:47:14 2004 Subject: [Tutor] mysql formatting In-Reply-To: <20041103214921.GA31976@niof.net> Message-ID: Thank you Rick, Danny and Lloyd. I am now equipped to start over! :^) Marilyn From keridee at jayco.net Wed Nov 3 23:41:07 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Nov 4 03:28:17 2004 Subject: [Tutor] Splitting at a capital letter in a string References: <417FB05E.1@cso.atmel.com> <6.1.0.6.0.20041027104356.02abd118@mail4.skillsoft.com> <41830047.10005@crackrabbit.com><20041030031435.GA91513@alexis.mi.celestial.com> <418309CE.90003@crackrabbit.com> Message-ID: <000001c4c215$d7445d20$1e5428cf@JSLAPTOP> >Yep. re looks like the only way. I was just wondering if I was missing >something in String. I'm sorry, but I prefer to disagree. Consider this code sample. [start of code] a = "HiImAStringWithCaps" seperator = " " a = list(a) x = 0 while x < len(a): if a[x] == a[x].upper(): # This is number 4 a.insert(x,seperator) x = x+1 x = x+1 a = "".join(a).lstrip(seperator) print a [end of code] The stuff goin' down here is 1) We define a 2) We define the seperator - You said in the email it would be a space 3) We convert the string a into a list so we can mess with each item in there 4) Next, we run through the list and search for uppercase letters. Fancy way of doing so, don't you think? 5) Then, we insert the seperator at that index 6) We increment x an extra 1 because we added an index (the seperator) 7) After all that's done, we join the list together into and string and strip the seperator off of the beginning How about that! I did it without the re module. HTH, Jacob Schmidt From klappnase at freenet.de Thu Nov 4 12:14:57 2004 From: klappnase at freenet.de (Michael Lange) Date: Thu Nov 4 12:14:44 2004 Subject: [Tutor] gettext mystery Message-ID: <20041104121457.456b11b4.klappnase@freenet.de> Hi, I've been playing a ittle with the gettext module, trying to add a german translation to Moleskine; from reading the docs I thought all I would have to do was creating a mo file and then adding the magic lines import gettext gettext.install('moleskine', '/usr/share/locale') to the main program file. I found that Moleskine's author had already tried to implement gettext support, but has given up for some reason, so I added these lines in the module where he had started (in site-packages/Moleskine/__init__.py); the result: Traceback (most recent call last): File "/usr/bin/moleskine", line 41, in ? import Moleskine File "/usr/lib/python2.2/site-packages/Moleskine/__init__.py", line 29, in ? gettext.install(domain, locale_dir) AttributeError: 'module' object has no attribute 'install' I changed the second line and wrote: import gettext print dir(gettext) and here's what I get: [pingu@localhost pingu]$ moleskine ['Catalog', '_', '__builtins__', '__doc__', '__file__', '__name__', '_aliases', '_cat', '_cats', '_expand_lang', '_intToLsbStr', '_lsbStrToInt', '_msbStrToInt', '_unalias_lang', 'bindtextdomain', 'dgettext', 'env', 'error', 'gettext', 'lang', 'localedir', 'os', 'prefix', 'string', 'test', 'textdomain'] Then I tried putting the gettext import into the main file (/usr/bin/moleskine) instead of __init__.py and the print statement gave me the expected output: [pingu@localhost pingu]$ moleskine ['Catalog', 'ENOENT', 'GNUTranslations', 'NullTranslations', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_current_domain', '_default_localedir', '_expand_lang', '_localedirs', '_translations', 'bindtextdomain', 'dgettext', 'find', 'gettext', 'install', 'os', 'struct', 'sys', 'textdomain', 'translation'] Does anyone have a clue why gettext shows a different behavior depending on where it's imported? I *think* it might have something to do with GNOME (some menu items are already translated although there is no german mo file, can GNOME do so automagically?) but it looks like in fact I've been importing two different modules, which I found quite confusing. Any pointers are appreciated. Thanks Michael From cyresse at gmail.com Thu Nov 4 14:25:38 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Nov 4 14:25:40 2004 Subject: [Tutor] Eek, help! Message-ID: Hi all, I have belatedly come to use dictionaries, and I was having some trouble with how to read/write them from a file, so I looked at Alan Gauld's section on it. I've pretty much copied his code straight through, and, well, I've broken it somehow. In fact, it's hanging Python, and it even hangs the debugger, which is a first, I must admit. The errant code as follows is - h={"Like":"two"} filename = './dat/hshmd5.tbl' store = file(filename,'w') for name, entry in h.items(): store.write(name + '\n') store.write(entry + '\n') store.close() print 'Wrote hash' pause.anyKey() print book={} store2 = file(filename,'r') while store2: name = store2.readline().strip() entry = store2.readline().strip() book[name] = entry store2.close() It writes OK, it gets up to anyKey bit and... stops. Anything jump out at anyone? I am confused. Thanking you in advance, Liam Clarke -- '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 kent_johnson at skillsoft.com Thu Nov 4 18:01:05 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Nov 4 18:01:11 2004 Subject: [Tutor] formClient or how to login to a web site? In-Reply-To: <4189A702.8070309@free.fr> References: <4189A702.8070309@free.fr> Message-ID: <6.1.0.6.0.20041104114425.02b0b788@mail4.skillsoft.com> Looking at the logon page you cite, the Valider button is calling a Javascript function Identification(). In the ClientForm General FAQ I found this question: Embedded script is messing up my web-scraping. What do I do? One suggested option is this: * Simply figure out what the embedded script is doing and emulate it in your Python code: for example, by manually adding cookies to your CookieJar instance, calling methods on HTMLForms, calling urlopen, etc. Viewing source of the web page, that function is not there, but there are a few external Javascript pages referenced. I thought that identmig.js looked promising so I loaded it by browsing to https://interactif.creditlyonnais.fr/js/identmig.js Most of the work of Identification() is done by the function ValidLogin(). This just looks at the form data and sets the submit url based on the data. So I have two suggestions: - Stop using ClientForm. Just figure out from the HTML form and the Javascript what data needs to be posted and do it directly using urllib2.urlopen() with a data argument. - Emulate the Javascript and set the url in the ClientForm before calling form.click() Kent At 10:50 PM 11/3/2004 -0500, kbond wrote: >Hello all of you, > >I am starting a project that has a simple objectif logon into a web site >(https://interactif.creditlyonnais.fr/), access a protected area and then >save a web page on my computer. >The idea is to be able to do this daily and then process the files >collection to do some statistic. > >After googling, I found out that there is a python module called: >clientForm (http://wwwsearch.sourceforge.net/ClientForm/) >here it is what the author wrote about it:"ClientForm is a Python module >for handling HTML forms on the client side, useful for parsing HTML forms, >filling them in and returning the completed forms to the server. " > >The problem is that I am not able to validate my form and send it back to >the server. My goal is then to be able to get the following web page. > >you will find below my code : >+++++++++++++++++++++++++++ >import urllib2 >from urllib2 import urlopen >from ClientForm import ParseResponse >forms = ParseResponse(urlopen("https://interactif.creditlyonnais.fr")) >form = forms[0] >print form > >form["agenceId"]="XXXXX" >form["compteId"]="XXXXXX" >form["CodeId"]="XXXXX" > >print form >request= form.click() ##My guess is that I am missing something there >print request >response= urlopen(request) >print response.geturl() ##Unfortunatly I am getting there the original URL. >print response.read() >response.close() >+++++++++++++++++++++++++++ > >Any help with clientForm or another solution would be more than welcome. > >Thank you for your help >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Thu Nov 4 18:04:15 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Nov 4 18:04:23 2004 Subject: [Tutor] gettext mystery In-Reply-To: <20041104121457.456b11b4.klappnase@freenet.de> References: <20041104121457.456b11b4.klappnase@freenet.de> Message-ID: <6.1.0.6.0.20041104120317.02b13530@mail4.skillsoft.com> If you print gettext.__file__ it will show you where it was loaded from. If you are loading two different modules that will show them you you. Kent At 12:14 PM 11/4/2004 +0100, Michael Lange wrote: >Hi, > >I've been playing a ittle with the gettext module, trying to add a german >translation to >Moleskine; from reading the docs I thought all I would have to do was >creating a mo file >and then adding the magic lines > >import gettext >gettext.install('moleskine', '/usr/share/locale') > >to the main program file. > >I found that Moleskine's author had already tried to implement gettext >support, but has given >up for some reason, so I added these lines in the module where he had started >(in site-packages/Moleskine/__init__.py); the result: > >Traceback (most recent call last): > File "/usr/bin/moleskine", line 41, in ? > import Moleskine > File "/usr/lib/python2.2/site-packages/Moleskine/__init__.py", line 29, > in ? > gettext.install(domain, locale_dir) >AttributeError: 'module' object has no attribute 'install' > >I changed the second line and wrote: > >import gettext >print dir(gettext) > >and here's what I get: > >[pingu@localhost pingu]$ moleskine >['Catalog', '_', '__builtins__', '__doc__', '__file__', '__name__', >'_aliases', '_cat', '_cats', '_expand_lang', '_intToLsbStr', >'_lsbStrToInt', '_msbStrToInt', '_unalias_lang', 'bindtextdomain', >'dgettext', 'env', 'error', 'gettext', 'lang', 'localedir', 'os', >'prefix', 'string', 'test', 'textdomain'] > >Then I tried putting the gettext import into the main file >(/usr/bin/moleskine) instead of __init__.py and the print >statement gave me the expected output: > >[pingu@localhost pingu]$ moleskine >['Catalog', 'ENOENT', 'GNUTranslations', 'NullTranslations', '__all__', >'__builtins__', '__doc__', '__file__', '__name__', '_current_domain', >'_default_localedir', '_expand_lang', '_localedirs', '_translations', >'bindtextdomain', 'dgettext', 'find', 'gettext', 'install', 'os', >'struct', 'sys', 'textdomain', 'translation'] > >Does anyone have a clue why gettext shows a different behavior depending >on where it's imported? >I *think* it might have something to do with GNOME (some menu items are >already translated although there >is no german mo file, can GNOME do so automagically?) but it looks like in >fact I've been importing >two different modules, which I found quite confusing. > >Any pointers are appreciated. > >Thanks > >Michael > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Thu Nov 4 18:10:27 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Nov 4 18:10:33 2004 Subject: [Tutor] Eek, help! In-Reply-To: References: Message-ID: <6.1.0.6.0.20041104120624.028ae1a8@mail4.skillsoft.com> Um...what does pause.anyKey() do? Is it possibly waiting for you to press a key? Kent At 02:25 AM 11/5/2004 +1300, Liam Clarke wrote: >Hi all, > >I have belatedly come to use dictionaries, and I was having some >trouble with how to read/write them from a file, so I looked at Alan >Gauld's section on it. I've pretty much copied his code straight >through, and, well, I've broken it somehow. In fact, it's hanging >Python, and it even hangs the debugger, which is a first, I must >admit. > >The errant code as follows is - > >h={"Like":"two"} >filename = './dat/hshmd5.tbl' > >store = file(filename,'w') > >for name, entry in h.items(): > store.write(name + '\n') > store.write(entry + '\n') > >store.close() > >print 'Wrote hash' >pause.anyKey() >print > >book={} > >store2 = file(filename,'r') > >while store2: > name = store2.readline().strip() > entry = store2.readline().strip() > book[name] = entry > >store2.close() > >It writes OK, it gets up to anyKey bit and... stops. Anything jump out >at anyone? I am confused. > >Thanking you in advance, > >Liam Clarke >-- >'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. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From ps_python at yahoo.com Thu Nov 4 18:40:11 2004 From: ps_python at yahoo.com (kumar s) Date: Thu Nov 4 18:40:15 2004 Subject: [Tutor] Object Orientation : Class XXX : def __init__ Message-ID: <20041104174012.23274.qmail@web53707.mail.yahoo.com> Dear group, I have a basic question and I am sure it might have been churned a lot. However, the concept is initially such a rock hard that is not easily palatable. Although I have been trying to get a grasp, when it comes to coding, I loose the connection why do I have to define class: and then always say: def __init__ function. Could any one help me please defining __init__ function in terms of a python program. Please also point me to some good tutorial (preferably example based case where it shows the differences between coding some script as an OOP and the other one as a simple script with out OOP functionality. Thank you, Suraj. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bill.mill at gmail.com Thu Nov 4 18:57:34 2004 From: bill.mill at gmail.com (Bill Mill) Date: Thu Nov 4 18:57:43 2004 Subject: [Tutor] Object Orientation : Class XXX : def __init__ In-Reply-To: <20041104174012.23274.qmail@web53707.mail.yahoo.com> References: <20041104174012.23274.qmail@web53707.mail.yahoo.com> Message-ID: <797fe3d4041104095768b972fc@mail.gmail.com> Kumar, I'm not really sure if I understand you, and I haven't seen any tutorials like the one you're asking for - the only school for that is experience. Anyway, about __init__ , you never have to define it as a function. Example: In [2]: class test: ...: def foo(self): print 'yo' ...: In [3]: t = test() In [4]: t.foo() yo This works as expected. __init__ is a convenience function which allows you to initialize the variables in your class. It is automatically called on object instantiation by the Python interpreter. Does that make sense? Peace Bill Mill bill.mill@gmail.com On Thu, 4 Nov 2004 09:40:11 -0800 (PST), kumar s wrote: > Dear group, > I have a basic question and I am sure it might have > been churned a lot. However, the concept is initially > such a rock hard that is not easily palatable. > Although I have been trying to get a grasp, when it > comes to coding, I loose the connection why do I have > to define class: and then always say: > > def __init__ function. > > Could any one help me please defining __init__ > function in terms of a python program. > > Please also point me to some good tutorial (preferably > example based case where it shows the differences > between coding some script as an OOP and the other one > as a simple script with out OOP functionality. > > Thank you, > > Suraj. > > __________________________________________________ > 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 > From maxnoel_fr at yahoo.fr Thu Nov 4 19:02:45 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Nov 4 19:03:16 2004 Subject: [Tutor] Object Orientation : Class XXX : def __init__ In-Reply-To: <20041104174012.23274.qmail@web53707.mail.yahoo.com> References: <20041104174012.23274.qmail@web53707.mail.yahoo.com> Message-ID: On Nov 4, 2004, at 17:40, kumar s wrote: > def __init__ function. > > Could any one help me please defining __init__ > function in terms of a python program. The __init__ method of a class is called every time you instantiate the class, i.e. each time you use the class to create a new object. Attached to this message is a fairly simple class I made: a Dice class, used to roll dice (duh). It's a little bit more complex than what a "basic" Dice class would be because I'm a roleplayer and thus need dice that are not necessarily six-sided and can be open-ended (i.e. if you roll the max result, reroll the dice and add); however it shouldn't be hard to understand. The __init__ function, here, is called each time you use the class to create a new die. It is used to set the die's characteristics: number of sides, and open-endedness. In the following piece of code: #!/usr/bin/env python import Dice sixSider = Dice.Dice() twentySider = Dice.Dice(numSides=20, openEnded=False) closeEndedSixSider = Dice.Dice(numSides=6, openEnded=False) Three dice are created. The parameters used in creating the class are passed to the __init__ method (in my example, parameters are not needed as defaults are provided). Therefore, sixSider is a standard, 6-sided, open-ended die (yeah, being a Shadowrun player, I use open-ended as a default). twentySider is a close-ended D20 (for D&D players). closeEndedSixSider is a close-ended D6. Now that they have been created, you can do whatever you want with them: roll them (for example, sixSider.roll() ), alter them (if you decide that after all you want your D20 to be open-ended, use twentySider.setOpenEnded(True) ), etc. You may also want to have a look at the OOP part of Guido's tutorial on www.python.org ; and of course you're welcome to keep asking questions here. HTH, -- 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?" -------------- next part -------------- Skipped content of type multipart/appledouble From mark.kels at gmail.com Thu Nov 4 19:04:01 2004 From: mark.kels at gmail.com (Mark Kels) Date: Thu Nov 4 19:04:03 2004 Subject: [Tutor] Input from CGI ? In-Reply-To: References: Message-ID: On Wed, 3 Nov 2004 13:34:46 -0800 (PST), Danny Yoo wrote: > > > On Wed, 3 Nov 2004, Mark Kels wrote: > > > How can I get input (string) from the user in CGI ? > > > Hi Mark, > > There are examples of doing this in the Standard Library documentation. > Here's a link to the documentation on the 'cgi' module: > > http://www.python.org/doc/lib/module-cgi.html > > The idea is to use the cgi module to grab form values. There are several > methods we can use, but the easiest one is probably > FieldStorage.getfirst(). > > Here's a quick example CGI program that takes in a number and prints out > its square: > > ### > #!/usr/bin/python > > """A small program to demonstrate simple CGIish stuff.""" > > import cgi > import cgitb; cgitb.enable() > > def main(): > form = cgi.FieldStorage() > if form.getfirst("number"): > doComputationAndPrintResult(form) > else: > printStartPage() > > def printStartPage(): > printHtmlHeader() > print """ > >
> > """ > > def doComputationAndPrintResult(form): > computedResult = square(int(form.getfirst("number"))) > > printHtmlHeader() > print """ > > %s > > """ % computedResult > > def printHtmlHeader(): > """Prints out the standard HTML header line.""" > print "Content-type: text/html\n\n" > > def square(x): > """Returns the square of x.""" > return x * x > > if __name__ == '__main__': > main() > ### > > You might also like to browse through the Web Programming topic guide > here: > > http://www.python.org/topics/web/ > > Good luck to you! > > Thank you!! It was very helpful. But how do I get more than one line ? And how can I make radio buttons and get the input wuth them ? And what this thing does ( I see it in almost every code example) : if __name__ == '__main__': main() ? Thanks!! From hscl at gotadsl.co.uk Thu Nov 4 18:08:11 2004 From: hscl at gotadsl.co.uk (Gavin Hunt) Date: Thu Nov 4 19:08:07 2004 Subject: [Tutor] Help on image creation and display from ASCII files Message-ID: <01C4C290.DDE38090.hscl@gotadsl.co.uk> Hi, I'm a newbie to python and wxpython, recently converting from the excellent but very costly IDL environment. I wish to rewrite my IDL program in which separate but consecutive ASCII output files from my line-scanning camera - each in the form of a CSV file of 256 * 600 floating point values - are read into a 3D (hyperspectral) image. The X and Z dimensions of the image remain the same, i.e. 256 diodes and 600 channels, but the Y dimension obviously increases as the number of line scans increase. This image is displayed to screen and refreshed each time a new scan line is added to the output image. Only three of the 600 channels available in the hyperspectral image will be displayed in RGB format. In addition, there should be scope to interrogate the image interactively with a cursor and display a spectral plot (600 channels) of any image pixel. i) Does anybody have any scripts that can read ASCII files and create an hyperspectral image? ii) Ditto scripts to display and refresh the image in real time? iii) Interact with the image and plot an image spectrum using a cursor to get the image X, Y co-ordinate? If not how do I convert between ASCII and image format - easy to do in IDL? Display the image on a line by line basis? Thnx GAH From bill.mill at gmail.com Thu Nov 4 19:16:59 2004 From: bill.mill at gmail.com (Bill Mill) Date: Thu Nov 4 19:17:01 2004 Subject: [Tutor] Help on image creation and display from ASCII files In-Reply-To: <01C4C290.DDE38090.hscl@gotadsl.co.uk> References: <01C4C290.DDE38090.hscl@gotadsl.co.uk> Message-ID: <797fe3d404110410166b80e8b5@mail.gmail.com> Gavin, GIYF. http://spectralpython.sourceforge.net/ . Peace Bill Mill bill.mill at gmail.com On Thu, 4 Nov 2004 17:08:11 -0000, Gavin Hunt wrote: > Hi, > > I'm a newbie to python and wxpython, recently converting from the excellent > but very costly IDL environment. > > I wish to rewrite my IDL program in which separate but consecutive ASCII > output files from my line-scanning camera - each in the form of a CSV file > of 256 * 600 floating point values - are read into a 3D (hyperspectral) > image. The X and Z dimensions of the image remain the same, i.e. 256 > diodes and 600 channels, but the Y dimension obviously increases as the > number of line scans increase. > > This image is displayed to screen and refreshed each time a new scan line > is added to the output image. Only three of the 600 channels available in > the hyperspectral image will be displayed in RGB format. In addition, > there should be scope to interrogate the image interactively with a cursor > and display a spectral plot (600 channels) of any image pixel. > > i) Does anybody have any scripts that can read ASCII files and create an > hyperspectral image? > ii) Ditto scripts to display and refresh the image in real time? > iii) Interact with the image and plot an image spectrum using a cursor to > get the image X, Y co-ordinate? > > If not how do I convert between ASCII and image format - easy to do in IDL? > Display the image on a line by line basis? > > Thnx > > GAH > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Thu Nov 4 20:24:06 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 4 20:24:11 2004 Subject: [Tutor] Eek, help! In-Reply-To: Message-ID: > I have belatedly come to use dictionaries, and I was having some > trouble with how to read/write them from a file, so I looked at Alan > Gauld's section on it. I've pretty much copied his code straight > through, and, well, I've broken it somehow. In fact, it's hanging > Python, and it even hangs the debugger, which is a first, I must > admit. Hi Liam, Whenever I hear something about a "hang", I almost immediately look at while loop conditions. *grin* Let's take a look: > store2 = file(filename,'r') > > while store2: > name = store2.readline().strip() > entry = store2.readline().strip() > book[name] = entry The while loop here needs to be fixed: store2 is a file, and files are true values, no matter what. This is an infinite loop. What you wanted to say, I think, was to keep the loop running as long as there's still content in store2. When we read the end of a file, we'll get the empty string from a readline. So one way to correct the loop may be: ### while True: name, entry = store2.readline(), store2.readline() if not name or not entry: break name, entry = name.strip(), entry.strip() book[name] = entry ### This is a little more verbose, and might look weird at first, with the 'while True' thing. The input is not exactly single-line oriented --- you're reading pairs of lines at a time --- so it complicates matters slightly. Hmmm... We can make the code a little nicer by pairing up adjacent lines. Here's a small utility function that may help: ### def groupAdjacentElements(someSequence, n = 2): """A little helper utility to group up adjacent elements.""" nextGroup = [] for element in someSequence: nextGroup.append(element) if len(nextGroup) == n: yield tuple(nextGroup) nextGroup = [] ### This bit of code will pair up adjacent elements, like this: ### >>> for a, b in groupAdjacentElements(range(20)): ... print a, b, a * b ... 0 1 0 2 3 6 4 5 20 6 7 42 8 9 72 10 11 110 12 13 156 14 15 210 16 17 272 18 19 342 ### With this helper, now the code that reads store2 can be written as a nice 'for' loop instead of the 'while' loop: ### store2 = file(filename,'r') for (name, entry) in groupAdjacentElements(store2): name = name.strip() entry = entry.strip() book[name] = entry store2.close() ### I hope this helps! From nvettese at pdistributors.com Thu Nov 4 20:38:51 2004 From: nvettese at pdistributors.com (Nicholas Vettese) Date: Thu Nov 4 20:42:40 2004 Subject: [Tutor] SPE Editor In-Reply-To: <20041101014505.92124.qmail@web54301.mail.yahoo.com> References: <20041101014505.92124.qmail@web54301.mail.yahoo.com> Message-ID: <418A854B.2030402@pdistributors.com> I am trying to use the SPE Python Editor on a Windows box, and I am having trouble. Has anyone been able to use it, or know if there is someothing special that needs to be done? Thanks, Nick From bill.mill at gmail.com Thu Nov 4 21:54:47 2004 From: bill.mill at gmail.com (Bill Mill) Date: Thu Nov 4 21:54:54 2004 Subject: [Tutor] SPE Editor In-Reply-To: <418A854B.2030402@pdistributors.com> References: <20041101014505.92124.qmail@web54301.mail.yahoo.com> <418A854B.2030402@pdistributors.com> Message-ID: <797fe3d40411041254308627e7@mail.gmail.com> Nick, I just downloaded the most recent version, installed it, ran "python SPE.py" in the SPE directory (c:/python23/Lib/site-packages/_spe on my system), and it seems to work fine. What's happening on yours? Peace Bill Mill bill.mill at gmail.com On Thu, 04 Nov 2004 14:38:51 -0500, Nicholas Vettese wrote: > I am trying to use the SPE Python Editor on a Windows box, and I am > having trouble. Has anyone been able to use it, or know if there is > someothing special that needs to be done? > > Thanks, > Nick > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From nick at javacat.f2s.com Thu Nov 4 21:56:43 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu Nov 4 21:56:46 2004 Subject: [Tutor] SPE Editor In-Reply-To: <418A854B.2030402@pdistributors.com> Message-ID: Well you dont say what your problem is. I just downloaded SPE for windows from http://projects.blender.org/frs/?group_id=30 and ran it. It installed fine but did not create an entry in the start->programs folder. So I ran C:\Python23\Lib\site-packages\_spe\SPE.pyw and it works no probs. This is with python2.3.3 on windowsXP. Cheers Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Nicholas Vettese Sent: 04 November 2004 19:39 To: Python Tutor List Subject: [Tutor] SPE Editor I am trying to use the SPE Python Editor on a Windows box, and I am having trouble. Has anyone been able to use it, or know if there is someothing special that needs to be done? Thanks, Nick _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01/11/2004 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01/11/2004 From nvettese at pdistributors.com Thu Nov 4 21:57:57 2004 From: nvettese at pdistributors.com (Nicholas Vettese) Date: Thu Nov 4 22:02:09 2004 Subject: [Tutor] SPE Editor In-Reply-To: <797fe3d40411041254308627e7@mail.gmail.com> References: <20041101014505.92124.qmail@web54301.mail.yahoo.com> <418A854B.2030402@pdistributors.com> <797fe3d40411041254308627e7@mail.gmail.com> Message-ID: <418A97D5.80406@pdistributors.com> Thanks for the response. The error I receive is: C:\Python23\Lib\site-packages\_spe>python SPE.py The name specified is not recognized as an internal or external command, operable program or batch file. I am running Windows NT4 with SP6a Bill Mill wrote: >Nick, > >I just downloaded the most recent version, installed it, ran "python >SPE.py" in the SPE directory (c:/python23/Lib/site-packages/_spe on my >system), and it seems to work fine. What's happening on yours? > >Peace >Bill Mill >bill.mill at gmail.com > > >On Thu, 04 Nov 2004 14:38:51 -0500, Nicholas Vettese > wrote: > > >>I am trying to use the SPE Python Editor on a Windows box, and I am >>having trouble. Has anyone been able to use it, or know if there is >>someothing special that needs to be done? >> >>Thanks, >>Nick >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > > From carroll at tjc.com Thu Nov 4 22:08:26 2004 From: carroll at tjc.com (Terry Carroll) Date: Thu Nov 4 22:08:30 2004 Subject: [Tutor] SPE Editor In-Reply-To: <418A97D5.80406@pdistributors.com> Message-ID: On Thu, 4 Nov 2004, Nicholas Vettese wrote: > Thanks for the response. The error I receive is: > > C:\Python23\Lib\site-packages\_spe>python SPE.py > The name specified is not recognized as an > internal or external command, operable program or batch file. That error means that "python" is not recognized by Windows. Try echo %PATH% and see if c:\Python23 is showing up in your path list. From bill.mill at gmail.com Thu Nov 4 22:11:43 2004 From: bill.mill at gmail.com (Bill Mill) Date: Thu Nov 4 22:11:47 2004 Subject: [Tutor] SPE Editor In-Reply-To: <418A97D5.80406@pdistributors.com> References: <20041101014505.92124.qmail@web54301.mail.yahoo.com> <418A854B.2030402@pdistributors.com> <797fe3d40411041254308627e7@mail.gmail.com> <418A97D5.80406@pdistributors.com> Message-ID: <797fe3d404110413111ee57254@mail.gmail.com> Nick, Windows doesn't know where python is, so you have two choices: 1) specify it exactly, like c:/Python23/python.exe SPE.py 2) add it to the Path variable, accessed in Control Panel -> System Properties -> Advanced (tab) -> Environment Variables (button) In the bottom pane (system variables) select Path, hit edit, and add your python directory to the end of the list. Note that all entries are separated with semicolons. Or, you could just click the SPE.py file in Windows Explorer, which should work as well. Peace Bill Mill On Thu, 04 Nov 2004 15:57:57 -0500, Nicholas Vettese wrote: > Thanks for the response. The error I receive is: > > C:\Python23\Lib\site-packages\_spe>python SPE.py > The name specified is not recognized as an > internal or external command, operable program or batch file. > > I am running Windows NT4 with SP6a > > > > Bill Mill wrote: > > >Nick, > > > >I just downloaded the most recent version, installed it, ran "python > >SPE.py" in the SPE directory (c:/python23/Lib/site-packages/_spe on my > >system), and it seems to work fine. What's happening on yours? > > > >Peace > >Bill Mill > >bill.mill at gmail.com > > > > > >On Thu, 04 Nov 2004 14:38:51 -0500, Nicholas Vettese > > wrote: > > > > > >>I am trying to use the SPE Python Editor on a Windows box, and I am > >>having trouble. Has anyone been able to use it, or know if there is > >>someothing special that needs to be done? > >> > >>Thanks, > >>Nick > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > >> > >> > > > > > > > > > > From bill.mill at gmail.com Thu Nov 4 22:13:39 2004 From: bill.mill at gmail.com (Bill Mill) Date: Thu Nov 4 22:13:44 2004 Subject: [Tutor] SPE Editor In-Reply-To: <797fe3d404110413111ee57254@mail.gmail.com> References: <20041101014505.92124.qmail@web54301.mail.yahoo.com> <418A854B.2030402@pdistributors.com> <797fe3d40411041254308627e7@mail.gmail.com> <418A97D5.80406@pdistributors.com> <797fe3d404110413111ee57254@mail.gmail.com> Message-ID: <797fe3d404110413137506f582@mail.gmail.com> Also note that you should use backslashes, not frontlsashes. Too many years on unix for me to switch when I use windows. The frontslashes should work, but the proper method is to use backslashes. Peace Bill Mill bill.mill at gmail.com On Thu, 4 Nov 2004 16:11:43 -0500, Bill Mill wrote: > Nick, > > Windows doesn't know where python is, so you have two choices: > > 1) specify it exactly, like c:/Python23/python.exe SPE.py > 2) add it to the Path variable, accessed in Control Panel -> System > Properties -> Advanced (tab) -> Environment Variables (button) > In the bottom pane (system variables) select Path, hit edit, and add > your python directory to the end of the list. Note that all entries > are separated with semicolons. > > Or, you could just click the SPE.py file in Windows Explorer, which > should work as well. > > Peace > Bill Mill > > On Thu, 04 Nov 2004 15:57:57 -0500, Nicholas Vettese > > > wrote: > > Thanks for the response. The error I receive is: > > > > C:\Python23\Lib\site-packages\_spe>python SPE.py > > The name specified is not recognized as an > > internal or external command, operable program or batch file. > > > > I am running Windows NT4 with SP6a > > > > > > > > Bill Mill wrote: > > > > >Nick, > > > > > >I just downloaded the most recent version, installed it, ran "python > > >SPE.py" in the SPE directory (c:/python23/Lib/site-packages/_spe on my > > >system), and it seems to work fine. What's happening on yours? > > > > > >Peace > > >Bill Mill > > >bill.mill at gmail.com > > > > > > > > >On Thu, 04 Nov 2004 14:38:51 -0500, Nicholas Vettese > > > wrote: > > > > > > > > >>I am trying to use the SPE Python Editor on a Windows box, and I am > > >>having trouble. Has anyone been able to use it, or know if there is > > >>someothing special that needs to be done? > > >> > > >>Thanks, > > >>Nick > > >>_______________________________________________ > > >>Tutor maillist - Tutor@python.org > > >>http://mail.python.org/mailman/listinfo/tutor > > >> > > >> > > >> > > > > > > > > > > > > > > > > > From igor at bioeng.ucsd.edu Thu Nov 4 23:12:54 2004 From: igor at bioeng.ucsd.edu (Igor Kaplounenko) Date: Thu Nov 4 23:12:59 2004 Subject: [Tutor] problems with 'freeze' on windows Message-ID: <418AA966.30404@bioeng.ucsd.edu> I've compiled my own version of Python for Windows, along with the Freeze utility. Freeze works fine for most things, but when I attempt to freeze the following code: ###### temp.py ######## import sys print sys.path from opengltk.OpenGL import GL ###################### I get the following error from running the executable only: E:\continuity_distribution\application_files\pcty>temp.exe ['E:\\continuity_distribution\\application_files\\pcty', 'E:\\Python23\\lib\\site-packages\\Numeric', 'E:\\WINDOWS\\System32\\python 23.zip', 'E:\\Python23\\lib\\site-packages\\Pythonwin', 'E:\\Python23\\lib\\site-packages\\win32', 'E:\\Python23\\lib\\site-packages \\win32\\lib', 'E:\\Python23\\lib\\site-packages', 'E:\\Python23\\Lib', 'E:\\Python23\\DLLs', 'E:\\Python23\\Lib\\lib-tk', 'E:\\cont inuity_distribution\\application_files\\pcty', 'E:\\Python23', 'E:\\Python23\\lib\\site-packages\\CONT', 'E:\\Python23\\lib\\site-pa ckages\\InsightToolkit', 'E:\\Python23\\lib\\site-packages\\PIL', 'e:\\Python23\\Lib\\site-packages\\opengltk'] Traceback (most recent call last): File "temp.py", line 4, in ? from opengltk.OpenGL import GL File "E:\Python23\lib\site-packages\opengltk\OpenGL\GL.py", line 9, in ? from gllib import * ImportError: No module named extent.utillib The .py version works just fine, however. Did anyone else run into this sort of trouble before, or knows what may have caused this? Incidentally, putting a "from gllib import *" statement into the body of temp.py works just fine in the frozen executable. So I thought it might be a problem with the paths, but I'm not sure about the specifics. From flaxeater at yahoo.com Thu Nov 4 23:49:13 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Nov 4 23:49:17 2004 Subject: [Tutor] Strange operator Message-ID: <20041104224913.6324.qmail@web54302.mail.yahoo.com> I was perusing the wax sourcecode and ran accross this style |= styles.frame(kwargs) style |= styles.window(kwargs) the pipe-equal operator is something I've never seen this before, after a little searching I found this Bitwise OR *|* 1 if lhs bit OR rhs bit = 1 http://www.mhuffman.com/notes/language/py_intro.htm#LOGIC which confuses me even more because I'm not sure how this is useful. Could someone please explain this? __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From klappnase at freenet.de Fri Nov 5 00:05:58 2004 From: klappnase at freenet.de (Michael Lange) Date: Fri Nov 5 00:05:44 2004 Subject: [Tutor] gettext mystery In-Reply-To: <6.1.0.6.0.20041104120317.02b13530@mail4.skillsoft.com> References: <20041104121457.456b11b4.klappnase@freenet.de> <6.1.0.6.0.20041104120317.02b13530@mail4.skillsoft.com> Message-ID: <20041105000558.1c9bfa89.klappnase@freenet.de> On Thu, 04 Nov 2004 12:04:15 -0500 Kent Johnson wrote: > If you print gettext.__file__ it will show you where it was loaded from. If > you are loading two different modules that will show them you you. > > Kent > Thanks, Kent that's it; version 1: [pingu@localhost pingu]$ moleskine /usr/lib/python2.2/site-packages/gtk-1.2/gettext.py version 2: [pingu@localhost pingu]$ moleskine /usr/lib/python2.2/gettext.pyc a simple RPM request shows that the (here) first gettext module is from my pygnome install. I wonder now if there is a way to force the import of the standard library module instead of pygnome's, which looks like it might be an outdated version of the standard library gettext.py . I tried to change sys.path and found that it actually worked to do a sys.path.sort() before importing gettext, but this doesn't look to me like it's the way it should be done. What's the recommended way to change the order of the module search path. Thanks for any hints Michael From marilyn at deliberate.com Fri Nov 5 00:11:39 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Nov 5 00:11:44 2004 Subject: [Tutor] Strange operator In-Reply-To: <20041104224913.6324.qmail@web54302.mail.yahoo.com> Message-ID: On Thu, 4 Nov 2004, Chad Crabtree wrote: > I was perusing the wax sourcecode and ran accross this > style |= styles.frame(kwargs) > style |= styles.window(kwargs) > > the pipe-equal operator is something I've never seen this before, > after > a little searching I found this > > Bitwise OR *|* 1 if lhs bit OR rhs bit = 1 It is totally cool. If you have a bit pattern, x = 10101100 And a mask, m = 00000010 Then x |= m turns *on* 10101110 any bit in x that has a 1 in m -- leaving the rest of x in tact. Similarly, If you have a bit pattern, x = 10101100 And a mask, m = 11111011 Then x &= m turns *off* 10101011 any bit in x that has a 0 in m -- leaving the rest of x in tact. Coolest is ^, the exclusive or. 1 ^ 0 = 1 1 ^ 1 = 0 0 ^ 0 = 0 If you have a bit pattern, x = 10101100 And a mask, m = 00000110 Then x ^= m turns *toggles* 10101011 any bit in x that has a 0 in m -- leaving the rest of x in tact. This is the basis of encryption! If x is your message and you give your friend a copy of your mask, you can ^= your message with your mask. Send the messed-up message to your friend and she can ^= the messed-up message with the same mask and get back to the original message. (I hope I didn't make any typos to confuse you!) Marilyn Davis > > http://www.mhuffman.com/notes/language/py_intro.htm#LOGIC > > which confuses me even more because I'm not sure how this is useful. > Could someone please explain this? > > > > > > __________________________________ > Do you Yahoo!? > Check out the new Yahoo! Front Page. > www.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From maxnoel_fr at yahoo.fr Fri Nov 5 00:33:39 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Nov 5 00:34:06 2004 Subject: [Tutor] SPE Editor In-Reply-To: <797fe3d404110413137506f582@mail.gmail.com> References: <20041101014505.92124.qmail@web54301.mail.yahoo.com> <418A854B.2030402@pdistributors.com> <797fe3d40411041254308627e7@mail.gmail.com> <418A97D5.80406@pdistributors.com> <797fe3d404110413111ee57254@mail.gmail.com> <797fe3d404110413137506f582@mail.gmail.com> Message-ID: On Nov 4, 2004, at 21:13, Bill Mill wrote: > Also note that you should use backslashes, not frontlsashes. Too many > years on unix for me to switch when I use windows. The frontslashes > should work, but the proper method is to use backslashes. > > Peace > Bill Mill > bill.mill at gmail.com However, in your programs, you should always use forward slashes. Backslashes need to be escaped (more typing, and more chances you may forget to escape one) and make your code non-portable (Bad Thing). -- 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 jeffpeery at yahoo.com Fri Nov 5 00:49:36 2004 From: jeffpeery at yahoo.com (Jeffrey Thomas Peery) Date: Fri Nov 5 00:49:38 2004 Subject: [Tutor] calling a CGI script Message-ID: <20041104234936.B8CE21E4002@bag.python.org> Hello I am trying to get a CGI script working, its my first time with this. I push my 'submit' button on my html document and my cgi script appears on my browser, it doesn't seem to actually run the script. Any ideas on whats wrong? Thanks, I included my html and my cgi below. Below is the test.html Test

my form

Name:

Below is the test.cgi file written in python #!c:\Program Files\Python\Python #test CGI import cgi import cgitb; cgitb.enable() form = cgi.FieldStorage() print "Content-Type: text/html" # HTML is following print # blank line, end of headers if not form.has_key("myName"): print "

Error

" print "Please fill in the name field." return print "

My Name is ", form["myName"].value -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041104/0fada4a1/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri Nov 5 01:25:15 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 5 01:25:41 2004 Subject: [Tutor] Strange operator In-Reply-To: <20041104224913.6324.qmail@web54302.mail.yahoo.com> Message-ID: On Thu, 4 Nov 2004, Chad Crabtree wrote: > I was perusing the wax sourcecode and ran accross this > style |= styles.frame(kwargs) > style |= styles.window(kwargs) > > the pipe-equal operator is something I've never seen this before, > after > a little searching I found this > > Bitwise OR *|* 1 if lhs bit OR rhs bit = 1 > > http://www.mhuffman.com/notes/language/py_intro.htm#LOGIC > > which confuses me even more because I'm not sure how this is useful. > Could someone please explain this? Hi Chad, Underneath the surface, integers in Python are stored as a series of bits. For example, the following sequence of bits: 100010100100 can stand for the integer 2212: ### >>> int('100010100100', 2) 2212 ### So that's a traditional interpretation of a series of bits. But there's another interpretation we can use: a series of bits may record a bunch of yes/no answers. In that sense, 100010100100 might mean: [Yes, No, No, No, Yes, No, Yes, No, No, Yes, No, No] A bitwise OR allows us to turn any one of those bits from No to Yes. For example, perhaps we may like to turn on the very last bit there. We can do this by saying: ### >>> 2212 | 1 2213 ### We should be careful not to interpret the result as an addition: it's not. We're actually turning on the very last bit, which we can see if we try doing another OR: ### >>> 2213 | 1 2213 ### That 'bit' is on already, so doing an OR again doesn't affect the answer. There are other bitwise operators out there that act like toggle switches; A bitwise representation of these yes/no choices is nice because it's VERY compact. A single integer can normally hold about 32 individual bits. (32 bit computing!) And to be able to represent 32 separate 'yes/no' flags in a single integer is a very neat thing. We may have run into this sort of thing before: the re.compile() function can take in an optional set of flags. For example, we might say something like: re.compile("hello world", re.VERBOSE | re.IGNORECASE) Without knowing about bits, that statement should actually look weird: how are we giving two particular bits of information in a single argument? We can look at what that OR is producing: ### >>> re.VERBOSE 64 >>> re.IGNORECASE 2 >>> re.VERBOSE | re.IGNORECASE 66 ### It's producing a single integer, but that integer is made up of bits! So we're really saying that two particular bits should be set to "Yes". ### >>> int('1000010', 2) 66 ### Does this make sense so far? A lot of this bit-fiddling just has to deal with using a very efficient representation for a collection of choices. Hope this helps! From jeff at ccvcorp.com Fri Nov 5 01:42:16 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Nov 5 01:39:17 2004 Subject: [Tutor] SPE Editor In-Reply-To: References: <20041101014505.92124.qmail@web54301.mail.yahoo.com> <418A854B.2030402@pdistributors.com> <797fe3d40411041254308627e7@mail.gmail.com> <418A97D5.80406@pdistributors.com> <797fe3d404110413111ee57254@mail.gmail.com> <797fe3d404110413137506f582@mail.gmail.com> Message-ID: <418ACC68.4060403@ccvcorp.com> Max Noel wrote: > > On Nov 4, 2004, at 21:13, Bill Mill wrote: > >> Also note that you should use backslashes, not frontlsashes. Too many >> years on unix for me to switch when I use windows. The frontslashes >> should work, but the proper method is to use backslashes. > > > However, in your programs, you should always use forward slashes. > Backslashes need to be escaped (more typing, and more chances you may > forget to escape one) and make your code non-portable (Bad Thing). Of course, if you're actually trying to write portable code, then you shouldn't be using *either* variety of slashes -- you should be using os.path.join() and the other os.path functions to do all of your file/path manipulations. :) Jeff Shannon Technician/Programmer Credit International From renx99 at gmail.com Fri Nov 5 01:49:01 2004 From: renx99 at gmail.com (Rene Lopez) Date: Fri Nov 5 01:49:08 2004 Subject: [Tutor] Input from CGI ? In-Reply-To: References: Message-ID: <57edb4ce041104164947e93482@mail.gmail.com> Okay here's how I get data from my forms in my cgi scripts... the quick and dirty method: #!/usr/bin/python """A small program to demonstrate simple CGIish stuff.""" import cgi import cgitb form = FieldStorage() if form.has_key("foo"): print "woohoo" if form.has_key("goo"): print "wup dee do" etc etc etc. How when you create your form and submit, all the info gets sent to the cgi script in FieldStorage. Doing a form = FieldStorage() puts it all in the form variable. All the info that the form submitted should be there. for example, I have a form that submits answer1 with a value of 2 and answer2 with a value of 50... if i want to get these values in my script i do: myanswer = form("answer1").value #assigns the value of "answer1" from the form.... hopefully this makes sense to you... I'm notorious for giving bad instructions ;-) Rene On Thu, 4 Nov 2004 20:04:01 +0200, Mark Kels wrote: > On Wed, 3 Nov 2004 13:34:46 -0800 (PST), Danny Yoo > > > wrote: > > > > > > On Wed, 3 Nov 2004, Mark Kels wrote: > > > > > How can I get input (string) from the user in CGI ? > > > > > > Hi Mark, > > > > There are examples of doing this in the Standard Library documentation. > > Here's a link to the documentation on the 'cgi' module: > > > > http://www.python.org/doc/lib/module-cgi.html > > > > The idea is to use the cgi module to grab form values. There are several > > methods we can use, but the easiest one is probably > > FieldStorage.getfirst(). > > > > Here's a quick example CGI program that takes in a number and prints out > > its square: > > > > ### > > #!/usr/bin/python > > > > """A small program to demonstrate simple CGIish stuff.""" > > > > import cgi > > import cgitb; cgitb.enable() > > > > def main(): > > form = cgi.FieldStorage() > > if form.getfirst("number"): > > doComputationAndPrintResult(form) > > else: > > printStartPage() > > > > def printStartPage(): > > printHtmlHeader() > > print """ > > > >

> > > > """ > > > > def doComputationAndPrintResult(form): > > computedResult = square(int(form.getfirst("number"))) > > > > printHtmlHeader() > > print """ > > > > %s > > > > """ % computedResult > > > > def printHtmlHeader(): > > """Prints out the standard HTML header line.""" > > print "Content-type: text/html\n\n" > > > > def square(x): > > """Returns the square of x.""" > > return x * x > > > > if __name__ == '__main__': > > main() > > ### > > > > You might also like to browse through the Web Programming topic guide > > here: > > > > http://www.python.org/topics/web/ > > > > Good luck to you! > > > > > > Thank you!! > It was very helpful. > > But how do I get more than one line ? > And how can I make radio buttons and get the input wuth them ? > And what this thing does ( I see it in almost every code example) : > if __name__ == '__main__': > main() > ? > > Thanks!! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Rene From kent_johnson at skillsoft.com Fri Nov 5 02:08:54 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Nov 5 02:09:01 2004 Subject: [Tutor] calling a CGI script In-Reply-To: <20041104234936.B8CE21E4002@bag.python.org> References: <20041104234936.B8CE21E4002@bag.python.org> Message-ID: <6.1.0.6.0.20041104200728.02b11860@mail4.skillsoft.com> It sounds like your web server is not configured for CGI scripts? or maybe the script is not executable? What OS and web server are you using? Kent At 03:49 PM 11/4/2004 -0800, Jeffrey Thomas Peery wrote: >Hello I am trying to get a CGI script working, its my first time with >this. I push my 'submit' button on my html document and my cgi script >appears on my browser, it doesn't seem to actually run the script. Any >ideas on whats wrong? Thanks, I included my html and my cgi below. > > >Below is the test.html > > >Test > > >

my form

> >
method="post"> >

Name:

> >

>

> >Below is the test.cgi file written in python > >#!c:\Program Files\Python\Python >#test CGI >import cgi >import cgitb; cgitb.enable() > >form = cgi.FieldStorage() > >print "Content-Type: text/html" # HTML is following >print # blank line, end of headers > >if not form.has_key("myName"): > print "

Error

" > print "Please fill in the name field." > return >print "

My Name is ", form["myName"].value >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From flaxeater at yahoo.com Fri Nov 5 03:17:58 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Nov 5 03:18:01 2004 Subject: [Tutor] Strange operator Message-ID: <20041105021758.12910.qmail@web54308.mail.yahoo.com> So if I understand this correctly it's similar to the chmod 777 directive, using binary representation to mean (111) I understood this system already but that is really neat. So to extrapolate LEFT=1 RIGHT=2 TOP=4 BOTTOM=8 WILLYWONKA=16 would be the proper progression of options. then to see if a option was set I would do it like this. if flag>=WILLYWONKA: print "Go to the Factory" Is that So? So this is like a really really really compact switch statement? Danny Yoo wrote: > Hi Chad, > > >Underneath the surface, integers in Python are stored as a series of bits. >For example, the following sequence of bits: > > 100010100100 > >can stand for the integer 2212: > >### > > >>>>int('100010100100', 2) >>>> >>>> >2212 >### > > >So that's a traditional interpretation of a series of bits. But there's >another interpretation we can use: a series of bits may record a bunch of >yes/no answers. In that sense, > > 100010100100 > >might mean: > > [Yes, No, No, No, Yes, No, Yes, No, No, Yes, No, No] > > > >A bitwise OR allows us to turn any one of those bits from No to Yes. For >example, perhaps we may like to turn on the very last bit there. We can >do this by saying: > >### > > >>>>2212 | 1 >>>> >>>> >2213 >### > > >We should be careful not to interpret the result as an addition: it's not. >We're actually turning on the very last bit, which we can see if we try >doing another OR: > >### > > >>>>2213 | 1 >>>> >>>> >2213 >### > >That 'bit' is on already, so doing an OR again doesn't affect the answer. >There are other bitwise operators out there that act like toggle switches; > > >A bitwise representation of these yes/no choices is nice because it's VERY >compact. A single integer can normally hold about 32 individual bits. >(32 bit computing!) And to be able to represent 32 separate 'yes/no' >flags in a single integer is a very neat thing. > > >We may have run into this sort of thing before: the re.compile() function >can take in an optional set of flags. For example, we might say something >like: > > re.compile("hello world", re.VERBOSE | re.IGNORECASE) > >Without knowing about bits, that statement should actually look weird: how >are we giving two particular bits of information in a single argument? > > >We can look at what that OR is producing: > >### > > >>>>re.VERBOSE >>>> >>>> >64 > > >>>>re.IGNORECASE >>>> >>>> >2 > > >>>>re.VERBOSE | re.IGNORECASE >>>> >>>> >66 >### > > >It's producing a single integer, but that integer is made up of bits! So >we're really saying that two particular bits should be set to "Yes". > >### > > >>>>int('1000010', 2) >>>> >>>> >66 >### > > > >Does this make sense so far? A lot of this bit-fiddling just has to deal >with using a very efficient representation for a collection of choices. > > >Hope this helps! > > > > > __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From dyoo at hkn.eecs.berkeley.edu Fri Nov 5 03:47:50 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 5 03:51:05 2004 Subject: [Tutor] Strange operator In-Reply-To: <20041105021758.12910.qmail@web54308.mail.yahoo.com> Message-ID: On Thu, 4 Nov 2004, Chad Crabtree wrote: > So if I understand this correctly it's similar to the chmod 777 > directive, using binary representation to mean (111) I understood > this > system already but that is really neat. So to extrapolate > > LEFT=1 > RIGHT=2 > TOP=4 > BOTTOM=8 > WILLYWONKA=16 > > would be the proper progression of options. Hi Chad, Yup, exactly. Each of those numbers corresponds to a bit pattern where one of those bits is set on. > if flag>=WILLYWONKA: > print "Go to the Factory" Yes. In the general case, we'd use an AND operator to see if a flag were set: if flags & LEFT: print "Turning left!" > So this is like a really really really compact switch statement? It's a very compact way of storing lots of individual flags. These bitwise operators aren't just for representing flags, though, because of the fact that the bitwise operators work against all the bits in an integer at once. It might be good to mention another common application for these bitwise operators. One fairly well-known bitwise operator is called XOR, the thing that toggles bits on or off. Characters can be represented as integers, so we can jury-rig a really silly program to obscure text just with XOR: ### >>> msg = map(ord, "hello world") >>> msg [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] ### So there's our message as a list of numbers. We can now apply an XOR across each number: ### >>> def encode(numbers, magicKey=42): ... return [n ^ magicKey for n in numbers] ... >>> encode(msg) [66, 79, 70, 70, 69, 10, 93, 69, 88, 70, 78] ### And just as toggling something twice gets us back to where we started, XORing twice --- with the same pattern --- handles the decryption: ### >>> encode(encode(msg)) [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] ### Of course, this is an abysmal way to do encryption. *grin* But these operators (including XOR) are actually at the heart of some encryption programs. I hope this helps! From bill.mill at gmail.com Fri Nov 5 03:53:54 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Nov 5 03:53:58 2004 Subject: [Tutor] Strange operator In-Reply-To: <20041105021758.12910.qmail@web54308.mail.yahoo.com> References: <20041105021758.12910.qmail@web54308.mail.yahoo.com> Message-ID: <797fe3d404110418536c4daadc@mail.gmail.com> Chad, On Thu, 4 Nov 2004 18:17:58 -0800 (PST), Chad Crabtree wrote: > So if I understand this correctly it's similar to the chmod 777 > directive, using binary representation to mean (111) I understood > this > system already but that is really neat. So to extrapolate > > LEFT=1 > RIGHT=2 > TOP=4 > BOTTOM=8 > WILLYWONKA=16 > > would be the proper progression of options. then to see if a option > was > set I would do it like this. > > if flag>=WILLYWONKA: > print "Go to the Factory" To see if it was set, you would do: if flag & WILLYWONKA: wonkify() Imagine if flag==32; that is "100000" in binary. In this case, flag >= WILLYWONKA is true, but flag & WILLYWONKA would be false, because the 5th bit is not set in flag. So, to set the WILLYWONKA value in flag, do "flag |= WILLYWONKA". To toggle it, do "flag ^ WILLYWONKA". To test if it's there, do "flag & WILLYWONKA". > So this is like a really really really compact switch statement? > Don't really understand what you mean here. Peace Bill Mill bill.mill at gmail.com > > Danny Yoo wrote: > > > Hi Chad, > > > > > >Underneath the surface, integers in Python are stored as a series of > bits. > >For example, the following sequence of bits: > > > > 100010100100 > > > >can stand for the integer 2212: > > > >### > > > > > >>>>int('100010100100', 2) > >>>> > >>>> > >2212 > >### > > > > > >So that's a traditional interpretation of a series of bits. But > there's > >another interpretation we can use: a series of bits may record a > bunch of > >yes/no answers. In that sense, > > > > 100010100100 > > > >might mean: > > > > [Yes, No, No, No, Yes, No, Yes, No, No, Yes, No, No] > > > > > > > >A bitwise OR allows us to turn any one of those bits from No to Yes. > For > >example, perhaps we may like to turn on the very last bit there. We > can > >do this by saying: > > > >### > > > > > >>>>2212 | 1 > >>>> > >>>> > >2213 > >### > > > > > >We should be careful not to interpret the result as an addition: > it's not. > >We're actually turning on the very last bit, which we can see if we > try > >doing another OR: > > > >### > > > > > >>>>2213 | 1 > >>>> > >>>> > >2213 > >### > > > >That 'bit' is on already, so doing an OR again doesn't affect the > answer. > >There are other bitwise operators out there that act like toggle > switches; > > > > > >A bitwise representation of these yes/no choices is nice because > it's VERY > >compact. A single integer can normally hold about 32 individual > bits. > >(32 bit computing!) And to be able to represent 32 separate > 'yes/no' > >flags in a single integer is a very neat thing. > > > > > >We may have run into this sort of thing before: the re.compile() > function > >can take in an optional set of flags. For example, we might say > something > >like: > > > > re.compile("hello world", re.VERBOSE | re.IGNORECASE) > > > >Without knowing about bits, that statement should actually look > weird: how > >are we giving two particular bits of information in a single > argument? > > > > > >We can look at what that OR is producing: > > > >### > > > > > >>>>re.VERBOSE > >>>> > >>>> > >64 > > > > > >>>>re.IGNORECASE > >>>> > >>>> > >2 > > > > > >>>>re.VERBOSE | re.IGNORECASE > >>>> > >>>> > >66 > >### > > > > > >It's producing a single integer, but that integer is made up of > bits! So > >we're really saying that two particular bits should be set to "Yes". > > > >### > > > > > >>>>int('1000010', 2) > >>>> > >>>> > >66 > >### > > > > > > > >Does this make sense so far? A lot of this bit-fiddling just has to > deal > >with using a very efficient representation for a collection of > choices. > > > > > >Hope this helps! > > > > > > > > > > > > __________________________________ > Do you Yahoo!? > Check out the new Yahoo! Front Page. > www.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Fri Nov 5 04:40:44 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 5 04:40:55 2004 Subject: [Tutor] Eek, help! In-Reply-To: References: Message-ID: Hi all, Kent - Sorry, misworded that one. pause.anyKey() is a little function I wrote because I missed INKEY$(1) from the days of QBASIC. It works fine. Danny - Thanks a bundle, it works great now! Regards, Liam Clarke On Thu, 4 Nov 2004 11:24:06 -0800 (PST), Danny Yoo wrote: > > > I have belatedly come to use dictionaries, and I was having some > > trouble with how to read/write them from a file, so I looked at Alan > > Gauld's section on it. I've pretty much copied his code straight > > through, and, well, I've broken it somehow. In fact, it's hanging > > Python, and it even hangs the debugger, which is a first, I must > > admit. > > Hi Liam, > > Whenever I hear something about a "hang", I almost immediately look at > while loop conditions. *grin* Let's take a look: > > > > store2 = file(filename,'r') > > > > while store2: > > name = store2.readline().strip() > > entry = store2.readline().strip() > > book[name] = entry > > > The while loop here needs to be fixed: store2 is a file, and files are > true values, no matter what. This is an infinite loop. > > What you wanted to say, I think, was to keep the loop running as long as > there's still content in store2. When we read the end of a file, we'll > get the empty string from a readline. So one way to correct the loop may > be: > > ### > while True: > name, entry = store2.readline(), store2.readline() > if not name or not entry: break > name, entry = name.strip(), entry.strip() > book[name] = entry > ### > > This is a little more verbose, and might look weird at first, with the > 'while True' thing. > > The input is not exactly single-line oriented --- you're reading pairs of > lines at a time --- so it complicates matters slightly. > > Hmmm... We can make the code a little nicer by pairing up adjacent lines. > Here's a small utility function that may help: > > ### > def groupAdjacentElements(someSequence, n = 2): > """A little helper utility to group up adjacent elements.""" > nextGroup = [] > for element in someSequence: > nextGroup.append(element) > if len(nextGroup) == n: > yield tuple(nextGroup) > nextGroup = [] > ### > > This bit of code will pair up adjacent elements, like this: > > ### > >>> for a, b in groupAdjacentElements(range(20)): > ... print a, b, a * b > ... > 0 1 0 > 2 3 6 > 4 5 20 > 6 7 42 > 8 9 72 > 10 11 110 > 12 13 156 > 14 15 210 > 16 17 272 > 18 19 342 > ### > > With this helper, now the code that reads store2 can be written as a nice > 'for' loop instead of the 'while' loop: > > ### > store2 = file(filename,'r') > > for (name, entry) in groupAdjacentElements(store2): > name = name.strip() > entry = entry.strip() > book[name] = entry > > store2.close() > ### > > I hope this helps! > > -- '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 cyresse at gmail.com Fri Nov 5 05:15:33 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 5 05:15:51 2004 Subject: [Tutor] Class mind boggle Message-ID: Hello all, I have a little prog I'm writing, and I'm creating a GUI with PythonCard. The actual functions accessed by the GUI are in a separate module. Now, I would like to call a dialog box if needed in one of the separate functions, if a password is wrong, get it via a nice little pop-up. PythonCard comes with built in basic dialogs, which are accessed like so: result = dialog.textEntryDialog(self, 'What is your favorite language?', 'A title' , 'Python') the self part is the parent window... OK, so I need to call the dialog from within my GUI. So, I've got - gui.py from PythonCard import model, dialog class Main(model.background): def some stuff def some more stuff def getPassword(self, user): result = dialog.textEntryDialog(self, 'Enter Password, 'Uhoh' , 'Python') app=model.application(Main) app.mainloop() and in function.py try: session.login(user, pwd) except: .... At this point I want to call gui.Main.getPassword, pass it the variable user, and get back a value from result.text. Which makes my head go all squiggly. Can you tell a class method to return values? I've tried creating a new object of gui.Main() and calling it's badPassword method in the except: clause like so: except: wd=gui.Main() pwd=wd.getPassword() No matter what I do, no dialog box opens, and I get no error messages in my console. Normally, I'm just calling functions from functions, and they all run def... return, which is nice and easy to comprehend. But, classes, they just have def... : o So yeah, the paradigm of OOP gets me again. Any help that can be offered is appreciated. Regards, Liam Clarke '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 ps_python at yahoo.com Fri Nov 5 05:18:45 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Nov 5 05:18:48 2004 Subject: [Tutor] making list into a dictionary Message-ID: <20041105041845.65335.qmail@web53708.mail.yahoo.com> Dear group, I want to convert 2 lists into a dictionary object. Can I do that using list comprehension or by any other method: a = ['apple', 'carrot', 'egg', 'cicken'] b = ['fruit', 'vegie', 'poultry', 'meat'] c = {} I want to create: c = {'fruit':'apple', 'vegie':'carrot', 'poultry':'egg', 'mean':'chicken'} Could any one help, please. Thanks Kumar. __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From cyresse at gmail.com Fri Nov 5 05:28:40 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 5 05:28:48 2004 Subject: [Tutor] making list into a dictionary In-Reply-To: <20041105041845.65335.qmail@web53708.mail.yahoo.com> References: <20041105041845.65335.qmail@web53708.mail.yahoo.com> Message-ID: Hey Kumar, I'd go - c={} for item in range(len(a)): c[b[item]]=a[item] But there is no doubt a simpler way. Good luck, Liam Clarke On Thu, 4 Nov 2004 20:18:45 -0800 (PST), kumar s wrote: > Dear group, > I want to convert 2 lists into a dictionary object. > > Can I do that using list comprehension or by any other > method: > > a = ['apple', 'carrot', 'egg', 'cicken'] > b = ['fruit', 'vegie', 'poultry', 'meat'] > > c = {} > > I want to create: > c = {'fruit':'apple', > 'vegie':'carrot', > 'poultry':'egg', > 'mean':'chicken'} > > Could any one help, please. > > Thanks > Kumar. > > __________________________________ > Do you Yahoo!? > Check out the new Yahoo! Front Page. > www.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 bill.mill at gmail.com Fri Nov 5 05:44:29 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Nov 5 05:44:33 2004 Subject: [Tutor] making list into a dictionary In-Reply-To: <20041105041845.65335.qmail@web53708.mail.yahoo.com> References: <20041105041845.65335.qmail@web53708.mail.yahoo.com> Message-ID: <797fe3d404110420445e61bb52@mail.gmail.com> Kumar, Here's what I'd do: a = [1,2,3] b = ['a','b','c'] d = {} for key, val in zip(a, b): d[key] = val The trick here is in the zip() function. This combines two lists like a zipper - first element of the first list followed by first element of the second list, then the second element of the first, and so on. An example might help more: >>> a = [1,2,3] >>> b = ['a', 'b', 'c'] >>> zip(a,b) [(1, 'a'), (2, 'b'), (3, 'c')] The resulting list of tuples is easy to unpack, as we showed in the earlier example. Peace Bill Mill bill.mill at gmail.com On Thu, 4 Nov 2004 20:18:45 -0800 (PST), kumar s wrote: > Dear group, > I want to convert 2 lists into a dictionary object. > > Can I do that using list comprehension or by any other > method: > > a = ['apple', 'carrot', 'egg', 'cicken'] > b = ['fruit', 'vegie', 'poultry', 'meat'] > > c = {} > > I want to create: > c = {'fruit':'apple', > 'vegie':'carrot', > 'poultry':'egg', > 'mean':'chicken'} > > Could any one help, please. > > Thanks > Kumar. > > __________________________________ > Do you Yahoo!? > Check out the new Yahoo! Front Page. > www.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From tmclaughlin at csu.edu.au Fri Nov 5 05:50:29 2004 From: tmclaughlin at csu.edu.au (McLaughlin, Toby) Date: Fri Nov 5 05:50:46 2004 Subject: [Tutor] making list into a dictionary Message-ID: <211F78EFD1D870409CC3E4158F4881DA09602B3C@xcww01.riv.csu.edu.au> Even c = dict(zip(a,b)) will work because of the overloaded constructor on "dict". >From help(dict) class dict(object) | dict() -> new empty dictionary. | dict(seq) -> new dictionary initialized as if via: | d = {} | for k, v in seq: | d[k] = v Toby McLaughlin. > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] On Behalf Of Bill Mill > Sent: Friday, 5 November 2004 3:44 PM > To: kumar s > Cc: tutor@python.org > Subject: Re: [Tutor] making list into a dictionary > > > Kumar, > > Here's what I'd do: > > a = [1,2,3] > b = ['a','b','c'] > d = {} > > for key, val in zip(a, b): > d[key] = val > > The trick here is in the zip() function. This combines two lists like > a zipper - first element of the first list followed by first element > of the second list, then the second element of the first, and so on. > An example might help more: > > >>> a = [1,2,3] > >>> b = ['a', 'b', 'c'] > >>> zip(a,b) > [(1, 'a'), (2, 'b'), (3, 'c')] > > The resulting list of tuples is easy to unpack, as we showed in the > earlier example. > > Peace > Bill Mill > bill.mill at gmail.com > > > On Thu, 4 Nov 2004 20:18:45 -0800 (PST), kumar s > wrote: > > Dear group, > > I want to convert 2 lists into a dictionary object. > > > > Can I do that using list comprehension or by any other > > method: > > > > a = ['apple', 'carrot', 'egg', 'cicken'] > > b = ['fruit', 'vegie', 'poultry', 'meat'] > > > > c = {} > > > > I want to create: > > c = {'fruit':'apple', > > 'vegie':'carrot', > > 'poultry':'egg', > > 'mean':'chicken'} > > > > Could any one help, please. > > > > Thanks > > Kumar. > > > > __________________________________ > > Do you Yahoo!? > > Check out the new Yahoo! Front Page. > > www.yahoo.com > > > > _______________________________________________ > > 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 jinlin555 at msn.com Fri Nov 5 07:38:45 2004 From: jinlin555 at msn.com (Lin Jin) Date: Fri Nov 5 07:39:03 2004 Subject: [Tutor] how to use the time module? Message-ID: i am new to python.i want to know that,if i have a variable a,and i want to use the time module,the strftime method to output the weekday,how could i do that? i know that i should use the the "%A",but if i write a code like this: >>>time.strftime("%A",a). it is not working.anyone can help me solve this one? _________________________________________________________________ Ãâ·ÑÏÂÔØ MSN Explorer: http://explorer.msn.com/lccn/ From rdm at rcblue.com Fri Nov 5 08:46:07 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Nov 5 08:46:12 2004 Subject: [Tutor] how to use the time module? In-Reply-To: References: Message-ID: <6.1.2.0.2.20041104232904.08841da0@rcblue.com> At 22:38 11/4/2004, Lin Jin wrote: >i am new to python.i want to know that,if i have a variable a,and i want >to use the time module,the strftime method to output the weekday,how >could i do that? i know that i should use the the "%A",but if i write a >code like this: >>>>time.strftime("%A",a). >it is not working.anyone can help me solve this one? This should do it (with Python 2.1 or later): >>> from time import strftime >>> a = strftime("%A") >>> a 'Thursday' Dick Moores From jfabiani at yolo.com Fri Nov 5 08:46:48 2004 From: jfabiani at yolo.com (John Fabiani) Date: Fri Nov 5 08:46:52 2004 Subject: [Tutor] how to use the time module? In-Reply-To: References: Message-ID: <200411042346.48327.jfabiani@yolo.com> On Thursday 04 November 2004 22:38, Lin Jin wrote: > i am new to python.i want to know that,if i have a variable a,and i want to > use the time module,the strftime method to output the weekday,how could i > do that? i know that i should use the the "%A",but if i write a code like > > this: > >>>time.strftime("%A",a). > > it is not working.anyone can help me solve this one? Try using import calendar today=weekday(year, month, day) #remember that it will return a number - 0=Monday John From jodegbami at amadeus.net Fri Nov 5 10:31:15 2004 From: jodegbami at amadeus.net (Joseph Odegbami) Date: Fri Nov 5 10:31:27 2004 Subject: [Tutor] Commenting lines in modified files Message-ID: Hi, I am quite new to Python, have written a few useful parsers and have found it very powerful indeed. However, working on XEDIT on MVS I came across a macro that add comments to lines in a file that has just been modified. Now, I thought it will be a very good idea to have something similar in a PC environment. You open a source file, modify it and run a python script against it to indicate all the lines that have just been modified with a preassigned string. Is there anything in Python out there that does something similar or that I can start from to implement such, or any ideas that you have will be very much appreciated as I don't even know where to begin. Best Regards, _____________________________________ Joseph From rdm at rcblue.com Fri Nov 5 10:47:46 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Nov 5 10:47:58 2004 Subject: [Tutor] how to use the time module? Message-ID: <6.1.2.0.2.20041105014643.0368b6c0@rcblue.com> OK, so you want to input a date and get that date's weekday? I don't know how to do that with the time module, but you can use the calendar module. Try: import string import datetime from calendar import weekday y,m,d=string.split(raw_input("Enter a date('YYYY-MM-DD'):"),"-") a=datetime.date(int(y),int(m),int(d)) weekday = weekday(int(y), int(m), int(d)) print "%s was a %s" % (a, weekday) You'll want to write a function that converts the integer to the corresponding weekday. From the calendar module doc: weekday( year, month, day) Returns the day of the week (0 is Monday) for year (1970-...), month (1-12), day (1-31). In your code, you reassigned a to strftime("%A"), so of course a becomes today's weekday. At 00:17 11/5/2004, Lin Jin wrote: >thx for your reply,but seems i still have some problem with my >program,my code is like this: > >import string >import datetime >import time >y,m,d=string.split(raw_input("Enter a date('YYYY-MM-DD'):"),"-") >a=datetime.date(int(y),int(m),int(d)) >from time import strftime >a=strftime("%A") >print "Today is "+a > >you can see that,my a variable is the user input year,month,and day.but >if i implement it like this,it seems it just give out the weekday of >today.what's wrong with my code? > >>From: Dick Moores >>To: "Lin Jin" ,tutor@python.org >>Subject: Re: [Tutor] how to use the time module? >>Date: Thu, 04 Nov 2004 23:46:07 -0800 >> >>At 22:38 11/4/2004, Lin Jin wrote: >>>i am new to python.i want to know that,if i have a variable a,and i >>>want to use the time module,the strftime method to output the >>>weekday,how could i do that? i know that i should use the the "%A",but >>>if i write a code like this: >>>>>>time.strftime("%A",a). >>>it is not working.anyone can help me solve this one? >> >>This should do it (with Python 2.1 or later): >> >> >>> from time import strftime >> >>> a = strftime("%A") >> >>> a >>'Thursday' >> >>Dick Moores From kent_johnson at skillsoft.com Fri Nov 5 10:57:24 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Nov 5 10:57:29 2004 Subject: [Tutor] Commenting lines in modified files In-Reply-To: References: Message-ID: <6.1.0.6.0.20041105045321.02a9e598@mail4.skillsoft.com> Joseph, I don't know how you can just look at a saved file and tell what has changed. A function like that would have to be integrated into the editor. If you want to compare the edited file against an unchanged original, the SequenceMatcher class in difflib can help a lot with this. Kent At 09:31 AM 11/5/2004 +0000, Joseph Odegbami wrote: >Hi, >I am quite new to Python, have written a few useful parsers and have found >it very powerful indeed. > >However, working on XEDIT on MVS I came across a macro that add comments to >lines in a file that has just been modified. > >Now, I thought it will be a very good idea to have something similar in a >PC environment. >You open a source file, modify it and run a python script against it to >indicate all the lines that have just been modified with a preassigned >string. >Is there anything in Python out there that does something similar or that I >can start from to implement such, or any ideas that you have will be >very much appreciated as I don't even know where to begin. > >Best Regards, >_____________________________________ >Joseph > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Fri Nov 5 11:11:18 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Nov 5 11:11:27 2004 Subject: [Tutor] how to use the time module? In-Reply-To: <6.1.2.0.2.20041105014643.0368b6c0@rcblue.com> References: <6.1.2.0.2.20041105014643.0368b6c0@rcblue.com> Message-ID: <6.1.0.6.0.20041105050909.02951f68@mail4.skillsoft.com> datetime.date objects support strftime() and weekday() directly: >>> import datetime >>> a=datetime.date(2004, 11, 5) >>> a.strftime('%A') 'Friday' >>> a.weekday() 4 So your code can be a little simpler import string import datetime y,m,d=string.split(raw_input("Enter a date('YYYY-MM-DD'):"),"-") a=datetime.date(int(y),int(m),int(d)) print a.strftime('%A') Kent At 01:47 AM 11/5/2004 -0800, Dick Moores wrote: >OK, so you want to input a date and get that date's weekday? I don't know >how to do that with the time module, but you can use the calendar module. > >Try: > >import string >import datetime >from calendar import weekday > >y,m,d=string.split(raw_input("Enter a date('YYYY-MM-DD'):"),"-") >a=datetime.date(int(y),int(m),int(d)) >weekday = weekday(int(y), int(m), int(d)) >print "%s was a %s" % (a, weekday) > >You'll want to write a function that converts the integer to the >corresponding weekday. > > From the calendar module doc: >weekday( year, month, day) >Returns the day of the week (0 is Monday) for year (1970-...), month >(1-12), day (1-31). > >In your code, you reassigned a to strftime("%A"), so of course a becomes >today's weekday. > >At 00:17 11/5/2004, Lin Jin wrote: >>thx for your reply,but seems i still have some problem with my program,my >>code is like this: >> >>import string >>import datetime >>import time >>y,m,d=string.split(raw_input("Enter a date('YYYY-MM-DD'):"),"-") >>a=datetime.date(int(y),int(m),int(d)) >>from time import strftime >>a=strftime("%A") >>print "Today is "+a >> >>you can see that,my a variable is the user input year,month,and day.but >>if i implement it like this,it seems it just give out the weekday of >>today.what's wrong with my code? >> >>>From: Dick Moores >>>To: "Lin Jin" ,tutor@python.org >>>Subject: Re: [Tutor] how to use the time module? >>>Date: Thu, 04 Nov 2004 23:46:07 -0800 >>> >>>At 22:38 11/4/2004, Lin Jin wrote: >>>>i am new to python.i want to know that,if i have a variable a,and i >>>>want to use the time module,the strftime method to output the >>>>weekday,how could i do that? i know that i should use the the "%A",but >>>>if i write a code like this: >>>>>>>time.strftime("%A",a). >>>>it is not working.anyone can help me solve this one? >>> >>>This should do it (with Python 2.1 or later): >>> >>> >>> from time import strftime >>> >>> a = strftime("%A") >>> >>> a >>>'Thursday' >>> >>>Dick Moores > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From renx99 at gmail.com Fri Nov 5 14:45:30 2004 From: renx99 at gmail.com (Rene Lopez) Date: Fri Nov 5 14:45:46 2004 Subject: [Tutor] Input from CGI ? In-Reply-To: References: Message-ID: <57edb4ce04110505451a539e5b@mail.gmail.com> > And what this thing does ( I see it in almost every code example) : > if __name__ == '__main__': > main() This is what runs when you run the program directly. the program's __name__ always equals "__main__" when it's the top most program and not some sort of module being imported into another program. -- Rene From rmkrauter at yahoo.com Fri Nov 5 15:08:22 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri Nov 5 15:08:11 2004 Subject: [Tutor] searching for data in one file from another Message-ID: <418B8956.7060905@yahoo.com> Hi Scott, I think it's probably just that the lines don't really start with '>'. In the post in which you originally showed the file format, it looked to me like lines started with '>'. In the last email I don't see any '>'. Do you think you can check for this, and modify the code to suit the actual file format? If you still have trouble, can you send me a file containing the first 500 or so lines of the fasta file, so I can check what is going wrong? (You may want to just send the truncated file to me and I can summarize it in my reply to the list. Ideally posting the files to the web and including the url in the posted question lets people interested in helping retrieve the files, without filling the inboxes of those who don't. I don't mind getting attachments in mail from this list, but I'm not sure about others.) Something like the code below will dump the first 500 lines of files passed in on command line. import sys for fname in sys.argv[1:]: infile = open(fname) outfile = '%s.trunc'%fname out = open(outfile,'w+') # enumerate() requires python 2.3 for n,line in enumerate(infile): if n >= 500: break else: out.write(line) Thanks. Rich From rmkrauter at yahoo.com Fri Nov 5 15:16:10 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri Nov 5 15:15:58 2004 Subject: [Fwd: Re: [Tutor] searching for data in one file from another] Message-ID: <418B8B2A.2030304@yahoo.com> [mail originally sent to my address only; attachment removed] Hej Rich! Thanks again for the help. I grabbed your script and put it together like this: import sys,string WFILE=open(sys.argv[1], 'w') def deleteExons(fname2='Z:/datasets/altsplice1.fasta',exons_to_delete='Z:/datasets/Exonlist.txt'): f = open(fname2) f2 = open(exons_to_delete) list = f2.readlines() exon = None for line in f: if line.startswith('>'): exon = line[1:].split('|')[0] if exon in list: continue yield line if __name__ == '__main__': for line in deleteExons(): print >> WFILE, line, exonlist is made from the last program you helped me with and consists of single lines of exons altsplice1.fasta is 85583 kb when I run the program it does not shrink the file at all, in fact althought the first and last 40 lines appear to be the same, the output file is larger than the original. It is a normal fast file: ENSE00001383339.1|ENSG00000187908.1|ENST00000339871.1 assembly=NCBI34|chr=10_NT _078087|strand=forward|bases 57203 to 57283|exons plus upstream and downstream r egions for exon ACCCAGCAAAATGGGGATCTCCACAGTCATCCTTGAAATGTGTCTTTTATGGGGACAAGTTCTATCTACAGGTATTACGT T ENSE00001387275.1|ENSG00000187908.1|ENST00000339871.1 assembly=NCBI34|chr=10_NT _078087|strand=forward|bases 72877 to 72981|exons plus upstream and downstream r egions for exon GAGATGGCAGGTGTCAGGGCCGAGTGGAGATCCTATACCGAGGCTCCTGGGGCACCGTGTGTGATGACAGCTGGGACACC AATGATGCCAACGTGGTCTGTAGGC ENSE00001378578.1|ENSG00000187908.1|ENST00000339871.1 assembly=NCBI34|chr=10_NT _078087|strand=forward|bases 82505 to 82835|exons plus upstream and downstream r egions for exon CTGAATCCAGTTTGGCCCTGAGGCTGGTGAATGGAGGTGACAGGTGTCAGGGCCGAGTGGAGGTCCTATACCGAGGCTCC TGGGGCACCGTGTGTGATGACAGCTGGGACACCAATGATGCCAATGTGGTCTGCAGGCAGCTGGGCTGTGGCTGGGCCAT GTTGGCCCCAGGAAATGCCCGGTTTGGTCAGGGCTCAGGACCCATTGTCCTGGATGACGTGCGCTGCTCAGGGAATGAGT CCTACTTGTGGAGCTGCCCCCACAATGGCTGGCTCTCCCATAACTGTGGCCATAGTGAAGACGCTGGTGTCATCTGCTCA GGTGGGCCTCC ENSE00001379544.1|ENSG00000187908.1|ENST00000339871.1 assembly=NCBI34|chr=10_NT _078087|strand=forward|bases 88623 to 89087|exons plus upstream and downstream r egions for exon Any thoughts? Scott From rdm at rcblue.com Fri Nov 5 15:22:31 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Nov 5 15:22:35 2004 Subject: [Tutor] how to use the time module? Message-ID: <6.1.2.0.2.20041105062216.03650030@rcblue.com> I just discovered that calendar.weekday() is usable back to year 1 instead of just 1900. "the datetime strftime() methods require year >= 1900" >>> from calendar import weekday >>> import string, datetime >>> print weekday(1,1,1) # doesn't need to be 0001,01,01 0 >>> print weekday(1000,1,1) # doesn't need to be 1000,01,01 2 >>> print weekday(1776,7,4) # ditto 3 >>> print weekday(9999,12,31) 4 Dick At 02:11 11/5/2004, Kent Johnson wrote: >datetime.date objects support strftime() and weekday() directly: > >>> import datetime > >>> a=datetime.date(2004, 11, 5) > >>> a.strftime('%A') >'Friday' > >>> a.weekday() >4 > >So your code can be a little simpler >import string >import datetime > >y,m,d=string.split(raw_input("Enter a date('YYYY-MM-DD'):"),"-") >a=datetime.date(int(y),int(m),int(d)) >print a.strftime('%A') > >Kent > >At 01:47 AM 11/5/2004 -0800, Dick Moores wrote: >>OK, so you want to input a date and get that date's weekday? I don't >>know how to do that with the time module, but you can use the calendar >>module. >> >>Try: >> >>import string >>import datetime >>from calendar import weekday >> >>y,m,d=string.split(raw_input("Enter a date('YYYY-MM-DD'):"),"-") >>a=datetime.date(int(y),int(m),int(d)) >>weekday = weekday(int(y), int(m), int(d)) >>print "%s was a %s" % (a, weekday) >> >>You'll want to write a function that converts the integer to the >>corresponding weekday. >> >> From the calendar module doc: >>weekday( year, month, day) >>Returns the day of the week (0 is Monday) for year (1970-...), month >>(1-12), day (1-31). >> >>In your code, you reassigned a to strftime("%A"), so of course a >>becomes today's weekday. >> >>At 00:17 11/5/2004, Lin Jin wrote: >>>thx for your reply,but seems i still have some problem with my >>>program,my code is like this: >>> >>>import string >>>import datetime >>>import time >>>y,m,d=string.split(raw_input("Enter a date('YYYY-MM-DD'):"),"-") >>>a=datetime.date(int(y),int(m),int(d)) >>>from time import strftime >>>a=strftime("%A") >>>print "Today is "+a >>> >>>you can see that,my a variable is the user input year,month,and >>>day.but if i implement it like this,it seems it just give out the >>>weekday of today.what's wrong with my code? >>> >>>>From: Dick Moores >>>>To: "Lin Jin" ,tutor@python.org >>>>Subject: Re: [Tutor] how to use the time module? >>>>Date: Thu, 04 Nov 2004 23:46:07 -0800 >>>> >>>>At 22:38 11/4/2004, Lin Jin wrote: >>>>>i am new to python.i want to know that,if i have a variable a,and i >>>>>want to use the time module,the strftime method to output the >>>>>weekday,how could i do that? i know that i should use the the >>>>>"%A",but if i write a code like this: >>>>>>>>time.strftime("%A",a). >>>>>it is not working.anyone can help me solve this one? >>>> >>>>This should do it (with Python 2.1 or later): >>>> >>>> >>> from time import strftime >>>> >>> a = strftime("%A") >>>> >>> a >>>>'Thursday' >>>> >>>>Dick Moores >> >>_______________________________________________ >>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 kent_johnson at skillsoft.com Fri Nov 5 15:39:00 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Nov 5 15:41:37 2004 Subject: [Fwd: Re: [Tutor] searching for data in one file from another] In-Reply-To: <418B8B2A.2030304@yahoo.com> References: <418B8B2A.2030304@yahoo.com> Message-ID: <6.1.0.6.0.20041105093234.02905608@mail4.skillsoft.com> Rich, When you read f2 with readlines, the newlines are included in the lines. So you will never get a match with the exon from f1. Also since you are apparently doing many tests for membership in list, a set would probably be faster. I suggest you try something like this to create 'list': from sets import Set list = Set() for line in open(exons_to_delete): list.add(line.strip()) The rest of the program stays the same, including the test 'if exon in list' You might want to use a different name for 'list' though. Kent At 09:16 AM 11/5/2004 -0500, Rich Krauter wrote: >import sys,string >WFILE=open(sys.argv[1], 'w') >def >deleteExons(fname2='Z:/datasets/altsplice1.fasta',exons_to_delete='Z:/datasets/Exonlist.txt'): > f = open(fname2) > f2 = open(exons_to_delete) > list = f2.readlines() > exon = None > for line in f: > if line.startswith('>'): > exon = line[1:].split('|')[0] > if exon in list: > continue > yield line > > >if __name__ == '__main__': > for line in deleteExons(): > print >> WFILE, line, > >exonlist is made from the last program you helped me with and consists >of single lines of exons > >altsplice1.fasta is 85583 kb >when I run the program it does not shrink the file at all, in fact >althought the first and last 40 lines appear to be the same, the >output file is larger than the original. > >It is a normal fast file: > > >ENSE00001383339.1|ENSG00000187908.1|ENST00000339871.1 >assembly=NCBI34|chr=10_NT > >_078087|strand=forward|bases 57203 to 57283|exons plus upstream and >downstream r >egions for exon >ACCCAGCAAAATGGGGATCTCCACAGTCATCCTTGAAATGTGTCTTTTATGGGGACAAGTTCTATCTACAGGTATTACGT >T > > >ENSE00001387275.1|ENSG00000187908.1|ENST00000339871.1 >assembly=NCBI34|chr=10_NT > >_078087|strand=forward|bases 72877 to 72981|exons plus upstream and >downstream r >egions for exon >GAGATGGCAGGTGTCAGGGCCGAGTGGAGATCCTATACCGAGGCTCCTGGGGCACCGTGTGTGATGACAGCTGGGACACC >AATGATGCCAACGTGGTCTGTAGGC > > >ENSE00001378578.1|ENSG00000187908.1|ENST00000339871.1 >assembly=NCBI34|chr=10_NT > >_078087|strand=forward|bases 82505 to 82835|exons plus upstream and >downstream r >egions for exon >CTGAATCCAGTTTGGCCCTGAGGCTGGTGAATGGAGGTGACAGGTGTCAGGGCCGAGTGGAGGTCCTATACCGAGGCTCC >TGGGGCACCGTGTGTGATGACAGCTGGGACACCAATGATGCCAATGTGGTCTGCAGGCAGCTGGGCTGTGGCTGGGCCAT >GTTGGCCCCAGGAAATGCCCGGTTTGGTCAGGGCTCAGGACCCATTGTCCTGGATGACGTGCGCTGCTCAGGGAATGAGT >CCTACTTGTGGAGCTGCCCCCACAATGGCTGGCTCTCCCATAACTGTGGCCATAGTGAAGACGCTGGTGTCATCTGCTCA >GGTGGGCCTCC > > >ENSE00001379544.1|ENSG00000187908.1|ENST00000339871.1 >assembly=NCBI34|chr=10_NT > >_078087|strand=forward|bases 88623 to 89087|exons plus upstream and >downstream r >egions for exon > >Any thoughts? > >Scott >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From ps_python at yahoo.com Fri Nov 5 17:34:15 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Nov 5 17:34:18 2004 Subject: [Tutor] Iterating over columns in a tab-delimited text and writing SQL statements Message-ID: <20041105163415.45123.qmail@web53707.mail.yahoo.com> Dear group, I have a file with ~200 Columns and 20,000 rows. Every column designates a patient sample. Each such patient sample data should be made as an experiment in my database. So, I have to write SQL insert statements on these. My data resembles likes this in its simplest form: Gene Name probe_name AL21 AL11 AL12 xyz 1000_at 272.3 345.2 -32.45 abc 1001_at 134.4 45.3 342.59 ............................................... up to 20K rows. Now I want to create an sql statement like the following: INSERT into expression (gene_name,probe_name,sample, exprs) VALUES ('xyz', '1000_at','AL21',272.3) import string >>> from string import split >>> f1 = open('insert_test.txt','r') >>> lines = f1.read() >>> rows = split(lines,'\n') >>> rows ['Gene Name\tprobe_name\tAL10\tAL21\tAL23', 'xyz\t1000_at\t272.3\t345.2\t-32.45', 'abc\t1001_at\t134.4\t45.3\t342.59', ''] >>> f2 = open('sql.txt','w') >>> for i in range(len(lst1)): cols = split(lst1[i],'\t') f2.write('(INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES('+cols[0]+','+cols[1]+','+sample+','+cols[2]+ ')''\n') Traceback (most recent call last): File "", line 3, in -toplevel- f2.write('(INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES('+cols[0]+','+cols[1]+','+sample+','+cols[2]+ ')''\n') IndexError: list index out of range >>> f2.close() Result from sql.txt: (INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES(Gene Name,probe_name,AL21,AL10) (INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES(xyz,1000_at,AL21,272.3) (INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES(abc,1001_at,AL21,134.4) My problem: I am unable to write a function that will take my matrix and write statements for every sample such as AL21, AL11,AL12. I know I am not good at looping over columns here. Take column 3 first and column 4 and then column 5 like that... However column 1 and 2 remains same for every sample, because they are common for evert sample column. Something like: (INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES(Gene Name,probe_name,AL21,AL10) (INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES(xyz,1000_at,AL21,272.3) (INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES(abc,1001_at,AL21,134.4) (INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES(xyz,1000_at,AL11,345.2) (INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES(abc,1001_at,AL11,45.3) (INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES(xyz,1000_at,AL12,-32.5) (INSERT INTO expr(gene_name,probe_name,sample,expr) VALUES(abc,1001_at,AL12,345.59) 2. Also why am I getting INdex out of range , IndexError: ? I have no explanation to it. Can any one please help me. Thank you. Kumar. __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From hugonz-lists at h-lab.net Fri Nov 5 18:17:12 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri Nov 5 18:17:15 2004 Subject: [Tutor] Taking over a program Message-ID: <418BB598.1070806@h-lab.net> Hi Tutors, I'm trying to "take over" a program on the console, that is... write a program, get it to run on its own up to a certain point, and then start writing python statements in the console, keeping the variables and program flow. Can it be done? This is basically for doing "what if" without having to write the whole program in the console... Thanks for your help, Hugo From kent_johnson at skillsoft.com Fri Nov 5 19:03:44 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Nov 5 19:06:26 2004 Subject: [Tutor] Taking over a program In-Reply-To: <418BB598.1070806@h-lab.net> References: <418BB598.1070806@h-lab.net> Message-ID: <6.1.0.6.0.20041105130213.029049f8@mail4.skillsoft.com> It sounds like you want the -i switch to the interpreter. If you type > python -i myprogram.py Python will run myprogram.py normally, but when myprogram finishes, you will get an interpreter prompt and all the names from myprogram will be available. Kent At 11:17 AM 11/5/2004 -0600, Hugo Gonz?lez Monteverde wrote: >Hi Tutors, > >I'm trying to "take over" a program on the console, that is... write a >program, get it to run on its own up to a certain point, and then start >writing python statements in the console, keeping the variables and >program flow. Can it be done? > >This is basically for doing "what if" without having to write the whole >program in the console... > >Thanks for your help, > >Hugo >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From flaxeater at yahoo.com Fri Nov 5 19:07:01 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Nov 5 19:12:41 2004 Subject: [Tutor] Class mind boggle Message-ID: <20041105180701.261.qmail@web54304.mail.yahoo.com> Liam Clarke wrote: >Hello all, > > > >I have a little prog I'm writing, and I'm creating a GUI with PythonCard. > >The actual functions accessed by the GUI are in a separate module. > > > >Now, I would like to call a dialog box if needed in one of the > >separate functions, if a password is wrong, get it via a nice little > >pop-up. > > Ok here's an example from one of my projects. results=dialog.colorDialog(self) if results.accepted: if DEBUG: print 'Accepted' self.displayColorValues(results.color) self.setMemory(results.color) I hope this helps. I don't think it's quite as bad as you think. def getPassword(self): get the password if password==isgood: then do stuff: else: self.results=dialog.textEntryDialog(self, 'Enter Password, now the self in this psuedo code means you can access this information outside of the function. 'Uhoh' , 'Python') __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From jerimed at myrealbox.com Fri Nov 5 19:35:53 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Fri Nov 5 19:39:46 2004 Subject: [Tutor] Function problem Message-ID: <418BC809.1030500@myrealbox.com> Hello All, First off, thanks again to all who answered my loop problem Re: 'IndexError....'. I got it understood now. The problem of my script below is in the proceed function: if Y is selected, instead of staying in the option menu, the program just shows the option menu then exits. ditto in the 'really quit program' prompt: i expect to go to main menu if i select N but again program exits. can you guys point me to my error? this is just a simple script but it took me some time to figure out on my own; its a good learning exercise nevertheless. what to do to improve the program further, e.g., make it simple but efficient? i love to hear your good advise. #!/usr/bin/env python # filename: tempConvert.py # description: temperature conversion program # Author: Eri Mendz # Fri Nov 5 13:53:16 AST 2004 import sys def print_options(): print ''' THIS IS A TEMPERATURE CONVERSION PROGRAM. Options: [C] - convert to Celsius [F] - convert to Fahrenheit [P] - print options [Q] - quit ''' print_options() def f2c(ctemp): return (9/5.0)*ctemp + 32 def c2f(ftemp): return (ftemp - 32) * 5/9.0 def proceed(): proceed = raw_input("do another conversion? [Y|N]: ") if proceed == 'y' or proceed =='Y': print_options() else: confirmQuit() def confirmQuit(): ask = raw_input("Really quit program? [Y|N]: ") if ask == 'y' or ask == 'Y' or ask == 'ye' or ask == 'yes': sys.exit("bye") else: print_options() # begin while 1: choice = raw_input("select options: ") if choice == 'c' or choice == 'C': try: getftemp = int(raw_input("enter fahrenheit temperature: ")) print "temp in C is: ", c2f(getftemp) proceed() except ValueError: print "error: not a valid input!" break elif choice == 'f' or choice == 'F': try: getctemp = int(raw_input("enter centigrade temperature: ")) print "temp in F is: ", f2c(getctemp) proceed() except ValueError: print "error: not a valid input!" break elif choice =='p' or choice == 'P': print_options() elif choice =='q' or choice == 'Q': confirmQuit() else: print "invalid option" print "bye" From mhansen at cso.atmel.com Fri Nov 5 21:13:50 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri Nov 5 21:13:54 2004 Subject: [Tutor] maintaining state in a web app Message-ID: <418BDEFE.40802@cso.atmel.com> Can anyone recommend any books/web-sites that discuss maintaining state in a web application? Various methods and pros/cons to each method. Cookies, form Vaiables, ??? ... The material can be Python specific or language neutral. Thanks, Mike From aicolburn at hotmail.com Fri Nov 5 21:30:15 2004 From: aicolburn at hotmail.com (Alan Colburn) Date: Fri Nov 5 21:31:05 2004 Subject: [Tutor] Adding Text to the Beginning of a File Message-ID: Hi all -- Can anyone offer me a suggestion for how to add text to the beginning of a file? I know that file.seek(0) takes me to the beginning of the file, but file.write() ultimately still adds new strings to the end of the file. (The file is opened in a+ mode...) As always, thanks ahead of time for your help. --Al C (aicolburn@yahoo.com) _________________________________________________________________ Get ready for school! Find articles, homework help and more in the Back to School Guide! http://special.msn.com/network/04backtoschool.armx From dyoo at hkn.eecs.berkeley.edu Fri Nov 5 21:55:19 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 5 21:55:23 2004 Subject: [Tutor] Function problem In-Reply-To: <418BC809.1030500@myrealbox.com> Message-ID: On Fri, 5 Nov 2004, Eri Mendz wrote: > The problem of my script below is in the proceed function: if Y is > selected, instead of staying in the option menu, the program just shows > the option menu then exits. Hi Eri, Ah! Check the 'break' statements in the main loop of the program: > choice = raw_input("select options: ") > if choice == 'c' or choice == 'C': > try: > getftemp = int(raw_input("enter fahrenheit temperature: ")) > print "temp in C is: ", c2f(getftemp) > proceed() > except ValueError: > print "error: not a valid input!" > break > elif choice == 'f' or choice == 'F': > try: > getctemp = int(raw_input("enter centigrade temperature: ")) > print "temp in F is: ", f2c(getctemp) > proceed() > except ValueError: > print "error: not a valid input!" > break The breaks cause us to jump out of the while loop if either temperature choice gets selected. I'm guessing that you're using a C switch statement idiom. But since that idiom isn't applicable in Python, you should just drop them. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Fri Nov 5 22:02:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 5 22:02:24 2004 Subject: [Tutor] Adding Text to the Beginning of a File In-Reply-To: Message-ID: On Fri, 5 Nov 2004, Alan Colburn wrote: > Can anyone offer me a suggestion for how to add text to the beginning of > a file? Hi Alan, The simplest approach I'd recommend is to not do that. *grin* Files act very much like VCR tapes sometimes: they don't make it very easy to splice new content at the beginning. Instead, you can take a slightly different approach: you can open a new file, write your text, and then write the content of your old file. The new file ends up having the content that you want. You can then rename the old file out of the way, and then rename the new file in its place. Would that work for you? Good luck! From jeff at ccvcorp.com Fri Nov 5 22:09:15 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Nov 5 22:06:19 2004 Subject: [Tutor] Adding Text to the Beginning of a File In-Reply-To: References: Message-ID: <418BEBFB.7080801@ccvcorp.com> Alan Colburn wrote: > Hi all -- > > Can anyone offer me a suggestion for how to add text > to the beginning of a file? I know that file.seek(0) > takes me to the beginning of the file, but > file.write() ultimately still adds new strings to the > end of the file. (The file is opened in a+ mode...) Even if you did get write() to start writing at the beginning of the file, it would (as I understand it) simply overwrite the existing data. AFAIK, the only good way to add text to the beginning of a file is to read the entire file in, make modifications to the text in-memory, and then write the entire file out again (presumably to the same filename). Jeff Shannon Technician/Programmer Credit International From mark.kels at gmail.com Fri Nov 5 23:00:04 2004 From: mark.kels at gmail.com (Mark Kels) Date: Fri Nov 5 23:00:12 2004 Subject: [Tutor] CGI problem. Message-ID: Hi, I made a CGI script, that checks if the user entered a vaild pass (that should be in "pass.txt"). Here is what I did: import cgi import cgitb; cgitb.enable() form = cgi.FieldStorage() x=open("pass.txt","r") form.getfirst("pass") print "Content-type: text/html\n\n" def printhtml(): print """

""" def checkpass(): a=x.readline() if a==form.getfirst("pass"): print "OK, come in." else: print "Wrong password, try again! " printhtml() checkpass() x.close() The problem is that when the page opens it writes "Wrong password, try again! ", and the user dont get a chance to write the password first. what can I do so that it will work like it shold (first get the password, and only then say if its good or not). I know (or at least hope) that there is a very simple solution for this problem, but cant find it by myself... Thanks!! From dactex at swbell.net Fri Nov 5 23:36:42 2004 From: dactex at swbell.net (David Carter) Date: Fri Nov 5 23:36:47 2004 Subject: [Tutor] sys.path contains a nonexistent zip file Message-ID: <000001c4c387$ecfa1470$2800005a@gobot> When I import sys and examine the value of sys.path, sys.path in my Python 2.3.3 installation contains 'D:\\WINNT\\system32\\python23.zip'. This file does not exist. Does anyone how to remove it more or less permanently from the sys.path? I've tried examing and editing the PythonPath from within Mark Hammond's PythonWin, but that value doesn't seem to show up in the "Browse PythonPath" or "Edit PythonPath" Tools. It's not hurting anything being there (as far as I know), I just want the path to be clean of extraneous material, so to speak. David Carter -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041105/6cf5b27b/attachment.htm From kent_johnson at skillsoft.com Sat Nov 6 00:44:47 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Nov 6 00:44:57 2004 Subject: [Tutor] gettext mystery In-Reply-To: <20041105000558.1c9bfa89.klappnase@freenet.de> References: <20041104121457.456b11b4.klappnase@freenet.de> <6.1.0.6.0.20041104120317.02b13530@mail4.skillsoft.com> <20041105000558.1c9bfa89.klappnase@freenet.de> Message-ID: <6.1.0.6.0.20041105184241.02b30548@mail4.skillsoft.com> I don't know why you get a different gettext depending on when you import it...maybe something is being added to sys.path? You might be able to get it to work by deleting the gtk-1.2/gettext.py so all imports find the standard version. If the newer one is backwards compatible I think this will work. Kent At 12:05 AM 11/5/2004 +0100, Michael Lange wrote: >On Thu, 04 Nov 2004 12:04:15 -0500 >Kent Johnson wrote: > > > If you print gettext.__file__ it will show you where it was loaded > from. If > > you are loading two different modules that will show them you you. > > > > Kent > > >Thanks, Kent > >that's it; version 1: > >[pingu@localhost pingu]$ moleskine >/usr/lib/python2.2/site-packages/gtk-1.2/gettext.py > >version 2: > >[pingu@localhost pingu]$ moleskine >/usr/lib/python2.2/gettext.pyc > >a simple RPM request shows that the (here) first gettext module is from my >pygnome install. > >I wonder now if there is a way to force the import of the standard library >module instead >of pygnome's, which looks like it might be an outdated version of the >standard library gettext.py . >I tried to change sys.path and found that it actually worked to do a >sys.path.sort() before >importing gettext, but this doesn't look to me like it's the way it should >be done. > >What's the recommended way to change the order of the module search path. > >Thanks for any hints > >Michael > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From inkedmn at gmail.com Sat Nov 6 00:58:25 2004 From: inkedmn at gmail.com (Brett Kelly) Date: Sat Nov 6 00:58:37 2004 Subject: [Tutor] Iterating over columns in a tab-delimited text and writing SQL statements In-Reply-To: References: <20041105163415.45123.qmail@web53707.mail.yahoo.com> Message-ID: ---------- Forwarded message ---------- From: Brett Kelly Date: Fri, 5 Nov 2004 12:48:40 -0800 Subject: Re: [Tutor] Iterating over columns in a tab-delimited text and writing SQL statements To: kumar s Hacked this together, hoping i understand your problem correctly: ------------------------------------------ data file to be read: foo bar baz blarg 1 2 3 "stuff" 4 5 6 "morestuff" ----------------------------------------- python code: # read data and create sql sqlbase = """ insert into mytable (%s) values (%s) """ fd = file("somedata.txt").readlines() cols = fd[0].split() # column names colstr = ','.join(cols) # formatted string that will plug in nicely sqlresult = file("somesql.txt", 'w') # output for r in fd[1:]: # loop through everything after first line vals = r.split() # split at whitespace valstr = ','.join(vals) # join with commas for sql sqlresult.write(sqlbase % (colstr, valstr)) # write to file sqlresult.close() print "done" ---------------------------------- result file: insert into mytable (foo,bar,baz,blarg) values (1,2,3,"stuff") insert into mytable (foo,bar,baz,blarg) values (4,5,6,"morestuff") ------------------------------------ Is that what you're after? Brett On Fri, 5 Nov 2004 08:34:15 -0800 (PST), kumar s wrote: > Dear group, > I have a file with ~200 Columns and 20,000 rows. > > Every column designates a patient sample. Each such > patient sample data should be made as an experiment in > my database. So, > I have to write SQL insert statements on these. > > My data resembles likes this in its simplest form: > > Gene Name probe_name AL21 AL11 AL12 > xyz 1000_at 272.3 345.2 -32.45 > abc 1001_at 134.4 45.3 342.59 > ............................................... > > up to 20K rows. > > Now I want to create an sql statement like the > following: > > INSERT into expression (gene_name,probe_name,sample, > exprs) VALUES ('xyz', '1000_at','AL21',272.3) > > import string > >>> from string import split > >>> f1 = open('insert_test.txt','r') > >>> lines = f1.read() > >>> rows = split(lines,'\n') > >>> rows > ['Gene Name\tprobe_name\tAL10\tAL21\tAL23', > 'xyz\t1000_at\t272.3\t345.2\t-32.45', > 'abc\t1001_at\t134.4\t45.3\t342.59', ''] > >>> f2 = open('sql.txt','w') > >>> for i in range(len(lst1)): > cols = split(lst1[i],'\t') > f2.write('(INSERT INTO > expr(gene_name,probe_name,sample,expr) > VALUES('+cols[0]+','+cols[1]+','+sample+','+cols[2]+ > ')''\n') > > Traceback (most recent call last): > File "", line 3, in -toplevel- > f2.write('(INSERT INTO > expr(gene_name,probe_name,sample,expr) > VALUES('+cols[0]+','+cols[1]+','+sample+','+cols[2]+ > ')''\n') > IndexError: list index out of range > >>> f2.close() > > Result from sql.txt: > > (INSERT INTO expr(gene_name,probe_name,sample,expr) > VALUES(Gene Name,probe_name,AL21,AL10) > (INSERT INTO expr(gene_name,probe_name,sample,expr) > VALUES(xyz,1000_at,AL21,272.3) > (INSERT INTO expr(gene_name,probe_name,sample,expr) > VALUES(abc,1001_at,AL21,134.4) > > My problem: > > I am unable to write a function that will take my > matrix and write statements for every sample such as > AL21, AL11,AL12. > > I know I am not good at looping over columns here. > Take column 3 first and column 4 and then column 5 > like that... However > column 1 and 2 remains same for every sample, because > they are common for evert sample column. > Something like: > > (INSERT INTO expr(gene_name,probe_name,sample,expr) > VALUES(Gene Name,probe_name,AL21,AL10) > (INSERT INTO expr(gene_name,probe_name,sample,expr) > VALUES(xyz,1000_at,AL21,272.3) > (INSERT INTO expr(gene_name,probe_name,sample,expr) > VALUES(abc,1001_at,AL21,134.4) > > (INSERT INTO expr(gene_name,probe_name,sample,expr) > VALUES(xyz,1000_at,AL11,345.2) > (INSERT INTO expr(gene_name,probe_name,sample,expr) > VALUES(abc,1001_at,AL11,45.3) > > (INSERT INTO expr(gene_name,probe_name,sample,expr) > VALUES(xyz,1000_at,AL12,-32.5) > (INSERT INTO expr(gene_name,probe_name,sample,expr) > VALUES(abc,1001_at,AL12,345.59) > > 2. Also why am I getting INdex out of range , > IndexError: ? I have no explanation to it. > > Can any one please help me. > > Thank you. > > Kumar. > > __________________________________ > Do you Yahoo!? > Check out the new Yahoo! Front Page. > www.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Brett Kelly http://inkedmn.com:8000 -- Brett Kelly http://inkedmn.com:8000 From kp8 at mac.com Sat Nov 6 02:32:45 2004 From: kp8 at mac.com (kevin parks) Date: Sat Nov 6 02:33:01 2004 Subject: [Tutor] help with splot & 3d data Message-ID: hi Python heads! i have some data that would like to plot with Gnuplot-py and need to get a little fancier than i am used to. I have data that looks like: 0 5.5 0 1 2 5.5 2 4 4 5.5 4 2 6 5.5 5 3 8 5.5 7 1 10 5.5 9 4 12 5.5 11 3 14 5.5 0 2 16 5.5 2 1 18 5.5 4 4 20 5.5 5 3 The first number is the start time of the event. The second is the duration. The third is the event identifier and the last is what stream it belongs to. I would like to use splot and points of different colors to convey as much info as i can. The X axis would be the time axis (that would take care of the first two parameters) and the Y axis could be the third column. Then for the fouth item, there are only four possibilities (1, 2, 3, or 4), so i thought that i could use points of red, blue, green, black to indicate that. So that is where i am headed... But i have a long way to go and am a gnuplot novice and not a great Python hacker to boot.. Could anyone help me along? I would be grateful for any help. Cheers, kevin Here is some (*gasp*) code. ------------ [snip] ---------------- #! /usr/bin/env python from Numeric import * import Gnuplot, Gnuplot.funcutils def main(): all = [ [ 0, 5.5, 0, 1 ], [ 2, 5.5, 2, 4 ], [ 4, 5.5, 4, 2 ], [ 6, 5.5, 5, 3 ], [ 8, 5.5, 7, 1 ], [ 10, 5.5, 9, 4 ], [ 12, 5.5, 11, 3 ], [ 14, 5.5, 0, 2 ], [ 16, 5.5, 2, 1 ], [ 18, 5.5, 4, 4 ], [ 20, 5.5, 5, 3 ], [ 22, 5.5, 7, 2 ], [ 24, 5.5, 9, 1 ], [ 26, 5.5, 11, 4 ], [ 28, 5.5, 0, 3 ], [ 30, 5.5, 2, 2 ], [ 32, 5.5, 4, 1 ], [ 34, 5.5, 5, 3 ], [ 36, 5.5, 7, 4 ], [ 38, 5.5, 9, 2 ], [ 40, 5.5, 11, 3 ], [ 42, 5.5, 0, 4 ], [ 44, 5.5, 2, 1 ], [ 46, 5.5, 4, 2 ], [ 48, 5.5, 5, 4 ], [ 50, 5.5, 7, 3 ], [ 52, 5.5, 9, 1 ], [ 54, 5.5, 11, 2 ], [ 56, 5.5, 0, 4 ], [ 58, 5.5, 2, 1 ], [ 60, 5.5, 4, 3 ], [ 62, 5.5, 5, 2 ], [ 64, 5.5, 7, 4 ], [ 66, 5.5, 9, 3 ], [ 68, 5.5, 9, 1 ], [ 70, 5.5, 0, 2 ], [ 72, 5.5, 2, 4 ], [ 74, 5.5, 4, 1 ], [ 76, 5.5, 5, 2 ], [ 78, 5.5, 7, 3 ], [ 80, 5.5, 9, 4 ], [ 82, 11.5, 11, 2 ], [ 84, 5.5, 0, 1 ], [ 86, 5.5, 2, 3 ], [ 88, 7.5, 4, 4 ], [ 90, 11.5, 5, 1 ], [ 92, 5.5, 7, 3 ], [ 94, 3.5, 9, 2 ], [ 96, 7.5, 11, 4 ], [ 98, 7.5, 0, 2 ], [ 100, 11.5, 2, 3 ], [ 102, 5.5, 4, 1 ], [ 104, 7.5, 5, 4 ], [ 106, 11.5, 7, 2 ], [ 108, 5.5, 9, 1 ], [ 110, 5.5, 11, 3 ], [ 112, 8.5, 0, 4 ], [ 114, 5.5, 2, 1 ], [ 116, 5.5, 4, 3 ], [ 118, 5.5, 5, 2 ], [ 120, 9.5, 7, 1 ], [ 122, 3.5, 9, 4 ], [ 124, 3.5, 11, 2 ], [ 126, 5.5, 0, 3 ], [ 128, 5.5, 2, 2 ], [ 130, 5.5, 4, 1 ], [ 132, 5.5, 5, 3 ], [ 134, 10, 7, 2 ], [ 136, 8, 9, 4 ], [ 138, 6, 11, 1 ], [ 140, 4, 0, 3 ] ] g = Gnuplot.Gnuplot(debug=1) g.title('REALLY COOL GRAPH') # (optional) g.xlabel('Start Time') g.ylabel('Duration') g('set data style linespoints') # give gnuplot an arbitrary command # Plot a list of (x, y) pairs (tuples or a Numeric array would # also be OK): #g.plot([[0,1.1], [1,5.8], [2,3.3], [3,4.2]]) g.plot(all) raw_input('Please press return to continue...\n') g.reset() # -- --------------- print '############### test splot ##################################' #g.splot(Gnuplot.Data(all, with='linesp', inline=1,)) g.splot(Gnuplot.Data(all, using=(1,), with='points', inline=1,)) #g.plot(Gnuplot.Data(d, with='lp 4 4')) #g.plot(Gnuplot.Data(d, cols=(0,1), inline=0), #Gnuplot.Data(d, cols=(0,2), inline=0)) #g.plot(Gnuplot.Data(d, cols=(0,1), inline=1), #Gnuplot.Data(d, cols=(0,2), inline=1)) #g.splot(Gnuplot.Data(all, with='linesp', inline=1)) # when executed, just run main if __name__ == '__main__': main() ------------ [snip] ---------------- From flaxeater at yahoo.com Sat Nov 6 04:08:36 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sat Nov 6 04:08:39 2004 Subject: [Tutor] CGI problem. Message-ID: <20041106030836.38532.qmail@web54308.mail.yahoo.com> Ok I don't quite have all the information to give you a definitive answer but I believe this is your trouble. You are loading the file from the cgi script which is fine however you still check for the password every time whether or not it's the first time to run. so you need to check to see if it's empty or if it exists. Mark Kels wrote: >import cgi > >import cgitb; cgitb.enable() > >form = cgi.FieldStorage() > >x=open("pass.txt","r") > >form.getfirst("pass") > >print "Content-type: text/html\n\n" > >def printhtml(): > > print """ > > > >
> > """ > >def checkpass(): > > a=x.readline() > > > if form.has_key("pass"): > if a==form.getfirst("pass"): > > print "OK, come in." > > else: > > print "Wrong password, try again! " > > > > > >printhtml() > >checkpass() > >x.close() > > I think adding that line should make this script work. Or you could put than line right before the checkpass statement like if form.has_key("pass"): checkpass() Good luck __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From bgailer at alum.rpi.edu Sat Nov 6 04:35:17 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Nov 6 04:34:20 2004 Subject: [Tutor] Function problem In-Reply-To: <418BC809.1030500@myrealbox.com> References: <418BC809.1030500@myrealbox.com> Message-ID: <6.1.2.0.0.20041105203110.04a28190@mail.mric.net> At 11:35 AM 11/5/2004, Eri Mendz wrote: >Hello All, > >First off, thanks again to all who answered my loop problem Re: >'IndexError....'. I got it understood now. > >The problem of my script below is in the proceed function: if Y is >selected, instead of staying in the option menu, the program just shows >the option menu then exits. ditto in the 'really quit program' prompt: i >expect to go to main menu if i select N but again program exits. can you >guys point me to my error? this is just a simple script but it took me >some time to figure out on my own; its a good learning exercise nevertheless. > >what to do to improve the program further, e.g., make it simple but >efficient? i love to hear your good advise. > >#!/usr/bin/env python ># filename: tempConvert.py ># description: temperature conversion program ># Author: Eri Mendz ># Fri Nov 5 13:53:16 AST 2004 > >import sys > >def print_options(): > print ''' > THIS IS A TEMPERATURE CONVERSION PROGRAM. > Options: > [C] - convert to Celsius > [F] - convert to Fahrenheit > [P] - print options > [Q] - quit > ''' >print_options() > >def f2c(ctemp): > return (9/5.0)*ctemp + 32 > >def c2f(ftemp): > return (ftemp - 32) * 5/9.0 > >def proceed(): > proceed = raw_input("do another conversion? [Y|N]: ") > if proceed == 'y' or proceed =='Y': > print_options() > else: > confirmQuit() > >def confirmQuit(): > ask = raw_input("Really quit program? [Y|N]: ") > if ask == 'y' or ask == 'Y' or ask == 'ye' or ask == 'yes': > sys.exit("bye") > else: > print_options() > ># begin >while 1: > choice = raw_input("select options: ") > if choice == 'c' or choice == 'C': > try: > getftemp = int(raw_input("enter fahrenheit temperature: ")) > print "temp in C is: ", c2f(getftemp) > proceed() > except ValueError: > print "error: not a valid input!" > break > elif choice == 'f' or choice == 'F': > try: > getctemp = int(raw_input("enter centigrade temperature: ")) > print "temp in F is: ", f2c(getctemp) > proceed() > except ValueError: > print "error: not a valid input!" > break > elif choice =='p' or choice == 'P': > print_options() > elif choice =='q' or choice == 'Q': > confirmQuit() > else: > print "invalid option" > >print "bye" Since I enjoy OOP I thought I'd see what your program might look like using classes. Here's a cut at it: import sys class Menu: input_prompt = '' def prompt(self): print '[%s] - %s' % (self.__class__.__name__, self.menu_prompt) def act(self): if self.input_prompt: try: inp = raw_input(self.input_prompt) self.act_on_input(inp) except KeyboardInterrupt: pass class Numeric(Menu): def act_on_input(self, inp): try: inp = int(inp) print self.output_prompt % self.convert(inp) except ValueError: print 'Input must be numeric.' class Character(Menu): pass class C(Numeric): menu_prompt = 'convert to Celsius' input_prompt = 'enter fahrenheit temperature: ' output_prompt = 'temp in C is %s' def convert(self, ctemp): return (9/5.0)*ctemp + 32 class F(Numeric): menu_prompt = 'convert to Fahrenheit' input_prompt = 'enter centigrade temperature: ' output_prompt = 'temp in F is %s' def convert(self, ftemp): return (ftemp - 32) * 5/9.0 class P(Character): menu_prompt = 'print options' def act_on_input(self, inp): print_options() class Q(Character): menu_prompt = 'quit' input_prompt = 'Really quit program? [Y|N]: ' def act_on_input(self, inp): if 'YES'.startswith(inp.upper()): sys.exit("bye") else: print_options() menu = [C(), F(), P(), Q()] def print_options(): print ''' THIS IS A TEMPERATURE CONVERSION PROGRAM. Options: ''' for item in menu: item.prompt() print_options() while 1: choice = raw_input("select option: ").upper() for item in menu: if item.__class__.__name__ == choice: item.act() break else: print "invalid option" print "bye" What I like about this is that all the information for a choice is packaged in the class definition, and there is minimal redundant code. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From kent_johnson at skillsoft.com Sat Nov 6 06:33:21 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Nov 6 06:33:27 2004 Subject: [Tutor] Iterating over columns in a tab-delimited text and writing SQL statements In-Reply-To: <20041105163415.45123.qmail@web53707.mail.yahoo.com> References: <20041105163415.45123.qmail@web53707.mail.yahoo.com> Message-ID: <6.1.0.6.0.20041106002924.02ae3080@mail4.skillsoft.com> You need two nested loops to do this. zip() is also very handy, it lets you iterate two lists at the same time. I think this does what you want: f1 = open('GeneName.txt', 'r') header = f1.readline().split()[3:] for line in f1: data = line.split() for sample, expr in zip(header, data[2:]): sql = '''INSERT into expression (gene_name,probe_name,sample,exprs) VALUES ('%s', '%s', '%s', %s)''' % (data[0], data[1], sample, expr) print sql For your sample data, it prints INSERT into expression (gene_name,probe_name,sample,exprs) VALUES ('xyz', '1000_at', 'AL21', 272.3) INSERT into expression (gene_name,probe_name,sample,exprs) VALUES ('xyz', '1000_at', 'AL11', 345.2) INSERT into expression (gene_name,probe_name,sample,exprs) VALUES ('xyz', '1000_at', 'AL12', -32.45) INSERT into expression (gene_name,probe_name,sample,exprs) VALUES ('abc', '1001_at', 'AL21', 134.4) INSERT into expression (gene_name,probe_name,sample,exprs) VALUES ('abc', '1001_at', 'AL11', 45.3) INSERT into expression (gene_name,probe_name,sample,exprs) VALUES ('abc', '1001_at', 'AL12', 342.59) By the way, why not update the database directly instead of generating a file with ~4,000,000 insert statements? (OK, I can think of one reason - it may well be faster to execute the inserts in batches rather than one at a time...) Kent At 08:34 AM 11/5/2004 -0800, kumar s wrote: >Dear group, > I have a file with ~200 Columns and 20,000 rows. > >Every column designates a patient sample. Each such >patient sample data should be made as an experiment in >my database. So, >I have to write SQL insert statements on these. > >My data resembles likes this in its simplest form: > >Gene Name probe_name AL21 AL11 AL12 >xyz 1000_at 272.3 345.2 -32.45 >abc 1001_at 134.4 45.3 342.59 >............................................... > > >up to 20K rows. > > >Now I want to create an sql statement like the >following: > >INSERT into expression (gene_name,probe_name,sample, >exprs) VALUES ('xyz', '1000_at','AL21',272.3) > > > > > >import string > >>> from string import split > >>> f1 = open('insert_test.txt','r') > >>> lines = f1.read() > >>> rows = split(lines,'\n') > >>> rows >['Gene Name\tprobe_name\tAL10\tAL21\tAL23', >'xyz\t1000_at\t272.3\t345.2\t-32.45', >'abc\t1001_at\t134.4\t45.3\t342.59', ''] > >>> f2 = open('sql.txt','w') > >>> for i in range(len(lst1)): > cols = split(lst1[i],'\t') > f2.write('(INSERT INTO >expr(gene_name,probe_name,sample,expr) >VALUES('+cols[0]+','+cols[1]+','+sample+','+cols[2]+ >')''\n') > > > >Traceback (most recent call last): > File "", line 3, in -toplevel- > f2.write('(INSERT INTO >expr(gene_name,probe_name,sample,expr) >VALUES('+cols[0]+','+cols[1]+','+sample+','+cols[2]+ >')''\n') >IndexError: list index out of range > >>> f2.close() > >Result from sql.txt: > > >(INSERT INTO expr(gene_name,probe_name,sample,expr) >VALUES(Gene Name,probe_name,AL21,AL10) >(INSERT INTO expr(gene_name,probe_name,sample,expr) >VALUES(xyz,1000_at,AL21,272.3) >(INSERT INTO expr(gene_name,probe_name,sample,expr) >VALUES(abc,1001_at,AL21,134.4) > > > >My problem: > >I am unable to write a function that will take my >matrix and write statements for every sample such as >AL21, AL11,AL12. > >I know I am not good at looping over columns here. >Take column 3 first and column 4 and then column 5 >like that... However >column 1 and 2 remains same for every sample, because >they are common for evert sample column. >Something like: > >(INSERT INTO expr(gene_name,probe_name,sample,expr) >VALUES(Gene Name,probe_name,AL21,AL10) >(INSERT INTO expr(gene_name,probe_name,sample,expr) >VALUES(xyz,1000_at,AL21,272.3) >(INSERT INTO expr(gene_name,probe_name,sample,expr) >VALUES(abc,1001_at,AL21,134.4) > > >(INSERT INTO expr(gene_name,probe_name,sample,expr) >VALUES(xyz,1000_at,AL11,345.2) >(INSERT INTO expr(gene_name,probe_name,sample,expr) >VALUES(abc,1001_at,AL11,45.3) > >(INSERT INTO expr(gene_name,probe_name,sample,expr) >VALUES(xyz,1000_at,AL12,-32.5) >(INSERT INTO expr(gene_name,probe_name,sample,expr) >VALUES(abc,1001_at,AL12,345.59) > > > >2. Also why am I getting INdex out of range , >IndexError: ? I have no explanation to it. > > > > >Can any one please help me. > >Thank you. > >Kumar. > > > > > >__________________________________ >Do you Yahoo!? >Check out the new Yahoo! Front Page. >www.yahoo.com > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From rmkrauter at yahoo.com Sat Nov 6 06:52:22 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sat Nov 6 06:52:11 2004 Subject: [Fwd: Re: [Tutor] searching for data in one file from another] In-Reply-To: <6.1.0.6.0.20041105093234.02905608@mail4.skillsoft.com> References: <418B8B2A.2030304@yahoo.com> <6.1.0.6.0.20041105093234.02905608@mail4.skillsoft.com> Message-ID: <418C6696.2030605@yahoo.com> Kent Johnson wrote: > When you read f2 with readlines, the newlines are included in the lines. > So you will never get a match with the exon from f1. Also since you are > apparently doing many tests for membership in list, a set would probably > be faster. I suggest you try something like this to create 'list': > > from sets import Set > list = Set() > for line in open(exons_to_delete): > list.add(line.strip()) > > The rest of the program stays the same, including the test 'if exon in > list' > > You might want to use a different name for 'list' though. Kent, Thanks very much for the reply. Right on the money and within a few minutes, as usual. I'm starting to think you're an automated help system. The OP should find these suggestions helpful for cleaning up his code. Rich From jerimed at myrealbox.com Sat Nov 6 06:54:28 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Sat Nov 6 06:54:27 2004 Subject: [Tutor] Function problem In-Reply-To: References: Message-ID: On Fri, 5 Nov 2004, Danny Yoo wrote: > On Fri, 5 Nov 2004, Eri Mendz wrote: > >> The problem of my script below is in the proceed function: if Y is >> selected, instead of staying in the option menu, the program just shows >> the option menu then exits. > > Hi Eri, > > Ah! Check the 'break' statements in the main loop of the program: > > >> choice = raw_input("select options: ") >> if choice == 'c' or choice == 'C': >> try: >> getftemp = int(raw_input("enter fahrenheit temperature: ")) >> print "temp in C is: ", c2f(getftemp) >> proceed() >> except ValueError: >> print "error: not a valid input!" >> break >> elif choice == 'f' or choice == 'F': >> try: >> getctemp = int(raw_input("enter centigrade temperature: ")) >> print "temp in F is: ", f2c(getctemp) >> proceed() >> except ValueError: >> print "error: not a valid input!" >> break > > The breaks cause us to jump out of the while loop if either temperature > choice gets selected. > > I'm guessing that you're using a C switch statement idiom. But since that > idiom isn't applicable in Python, you should just drop them. > > Good luck to you! Hi Danny, I tried learning C++ few years back but didnt go too far. So does Perl and shell scripting, all on my own pace. Dunno if all mixed up in my head. Drop them as in not use break all together? I look over my code again without the break in the temperature conversion. -- Regards, Eri Mendz Using PC-Pine 4.61 From kent_johnson at skillsoft.com Sat Nov 6 07:12:26 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Nov 6 07:12:32 2004 Subject: [Fwd: Re: [Tutor] searching for data in one file from another] In-Reply-To: <418C6696.2030605@yahoo.com> References: <418B8B2A.2030304@yahoo.com> <6.1.0.6.0.20041105093234.02905608@mail4.skillsoft.com> <418C6696.2030605@yahoo.com> Message-ID: <6.1.0.6.0.20041106010851.02ae3840@mail4.skillsoft.com> At 12:52 AM 11/6/2004 -0500, Rich Krauter wrote: Kent, >Thanks very much for the reply. Right on the money and within a few >minutes, as usual. I'm starting to think you're an automated help system. >The OP should find these suggestions helpful for cleaning up his code. Just call me the Kent-bot! :-) From jerimed at myrealbox.com Sat Nov 6 10:26:28 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Sat Nov 6 10:26:37 2004 Subject: [Tutor] Function problem In-Reply-To: References: Message-ID: On Fri, 5 Nov 2004, Danny Yoo wrote: > > On Fri, 5 Nov 2004, Eri Mendz wrote: > >> The problem of my script below is in the proceed function: if Y is >> selected, instead of staying in the option menu, the program just shows >> the option menu then exits. [...] > The breaks cause us to jump out of the while loop if either temperature > choice gets selected. > > I'm guessing that you're using a C switch statement idiom. But since that > idiom isn't applicable in Python, you should just drop them. > Got it working now, thanks for the tip. Indeed the break keyword is the culprit. Here is the corrected code: import sys def print_options(): print ''' THIS IS A TEMPERATURE CONVERSION PROGRAM. Options: [C] - convert to Celsius [F] - convert to Fahrenheit [P] - print options [Q] - quit ''' print_options() def f2c(ctemp): return (9/5.0)*ctemp + 32 def c2f(ftemp): return (ftemp - 32) * 5/9.0 def proceed(): proceed = raw_input("do another conversion? [Y|N]: ") if proceed == 'y' or proceed =='Y': print_options() else: confirmQuit() def confirmQuit(): ask = raw_input("Really quit program? [Y|N]: ") if ask == 'y' or ask == 'Y' or ask == 'ye' or ask == 'yes': sys.exit("bye") else: print_options() # begin while 1: choice = raw_input("select options: ") if choice == 'c' or choice == 'C': try: getftemp = int(raw_input("enter fahrenheit temperature: ")) print "temp in C is: ", c2f(getftemp) proceed() except ValueError: print "error: not a valid input!" print_options() # new added: return to main menu # break elif choice == 'f' or choice == 'F': try: getctemp = int(raw_input("enter centigrade temperature: ")) print "temp in F is: ", f2c(getctemp) proceed() except ValueError: print "error: not a valid input!" print_options() # ditto # break elif choice =='p' or choice == 'P': print_options() elif choice =='q' or choice == 'Q': confirmQuit() else: print "invalid option" print_options() # ditto print "bye" How do i make the program accept decimal numbers, not just integers? Inputting the former is caught by the exception and i want to correct that. I also want to use regular expression for the Y|N portion; e.g., something like if ask == [Y|y|ye|yes] or ask == [N|n|no|nope]... to that effect. Any help is appreciated. -- Regards, Eri Mendz Using PC-Pine 4.61 From jerimed at myrealbox.com Sat Nov 6 10:44:36 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Sat Nov 6 10:44:35 2004 Subject: [Tutor] Function problem In-Reply-To: <6.1.2.0.0.20041105203110.04a28190@mail.mric.net> References: <418BC809.1030500@myrealbox.com> <6.1.2.0.0.20041105203110.04a28190@mail.mric.net> Message-ID: On Fri, 5 Nov 2004, Bob Gailer wrote: Hi Bob, Thanks for the advanced version of the program. I'm not into classes yet so pardon me if much of it is vague to me. Good study material nevertheless, thanks. -- Regards, Eri Mendz Using PC-Pine 4.61 >> [snip own post] > Since I enjoy OOP I thought I'd see what your program might look like using > classes. Here's a cut at it: > > import sys > class Menu: > input_prompt = '' > def prompt(self): > print '[%s] - %s' % (self.__class__.__name__, self.menu_prompt) > def act(self): > if self.input_prompt: > try: > inp = raw_input(self.input_prompt) > self.act_on_input(inp) > except KeyboardInterrupt: > pass > > class Numeric(Menu): > def act_on_input(self, inp): > try: > inp = int(inp) > print self.output_prompt % self.convert(inp) > except ValueError: > print 'Input must be numeric.' > > class Character(Menu): > pass > > class C(Numeric): > menu_prompt = 'convert to Celsius' > input_prompt = 'enter fahrenheit temperature: ' > output_prompt = 'temp in C is %s' > def convert(self, ctemp): > return (9/5.0)*ctemp + 32 > > class F(Numeric): > menu_prompt = 'convert to Fahrenheit' > input_prompt = 'enter centigrade temperature: ' > output_prompt = 'temp in F is %s' > def convert(self, ftemp): > return (ftemp - 32) * 5/9.0 > > class P(Character): > menu_prompt = 'print options' > def act_on_input(self, inp): > print_options() > > class Q(Character): > menu_prompt = 'quit' > input_prompt = 'Really quit program? [Y|N]: ' > def act_on_input(self, inp): > if 'YES'.startswith(inp.upper()): > sys.exit("bye") > else: > print_options() > > menu = [C(), F(), P(), Q()] > > def print_options(): > print ''' > THIS IS A TEMPERATURE CONVERSION PROGRAM. > Options: ''' > for item in menu: > item.prompt() > > print_options() > while 1: > choice = raw_input("select option: ").upper() > for item in menu: > if item.__class__.__name__ == choice: > item.act() > break > else: > print "invalid option" > print "bye" > > What I like about this is that all the information for a choice is packaged > in the class definition, and there is minimal redundant code. > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > > From kbond at free.fr Sat Nov 6 16:56:58 2004 From: kbond at free.fr (kbond) Date: Sat Nov 6 10:57:00 2004 Subject: [Tutor] urllib2 with a proxy Message-ID: <418CF44A.7040605@free.fr> hello, I am trying to get access an internet page using urllib2. I am able to do so form home where I do not have proxy but for some reason I am unable to do it form my company. I found many ressource on the internet explaining how to do it but I was unable to apply it to my contexte. The interesting thing is that I did manage to configure Firefox (my fovourite browser) so I guess I should have all the information to do it by script. I think I am doing something is the usage of "add_password". Could you please explain me what realm and host are? and how can I get them? You will find bellow my firefox configuration. It would be great If someone can help me to put all this together. Thank you for your help *Code* import urllib2 # set up authentication info authinfo = urllib2.HTTPDigestAuthHandler() #proxy_auth_handler.add_password('realm', 'host', 'username', 'password') authinfo.add_password(None, "http://google.com", 'userName', 'pwd') * * proxy_support = urllib2.ProxyHandler({"http" : "proxy:8080"}) # build a new opener that adds authentication and caching FTP handlers opener = urllib2.build_opener(proxy_support, authinfo,urllib2.CacheFTPHandler) # install it urllib2.install_opener(opener) f = urllib2.urlopen('http://google.com') buf = f.read() print buf f.close() *Error Message* Traceback (most recent call last): File "test.py", line 18, in ? f = urllib2.urlopen('http://google.com') File "E:\users\install\Python\lib\urllib2.py", line 129, in urlopen return _opener.open(url, data) File "E:\users\install\Python\lib\urllib2.py", line 326, in open '_open', req) File "E:\users\install\Python\lib\urllib2.py", line 306, in _call_chain result = func(*args) File "E:\users\install\Python\lib\urllib2.py", line 491, in lambda r, proxy=url, type=type, meth=self.proxy_open: \ File "E:\users\install\Python\lib\urllib2.py", line 498, in proxy_open if '@' in host: TypeError: iterable argument required *Firefox configuration* From kent_johnson at skillsoft.com Sat Nov 6 13:33:42 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Nov 6 13:33:51 2004 Subject: [Tutor] urllib2 with a proxy In-Reply-To: <418CF44A.7040605@free.fr> References: <418CF44A.7040605@free.fr> Message-ID: <6.1.0.6.0.20041106072427.02b3c940@mail4.skillsoft.com> I'm not familiar with this library but looking at your code and the docs I can make some guesses where the problem might be: - The second argument to ProxyHandler should be a complete URL, e.g. 'http://proxy:8080'. This is the cause of the exception you are seeing. - Try using a HTTPBasicAuthHandler instead of a HTTPDigestAuthHandler unless you are sure your proxy uses digest authentication - You should pass an instance of CacheFTPHandler to build_opener, not the class itself. In other words, pass CacheFTPHandler() with parentheses. HTH Kent At 10:56 AM 11/6/2004 -0500, kbond wrote: >hello, > >I am trying to get access an internet page using urllib2. I am able to do >so form home where I do not have proxy but for some reason I am unable to >do it form my company. > >I found many ressource on the internet explaining how to do it but I was >unable to apply it to my contexte. The interesting thing is that I did >manage to configure Firefox (my fovourite browser) so I guess I should >have all the information to do it by script. >I think I am doing something is the usage of "add_password". Could you >please explain me what realm and host are? and how can I get them? > >You will find bellow my firefox configuration. >It would be great If someone can help me to put all this together. >Thank you for your help > >*Code* >import urllib2 ># set up authentication info >authinfo = urllib2.HTTPDigestAuthHandler() >#proxy_auth_handler.add_password('realm', 'host', 'username', 'password') >authinfo.add_password(None, "http://google.com", 'userName', 'pwd') * * >proxy_support = urllib2.ProxyHandler({"http" : "proxy:8080"}) ># build a new opener that adds authentication and caching FTP handlers >opener = urllib2.build_opener(proxy_support, authinfo,urllib2.CacheFTPHandler) ># install it >urllib2.install_opener(opener) >f = urllib2.urlopen('http://google.com') >buf = f.read() >print buf >f.close() > >*Error Message* > >Traceback (most recent call last): > File "test.py", line 18, in ? > f = urllib2.urlopen('http://google.com') > File "E:\users\install\Python\lib\urllib2.py", line 129, in urlopen > return _opener.open(url, data) > File "E:\users\install\Python\lib\urllib2.py", line 326, in open > '_open', req) > File "E:\users\install\Python\lib\urllib2.py", line 306, in _call_chain > result = func(*args) > File "E:\users\install\Python\lib\urllib2.py", line 491, in > lambda r, proxy=url, type=type, meth=self.proxy_open: \ > File "E:\users\install\Python\lib\urllib2.py", line 498, in proxy_open > if '@' in host: >TypeError: iterable argument required > >*Firefox configuration* > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sat Nov 6 13:41:36 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Nov 6 13:41:43 2004 Subject: [Tutor] Iterating over columns in a tab-delimited text and writing SQL statements In-Reply-To: <6.1.0.6.0.20041106002924.02ae3080@mail4.skillsoft.com> References: <20041105163415.45123.qmail@web53707.mail.yahoo.com> <6.1.0.6.0.20041106002924.02ae3080@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041106073417.02b44c90@mail4.skillsoft.com> Oh, I forgot - my guess is the reason you get an IndexError is that you have a blank line in your file. I would check for the expected number of fields in each data line before processing it. I've modified my program below to do this. <...goes to change the program to check for short lines...> No, actually, I don't have to change my program. The semantics of slicing and zip() make it work fine for short lines. data[2:] just returns an empty list if len(data) <= 2 zip(header, []) also returns an empty list so the iteration over zip(header, data[2:]) is just empty when a data line is too short. For lines that are longer than 2 items but shorter than expected it will just use what is there. Kent At 12:33 AM 11/6/2004 -0500, Kent Johnson wrote: >You need two nested loops to do this. zip() is also very handy, it lets >you iterate two lists at the same time. I think this does what you want: > >f1 = open('GeneName.txt', 'r') >header = f1.readline().split()[3:] > >for line in f1: > data = line.split() > for sample, expr in zip(header, data[2:]): > sql = '''INSERT into expression (gene_name,probe_name,sample,exprs) > VALUES ('%s', '%s', '%s', %s)''' % (data[0], data[1], sample, > expr) > print sql > >For your sample data, it prints >INSERT into expression (gene_name,probe_name,sample,exprs) > VALUES ('xyz', '1000_at', 'AL21', 272.3) >INSERT into expression (gene_name,probe_name,sample,exprs) > VALUES ('xyz', '1000_at', 'AL11', 345.2) >INSERT into expression (gene_name,probe_name,sample,exprs) > VALUES ('xyz', '1000_at', 'AL12', -32.45) >INSERT into expression (gene_name,probe_name,sample,exprs) > VALUES ('abc', '1001_at', 'AL21', 134.4) >INSERT into expression (gene_name,probe_name,sample,exprs) > VALUES ('abc', '1001_at', 'AL11', 45.3) >INSERT into expression (gene_name,probe_name,sample,exprs) > VALUES ('abc', '1001_at', 'AL12', 342.59) From kent_johnson at skillsoft.com Sat Nov 6 13:43:36 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Nov 6 13:43:45 2004 Subject: [Tutor] Function problem In-Reply-To: References: Message-ID: <6.1.0.6.0.20041106074211.02b32b90@mail4.skillsoft.com> At 12:26 PM 11/6/2004 +0300, Eri Mendz wrote: > getftemp = int(raw_input("enter fahrenheit temperature: ")) > >How do i make the program accept decimal numbers, not just integers? Use float() instead of int() to convert the input value: getftemp = float(raw_input("enter fahrenheit temperature: ")) Kent From kent_johnson at skillsoft.com Sat Nov 6 14:03:26 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Nov 6 14:03:32 2004 Subject: [Tutor] Function problem In-Reply-To: References: Message-ID: <6.1.0.6.0.20041106075422.02b3c7f8@mail4.skillsoft.com> At 12:26 PM 11/6/2004 +0300, Eri Mendz wrote: >I also want to use regular expression for the Y|N portion; e.g., >something like if ask == [Y|y|ye|yes] or ask == [N|n|no|nope]... to that >effect. Any help is appreciated. import re yes = re.compile('y|ye|yes', re.IGNORECASE) if yes.match(ask): ... This will also match 'you' and 'yesterday', if you want to be stricter change the RE to '(y|ye|yes)$' By the way you might want to break out the handlers for C and F into separate functions, that would make your main loop more readable. And if you convert choice to upper or lower case (e.g. choice = choice.upper()) then you only have to test against one style of each character. Kent From kbond at free.fr Sat Nov 6 20:59:17 2004 From: kbond at free.fr (kbond) Date: Sat Nov 6 14:59:19 2004 Subject: [Tutor] urllib2 with a proxy In-Reply-To: <6.1.0.6.0.20041106072427.02b3c940@mail4.skillsoft.com> References: <418CF44A.7040605@free.fr> <6.1.0.6.0.20041106072427.02b3c940@mail4.skillsoft.com> Message-ID: <418D2D15.8030006@free.fr> Thank you for your help kent. Already the second time that you are helping me. In fact I face this proxy trouble right after your first answer I was about to try your suggestion to solve the clientForm trouble when this proxy came into the danse. :-) When I started my project I was far to imagine that talking to the world wide web was that difficult by script. Unfortunatly I will not be able to test before monday because I do not use a proxy at home. Do you have an idea of what are realm and host in the add_password() method? I am making the assomption that host stand for the host I want to contact but I do not have any idea of what realm is? Do you know how I can get it? Why firefox don't need this information to go out? You will find below the code I will try on monday. Thank you for your help *Code* import urllib2 # set up authentication info authinfo = urllib2.HTTPBasicAuthHandler() #add_password('realm', 'host', 'username', 'password') authinfo.add_password(None, "http://google.com", 'userName', 'pwd') proxy_support = urllib2.ProxyHandler({"http" : "http//:proxy:8080"}) # build a new opener that adds authentication and caching FTP handlers opener = urllib2.build_opener(proxy_support, authinfo,urllib2.CacheFTPHandler()) # install it urllib2.install_opener(opener) f = urllib2.urlopen('http://google.com') buf = f.read() print buf f.close() Kent Johnson wrote: > I'm not familiar with this library but looking at your code and the > docs I can make some guesses where the problem might be: > - The second argument to ProxyHandler should be a complete URL, e.g. > 'http://proxy:8080'. This is the cause of the exception you are seeing. > - Try using a HTTPBasicAuthHandler instead of a HTTPDigestAuthHandler > unless you are sure your proxy uses digest authentication > - You should pass an instance of CacheFTPHandler to build_opener, not > the class itself. In other words, pass CacheFTPHandler() with > parentheses. > > HTH > Kent > > At 10:56 AM 11/6/2004 -0500, kbond wrote: > >> hello, >> >> I am trying to get access an internet page using urllib2. I am able >> to do so form home where I do not have proxy but for some reason I am >> unable to do it form my company. >> >> I found many ressource on the internet explaining how to do it but I >> was unable to apply it to my contexte. The interesting thing is that >> I did manage to configure Firefox (my fovourite browser) so I guess >> I should have all the information to do it by script. >> I think I am doing something is the usage of "add_password". Could >> you please explain me what realm and host are? and how can I get them? >> >> You will find bellow my firefox configuration. >> It would be great If someone can help me to put all this together. >> Thank you for your help >> >> *Code* >> import urllib2 >> # set up authentication info >> authinfo = urllib2.HTTPDigestAuthHandler() >> #proxy_auth_handler.add_password('realm', 'host', 'username', >> 'password') >> authinfo.add_password(None, "http://google.com", 'userName', 'pwd') * * >> proxy_support = urllib2.ProxyHandler({"http" : "proxy:8080"}) >> # build a new opener that adds authentication and caching FTP handlers >> opener = urllib2.build_opener(proxy_support, >> authinfo,urllib2.CacheFTPHandler) >> # install it >> urllib2.install_opener(opener) >> f = urllib2.urlopen('http://google.com') >> buf = f.read() >> print buf >> f.close() >> >> *Error Message* >> >> Traceback (most recent call last): >> File "test.py", line 18, in ? >> f = urllib2.urlopen('http://google.com') >> File "E:\users\install\Python\lib\urllib2.py", line 129, in urlopen >> return _opener.open(url, data) >> File "E:\users\install\Python\lib\urllib2.py", line 326, in open >> '_open', req) >> File "E:\users\install\Python\lib\urllib2.py", line 306, in _call_chain >> result = func(*args) >> File "E:\users\install\Python\lib\urllib2.py", line 491, in >> lambda r, proxy=url, type=type, meth=self.proxy_open: \ >> File "E:\users\install\Python\lib\urllib2.py", line 498, in proxy_open >> if '@' in host: >> TypeError: iterable argument required >> >> *Firefox configuration* >> >> >> _______________________________________________ >> 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 kent_johnson at skillsoft.com Sat Nov 6 16:59:53 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Nov 6 17:00:01 2004 Subject: [Tutor] help with splot & 3d data In-Reply-To: References: Message-ID: <6.1.0.6.0.20041106104259.02ad9e00@mail4.skillsoft.com> Well, this was quite a learning experience. Mostly I learned that gnuplot is not going to make it to my list of favorite tools...although to be fair, it did get the job done and it didn't take a lot of code to do it...it just took a long time to figure out the code, and it wasn't much fun. Anyway...I don't think you want to use splot(), you only have two dimensions in your data - time and event. The other two variables are shown as delta-time and color. So just plain plot() does the job. The 'vector' line style draws line segments from a start location to an end location. They are specified as x, y, xdelta, ydelta. By looking at the arrowstyle demo I learned how to make the vectors draw as intervals - lines with little crossbars on each end - which seemed appropriate. I divided the dataset into four and drew each one in a different line type. That makes them draw in different colors. Anyway, here is the code, I hope it does what you want! Kent import Gnuplot def main(): all = [ [ 0, 5.5, 0, 1 ], [ 2, 5.5, 2, 4 ], [ 4, 5.5, 4, 2 ], [ 6, 5.5, 5, 3 ], [ 8, 5.5, 7, 1 ], [ 10, 5.5, 9, 4 ], [ 12, 5.5, 11, 3 ], [ 14, 5.5, 0, 2 ], [ 16, 5.5, 2, 1 ], [ 18, 5.5, 4, 4 ], [ 20, 5.5, 5, 3 ], [ 22, 5.5, 7, 2 ], [ 24, 5.5, 9, 1 ], [ 26, 5.5, 11, 4 ], [ 28, 5.5, 0, 3 ], [ 30, 5.5, 2, 2 ], [ 32, 5.5, 4, 1 ], [ 34, 5.5, 5, 3 ], [ 36, 5.5, 7, 4 ], [ 38, 5.5, 9, 2 ], [ 40, 5.5, 11, 3 ], [ 42, 5.5, 0, 4 ], [ 44, 5.5, 2, 1 ], [ 46, 5.5, 4, 2 ], [ 48, 5.5, 5, 4 ], [ 50, 5.5, 7, 3 ], [ 52, 5.5, 9, 1 ], [ 54, 5.5, 11, 2 ], [ 56, 5.5, 0, 4 ], [ 58, 5.5, 2, 1 ], [ 60, 5.5, 4, 3 ], [ 62, 5.5, 5, 2 ], [ 64, 5.5, 7, 4 ], [ 66, 5.5, 9, 3 ], [ 68, 5.5, 9, 1 ], [ 70, 5.5, 0, 2 ], [ 72, 5.5, 2, 4 ], [ 74, 5.5, 4, 1 ], [ 76, 5.5, 5, 2 ], [ 78, 5.5, 7, 3 ], [ 80, 5.5, 9, 4 ], [ 82, 11.5, 11, 2 ], [ 84, 5.5, 0, 1 ], [ 86, 5.5, 2, 3 ], [ 88, 7.5, 4, 4 ], [ 90, 11.5, 5, 1 ], [ 92, 5.5, 7, 3 ], [ 94, 3.5, 9, 2 ], [ 96, 7.5, 11, 4 ], [ 98, 7.5, 0, 2 ], [ 100, 11.5, 2, 3 ], [ 102, 5.5, 4, 1 ], [ 104, 7.5, 5, 4 ], [ 106, 11.5, 7, 2 ], [ 108, 5.5, 9, 1 ], [ 110, 5.5, 11, 3 ], [ 112, 8.5, 0, 4 ], [ 114, 5.5, 2, 1 ], [ 116, 5.5, 4, 3 ], [ 118, 5.5, 5, 2 ], [ 120, 9.5, 7, 1 ], [ 122, 3.5, 9, 4 ], [ 124, 3.5, 11, 2 ], [ 126, 5.5, 0, 3 ], [ 128, 5.5, 2, 2 ], [ 130, 5.5, 4, 1 ], [ 132, 5.5, 5, 3 ], [ 134, 10, 7, 2 ], [ 136, 8, 9, 4 ], [ 138, 6, 11, 1 ], [ 140, 4, 0, 3 ] ] # Split the data into four datasets by stream # Each data set will be drawn in 'vector' style with a different color allData = [] # This will contain the four datasets for stream in [1, 2, 3, 4]: # Select the raw data for the stream rawData = [ item for item in all if item[3] == stream ] # Make a Gnuplot.Data to contain the raw data data = Gnuplot.Data(rawData, using=(1, 3, 2, '(0)'), # This gives 1-based index into the data for x, y, xdelta, ydelta # ydelta is a literal 0 with='vectors arrowstyle %s' % stream, # This sets the style of the dataset # styles are defined below title='Stream %s' % stream) # This names the dataset for the legend allData.append(data) # Set up general plot parameters g = Gnuplot.Gnuplot(debug=1) g.title('REALLY COOL GRAPH') # (optional) g.xlabel('Time') g.ylabel('Event') # These lines create four vector styles that have bars at each end # The only difference between the styles is the line type they use, # which determines the color # Shamelessly cribbed from the gnuplot arrowstyle demo g('set style line 1 lt 1 lw 2') # Set a line style for the vectors g('set style line 2 lt 2 lw 2') g('set style line 3 lt 3 lw 2') g('set style line 4 lt 4 lw 2') g('set style arrow 1 heads size screen 0.008,90 ls 1') # Set an arrow style for the vectors g('set style arrow 2 heads size screen 0.008,90 ls 2') g('set style arrow 3 heads size screen 0.008,90 ls 3') g('set style arrow 4 heads size screen 0.008,90 ls 4') g('set key outside box') # Include a legend; put it outside the graph # This actually does the plot # The * makes it treat the elements of allData as individual function arguments # It is the same as g.plot(allData[0], allData[1], allData[2], allData[3] g.plot(*allData) raw_input('Please press return to continue...\n') if __name__ == '__main__': main() At 08:32 PM 11/5/2004 -0500, kevin parks wrote: >hi Python heads! > >i have some data that would like to plot with Gnuplot-py and need to get a >little fancier than i am used to. > >I have data that looks like: > >0 5.5 0 1 >2 5.5 2 4 >4 5.5 4 2 >6 5.5 5 3 >8 5.5 7 1 >10 5.5 9 4 >12 5.5 11 3 >14 5.5 0 2 >16 5.5 2 1 >18 5.5 4 4 >20 5.5 5 3 > > >The first number is the start time of the event. The second is the >duration. The third is the event identifier and the last is what stream it >belongs to. I would like to use splot and points of different colors to >convey as much info as i can. The X axis would be the time axis (that >would take care of the first two parameters) and the Y axis could be the >third column. Then for the fouth item, there are only four possibilities >(1, 2, 3, or 4), so i thought that i could use points of red, blue, green, >black to indicate that. > >So that is where i am headed... But i have a long way to go and am a >gnuplot novice and not a great Python hacker to boot.. Could anyone help >me along? > >I would be grateful for any help. > >Cheers, > >kevin > > > >Here is some (*gasp*) code. > > >------------ [snip] ---------------- > >#! /usr/bin/env python > >from Numeric import * >import Gnuplot, Gnuplot.funcutils > >def main(): > > all = [ [ 0, 5.5, 0, 1 ], [ 2, 5.5, 2, 4 ], [ 4, 5.5, 4, 2 ], [ 6, > 5.5, 5, 3 ], [ 8, 5.5, 7, 1 ], [ 10, 5.5, 9, 4 ], [ 12, 5.5, 11, 3 ], [ > 14, 5.5, 0, 2 ], [ 16, 5.5, 2, 1 ], [ 18, 5.5, 4, 4 ], [ 20, 5.5, 5, 3 ], > [ 22, 5.5, 7, 2 ], [ 24, 5.5, 9, 1 ], [ 26, 5.5, 11, 4 ], [ 28, 5.5, 0, 3 > ], [ 30, 5.5, 2, 2 ], [ 32, 5.5, 4, 1 ], [ 34, 5.5, 5, 3 ], [ 36, 5.5, 7, > 4 ], [ 38, 5.5, 9, 2 ], [ 40, 5.5, 11, 3 ], [ 42, 5.5, 0, 4 ], [ 44, 5.5, > 2, 1 ], [ 46, 5.5, 4, 2 ], [ 48, 5.5, 5, 4 ], [ 50, 5.5, 7, 3 ], [ 52, > 5.5, 9, 1 ], [ 54, 5.5, 11, 2 ], [ 56, 5.5, 0, 4 ], [ 58, 5.5, 2, 1 ], [ > 60, 5.5, 4, 3 ], [ 62, 5.5, 5, 2 ], [ 64, 5.5, 7, 4 ], [ 66, 5.5, 9, 3 ], > [ 68, 5.5, 9, 1 ], [ 70, 5.5, 0, 2 ], [ 72, 5.5, 2, 4 ], [ 74, 5.5, 4, 1 > ], [ 76, 5.5, 5, 2 ], [ 78, 5.5, 7, 3 ], [ 80, 5.5, 9, 4 ], [ 82, 11.5, > 11, 2 ], [ 84, 5.5, 0, 1 ], [ 86, 5.5, 2, 3 ], [ 88, 7.5, 4, 4 ], [ 90, > 11.5, 5, 1 ], [ 92, 5.5, 7, 3 ], [ 94, 3.5, 9, 2 ], [ 96, 7.5, 11, 4 ], [ > 98, 7.5, 0, 2 ], [ 100, 11.5, 2, 3 ], [ 102, 5.5, 4, 1 ], [ 104, 7.5, 5, > 4 ], [ 106, 11.5, 7, 2 ], [ 108, 5.5, 9, 1 ], [ 110, 5.5, 11, 3 ], [ 112, > 8.5, 0, 4 ], [ 114, 5.5, 2, 1 ], [ 116, 5.5, 4, 3 ], [ 118, 5.5, 5, 2 ], > [ 120, 9.5, 7, 1 ], [ 122, 3.5, 9, 4 ], [ 124, 3.5, 11, 2 ], [ 126, 5.5, > 0, 3 ], [ 128, 5.5, 2, 2 ], [ 130, 5.5, 4, 1 ], [ 132, 5.5, 5, 3 ], [ > 134, 10, 7, 2 ], [ 136, 8, 9, 4 ], [ 138, 6, 11, 1 ], [ 140, 4, 0, 3 ] ] > g = Gnuplot.Gnuplot(debug=1) > g.title('REALLY COOL GRAPH') # (optional) > g.xlabel('Start Time') > g.ylabel('Duration') > g('set data style linespoints') # give gnuplot an arbitrary command > # Plot a list of (x, y) pairs (tuples or a Numeric array would > # also be OK): > #g.plot([[0,1.1], [1,5.8], [2,3.3], [3,4.2]]) > g.plot(all) > raw_input('Please press return to continue...\n') > g.reset() ># -- --------------- > print '############### test splot ##################################' > #g.splot(Gnuplot.Data(all, with='linesp', inline=1,)) > g.splot(Gnuplot.Data(all, using=(1,), with='points', inline=1,)) >#g.plot(Gnuplot.Data(d, with='lp 4 4')) >#g.plot(Gnuplot.Data(d, cols=(0,1), inline=0), >#Gnuplot.Data(d, cols=(0,2), inline=0)) >#g.plot(Gnuplot.Data(d, cols=(0,1), inline=1), >#Gnuplot.Data(d, cols=(0,2), inline=1)) > > #g.splot(Gnuplot.Data(all, with='linesp', inline=1)) > > ># when executed, just run main > >if __name__ == '__main__': > main() > > >------------ [snip] ---------------- > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From mynameissam at gmail.com Sat Nov 6 18:09:55 2004 From: mynameissam at gmail.com (Sam) Date: Sat Nov 6 18:09:58 2004 Subject: [Tutor] modifying the look of a program Message-ID: <895e1f0f0411060909668da76c@mail.gmail.com> Hi all, First of all, i have to say that this is a very basic question, but im just starting, so it's confusing. The very first programming languange i learned was Visual Basic, which is a program that lets you see the program as you build it, and lets you choose exactly which button has which property. So now I am very confused because even though i understand the basic structure of the language, and how to work with it, I have no idea what will the program look like, or even how to compile it (I havent done an independent program yet...). So please, i would really appreciate if you could help me out in this. Thank you all! Sam From mark.kels at gmail.com Sat Nov 6 20:01:58 2004 From: mark.kels at gmail.com (Mark Kels) Date: Sat Nov 6 20:02:01 2004 Subject: [Tutor] CGI problem. In-Reply-To: <20041106174835.95395.qmail@web54307.mail.yahoo.com> References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> Message-ID: On Sat, 6 Nov 2004 09:48:35 -0800 (PST), Chad Crabtree wrote: > Mark Kels wrote: > > > > >Thank you! > > > >But know I have another problem: > > > >I tried to add md5 hashing to the script, but for some reason it > > > >always says the the password is wrong... > > > >Hare is the program: > > > > > > > >import cgi > > > >import cgitb; cgitb.enable() > > > >import md5 > > > >form = cgi.FieldStorage() > > > >x=open("pass.txt","r") > > > >form.getfirst("pass") > > > >print "Content-type: text/html\n\n" > > > >def printhtml(): > > > > print """ > > > > > > > >
> > > > """ > > > >def checkpass(): > > > > filepass=x.readline() # The password in the file is already > digested. > > > > userpass=md5.new(form.getfirst("pass")).digest() > > > > if filepass==userpass: > > > > print "OK, come in." > > > > else: > > > > print "Wrong password, try again!" > > > > > > > > > > > >printhtml() > > > >if form.has_key("pass"): > > > > checkpass() > > > >x.close() > > > Well I would instead of checking the password I would print the > hashed > value and the unhashed value to the page so that you can inspect it > with > the password file. > > Generally when I'm trying to figure out problems like this I print > everything out so that it can be inspected. This helps a lot with > debugging. > > __________________________________ > > > Do you Yahoo!? > Check out the new Yahoo! Front Page. > www.yahoo.com > > Actualy I did that, but didnt think you will need it... Here is the file content: \xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E And here is the user password after digestion (in UTF-8 encoding): ????&?R?=??F?E Thanks! From pythonTutor at venix.com Sat Nov 6 20:20:52 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Nov 6 20:21:03 2004 Subject: [Tutor] CGI problem. In-Reply-To: References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> Message-ID: <1099768851.4942.11.camel@laptop.venix.com> My guess is that you have a trailing \n on the password that you read from the file. I believe that the md5 digest is 16 characters, but you can double check that easily. If that's true then filepass = filepass[:16] would extract the digest. This avoids any kind of issues with line marks between different operating systems. One other point. It is best to have a secret seed value that is used in conjunction with the user password when computing the digest. This makes it harder to mount a dictionary attack against a copy of the password file. You are still vulnerable to on-line dictionary attacks since your script "knows" the seed. In actual practice someone who obtained the password file would often have also been able to obtain your secret seed value. On Sat, 2004-11-06 at 14:01, Mark Kels wrote: > On Sat, 6 Nov 2004 09:48:35 -0800 (PST), Chad Crabtree > wrote: > > Mark Kels wrote: > > > > > > > > >Thank you! > > > > > >But know I have another problem: > > > > > >I tried to add md5 hashing to the script, but for some reason it > > > > > >always says the the password is wrong... > > > > > >Hare is the program: > > > > > > > > > > > >import cgi > > > > > >import cgitb; cgitb.enable() > > > > > >import md5 > > > > > >form = cgi.FieldStorage() > > > > > >x=open("pass.txt","r") > > > > > >form.getfirst("pass") > > > > > >print "Content-type: text/html\n\n" > > > > > >def printhtml(): > > > > > > print """ > > > > > > > > > > > >
> > > > > > """ > > > > > >def checkpass(): > > > > > > filepass=x.readline() # The password in the file is already > > digested. > > > > > > userpass=md5.new(form.getfirst("pass")).digest() > > > > > > if filepass==userpass: > > > > > > print "OK, come in." > > > > > > else: > > > > > > print "Wrong password, try again!" > > > > > > > > > > > > > > > > > >printhtml() > > > > > >if form.has_key("pass"): > > > > > > checkpass() > > > > > >x.close() > > > > > Well I would instead of checking the password I would print the > > hashed > > value and the unhashed value to the page so that you can inspect it > > with > > the password file. > > > > Generally when I'm trying to figure out problems like this I print > > everything out so that it can be inspected. This helps a lot with > > debugging. > > > > __________________________________ > > > > > > Do you Yahoo!? > > Check out the new Yahoo! Front Page. > > www.yahoo.com > > > > > > Actualy I did that, but didnt think you will need it... > Here is the file content: \xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E > And here is the user password after digestion (in UTF-8 encoding): > ????&?R?=??F?E > > Thanks! > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From amonroe at columbus.rr.com Sat Nov 6 20:27:02 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Nov 6 20:27:18 2004 Subject: [Tutor] Function problem In-Reply-To: <6.1.0.6.0.20041106075422.02b3c7f8@mail4.skillsoft.com> References: <6.1.0.6.0.20041106075422.02b3c7f8@mail4.skillsoft.com> Message-ID: <143-1629373255.20041106142702@columbus.rr.com> > At 12:26 PM 11/6/2004 +0300, Eri Mendz wrote: >>I also want to use regular expression for the Y|N portion; e.g., >>something like if ask == [Y|y|ye|yes] or ask == [N|n|no|nope]... to that >>effect. Any help is appreciated. > import re > yes = re.compile('y|ye|yes', re.IGNORECASE) > if yes.match(ask): > ... > This will also match 'you' and 'yesterday', if you want to be stricter > change the RE to '(y|ye|yes)$' This might be quicker and cleaner than re: if ask.upper().startswith('Y'): #do stuff Alan From bgailer at alum.rpi.edu Sat Nov 6 21:26:09 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Nov 6 21:25:17 2004 Subject: [Tutor] Function problem In-Reply-To: <143-1629373255.20041106142702@columbus.rr.com> References: <6.1.0.6.0.20041106075422.02b3c7f8@mail4.skillsoft.com> <143-1629373255.20041106142702@columbus.rr.com> Message-ID: <6.1.2.0.0.20041106132418.03f2d310@mail.mric.net> At 12:27 PM 11/6/2004, R. Alan Monroe wrote: > > At 12:26 PM 11/6/2004 +0300, Eri Mendz wrote: > >>I also want to use regular expression for the Y|N portion; e.g., > >>something like if ask == [Y|y|ye|yes] or ask == [N|n|no|nope]... to that > >>effect. Any help is appreciated. > > > import re > > yes = re.compile('y|ye|yes', re.IGNORECASE) > > if yes.match(ask): > > ... > > > This will also match 'you' and 'yesterday', if you want to be stricter > > change the RE to '(y|ye|yes)$' > >This might be quicker and cleaner than re: > >if ask.upper().startswith('Y'): > #do stuff I still favor: if 'YES'.startswith(ask.upper()) Covers all cases and abbreviations. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From amonroe at columbus.rr.com Sat Nov 6 22:12:42 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Nov 6 22:13:00 2004 Subject: [Tutor] Function problem In-Reply-To: <6.1.2.0.0.20041106132418.03f2d310@mail.mric.net> References: <6.1.0.6.0.20041106075422.02b3c7f8@mail4.skillsoft.com> <143-1629373255.20041106142702@columbus.rr.com> <6.1.2.0.0.20041106132418.03f2d310@mail.mric.net> Message-ID: <134-1623033058.20041106161242@columbus.rr.com> > I still favor: > if 'YES'.startswith(ask.upper()) > Covers all cases and abbreviations. I don't think it works with "Yep" :^) (Original poster predicted "nope" as a user response) Alan From keridee at jayco.net Sun Nov 7 02:50:25 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Nov 7 03:29:14 2004 Subject: [Tutor] Function problem References: Message-ID: <000101c4c471$81965c80$f65328cf@JSLAPTOP> You know, I would probably do something that was suggested a little while ago on the list. ask = raw_input("Give me something like yes or no. ") ask = ask.lower() li = ['y','ye','yes','yep','affirmative','okay','alright'] # etc. if ask in li: print "You typed in something that meant yes. " else: print "You typed in something that means no or something that I don't recognize. " From keridee at jayco.net Sun Nov 7 03:13:29 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Nov 7 03:29:21 2004 Subject: [Tutor] how to use the time module? References: <6.1.2.0.2.20041105014643.0368b6c0@rcblue.com> <6.1.0.6.0.20041105050909.02951f68@mail4.skillsoft.com> Message-ID: <000201c4c471$850c9780$f65328cf@JSLAPTOP> >import string >import datetime >y,m,d=string.split(raw_input("Enter a date('YYYY-MM-DD'):"),"-") >a=datetime.date(int(y),int(m),int(d)) >print a.strftime('%A') I can make it simpler yet First, get rid of importing the string module. You only want string.split() and you can use string methods for that. Then, you can change the code from there to: import datetime y,m,d = raw_input("Enter a date('YYYY-MM-DD'):").split("-") a = datetime.date(int(y),int(m),int(d)) print a.strftime("%A") HTH, Jacob Schmidt From keridee at jayco.net Sun Nov 7 02:29:25 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Nov 7 03:29:47 2004 Subject: [Tutor] Eek, help! References: Message-ID: <000001c4c471$80bbdb00$f65328cf@JSLAPTOP> Okay, Just a quick question. How did you define your function? What is pause? Is it a list or something that you have added attributes to? Or maybe a class? Your function pause.getKey() might look this no doubt? class pause: def getKey(): raw_input() Is that how it is? I'm just curious. Jacob Schmidt From mohamed at your-site.com Sun Nov 7 04:03:27 2004 From: mohamed at your-site.com (Mohamed Lrhazi) Date: Sun Nov 7 04:03:35 2004 Subject: [Tutor] time.sleep does not return at turn of the hour!!! Message-ID: <540732296.1099778607@[192.168.1.102]> Hello all, I am stuck with is strange problem. Here is the srouce: ... while 1: self.where=self.fp.tell() inbuffer=self.fp.read(self.inbuffersize) if not inbuffer: if self.onefile: self.lines=["DONE"] break new_filename=self.makeFileName() if not new_filename == self.filename: old_filename=self.filename self.fileShift() fileshifted=1 passe=0 break passe=passe+1 #if not passe % 60: log.logLine('logStream.refillLines',"%d: Waiting for new lines..."%(passe)) time.sleep(1) #It seems at the turn of the hour, we dont wakeup at all from this call!!! log.logLine('logStream.refillLines',"%d: Woke up..."%(passe)) self.fp.seek(self.where) else: self.bytesRead = self.bytesRead + len(inbuffer) ... Here is the output: 1106 20:59:56:logStream.refillLines: 7: Waiting for new lines... 1106 20:59:57:logStream.refillLines: 7: Woke up... 1106 20:59:57:logStream.refillLines: 8: Waiting for new lines... 1106 20:59:58:logStream.refillLines: 8: Woke up... 1106 20:59:58:logStream.refillLines: 9: Waiting for new lines... 1106 20:59:59:logStream.refillLines: 9: Woke up... 1106 20:59:59:logStream.refillLines: 10: Waiting for new lines... It just hangs there... till I control-C and then: Traceback (most recent call last): File "./parseDaemon.py", line 355, in ? l=zeusLog.getNextLine() File "./parseDaemon.py", line 237, in getNextLine self.refillLines() File "./parseDaemon.py", line 206, in refillLines time.sleep(1) #It seems at the turn of the hour, we dont wakeup at all from this call!!! KeyboardInterrupt This happens systematically and only when we turn to the next Hour!!! I tried with both python python-2.2.3-7 and python2.3-2.3.3-2pydotorg I am using Fedora Core 1 Any ideas? Thanks, Mohamed~ From kent_johnson at skillsoft.com Sun Nov 7 05:03:00 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Nov 7 05:03:06 2004 Subject: [Tutor] time.sleep does not return at turn of the hour!!! In-Reply-To: <540732296.1099778607@[192.168.1.102]> References: <540732296.1099778607@[192.168.1.102]> Message-ID: <6.1.0.6.0.20041106230204.02a6e328@mail4.skillsoft.com> What if you take out the file stuff and just do the sleep? For example this works fine for me (Win2K, Python 2.3.4): >>> from time import strftime, sleep >>> while True: ... sleep(1) ... print strftime('%H:%M:%S') ... Kent At 10:03 PM 11/6/2004 -0500, Mohamed Lrhazi wrote: >Hello all, > >I am stuck with is strange problem. Here is the srouce: > >... >while 1: > self.where=self.fp.tell() > inbuffer=self.fp.read(self.inbuffersize) > if not inbuffer: > if self.onefile: > self.lines=["DONE"] > break > new_filename=self.makeFileName() > if not new_filename == self.filename: > old_filename=self.filename > self.fileShift() > fileshifted=1 > passe=0 > break > passe=passe+1 > #if not passe % 60: > log.logLine('logStream.refillLines',"%d: > Waiting for new lines..."%(passe)) > time.sleep(1) #It seems at the turn of > the hour, we dont wakeup at all from this call!!! > log.logLine('logStream.refillLines',"%d: > Woke up..."%(passe)) > self.fp.seek(self.where) > else: > self.bytesRead = self.bytesRead + > len(inbuffer) > >... > >Here is the output: > >1106 20:59:56:logStream.refillLines: 7: Waiting for new lines... >1106 20:59:57:logStream.refillLines: 7: Woke up... >1106 20:59:57:logStream.refillLines: 8: Waiting for new lines... >1106 20:59:58:logStream.refillLines: 8: Woke up... >1106 20:59:58:logStream.refillLines: 9: Waiting for new lines... >1106 20:59:59:logStream.refillLines: 9: Woke up... >1106 20:59:59:logStream.refillLines: 10: Waiting for new lines... > > >It just hangs there... till I control-C and then: > >Traceback (most recent call last): > File "./parseDaemon.py", line 355, in ? > l=zeusLog.getNextLine() > File "./parseDaemon.py", line 237, in getNextLine > self.refillLines() > File "./parseDaemon.py", line 206, in refillLines > time.sleep(1) #It seems at the turn of the hour, we dont wakeup at all > from this call!!! >KeyboardInterrupt > > >This happens systematically and only when we turn to the next Hour!!! > >I tried with both python python-2.2.3-7 and python2.3-2.3.3-2pydotorg >I am using Fedora Core 1 > >Any ideas? > >Thanks, >Mohamed~ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From mohamed at your-site.com Sun Nov 7 07:17:48 2004 From: mohamed at your-site.com (Mohamed Lrhazi) Date: Sun Nov 7 07:17:56 2004 Subject: [Tutor] time.sleep does not return at turn of the hour!!! In-Reply-To: <6.1.0.6.0.20041106230204.02a6e328@mail4.skillsoft.com> References: <540732296.1099778607@[192.168.1.102]> <6.1.0.6.0.20041106230204.02a6e328@mail4.skillsoft.com> Message-ID: <552392984.1099790268@[192.168.1.102]> Yes. I actually did try that before and it does not hang! So you're right, it must be hanging somewhere else... I will try to narrow it down more... Thanks, Mohamed~ --On Saturday, November 06, 2004 11:03 PM -0500 Kent Johnson wrote: > What if you take out the file stuff and just do the sleep? For example > this works fine for me (Win2K, Python 2.3.4): > >>> from time import strftime, sleep > >>> while True: > ... sleep(1) > ... print strftime('%H:%M:%S') > ... > > Kent > > At 10:03 PM 11/6/2004 -0500, Mohamed Lrhazi wrote: >> Hello all, >> >> I am stuck with is strange problem. Here is the srouce: >> >> ... >> while 1: >> self.where=self.fp.tell() >> inbuffer=self.fp.read(self.inbuffersize) >> if not inbuffer: >> if self.onefile: >> self.lines=["DONE"] >> break >> new_filename=self.makeFileName() >> if not new_filename == self.filename: >> old_filename=self.filename >> self.fileShift() >> fileshifted=1 >> passe=0 >> break >> passe=passe+1 >> # if not passe % 60: >> log.logLine('logStream.refillLines',"%d: >> Waiting for new lines..."%(passe)) >> time.sleep(1) #It seems at the turn of >> the hour, we dont wakeup at all from this call!!! >> log.logLine('logStream.refillLines',"%d: >> Woke up..."%(passe)) >> self.fp.seek(self.where) >> else: >> self.bytesRead = self.bytesRead + >> len(inbuffer) >> >> ... >> >> Here is the output: >> >> 1106 20:59:56:logStream.refillLines: 7: Waiting for new lines... >> 1106 20:59:57:logStream.refillLines: 7: Woke up... >> 1106 20:59:57:logStream.refillLines: 8: Waiting for new lines... >> 1106 20:59:58:logStream.refillLines: 8: Woke up... >> 1106 20:59:58:logStream.refillLines: 9: Waiting for new lines... >> 1106 20:59:59:logStream.refillLines: 9: Woke up... >> 1106 20:59:59:logStream.refillLines: 10: Waiting for new lines... >> >> >> It just hangs there... till I control-C and then: >> >> Traceback (most recent call last): >> File "./parseDaemon.py", line 355, in ? >> l=zeusLog.getNextLine() >> File "./parseDaemon.py", line 237, in getNextLine >> self.refillLines() >> File "./parseDaemon.py", line 206, in refillLines >> time.sleep(1) #It seems at the turn of the hour, we dont wakeup at >> all from this call!!! >> KeyboardInterrupt >> >> >> This happens systematically and only when we turn to the next Hour!!! >> >> I tried with both python python-2.2.3-7 and python2.3-2.3.3-2pydotorg >> I am using Fedora Core 1 >> >> Any ideas? >> >> Thanks, >> Mohamed~ >> >> _______________________________________________ >> 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 mohamed at your-site.com Sun Nov 7 07:54:44 2004 From: mohamed at your-site.com (Mohamed Lrhazi) Date: Sun Nov 7 07:54:53 2004 Subject: [Tutor] time.sleep does not return at turn of the hour!!! In-Reply-To: <6.1.0.6.0.20041106230204.02a6e328@mail4.skillsoft.com> References: <540732296.1099778607@[192.168.1.102]> <6.1.0.6.0.20041106230204.02a6e328@mail4.skillsoft.com> Message-ID: <554608609.1099792484@[192.168.1.102]> So sorry... overlooked something: >> ... >> while 1: ... log.logLine('logStream.refillLines',"%d: Waiting for new lines..."%(passe)) time.sleep(1) #It seems at the turn of the hour, we dont wakeup at all from this call!!! log.logLine('logStream.refillLines',"%d: Woke up..."%(passe)) ... It hangs not at sleep but at: log.logLine, which is a class of mine I did not check at all!! a lot of stuff going there I forgot about and which has to do with hour changing... Sorry again. Mohamed~ From cyresse at gmail.com Sun Nov 7 09:21:40 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Nov 7 09:21:53 2004 Subject: [Tutor] Eek, help! In-Reply-To: <000001c4c471$80bbdb00$f65328cf@JSLAPTOP> References: <000001c4c471$80bbdb00$f65328cf@JSLAPTOP> Message-ID: Hi all, Jacob - this is anyKey() def anyKey(prompt=None): if prompt is None: prompt = "Press any key" print prompt while not msvcrt.kbhit(): # kbhit() returns 1 (true) or 0 (false), true if any key is pressed pass return But, it was as Danny said, my while loop was always true, which is odd, because, I had copied this - def readBook(book): import os filename = 'addbook.dat' if os.path.exists(filename): store = file(filename,'r') while store: name = store.readline().strip() entry = store.readline().strip() book[name] = entry else: store = file(filename,'w') # create new empty file store.close() from Alan Gauld's tutorial, and it works fine... so Liam == confused is True. But thanks all round, Liam Clarke On Sat, 6 Nov 2004 20:29:25 -0500, Jacob S. wrote: > Okay, > Just a quick question. How did you define your function? What is pause? > Is it a list or something that you have added attributes to? Or maybe a > class? > > Your function pause.getKey() might look this no doubt? > > class pause: > def getKey(): > raw_input() > > Is that how it is? I'm just curious. > Jacob Schmidt > > -- '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 cyresse at gmail.com Sun Nov 7 09:36:57 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Nov 7 09:37:07 2004 Subject: [Tutor] modifying the look of a program In-Reply-To: <895e1f0f0411060909668da76c@mail.gmail.com> References: <895e1f0f0411060909668da76c@mail.gmail.com> Message-ID: I assume you're on Windows? Open c:\python23, or wherever Python installed. Double click on python.exe You should get a DOSBOX with a prompt like so - >>> type in the following - print('hello world, the mandatory first programme.') and hit enter. >>>print('hello world, the mandatory first programme') hello world, the mandatory first programme >>> And that's it. Well, that's it in an interactive interpreter (which is great for trialling code snippets). To run a programme, you open your Python-friendly text editor(good selection here http://www.python.org/moin/PythonEditors, I recommend Pype) and write your programme like so - print(''hello world, the mandatory first programme.") save it, we'll call this dude.py, and then in your DOSBOX go to c:\python23 and type c:\python23\> python dude.py hello world, the mandatory first programme. Of course that's if you saved dude.py to your python23 directory. For working with a GUI, which is what it sounds like you're after... it's a little different. The classic GUI toolkit used for Python is Tkinter, and you can't lay it out visually. You could also use wxPython. What you are probably looking for is Spectix, PythonCard or Easygui. Google them, and see what you think. They let you lay it out, a la Visual Basic. Easygui is just quick & dirty functions. To be honest though, you'd do better to get into Python proper before hitting the GUI toolkits. http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/index.htm Good luck, Liam Clarke Oh, and generally, you don't compile Python, it compiles as it goes : ) On Sat, 6 Nov 2004 12:09:55 -0500, Sam wrote: > Hi all, > First of all, i have to say that this is a very basic question, but im > just starting, so it's confusing. The very first programming languange > i learned was Visual Basic, which is a program that lets you see the > program as you build it, and lets you choose exactly which button has > which property. So now I am very confused because even though i > understand the basic structure of the language, and how to work with > it, I have no idea what will the program look like, or even how to > compile it (I havent done an independent program yet...). So please, i > would really appreciate if you could help me out in this. > > Thank you all! > > Sam > _______________________________________________ > 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 kent_johnson at skillsoft.com Sun Nov 7 12:41:08 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Nov 7 12:41:15 2004 Subject: [Tutor] time.sleep does not return at turn of the hour!!! In-Reply-To: <554608609.1099792484@[192.168.1.102]> References: <540732296.1099778607@[192.168.1.102]> <6.1.0.6.0.20041106230204.02a6e328@mail4.skillsoft.com> <554608609.1099792484@[192.168.1.102]> Message-ID: <6.1.0.6.0.20041107063632.02b2df78@mail4.skillsoft.com> I should have asked about that...do you know about the logging package in the standard library? It is pretty handy and has lots of useful features. You can read about it here: http://docs.python.org/lib/module-logging.html In Python 2.4 it supports timed rollover logs, though they are not in the docs yet - you have to look at the source for information about them. If you can't use 2.4 you could download the latest version of logging from http://www.red-dove.com/python_logging.html Kent At 01:54 AM 11/7/2004 -0500, Mohamed Lrhazi wrote: >So sorry... overlooked something: > >>>... >>>while 1: >... > > log.logLine('logStream.refillLines',"%d: Waiting for new > lines..."%(passe)) > time.sleep(1) #It seems at the turn of the hour, we dont wakeup > at all from this call!!! > log.logLine('logStream.refillLines',"%d: Woke up..."%(passe)) >... > > >It hangs not at sleep but at: log.logLine, which is a class of mine I did >not check at all!! a lot of stuff going there >I forgot about and which has to do with hour changing... > >Sorry again. >Mohamed~ >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From jerimed at myrealbox.com Sun Nov 7 13:09:37 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Sun Nov 7 13:09:48 2004 Subject: [Tutor] Function problem In-Reply-To: <6.1.0.6.0.20041106074211.02b32b90@mail4.skillsoft.com> References: <6.1.0.6.0.20041106074211.02b32b90@mail4.skillsoft.com> Message-ID: <418E1081.7010801@myrealbox.com> Hello Kent & everyone, Thanks again for helping. For the regexp question i used the re module to get it over with. I think the program is fine now, i have modularized it into different functions: #!/usr/bin/env python # filename: tempConvert.py # a modular version broken down into separate functions # Author: Eri Mendz # Sun Nov 7 13:47:50 AST 2004 import sys, re def print_options(): print ''' THIS IS A TEMPERATURE CONVERSION PROGRAM. Options: [C] - convert to Celsius [F] - convert to Fahrenheit [P] - print options [Q] - quit ''' print_options() def f2c(ctemp): return (9/5.0)*ctemp + 32 def c2f(ftemp): return (ftemp - 32) * 5/9.0 def proceed(): proceed = raw_input("do another conversion? [Y|N]: ") yes = re.compile('(y|ye|yep|yes|ok|okey|okay)$', re.IGNORECASE) if yes.match(proceed): print_options() else: confirmQuit() def confirmQuit(): ask = raw_input("Really quit program? [Y|N]: ") yes = re.compile('(y|ye|yep|yes|ok|okey|okay)$', re.IGNORECASE) if yes.match(ask): sys.exit(bye()) # call function w/n function else: print_options() def askFahrenheit(): try: getftemp = float(raw_input("enter fahrenheit temperature: ")) print "temp in C is: ", c2f(getftemp) proceed() except ValueError: print "error: not a valid input!" print_options() def askCentigrade(): try: getctemp = float(raw_input("enter centigrade temperature: ")) print "temp in F is: ", f2c(getctemp) proceed() except ValueError: print "error: not a valid input!" print_options() def showErrorPrompt(): print "invalid option" print_options() def bye(): print "THANK YOU: GOODBYE!!!" # begin main menu while 1: choice = raw_input("select options: ") if choice == 'c' or choice == 'C': askFahrenheit() elif choice == 'f' or choice == 'F': askCentigrade() elif choice =='p' or choice == 'P': print_options() elif choice =='q' or choice == 'Q': confirmQuit() else: showErrorPrompt() bye() I think i can move on now to the next chapter of my tutorial. I'm intrigue of Bob's class version but i think that can wait until i reach the topic classes. -- Regards, erimendz ** use firefox/thunderbird ** http://www.spreadfirefox.com/?q=affiliates&id=6670&t=58 Kent Johnson wrote: > At 12:26 PM 11/6/2004 +0300, Eri Mendz wrote: > >> getftemp = int(raw_input("enter fahrenheit temperature: ")) >> >> How do i make the program accept decimal numbers, not just integers? > > > Use float() instead of int() to convert the input value: > getftemp = float(raw_input("enter fahrenheit temperature: ")) > > Kent > -- Regards, erimendz ** use firefox/thunderbird ** http://www.spreadfirefox.com/?q=affiliates&id=6670&t=58 From alan.gauld at freenet.co.uk Sun Nov 7 13:40:47 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Nov 7 13:40:27 2004 Subject: [Tutor] My new web tutor launched Message-ID: <004d01c4c4c7$029917a0$1fcb8751@xp> Its taken much longer than expected but my all-new, all-singin' all-dancin' web tutor is officially launched! Thanks to all those who submitted comments on the drafts. A quick summary of the new features: - Uses Python 2.3 as the main language Not all features but where there have been changes in preferred approach these are adopted, for example string methods etc. - Uses VBScript and JavaScript as comparison languages Wheras Tcl and QBASIC were strictly used for comparisons and only given about 25% of the coverage of Python VBScript and JavaScript now get around 75% of Python's coverage. I believe you could actually learn these languages from the tutor now. - Has new chapters on text processing and regular expressions The text processing was very thin, there is much more on using string methods and a whole intro to regular expressions, basically reproducing the regex chapter from my book. - has many more examples This was one comon criticism, hopefully the increased code count will keep folks happy. There will inevitably be bugs so if you find any please let me know so i can fix 'em! - has much more detailed explanations - overall its about 50% bigger My priorities for the immediate future are getting two new translations loaded onto the site - an update of the Czech one based on the new material, and a brand new Polish edition also based on the new material. After that I'll be starting a series of new topics focused on practical applications: using os, path, CGI, sockets, xml etc... Enjoy, and as ever send that feedback to me. Alan G. http://www.freenetpages.co.uk/hp/alan.gauld/ From chandrakirti at gmail.com Sun Nov 7 13:52:42 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Sun Nov 7 13:52:44 2004 Subject: [Tutor] disk images? Message-ID: <24d253d9041107045273d1c514@mail.gmail.com> I'm googling but not finding what I want. First, background. * There is a tool called something like "Bart's Bootable CD Creator" (see http://www.nu2.nu/bootcd/ ), which allows a single CD to hold multiple boot floppies. * My workplace uses multiple boot floppies to deploy hard drive images. Which boot disk should be used depends on where the computer is physically located and what kind of computer it is. Most of the boot disks differ by about four characters in a single file. My goal is to generate all of the boot floppy images, in order to burn them to a single CD. Then techs would only have to carry a single CD, which boots quickly and reliably, instead of continually modifying a floppy, which boots slowly and then fails. Is there a utility for viewing and editing (mounting, essentially) dos-formatted disk images from within Python? Would this be non-trivial to create? Thanks! From mark.kels at gmail.com Sun Nov 7 14:05:01 2004 From: mark.kels at gmail.com (Mark Kels) Date: Sun Nov 7 14:05:08 2004 Subject: [Tutor] CGI problem. In-Reply-To: <1099777499.4942.32.camel@laptop.venix.com> References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <1099768851.4942.11.camel@laptop.venix.com> <1099777499.4942.32.camel@laptop.venix.com> Message-ID: On Sat, 06 Nov 2004 16:44:59 -0500, Lloyd Kvam wrote: > On Sat, 2004-11-06 at 14:51, Mark Kels wrote: > > > > On Sat, 06 Nov 2004 14:20:52 -0500, Lloyd Kvam wrote: > > > My guess is that you have a trailing \n on the password that you read > > > from the file. I believe that the md5 digest is 16 characters, but you > > > can double check that easily. If that's true then > > > filepass = filepass[:16] > > > would extract the digest. > > > > > > This avoids any kind of issues with line marks between different > > > operating systems. > > > > > > One other point. It is best to have a secret seed value that is used in > > > conjunction with the user password when computing the digest. This > > > makes it harder to mount a dictionary attack against a copy of the > > > password file. You are still vulnerable to on-line dictionary attacks > > > since your script "knows" the seed. In actual practice someone who > > > obtained the password file would often have also been able to obtain > > > your secret seed value. > > > > I'm sorry, but I dint understand what you just wrote... (maybe because > > of my english, and maybe because of my litle knowldge about this > > subject). > your code was something like: > filepass = passwordfile.readline() > The '\n' (new-line) character is part of the data read in from the > file. So, filepass contains the MD5 digest along with the character > that marks the end of the line in the file. Since the MD5 digest is 16 > bytes long, you can extract the digest from the line you just read in by > using: > filepass = filepass[:16] > This takes the first 16 characters from the line and saves it using the > same name as was used originally to save the whole line. I hope this is > clear. > > I do not have any simple links covering security in program design. > Bruce Schneier has written books about security. The ACM (Association > for Computer Machinery) also has security information and courses. > http://acm.org/ > You would need to join to take advantage of much of their material. > > > Can you please fix my code so I'll understand what was the mistake? > > > > And BTW, this encription thing security thing is kind of intresting... > > I'll be glad if you will send me a link or two about this subject ( > > not too complex, and related to python). > > > > Thank you very much!! > -- > Lloyd Kvam > Venix Corp > > Thank you, now I underastand it... But I doesn't work. First, I got 49 characters and not 16 in the hash (\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E). But, anyway, It doesn't help me... I think the problem is to hash the user input (I get ????&?R?=??F?E, and not the real hash). More ideas ? From flaxeater at yahoo.com Sun Nov 7 15:21:25 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sun Nov 7 15:21:28 2004 Subject: [Tutor] CGI problem. Message-ID: <20041107142125.73399.qmail@web54302.mail.yahoo.com> Mark Kels wrote: >Thank you, now I underastand it... > >But I doesn't work. > > > >First, I got 49 characters and not 16 in the hash > >(\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E). > >But, anyway, It doesn't help me... > >I think the problem is to hash the user input (I get ��饇�&�R�=��F�E, > >and not the real hash). > > Maybe it has something to do with UTF-8 encoding. However if that is the case I won't be able to to help yyou because being an American I can blissfully live in ascii world. __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From kent_johnson at skillsoft.com Sun Nov 7 15:53:07 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Nov 7 15:53:26 2004 Subject: [Tutor] CGI problem. In-Reply-To: References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <1099768851.4942.11.camel@laptop.venix.com> <1099777499.4942.32.camel@laptop.venix.com> Message-ID: <6.1.0.6.0.20041107094512.02b37de0@mail4.skillsoft.com> At 03:05 PM 11/7/2004 +0200, Mark Kels wrote: >First, I got 49 characters and not 16 in the hash >(\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E). Actually I think that is 16 characters. Many of them are being printed as \x escapes. For example \xc8 represents a single character. >But, anyway, It doesn't help me... >I think the problem is to hash the user input (I >get ????????????&???R???=??????F???E, >and not the real hash). How is the user input getting converted to UTF-8? The CGI you posted before showed a content-type of text/html with no charset specified. Usually a browser will return form data in the same charset as the page containing the form. Anyway, I suggest you break your problem in two. One problem is getting recognizable data from the user in a CGI form. The other problem is computing MD5 hashes and comparing against the value in a file. For the CGI piece, see if you can write a program that accepts a password from the user and prints it out, or compares it to a hard-coded string. Make sure you get the data you expect in the CGI. For the MD5 piece, write a program that takes a known correct password, computes the MD5 hash and compares it with what is in a file. When you have both of these working, you can combine them into one program. If you initially write the CGI with a checkPassword() function that just compares to a fixed string, you can later drop in a checkPassword() function you develop for the second program. You could even write the MD5 part as a module, then the CGI program just has to import the checkPassword() function from the module. Kent From kent_johnson at skillsoft.com Sun Nov 7 16:07:15 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Nov 7 16:07:23 2004 Subject: [Tutor] sys.path contains a nonexistent zip file In-Reply-To: <000001c4c387$ecfa1470$2800005a@gobot> References: <000001c4c387$ecfa1470$2800005a@gobot> Message-ID: <6.1.0.6.0.20041107100311.02b776f0@mail4.skillsoft.com> This path element is added by Python as part of the boot process. The intent seems to be to allow the python library to be in a zip file without breaking the boot. See the "Booting" section of PEP 273 for more information: http://www.python.org/peps/pep-0273.html I suggest you just ignore the extra path element, it isn't hurting anything. If you really can't stand it, you could write a site-customize.py module that deletes it; sys.path is a mutable list, you can change it however you like. Let me know if you want more details... Kent At 04:36 PM 11/5/2004 -0600, David Carter wrote: >When I import sys and examine the value of sys.path, sys.path in my Python >2.3.3 installation contains 'D:\\WINNT\\system32\\python23.zip'. This file >does not exist. Does anyone how to remove it more or less permanently >from the sys.path? > >I've tried examing and editing the PythonPath from within Mark Hammond's >PythonWin, but that value doesn't seem to show up in the "Browse >PythonPath" or "Edit PythonPath" Tools. > >It's not hurting anything being there (as far as I know), I just want the >path to be clean of extraneous material, so to speak. > >David Carter >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sun Nov 7 18:14:45 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Nov 7 18:14:51 2004 Subject: [Tutor] CGI problem. In-Reply-To: References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <1099768851.4942.11.camel@laptop.venix.com> <1099777499.4942.32.camel@laptop.venix.com> <6.1.0.6.0.20041107094512.02b37de0@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> At 06:22 PM 11/7/2004 +0200, Mark Kels wrote: >The problem is that I cant hash the password that the user inputs, so >there is no need to break the problem in two (the first part is >working with no problems). OK, I misunderstood. >Is the input in CGI different from the input in normal programs? >Can it be that the md5 module has a problem with that kind of input? No, they are just strings like any other. >Is there another module like md5 that I can use instead? Can you post an example of a clear-text password and the hash you expect to see from it? How are you generating the hashes you are comparing against? Kent From mark.kels at gmail.com Sun Nov 7 20:31:26 2004 From: mark.kels at gmail.com (Mark Kels) Date: Sun Nov 7 20:31:40 2004 Subject: [Tutor] CGI problem. In-Reply-To: <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <1099768851.4942.11.camel@laptop.venix.com> <1099777499.4942.32.camel@laptop.venix.com> <6.1.0.6.0.20041107094512.02b37de0@mail4.skillsoft.com> <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> Message-ID: On Sun, 07 Nov 2004 12:14:45 -0500, Kent Johnson wrote: > At 06:22 PM 11/7/2004 +0200, Mark Kels wrote: > >The problem is that I cant hash the password that the user inputs, so > >there is no need to break the problem in two (the first part is > >working with no problems). > > OK, I misunderstood. > > >Is the input in CGI different from the input in normal programs? > >Can it be that the md5 module has a problem with that kind of input? > > No, they are just strings like any other. > > >Is there another module like md5 that I can use instead? > > Can you post an example of a clear-text password and the hash you expect to > see from it? > How are you generating the hashes you are comparing against? > > Kent > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > The password is 124 (as a string), and the hash is \xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E . I generated the hash that is in the file with IDLE (using the md5 module). From klappnase at freenet.de Sun Nov 7 21:20:14 2004 From: klappnase at freenet.de (Michael Lange) Date: Sun Nov 7 21:20:01 2004 Subject: [Tutor] Re: module search path order (was: gettext mystery) In-Reply-To: <6.1.0.6.0.20041105184241.02b30548@mail4.skillsoft.com> References: <20041104121457.456b11b4.klappnase@freenet.de> <6.1.0.6.0.20041104120317.02b13530@mail4.skillsoft.com> <20041105000558.1c9bfa89.klappnase@freenet.de> <6.1.0.6.0.20041105184241.02b30548@mail4.skillsoft.com> Message-ID: <20041107212014.5a6ac9dd.klappnase@freenet.de> On Fri, 05 Nov 2004 18:44:47 -0500 Kent Johnson wrote: Kent, thanks for the reply, > I don't know why you get a different gettext depending on when you import > it...maybe something is being added to sys.path? There's nothing added to sys.path, it's the order which is different; if I add a " print sys.path " to /usr/bin/moleskine I get: ['/usr/bin', '/usr/lib/python2.2', '/usr/lib/python2.2/plat-linux-i386', '/usr/lib/python2.2/lib-tk', '/usr/lib/python2.2/lib-dynload', '/usr/lib/python2.2/site-packages', '/usr/lib/python2.2/site-packages/Numeric', '/usr/lib/python2.2/site-packages/PIL', '/usr/lib/python2.2/site-packages/gtk-1.2'] if I add it to /usr/lib/python2.2/site-packages/Moleskine/MoleskineApp.py I get: ['/usr/bin', '/usr/lib/python2.2/site-packages/gtk-1.2', '/usr/bin', '/usr/lib/python2.2', '/usr/lib/python2.2/plat-linux-i386', '/usr/lib/python2.2/lib-tk', '/usr/lib/python2.2/lib-dynload', '/usr/lib/python2.2/site-packages', '/usr/lib/python2.2/site-packages/Numeric', '/usr/lib/python2.2/site-packages/PIL'] I guess that's the reason why MoleskineApp.py imports the gettext module from the site-packages/gtk-1.2 directory . > You might be able to get it to work by deleting the gtk-1.2/gettext.py so > all imports find the standard version. If the newer one is backwards > compatible I think this will work. > Unfortunately the two gettext modules aren't compatible, so deleting the one from pygnome is probably no good idea; anyway, for my current problem doing a sys.path.sort() before importing gettext did the job just fine, I was just wondering if there is a proper way to change the order of the module search path to force the import of the standard library's module in cases like this. Best regards Michael From kent_johnson at skillsoft.com Sun Nov 7 21:41:49 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Nov 7 21:42:00 2004 Subject: [Tutor] CGI problem. In-Reply-To: References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <1099768851.4942.11.camel@laptop.venix.com> <1099777499.4942.32.camel@laptop.venix.com> <6.1.0.6.0.20041107094512.02b37de0@mail4.skillsoft.com> <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041107151641.02af98b0@mail4.skillsoft.com> At 09:31 PM 11/7/2004 +0200, Mark Kels wrote: >On Sun, 07 Nov 2004 12:14:45 -0500, Kent Johnson > wrote: > > Can you post an example of a clear-text password and the hash you expect to > > see from it? > > How are you generating the hashes you are comparing against? > >The password is 124 (as a string), and the hash is >\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E . >I generated the hash that is in the file with IDLE (using the md5 module). Aahhhhh...the light goes on.... You did something like this in IDLE: >>> import md5 >>> p='124' >>> md5.new(p).digest() '\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E' Then you copied \xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E and pasted it into a file. Later you read it back from the file and compare with the hash you get in the CGI and they don't match. The problem is that the string you are pasting into the file is the repr() of the string - it is the way the string would look if you put it into source code in a Python program. The characters in the string with values > 127 are represented with \x escapes, not as the actual character. Whenever you work in the interactive interpreter, results can be printed in two different ways. If you let the interpreter print for you, it prints repr(value). If you explicitly use print, you get str(value). These are often similar, but not always. I think of repr() as the programmer's view of the data, and str() as the user's view. For example, even with a simple string there is a difference: >>> s='a' >>> s 'a' >>> print s a >>> s == repr(s) False Note that the first one has quotes - 'a' - while the second one is just an a. A small difference, but they are different. More important, for your problem, is that s is not equal to its repr(). How about this: >>> s='?' >>> s '\x81' >>> print s ? >>> s == repr(s) False (That's a u-umlaut, just in case it gets mangled by mail.) The first output looks nothing like the second. repr(s) uses \x escapes to print out the value in ASCII; print s prints the actual character. OK, back to hashes...with your sample data, we have >>> d = md5.new(p).digest() >>> d '\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E' >>> print d + T???&?Rf=??F?E Once again, the results are very different. This shows the actual hex values in the hash: >>> print ' '.join( [ hex(ord(c)) for c in d ] ) 0xc8 0xff 0xe9 0xa5 0x87 0xb1 0x26 0xf1 0x52 0xed 0x3d 0x89 0xa1 0x46 0xb4 0x45 You can see that in repr(d) the characters less than 0x80 are shown verbatim, while characters >= 0x80 are escaped. So, what to do? I can think of two solutions: - In your CGI, when you compute the hash, compare repr(hash) against what you find in the file. - Create the file with the actual hash, instead of it's repr(). If there is only one password in the file, you could do this from the command line, just open the file and write the string to it. If you have more than one password, you might want to write a small program to help with this. Kent From tmclaughlin at csu.edu.au Mon Nov 8 00:34:32 2004 From: tmclaughlin at csu.edu.au (McLaughlin, Toby) Date: Mon Nov 8 00:34:53 2004 Subject: [Tutor] disk images? Message-ID: <211F78EFD1D870409CC3E4158F4881DA08B32E1B@xcww01.riv.csu.edu.au> [Note: off-topic] Hi Lloyd, I'm not sure about Python, but this is trivial to do with Linux. In a Unix/Linux environment, you can mount files as easily as devices (in fact, devices _are_ files in Unix). The command to mount a floppy image would look like: mount imagefile /mnt/floppy -o loop You can then change into the /mnt/floppy directory and do whatever you want with the contents. Then you unmount the image ("umount /mnt/floppy") and write it out to your physical media. If you don't have a Linux machine handy, consider using a CD based distribution like Knoppix to do the work. Good luck, Toby McLaughlin. > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] On Behalf Of Lloyd Hugh Allen > Sent: Sunday, 7 November 2004 11:53 PM > To: tutor@python.org > Subject: [Tutor] disk images? > > > I'm googling but not finding what I want. First, background. > > * There is a tool called something like "Bart's Bootable CD Creator" > (see http://www.nu2.nu/bootcd/ ), which allows a single CD to hold > multiple boot floppies. > > * My workplace uses multiple boot floppies to deploy hard drive > images. Which boot disk should be used depends on where the computer > is physically located and what kind of computer it is. Most of the > boot disks differ by about four characters in a single file. > > My goal is to generate all of the boot floppy images, in order to burn > them to a single CD. Then techs would only have to carry a single CD, > which boots quickly and reliably, instead of continually modifying a > floppy, which boots slowly and then fails. > > Is there a utility for viewing and editing (mounting, essentially) > dos-formatted disk images from within Python? Would this be > non-trivial to create? > > Thanks! > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From melnyk at gmail.com Mon Nov 8 14:58:11 2004 From: melnyk at gmail.com (Scott Melnyk) Date: Mon Nov 8 14:58:17 2004 Subject: [Fwd: Re: [Tutor] searching for data in one file from another] In-Reply-To: <6.1.0.6.0.20041106010851.02ae3840@mail4.skillsoft.com> References: <418B8B2A.2030304@yahoo.com> <6.1.0.6.0.20041105093234.02905608@mail4.skillsoft.com> <418C6696.2030605@yahoo.com> <6.1.0.6.0.20041106010851.02ae3840@mail4.skillsoft.com> Message-ID: Hello all! Thanks for the guidance so far. The fasta file is such that one line begins with > and contains the name of the exon, the transcript it is from the gene, etc. The next line down contains the actual sequence data (ACCCAGCAAAATGG etc) I needed to match on the "title line" (beginning with >) line then remove that line and the following, or just not write into the new file that line and the following I guess is the more correct way to describe it. I modified things to: import sys,string from sets import Set WFILE=open(sys.argv[1], 'w') def deleteExons(fname2='Z:/datasets/altsplice1.fasta',exons_to_delete='Z:/datasets/Exonlist.txt'): f = open(fname2) f2 = open(exons_to_delete) sExcise=Set() flag=0 for line in open(exons_to_delete): sExcise.add(line.strip()) exon = None for line in f: if flag: flag=0 continue if line.startswith('>'): exon = line[1:].split('|')[0] if exon in sExcise: flag=1 continue yield line if __name__ == '__main__': for line in deleteExons(): print >> WFILE, line, #write new file minus the redundant exons Everything seems to be working now. The original fasta file was aprox 85 mb and now is down to 47 mb after the information matching the excise file was removed. I am moving on to my next steps now but still interested in comments on how this could be done more effectively. Thanks again to all for their input. Mvh, Scott On Sat, 06 Nov 2004 01:12:26 -0500, Kent Johnson wrote: > At 12:52 AM 11/6/2004 -0500, Rich Krauter wrote: > Kent, > > >Thanks very much for the reply. Right on the money and within a few > >minutes, as usual. I'm starting to think you're an automated help system. > >The OP should find these suggestions helpful for cleaning up his code. > > Just call me the Kent-bot! > > :-) > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Scott Melnyk From mhansen at cso.atmel.com Mon Nov 8 16:15:42 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Mon Nov 8 16:16:35 2004 Subject: [Tutor] maintaining state in a web app In-Reply-To: <797fe3d404110512311d2b8ec1@mail.gmail.com> References: <418BDEFE.40802@cso.atmel.com> <797fe3d404110512311d2b8ec1@mail.gmail.com> Message-ID: <418F8D9E.4080907@cso.atmel.com> Hi Bill, I'm leaning toward using cookies. The app will be used on our intranet, and other apps already require the use of cookies. The application will have multiple form pages, so I wanted to keep track of the user and form id. There won't be any sensitive information being used, so I'm not too concerned about it. I was hoping to find a book that discusses common web application problems and recommended solutions. So far, I haven't found anything. Maybe I haven't been putting in the magic keywords into Safari or Amazon. I'm also curious about if there's any easy to use web-frameworks that keep track of state for you. Most of the python web frameworks that I've taken a look at seem a little too complicated for smaller web apps. Maybe I need to get a couple of web apps under my belt before I see the light of some of the frameworks. Mike Bill Mill wrote: >Mike, > >I don't have any books to recommend, but saving state in a web >application is fairly simple. What you want to do is save data for a >user, and attach it to a session ID. > >There are two ways to save data for a user that I've used. First, you >could make a text file with a unique name (using a session ID for the >filename is a Good Idea), and everytime you need a variable for the >user, simply open the file with their session ID, and parse it for the >variable you need. For the actual file format, you could use one of >the various configuration file formats which have python parsers, or >just straight python code. > >Second, you could create a table in a database which relates a session >ID to whatever bits of data you want. If you're moving a lot of data, >this may be more efficient than the previous method. It is, however, >somewhat more complicated. > >To store the session ID, you should use a cookie. It's a bit more >secure than using GET or POST variables, and it means that you can set >and forget - no worries about hidden form variables in your pages. > >I believe that you can also store the actual data in a cookie, but >that means that it's being transmitted over the web everytime the user >accesses a page, which means that you need to be a little paranoid >about what you put in there. In general, I think it's safer to put the >data on your web server, where an attacker would at least have to >figure out your system to access it. > >Hope this helps. > >Peace >Bill Mill >bill.mill at gmail.com > > >On Fri, 05 Nov 2004 13:13:50 -0700, Mike Hansen wrote: > > >>Can anyone recommend any books/web-sites that discuss maintaining state >>in a web application? Various methods and pros/cons to each method. >>Cookies, form Vaiables, ??? ... The material can be Python specific or >>language neutral. >> >>Thanks, >> >>Mike >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> From mark.kels at gmail.com Mon Nov 8 16:32:46 2004 From: mark.kels at gmail.com (Mark Kels) Date: Mon Nov 8 16:32:55 2004 Subject: [Tutor] CGI problem. In-Reply-To: <6.1.0.6.0.20041107151641.02af98b0@mail4.skillsoft.com> References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <1099768851.4942.11.camel@laptop.venix.com> <1099777499.4942.32.camel@laptop.venix.com> <6.1.0.6.0.20041107094512.02b37de0@mail4.skillsoft.com> <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> <6.1.0.6.0.20041107151641.02af98b0@mail4.skillsoft.com> Message-ID: On Sun, 07 Nov 2004 15:41:49 -0500, Kent Johnson wrote: > At 09:31 PM 11/7/2004 +0200, Mark Kels wrote: > > > >On Sun, 07 Nov 2004 12:14:45 -0500, Kent Johnson > > wrote: > > > Can you post an example of a clear-text password and the hash you expect to > > > see from it? > > > How are you generating the hashes you are comparing against? > > > >The password is 124 (as a string), and the hash is > >\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E . > >I generated the hash that is in the file with IDLE (using the md5 module). > > Aahhhhh...the light goes on.... > You did something like this in IDLE: > >>> import md5 > >>> p='124' > >>> md5.new(p).digest() > '\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E' > > Then you copied \xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E and > pasted it into a file. Later you read it back from the file and compare > with the hash you get in the CGI and they don't match. > > The problem is that the string you are pasting into the file is the repr() > of the string - it is the way the string would look if you put it into > source code in a Python program. The characters in the string with values > > 127 are represented with \x escapes, not as the actual character. > > Whenever you work in the interactive interpreter, results can be printed in > two different ways. If you let the interpreter print for you, it prints > repr(value). If you explicitly use print, you get str(value). These are > often similar, but not always. I think of repr() as the programmer's view > of the data, and str() as the user's view. > > For example, even with a simple string there is a difference: > >>> s='a' > >>> s > 'a' > >>> print s > a > >>> s == repr(s) > False > > Note that the first one has quotes - 'a' - while the second one is just an > a. A small difference, but they are different. More important, for your > problem, is that s is not equal to its repr(). How about this: > >>> s='?' > >>> s > '\x81' > >>> print s > ? > >>> s == repr(s) > False > > (That's a u-umlaut, just in case it gets mangled by mail.) The first output > looks nothing like the second. repr(s) uses \x escapes to print out the > value in ASCII; print s prints the actual character. > > OK, back to hashes...with your sample data, we have > >>> d = md5.new(p).digest() > >>> d > '\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E' > >>> print d > + T???&?Rf=??F?E > > Once again, the results are very different. This shows the actual hex > values in the hash: > >>> print ' '.join( [ hex(ord(c)) for c in d ] ) > 0xc8 0xff 0xe9 0xa5 0x87 0xb1 0x26 0xf1 0x52 0xed 0x3d 0x89 0xa1 0x46 0xb4 0x45 > > You can see that in repr(d) the characters less than 0x80 are shown > verbatim, while characters >= 0x80 are escaped. > > So, what to do? I can think of two solutions: > - In your CGI, when you compute the hash, compare repr(hash) against what > you find in the file. > - Create the file with the actual hash, instead of it's repr(). If there is > only one password in the file, you could do this from the command line, > just open the file and write the string to it. If you have more than one > password, you might want to write a small program to help with this. > > > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > I doesn't work :( ... Here is what I did : import cgi import cgitb; cgitb.enable() import md5 form = cgi.FieldStorage() x=open("pass.txt","r") form.getfirst("pass") print "Content-type: text/html\n\n" def printhtml(): print """
""" def checkpass(): filepass=x.readline() # The password in the file is already digested. userpass=md5.new(form.getfirst("pass")).digest() if repr(userpass)==filepass: print "OK, come in." else: print "Wrong password, try again!" printhtml() if form.has_key("pass"): checkpass() x.close() the result is the same (out put is always for wrong password...). From kent_johnson at skillsoft.com Mon Nov 8 16:34:46 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Nov 8 16:39:19 2004 Subject: [Tutor] CGI problem. In-Reply-To: References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <1099768851.4942.11.camel@laptop.venix.com> <1099777499.4942.32.camel@laptop.venix.com> <6.1.0.6.0.20041107094512.02b37de0@mail4.skillsoft.com> <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> <6.1.0.6.0.20041107151641.02af98b0@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041108103300.02ab44a0@mail4.skillsoft.com> At 05:32 PM 11/8/2004 +0200, Mark Kels wrote: >I doesn't work :( ... >Here is what I did : > >import cgi >import cgitb; cgitb.enable() >import md5 >form = cgi.FieldStorage() >x=open("pass.txt","r") >form.getfirst("pass") >print "Content-type: text/html\n\n" >def printhtml(): > print """ > >
> """ >def checkpass(): > > filepass=x.readline() # The password in the file is already digested. > userpass=md5.new(form.getfirst("pass")).digest() > if repr(userpass)==filepass: > print "OK, come in." > else: > print "Wrong password, try again!" > >printhtml() >if form.has_key("pass"): > checkpass() >x.close() > > >the result is the same (out put is always for wrong password...). I think you need to strip the newline from filepass: filepass=x.readline().strip() If this doesn't work put in print filepass print repr(userpass) so you can see what it is comparing Kent From John.Gooch at echostar.com Mon Nov 8 18:39:49 2004 From: John.Gooch at echostar.com (Gooch, John) Date: Mon Nov 8 18:40:00 2004 Subject: [Tutor] Releasing Memory ( In Reference to Window COM Objects ) Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC00F2@riv-excha5.echostar.com> I have a Python script that hits a few thousand systems a day. It runs about 60 threads at a time, each making a WMI connection to a system and then getting some data for later insertion into a database. Every since I starting running the script ( daily ), the Windows 2000 SP4 system it runs on will no longer allow access to Windows networking resources ( says "not enough storage to process this request". The system is running and pingable, but it will repeat that error it you try to access a network resource such as a Windows file share or other network connection. I did notice I put the "CoInitialize()" command within a loop that ran for each system the thread queried, while I have the "CoUninitialize()" command running once at the end. I moved the "CoInitialize()" command out of the loop so it only runs once now instead of several hundred/thousand times, but I want to make sure I am releasing resources properly. One thing I am looking at is closing the WMI connection to a system before I make a connection to another system. I can't seem to find a "close" command for WMI, though. To help readers understand what my script is doing, here is some psuedocode "pythoncom.CoInitialize()" while the hostname queue is not empty Get hostname from Queue Object ping the system if it is online, attempt to make a WMI connection i.e. "wmi = win32com.client.GetObject('winmgmts://'+hostname )" if connection is successful, query for some data and put it back in another Queue object "pythoncom.CoUninitialize()" In vbscript, the wmi object is set to 'nothing' like so "Set wmi = Nothing", which I guess releases the resources for that connection. Is there a way I should be doing this in Python? Are there any other possible 'memory leaks' that could be causing the issue detailed above? Your help is appreciated. Thank You, John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 From mark.kels at gmail.com Mon Nov 8 20:35:29 2004 From: mark.kels at gmail.com (Mark Kels) Date: Mon Nov 8 20:35:43 2004 Subject: [Tutor] CGI problem. In-Reply-To: <6.1.0.6.0.20041108103300.02ab44a0@mail4.skillsoft.com> References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <1099777499.4942.32.camel@laptop.venix.com> <6.1.0.6.0.20041107094512.02b37de0@mail4.skillsoft.com> <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> <6.1.0.6.0.20041107151641.02af98b0@mail4.skillsoft.com> <6.1.0.6.0.20041108103300.02ab44a0@mail4.skillsoft.com> Message-ID: On Mon, 08 Nov 2004 10:34:46 -0500, Kent Johnson wrote: > At 05:32 PM 11/8/2004 +0200, Mark Kels wrote: > > > >I doesn't work :( ... > >Here is what I did : > > > >import cgi > >import cgitb; cgitb.enable() > >import md5 > >form = cgi.FieldStorage() > >x=open("pass.txt","r") > >form.getfirst("pass") > >print "Content-type: text/html\n\n" > >def printhtml(): > > print """ > > > >
> > """ > >def checkpass(): > > > > filepass=x.readline() # The password in the file is already digested. > > userpass=md5.new(form.getfirst("pass")).digest() > > if repr(userpass)==filepass: > > print "OK, come in." > > else: > > print "Wrong password, try again!" > > > >printhtml() > >if form.has_key("pass"): > > checkpass() > >x.close() > > > > > >the result is the same (out put is always for wrong password...). > > > I think you need to strip the newline from filepass: > filepass=x.readline().strip() > > If this doesn't work put in > print filepass > print repr(userpass) > so you can see what it is comparing > > > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Sorry, it doesn't work... Here is what I get when I'm printing filepass and repr(userpass): \xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E (filepass) ' ,\xb9b\xacY\x07[\x96K\x07\x15-#Kp' (repr(userpass)) From mark.kels at gmail.com Mon Nov 8 20:40:08 2004 From: mark.kels at gmail.com (Mark Kels) Date: Mon Nov 8 20:40:31 2004 Subject: [Tutor] CGI problem. In-Reply-To: References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <6.1.0.6.0.20041107094512.02b37de0@mail4.skillsoft.com> <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> <6.1.0.6.0.20041107151641.02af98b0@mail4.skillsoft.com> <6.1.0.6.0.20041108103300.02ab44a0@mail4.skillsoft.com> Message-ID: On Mon, 8 Nov 2004 21:35:29 +0200, Mark Kels wrote: > On Mon, 08 Nov 2004 10:34:46 -0500, Kent Johnson > > > wrote: > > At 05:32 PM 11/8/2004 +0200, Mark Kels wrote: > > > > > > >I doesn't work :( ... > > >Here is what I did : > > > > > >import cgi > > >import cgitb; cgitb.enable() > > >import md5 > > >form = cgi.FieldStorage() > > >x=open("pass.txt","r") > > >form.getfirst("pass") > > >print "Content-type: text/html\n\n" > > >def printhtml(): > > > print """ > > > > > >
> > > """ > > >def checkpass(): > > > > > > filepass=x.readline() # The password in the file is already digested. > > > userpass=md5.new(form.getfirst("pass")).digest() > > > if repr(userpass)==filepass: > > > print "OK, come in." > > > else: > > > print "Wrong password, try again!" > > > > > >printhtml() > > >if form.has_key("pass"): > > > checkpass() > > >x.close() > > > > > > > > >the result is the same (out put is always for wrong password...). > > > > > > I think you need to strip the newline from filepass: > > filepass=x.readline().strip() > > > > If this doesn't work put in > > print filepass > > print repr(userpass) > > so you can see what it is comparing > > > > > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > Sorry, it doesn't work... > Here is what I get when I'm printing filepass and repr(userpass): > \xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E (filepass) > ' ,\xb9b\xacY\x07[\x96K\x07\x15-#Kp' (repr(userpass)) > Oops... I'm sorry about the last post, I was cmparing 124 and 123. here is what I get when I do it right (124 and 124): \xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E (filepass) '\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E' (repr(userpass)) Now its easy to just take off the ' chars from the string, and I hope it will work... From kent_johnson at skillsoft.com Mon Nov 8 20:36:54 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Nov 8 20:41:55 2004 Subject: [Tutor] CGI problem. In-Reply-To: References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <1099777499.4942.32.camel@laptop.venix.com> <6.1.0.6.0.20041107094512.02b37de0@mail4.skillsoft.com> <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> <6.1.0.6.0.20041107151641.02af98b0@mail4.skillsoft.com> <6.1.0.6.0.20041108103300.02ab44a0@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041108143538.02a3e930@mail4.skillsoft.com> At 09:35 PM 11/8/2004 +0200, Mark Kels wrote: >On Mon, 08 Nov 2004 10:34:46 -0500, Kent Johnson > > If this doesn't work put in > > print filepass > > print repr(userpass) > > so you can see what it is comparing > > >Sorry, it doesn't work... >Here is what I get when I'm printing filepass and repr(userpass): >\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E (filepass) >' ,\xb9b\xacY\x07[\x96K\x07\x15-#Kp' (repr(userpass)) print form.getfirst("pass"), too - Kent From invisible.dog at gmail.com Mon Nov 8 20:56:06 2004 From: invisible.dog at gmail.com (Matt Hauser) Date: Mon Nov 8 20:56:16 2004 Subject: [Tutor] koders.com - Open Source Code Search Message-ID: <457b5fac04110811564627e6e0@mail.gmail.com> I ran across this on a .Net Junkies blog. koders.com is a search engine for open source code. You can search by language and license type. Great tool if you are searching for Python examples. -Matt- -- Have you seen the dog lately? Email - invisible.dog@gmail.com Blog - invisibledog.blogspot.com From klas.martelleur at telia.com Mon Nov 8 21:07:06 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Mon Nov 8 21:07:08 2004 Subject: [Tutor] Execute programs for example cdrecord from a python script? Message-ID: <200411082107.06144.klas.martelleur@telia.com> Hi Two quick questions. Is it possible to execute a program/binary(?) for example "cdrecord" from a python script? In that case how? :) Kind regards Klas Thanks for a good list From kent_johnson at skillsoft.com Mon Nov 8 21:19:38 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Nov 8 21:24:18 2004 Subject: [Tutor] Execute programs for example cdrecord from a python script? In-Reply-To: <200411082107.06144.klas.martelleur@telia.com> References: <200411082107.06144.klas.martelleur@telia.com> Message-ID: <6.1.0.6.0.20041108151746.02ad82c0@mail4.skillsoft.com> os.system() is the simplest way. If you need access to the input or output streams of the other program, use one of the variants of os.popen() or in Python 2.4 look at the new subprocess module. Kent At 09:07 PM 11/8/2004 +0100, Klas Marteleur wrote: >Hi >Two quick questions. >Is it possible to execute a program/binary(?) for example "cdrecord" from a >python script? >In that case how? :) > >Kind regards >Klas > >Thanks for a good list >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From csingley at gmail.com Mon Nov 8 21:29:11 2004 From: csingley at gmail.com (Christopher Singley) Date: Mon Nov 8 21:29:24 2004 Subject: [Tutor] How to generate instance names? Message-ID: <3bd1bdf04110812293caa7996@mail.gmail.com> I am new to object-oriented programming, and have a basic question. How can I generate an object name when creating an instance of a class, rather than hard-coding the name at creation? I'd like to say something like this: -- class Person(object): def __init__(self,name): self.name = name names = ["Tom", "Dick", "Harry"] personlist = [ ] i=0 for name in names: dude"i" = Person(name) personlist.append(dude"i") i += 1 -- in order to create dude1 with dude1.name = "Tom", dude2 with dude2.name = "Dick", and so forth. How can this be done? A second question: how can i define a function that takes as input an integer i, and returns the name of the object at personlist[ i ] (in this case, dude"i")? Also a meta-question: how can I search for the answers to these types of Python-programming questions? TIA cs From carroll at tjc.com Mon Nov 8 22:31:45 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon Nov 8 22:31:49 2004 Subject: [Tutor] How to generate instance names? In-Reply-To: <3bd1bdf04110812293caa7996@mail.gmail.com> Message-ID: On Mon, 8 Nov 2004, Christopher Singley wrote: > I am new to object-oriented programming, and have a basic question. > How can I generate an object name when creating an instance of a > class, rather than hard-coding the name at creation? When someone asks this, the answer is almost always they they should use dictionaries. > I'd like to say something like this: > -- > class Person(object): > def __init__(self,name): > self.name = name > > names = ["Tom", "Dick", "Harry"] > personlist = [ ] > i=0 > for name in names: > dude"i" = Person(name) > personlist.append(dude"i") > i += 1 How about: names = ["Tom", "Dick", "Harry"] dudes = {} i=0 for name in names: dude[i] = Person(name) personlist.append(dude[i]) i += 1 From csingley at gmail.com Mon Nov 8 23:22:59 2004 From: csingley at gmail.com (Christopher Singley) Date: Mon Nov 8 23:23:09 2004 Subject: [Tutor] How to generate instance names? In-Reply-To: References: <3bd1bdf04110812293caa7996@mail.gmail.com> Message-ID: <3bd1bdf0411081422204fa632@mail.gmail.com> > When someone asks this, the answer is almost always they they should use > dictionaries. That was my original plan. However, I am trying to cast my program along object-oriented lines. I am writing a Python program to manage a SQL database. I wish to represent database tables by object classes, and table rows by instances of classes. Object attributes correspond to table columns. A SQL query causes object instantiation; since there will be an unknown number of query results, I'm looking for a way to generate arbitrary numbers of instances. I had thought to package the query-objects into lists and iterate over them; each object in the list can be processed by invoking its methods. Is this a doomed plan? Is there a better way, or a standard solution for this problem? TIA cs From kent_johnson at skillsoft.com Mon Nov 8 23:54:54 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Nov 8 23:55:01 2004 Subject: [Tutor] How to generate instance names? In-Reply-To: <3bd1bdf0411081422204fa632@mail.gmail.com> References: <3bd1bdf04110812293caa7996@mail.gmail.com> <3bd1bdf0411081422204fa632@mail.gmail.com> Message-ID: <6.1.0.6.0.20041108173142.0293e1b8@mail4.skillsoft.com> At 04:22 PM 11/8/2004 -0600, Christopher Singley wrote: >I am writing a Python program to manage a SQL database. I wish to >represent database tables by object classes, and table rows by >instances of classes. Object attributes correspond to table columns. >A SQL query causes object instantiation; since there will be an >unknown number of query results, I'm looking for a way to generate >arbitrary numbers of instances. I had thought to package the >query-objects into lists and iterate over them; each object in the >list can be processed by invoking its methods. > >Is this a doomed plan? Is there a better way, or a standard solution >for this problem? This is a fine plan. The only flaw is thinking that you have to give a different name to each instance :-) Before I answer your question, let me point out that this is a common desire. It is pretty easy to create a simple solution yourself, but other people have already invented ways to do it. SQLObject seems to be one of the more popular: http://sqlobject.org/ OK, about names...a name is not a property of an object or a container for the object. It is more like a pointer to the object, or a label you stick on the object so you can refer to it. This article may help you understand: http://effbot.org/zone/python-objects.htm You don't need a unique name for each object, you just need some way of keeping track of it. Other ways of keeping track of objects are to put them in a list or dictionary. You can make a list of objects without giving the objects any name at all. Referring to your original post: >class Person(object): > def __init__(self,name): > self.name = name > >names = ["Tom", "Dick", "Harry"] >personlist = [ ] >i=0 >for name in names: > dude"i" = Person(name) > personlist.append(dude"i") > i += 1 All you really care about here is personlist. The name is temporary and of little consequence. You could write this loop more simply like this: names = ["Tom", "Dick", "Harry"] personlist = [ ] for name in names: dude = Person(name) personlist.append(dude) You don't need to assign Person to a name at all - this works just as well: personlist = [ ] for name in names: personlist.append(Person(name)) or you can use a list comprehension and make it really short and sweet: personlist = [ Person(name) for name in names ] All three have the same result - personlist is a list containing three Person objects with the names Tom, Dick and Harry. >A second question: how can i define a function that takes as input an >integer i, and returns the name of the object at personlist[ i ] (in >this case, dude"i")? You want to return the value - the actual object - not the name. The name is just a way of talking about the value. All you have to do is index personlist: def getPerson(i): return personlist[i] >Also a meta-question: how can I search for the answers to these types >of Python-programming questions? You can search the Tutor list at ActiveState: http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor The comp.lang.python newsgroup is a more advanced resource. You can search it from Google groups: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&c2coff=1&group=comp.lang.python Kent From kent_johnson at skillsoft.com Tue Nov 9 00:49:28 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Nov 9 00:49:32 2004 Subject: [Tutor] CGI problem. In-Reply-To: References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <6.1.0.6.0.20041107094512.02b37de0@mail4.skillsoft.com> <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> <6.1.0.6.0.20041107151641.02af98b0@mail4.skillsoft.com> <6.1.0.6.0.20041108103300.02ab44a0@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041108184758.0296cc38@mail4.skillsoft.com> At 09:40 PM 11/8/2004 +0200, Mark Kels wrote: >I'm sorry about the last post, I was cmparing 124 and 123. >here is what I get when I do it right (124 and 124): >\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E (filepass) >'\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E' (repr(userpass)) >Now its easy to just take off the ' chars from the string, and I hope >it will work... I just noticed the md5 function hexdigest(). If you use this instead of digest() you will get a nice clean hex string right at the start and dispense with all this \x and repr() stuff. Kent From dleigh0 at carolina.rr.com Tue Nov 9 05:13:26 2004 From: dleigh0 at carolina.rr.com (Diana Furr) Date: Tue Nov 9 05:11:48 2004 Subject: [Tutor] sorting lists Message-ID: <000601c4c612$774a5e50$121c8645@oemcomputer> I have a couple of lists that are made by user input. They will input one thing for the first list and a related thing for the other list. I want the list to be sorted alphabetically and then printed. This is an example of the problem. After user input list1[oranges, apples] list2[2,4] # The user is saying that they have 2 oranges and 4 apples If I alphabetize the first list the output looks like 2 apples and 4 oranges. I guess what I'm asking is how do I connect the lists so that when one is sorted the other list changes too. I hope that makes sense. Thank you in advance for your help. Diana -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041108/12930469/attachment.html From alan.gauld at freenet.co.uk Tue Nov 9 05:41:26 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Nov 9 05:41:01 2004 Subject: [Tutor] How to generate instance names? References: <3bd1bdf04110812293caa7996@mail.gmail.com> Message-ID: <001201c4c616$601dea90$833c8651@xp> > I am new to object-oriented programming, and have a basic question. > How can I generate an object name when creating an instance of a > class, rather than hard-coding the name at creation? This is nearly always a bad idea, it's better to use a dictionary. See my tutorial OOP topic for an example of this. There was also an extended thread on this a few weeks ago (and indeed almost every month! ;-) 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 Tue Nov 9 05:45:56 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Nov 9 05:45:35 2004 Subject: [Tutor] How to generate instance names? References: <3bd1bdf04110812293caa7996@mail.gmail.com> <3bd1bdf0411081422204fa632@mail.gmail.com> Message-ID: <001901c4c617$018e31a0$833c8651@xp> > > When someone asks this, the answer is almost always they they should use > > dictionaries. > > That was my original plan. However, I am trying to cast my program > along object-oriented lines. What makes you think dictionaries are not OO? :-) > I am writing a Python program to manage a SQL database. I wish to > represent database tables by object classes, and table rows by > instances of classes. Object attributes correspond to table columns. Thats a fairly common approach. > arbitrary numbers of instances. I had thought to package the > query-objects into lists and iterate over them; each object in the > list can be processed by invoking its methods. Such a list would be a lot like a cursor, no? So why not just use a cursor? THe roblem with creating lots of new variables is that the rest of your program won't know about them. How would your code access foo927 in advance? But if you have a single list or dictionary object that you fill your code can just iterate over the list and find all objects. Much easier that way. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From bill.mill at gmail.com Tue Nov 9 07:15:03 2004 From: bill.mill at gmail.com (Bill Mill) Date: Tue Nov 9 07:15:14 2004 Subject: [Tutor] sorting lists In-Reply-To: <000601c4c612$774a5e50$121c8645@oemcomputer> References: <000601c4c612$774a5e50$121c8645@oemcomputer> Message-ID: <797fe3d4041108221526252383@mail.gmail.com> On Mon, 8 Nov 2004 23:13:26 -0500, Diana Furr wrote: > > I have a couple of lists that are made by user input. They will input one > thing for the first list and a related thing for the other list. I want the > list to be sorted alphabetically and then printed. This is an example of the > problem. > After user input > list1[oranges, apples] > list2[2,4] > # The user is saying that they have 2 oranges and 4 apples > If I alphabetize the first list the output looks like 2 apples and 4 > oranges. > I guess what I'm asking is how do I connect the lists so that when one is > sorted the other list changes too. I hope that makes sense. > Thank you in advance for your help. > Diana Diana, I think what you should do is something like this: In [7]: fruit = ['zucchini', 'oranges', 'apples'] In [8]: fruit_id = [4,2,8] In [9]: fruit = zip(fruit, fruit_id) In [10]: fruit Out[10]: [('zucchini', 4), ('oranges', 2), ('apples', 8)] In [11]: fruit.sort() In [12]: fruit Out[12]: [('apples', 8), ('oranges', 2), ('zucchini', 4)] In general, it's better to maintain one list of connected elements than it is to try and maintain two parallel lists of information, for specifically the reasons you mention. Peace Bill Mill bill.mill at gmail.com From pthorstenson at co.montezuma.co.us Tue Nov 9 18:05:56 2004 From: pthorstenson at co.montezuma.co.us (Patrick Thorstenson) Date: Tue Nov 9 18:05:43 2004 Subject: [Tutor] How to insert a variable into a pathname? Message-ID: <000001c4c67e$6128cfa0$8235a8c0@co.montezuma.co.us> Help. I am very new to python. I am trying to allow a user to create a variable and then drop that variable into a file path name. It will then run a command - in this case a copy/paste command. LIKE: I want to copy parcel 5355 into the archives. The variable "VAR_Archive" is a 4 digit non-integer string such as 5355 or 5079. I want to insert it into both the input and output sides of the command. I want the final result to be: Testfile = "F:/Parcels/Parcelshapefiles/p5355_test.shp" Archive = "F:/Parcels/Aparcelarchives/p5355Archive.shp" I have received copious amounts of great advice but I keep missing something in the syntax(?). What I need is for somebody to spell out how the file pathname should read. ### # Import system modules import sys, string, os, win32com.client # Create the Geoprocessor object gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") #this parameter selects the parcel to archive from the parameter window in ArcGIS VAR_Archive = sys.argv [1] testfile = "F:/Parcels/ParcelShapefiles/p%s_test.shp" testfile % (VAR_Archive) archfile = "F:/Parcels/Aparcelupdate/p%sArchive.shp" archfile % (VAR_Archive) # copy (input, output) gp.copy_management(testfile, archfile) ### Thank you. Patrick Thorstenson GIS Specialist Montezuma County (970) 564-9298 pthorstenson@co.montezuma.co.us -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041109/9e2197ca/attachment.htm From mark.kels at gmail.com Tue Nov 9 18:06:15 2004 From: mark.kels at gmail.com (Mark Kels) Date: Tue Nov 9 18:06:18 2004 Subject: [Tutor] CGI problem. In-Reply-To: <6.1.0.6.0.20041108184758.0296cc38@mail4.skillsoft.com> References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> <6.1.0.6.0.20041107151641.02af98b0@mail4.skillsoft.com> <6.1.0.6.0.20041108103300.02ab44a0@mail4.skillsoft.com> <6.1.0.6.0.20041108184758.0296cc38@mail4.skillsoft.com> Message-ID: On Mon, 08 Nov 2004 18:49:28 -0500, Kent Johnson wrote: > At 09:40 PM 11/8/2004 +0200, Mark Kels wrote: > >I'm sorry about the last post, I was cmparing 124 and 123. > >here is what I get when I do it right (124 and 124): > >\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E (filepass) > >'\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E' (repr(userpass)) > >Now its easy to just take off the ' chars from the string, and I hope > >it will work... > > I just noticed the md5 function hexdigest(). If you use this instead of > digest() you will get a nice clean hex string right at the start and > dispense with all this \x and repr() stuff. > > > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > It works!! Here is the complete (and working) code: import cgi import cgitb; cgitb.enable() import md5 import re form = cgi.FieldStorage() x=open("pass.txt","r") form.getfirst("pass") print "Content-type: text/html\n\n" def printhtml(): print """
""" def checkpass(): filepass=x.readline() # The password in the file is already digested. userpass=md5.new(form.getfirst("pass")).digest() userpass=repr(userpass) userpass=re.sub("'","",userpass) if userpass==filepass: print "OK, come in." else: print "Wrong password, try again!" printhtml() if form.has_key("pass"): checkpass() x.close() Thanks to all who helped me!! From kent37 at tds.net Tue Nov 9 18:08:48 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Nov 9 18:14:01 2004 Subject: [Tutor] CGI problem. In-Reply-To: References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> <6.1.0.6.0.20041107151641.02af98b0@mail4.skillsoft.com> <6.1.0.6.0.20041108103300.02ab44a0@mail4.skillsoft.com> <6.1.0.6.0.20041108184758.0296cc38@mail4.skillsoft.com> Message-ID: <4190F9A0.5020103@tds.net> Mark Kels wrote: > It works!! Congratulations! One small comment below: > Here is the complete (and working) code: > > import cgi > import cgitb; cgitb.enable() > import md5 > import re > form = cgi.FieldStorage() > x=open("pass.txt","r") > form.getfirst("pass") > print "Content-type: text/html\n\n" > def printhtml(): > print """ > >
> """ > def checkpass(): > filepass=x.readline() # The password in the file is already digested. > userpass=md5.new(form.getfirst("pass")).digest() > userpass=repr(userpass) > userpass=re.sub("'","",userpass) userpass = userpass[1:-1] might be a better choice here, in case the actual hash includes a ' character. Kent > if userpass==filepass: > print "OK, come in." > else: > print "Wrong password, try again!" > > > > printhtml() > if form.has_key("pass"): > checkpass() > x.close() > > Thanks to all who helped me!! > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From tbs677 at yahoo.com Tue Nov 9 18:16:58 2004 From: tbs677 at yahoo.com (Ben) Date: Tue Nov 9 18:17:03 2004 Subject: [Tutor] SSL Suggestions Message-ID: <20041109171658.59919.qmail@web50401.mail.yahoo.com> Hi, I'm working on a C++ project and we got a curve ball the other day. They what to extend the project by allowing it to except a data feed from a secure server. We were able to connect and get data using Perl. We would like to use imbedded Python instead. I'm new to Python with no experience in SSL. I did look at the python.org to see what classes where available, but my inexperience didn't help understand how to use the documentation offered. And I looked at the Python Cryptography mailing list, I didn't find much to jump start me. Any suggestions on where to start. Thanks in advance for considering my question. Ben __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From kent37 at tds.net Tue Nov 9 18:12:38 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Nov 9 18:18:10 2004 Subject: [Tutor] How to insert a variable into a pathname? In-Reply-To: <000001c4c67e$6128cfa0$8235a8c0@co.montezuma.co.us> References: <000001c4c67e$6128cfa0$8235a8c0@co.montezuma.co.us> Message-ID: <4190FA86.3080209@tds.net> Patrick Thorstenson wrote: > The variable ?VAR_Archive? is a 4 digit non-integer string such as 5355 > or 5079. I want to insert it into both the input and output sides of the > command. > > I want the final result to be: > > Testfile = ?F:/Parcels/Parcelshapefiles/p5355_test.shp? > > Archive = ?F:/Parcels/Aparcelarchives/p5355Archive.shp? > ### > > testfile = "F:/Parcels/ParcelShapefiles/p%s_test.shp" > > testfile % (VAR_Archive) This creates a NEW string with the value you want, but doesn't do anything with it. You need to assign it back to testfile: testfile = testfile % (VAR_Archive) > archfile = "F:/Parcels/Aparcelupdate/p%sArchive.shp" > > archfile % (VAR_Archive) Likewise here archfile = archfile % (VAR_Archive) Kent From kent37 at tds.net Tue Nov 9 18:55:48 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Nov 9 19:01:01 2004 Subject: [Tutor] SSL Suggestions In-Reply-To: <20041109171658.59919.qmail@web50401.mail.yahoo.com> References: <20041109171658.59919.qmail@web50401.mail.yahoo.com> Message-ID: <419104A4.30404@tds.net> If you need to talk to a web server using HTTPS, I think the urllib module supports HTTPS directly. Try something like import urllib data = urllib.urlopen('https://myserver.com/myresource').read() If you need a socket-level interface, look at the sockets module, it has an ssl() function that creates an SSL connection. Kent Ben wrote: > Hi, > I'm working on a C++ project and we got a curve ball > the other day. They what to extend the project by > allowing it to except a data feed from a secure > server. We were able to connect and get data using > Perl. We would like to use imbedded Python instead. > I'm new to Python with no experience in SSL. > I did look at the python.org to see what classes > where available, but my inexperience didn't help > understand how to use the documentation offered. And > I looked at the Python Cryptography mailing list, I > didn't find much to jump start me. > Any suggestions on where to start. Thanks in > advance for considering my question. > > Ben > > > > __________________________________ > Do you Yahoo!? > Check out the new Yahoo! Front Page. > www.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From isrgish at fastem.com Wed Nov 10 01:10:10 2004 From: isrgish at fastem.com (Isr Gish) Date: Wed Nov 10 01:36:57 2004 Subject: [Tutor] C mailing list Message-ID: <20041110003655.C3E6D1E4002@bag.python.org> *** Off Topic *** Where can I find a good C mailing list for beginners. All the best, Isr From david at zettazebra.com Wed Nov 10 03:28:30 2004 From: david at zettazebra.com (David Clymer) Date: Wed Nov 10 03:29:24 2004 Subject: [Tutor] script hangs when attempting to read Popen3 output Message-ID: <1100053709.5303.110.camel@localhost> Are python's popen* commands/classes really supposed to work like pipes? When I try to do somthing that works like this: continuing input >> popen3('cat') >> read output the script hangs when I try to read the command output. It seems I can provide multi-line input, but I cant read any lines from the output of a command that is still recieving input. I have to close the input before reading any output. That doesnt seem very "pipe-ish" to me. Am I doing something wrong, or just expecting the wrong behavior? The script that I am working on is below. TIA for any enlightenment you can provide me. -davidc david@gorilla:~/dev/debian/packages/userutils/experimental$ cat shellcommands.py """ Utilities & wrappers for running shell commands """ import sys, os from debug import debug from popen2 import Popen3 def cmd(command,input=None, dbg=False): pcmd = Popen3(command) # dont bother writing if no input is available if input != None: debug('input >> ' + input, dbg) try: pcmd.tochild.write(input + "\n") pcmd.tochild.flush() if pcmd.poll(): print "still running" except IOError, e: print e # this magical line allows me to read pcmd.tochild.close() output='' while True: try: output += pcmd.fromchild.next() print 'output: %s' % output except StopIteration: break except IOError, e: print e break debug('output << ' + output, dbg) return output # -- try it out -- # input='' # if input is provided from the cmd line, lets use it if len(sys.argv) > 1: input = sys.argv[1] print cmd("cat", input, dbg=True) From cajuntechie at gmail.com Wed Nov 10 03:49:25 2004 From: cajuntechie at gmail.com (Anthony P.) Date: Wed Nov 10 03:49:28 2004 Subject: [Tutor] koders.com - Open Source Code Search In-Reply-To: <457b5fac04110811564627e6e0@mail.gmail.com> References: <457b5fac04110811564627e6e0@mail.gmail.com> Message-ID: Hi Matt, I visited the koders.com website after seeing it discussed somewhere on the Slashdot website the other day. While the site is a good idea, I do wish that they'd allow you to browse instead of having to structure your search and hope that it's going to match something in the db. A good start but some ways to go. Anthony On Mon, 8 Nov 2004 14:56:06 -0500, Matt Hauser wrote: > I ran across this on a .Net Junkies blog. koders.com is a search > engine for open source code. You can search by language and license > type. Great tool if you are searching for Python examples. > > -Matt- > > -- > Have you seen the dog lately? > Email - invisible.dog@gmail.com > Blog - invisibledog.blogspot.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- --- CajunTechie Quality On-Site and Remote Technical Services at affordable Prices Ph: (918) 926-0139 24: (918) 542-8251 Pager: (918) 220-2929 From kent37 at tds.net Wed Nov 10 03:56:08 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Nov 10 03:56:16 2004 Subject: [Tutor] script hangs when attempting to read Popen3 output In-Reply-To: <1100053709.5303.110.camel@localhost> References: <1100053709.5303.110.camel@localhost> Message-ID: <41918348.8030303@tds.net> I think there are deadlock issues with popen. The new subprocess module in Python 2.4 is supposed to help with this, you might want to check it out: http://www.python.org/peps/pep-0324.html Kent David Clymer wrote: > Are python's popen* commands/classes really supposed to work like pipes? > When I try to do somthing that works like this: > > continuing input >> popen3('cat') >> read output > > the script hangs when I try to read the command output. It seems I can > provide multi-line input, but I cant read any lines from the output of a > command that is still recieving input. I have to close the input before > reading any output. That doesnt seem very "pipe-ish" to me. Am I doing > something wrong, or just expecting the wrong behavior? > > The script that I am working on is below. > > TIA for any enlightenment you can provide me. > > -davidc > > > david@gorilla:~/dev/debian/packages/userutils/experimental$ cat > shellcommands.py > > """ > Utilities & wrappers for running shell commands > """ > > import sys, os > from debug import debug > from popen2 import Popen3 > > def cmd(command,input=None, dbg=False): > pcmd = Popen3(command) > > # dont bother writing if no input is available > if input != None: > debug('input >> ' + input, dbg) > try: > pcmd.tochild.write(input + "\n") > pcmd.tochild.flush() > if pcmd.poll(): > print "still running" > except IOError, e: > print e > > # this magical line allows me to read > pcmd.tochild.close() > > output='' > while True: > try: > output += pcmd.fromchild.next() > print 'output: %s' % output > except StopIteration: > break > except IOError, e: > print e > break > > debug('output << ' + output, dbg) > > return output > > > # -- try it out -- # > > input='' > > # if input is provided from the cmd line, lets use it > if len(sys.argv) > 1: > input = sys.argv[1] > > print cmd("cat", input, dbg=True) > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Wed Nov 10 04:02:15 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Nov 10 04:02:22 2004 Subject: [Tutor] C mailing list In-Reply-To: <20041110003655.C3E6D1E4002@bag.python.org> References: <20041110003655.C3E6D1E4002@bag.python.org> Message-ID: Try the following link http://www.google.co.nz/search?hl=en&q=c+beginners+mailing+list&btnG=Google+Search&meta= Works a treat every time. Regards, Liam Clarke On Tue, 9 Nov 2004 19:10:10 -0500, Isr Gish wrote: > *** Off Topic *** > > Where can I find a good C mailing list for beginners. > > All the best, > Isr > > _______________________________________________ > 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 tisza421 at gmail.com Wed Nov 10 04:10:14 2004 From: tisza421 at gmail.com (Eric) Date: Wed Nov 10 04:10:16 2004 Subject: [Tutor] how do i use p2exe Message-ID: <1033bb7f041109191055f46aee@mail.gmail.com> http://starship.python.net/crew/theller/py2exe/ Ok, im really new to programming and python. Well anyway i made a program for my classmates to help study vocabulary. The only problem is I dont want them to have to install python. So i figure ill use p2exe except i am pretty confused. How do i do this, heres the program if you need it. import random WORDS = ("derm", "ego", "erg, urg", "fact, fict, fect, fy") ANSWERS = ("skin", "I, self", "work, power", "do, make") amt = len(WORDS) print "\tWelcome to the English 10 Vocabulary Quiz program!" print "\t\\\\\\\\\\\\\\ \\\\ \\\\\\ \\\\\\\\\\\\\\ \\\\ \\\\\\\\\\\\\\\\\\\\ \\\\\\\\ \\\\\\\\\\\\\\\\\n" print "There are three difficulty levels:\n" print "\tLevel 1: 10 words\n\tLevel 2: 25 words\n\tLevel 3: All words" print "\nYou will get a point for each word." print "Try and beat your high score!" diff = "" while diff == "": diff = raw_input("\nWhich level: ") if diff == "1": wordamt = 10 elif diff == "2": wordamt = 25 elif diff == "3": wordamt = amt else: diff = "" print "\nYou've picked level", diff, "." print "You are going to be tested on", wordamt, "words.\n" num = 1 pts = 0 tpts = wordamt while wordamt > 0: guess = "" print "\n----- Word #", num, "-----" num += 1 wordnum = random.randrange(amt) print "Q:", WORDS[wordnum] ansnum = random.randrange(len(WORDS)) if ansnum == 0: print "A: 1.", ANSWERS[wordnum] print " 2.", ANSWERS[random.randrange(amt)] print " 3.", ANSWERS[random.randrange(amt)] print " 4.", ANSWERS[random.randrange(amt)] elif ansnum == 1: print "A: 1.", ANSWERS[random.randrange(amt)] print " 2.", ANSWERS[wordnum] print " 3.", ANSWERS[random.randrange(amt)] print " 4.", ANSWERS[random.randrange(amt)] elif ansnum == 2: print "A: 1.", ANSWERS[random.randrange(amt)] print " 2.", ANSWERS[random.randrange(amt)] print " 3.", ANSWERS[wordnum] print " 4.", ANSWERS[random.randrange(amt)] elif ansnum == 3: print "A: 1.", ANSWERS[random.randrange(amt)] print " 2.", ANSWERS[random.randrange(amt)] print " 3.", ANSWERS[random.randrange(amt)] print " 4.", ANSWERS[wordnum] while guess == "": guess = raw_input("What is your answer: ") if len(guess) > 1 or len(guess) < 1: guess = "" continue elif int(guess) != 1 and int(guess) != 2 and int(guess) != 3 and int(guess) != 4 and guess != "1" and guess != "2" and guess != "3" and guess != "4": guess = "" continue elif int(guess) - 1 == ansnum: print "Correct!\n" pts += 1 continue else: continue wordamt -= 1 pct = (float(pts) / float(tpts)) * 100 print "\nYou finished! You got", pts, "out of", tpts, "which is", pct, "%!" raw_input("\nPress enter to exit.") Can someone give me a run through of how to use p2exe? Thansk! -- http://www.freeiPods.com/?r=7485183 Get a free ipod! Actually works! From keridee at jayco.net Wed Nov 10 03:48:43 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Nov 10 04:17:05 2004 Subject: [Tutor] executing automatically a command in a PyShell References: <003c01c4bba0$ee61ba00$e0c3010a@andreroberge> Message-ID: <00df01c4c6d3$b1080b30$db5428cf@JSLAPTOP> Sorry, this does not answer your question. However, I will warn you that if you try to from __future__ import * in the python interpreter, it will give you this traceback. File "", line 1 SyntaxError: future statement does not support import * HTH, Jacob Schmidt From keridee at jayco.net Wed Nov 10 02:38:58 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Nov 10 04:17:09 2004 Subject: [Tutor] Eek, help! References: <000001c4c471$80bbdb00$f65328cf@JSLAPTOP> Message-ID: <00dc01c4c6d3$abf84470$db5428cf@JSLAPTOP> Thanks for showing me your pause key function! Jacob Schmidt From keridee at jayco.net Wed Nov 10 03:22:58 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Nov 10 04:17:12 2004 Subject: [Fwd: Re: [Tutor] searching for data in one file from another] References: <418B8B2A.2030304@yahoo.com><6.1.0.6.0.20041105093234.02905608@mail4.skillsoft.com><418C6696.2030605@yahoo.com><6.1.0.6.0.20041106010851.02ae3840@mail4.skillsoft.com> Message-ID: <00de01c4c6d3$adfcc700$db5428cf@JSLAPTOP> The only improvement that I can supply is that you don't need to import the string module anymore. Jacob Schmidt From keridee at jayco.net Wed Nov 10 03:16:39 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Nov 10 04:17:54 2004 Subject: [Tutor] Would an OOP approach be simpler? References: Message-ID: <00dd01c4c6d3$ad2e7a80$db5428cf@JSLAPTOP> Hi all! >def checkIfDoesExist(weekstart): > if os.path.exists('./archives/wb%s' % weekstart): > done=file('./archives/wb%s/got.lst' %weekstart, 'rb') > donelist=done.readlines() > done.close() > list=donelist[0].split('/') > return (list, 1) > else: > return (None, 0) Okay, three things. 1) Does this section of code do the same thing? def checkIfDoesExist(weekstart): a = './archives/wb%s' % weekstart if os.path.exists(a): li = file(a,'rb').readlines()[0].split('/') return (li,1) else: return (None,0) 2) Do any of you advise against/for my modified code block? 3) Does li automatically close? The file seems accessible even though I haven't explicitly closed it. Thanks for answering these when you get around to it. Jacob Schmidt From xcentric at unixgeek.net Wed Nov 10 04:35:49 2004 From: xcentric at unixgeek.net (xcentric@unixgeek.net) Date: Wed Nov 10 04:39:57 2004 Subject: [Tutor] python email forwarder via postfix Message-ID: <200411092235.49743.xcentric@unixgeek.net> Hi there, I'm posting this here, because I'm a bit green and I'd prefer not to reinvent the wheel if possible. Can someone please point me in the right direction on parsing emails w/ Python? My goal is to read in an email that is piped in from postfix and then forward the message (whole) based an arbitrary system. Thanks, Mike From keridee at jayco.net Wed Nov 10 04:59:15 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Nov 10 05:00:16 2004 Subject: [Tutor] how do i use p2exe References: <1033bb7f041109191055f46aee@mail.gmail.com> Message-ID: <00e701c4c6d9$ac052e00$db5428cf@JSLAPTOP> This is what I did. I'm using Windows XP, but it would work for any other windows version... 1) Take code below and copy into file named "setup.py". ### Start of Code ### from distutils.core import setup import py2exe import os def lookdir(): print "Current directory is: %s" % os.getcwd() look = raw_input('Do you wish to see what\'s in directory? ') if look.lower() in m: print "\n".join(os.listdir(os.getcwd())) def changedir(): m = ['y','ye','yes','yep','okay','affirmative','sure'] ask = 'y' lookdir() while ask not in m: di = raw_input('What directory do you want? ') os.chdir(di) lookdir() ask = raw_input('Do you want this directory? ') changedir() listed = [] while 1: ask = raw_input('What is the file you want as an executable? (Type \'quit\' to break out of loop) ') if ask == 'quit' or ask == 'stop' or ask == '': break else: listed.append(os.path.join(desktop,ask)) setup(console = listed) ### End of Code ### 2) Take following code and save as a batch file. You will have to change the second line to change the directory to your python dir rem Start of Code @echo off cd\python23 start python setup.py py2exe rem End of Code 3) Run the batch file. It will ask you which directory the script file is in. That would be the file that you're trying to make and executable. Then, when you decide which directory it is in, it will ask you the name of the file. You type in the name. If you want more than one file, you can type in another file name in the next prompt, else you can type in 'quit' or 'stop' or just hit enter. When all is done and the shell window closes, you can check out the directory that you chose. In that directory, there will be two new folders. One is labeled build. That folder is not necessary to run your executable and can be deleted. I usually delete it. The other is labeled dist. It contains the files needed for your program. Your program will have the same name, just with a exe extension instead of a py extension. Send the whole folder on to your students, and they can double-click on the exe file, and it will run your script as if you double-clicked it in Windows Explorer. Also, in your code (which I will try to rewrite for fun on my own (no offense)) you might try this instead: print "".join(["\t","\\"*7," ","\\"*4," ","\\"*6," ","\\"*7," ","\\"*2," ","\\"*10," ","\\"*2," ","\\"*8,"\n"]) Ignore the underline and blue if it shows up in your email thing. This just shows that you can multiply a particular string by an integer to copy it. Hope all this helps, Jacob Schmidt From nvettese at pdistributors.com Wed Nov 10 11:40:09 2004 From: nvettese at pdistributors.com (nvettese@pdistributors.com) Date: Wed Nov 10 11:40:12 2004 Subject: [Tutor] C mailing list Message-ID: <262870-220041131010409261@M2W035.mail2web.com> or c++ Original Message: ----------------- From: Isr Gish isrgish@fastem.com Date: Tue, 9 Nov 2004 19:10:10 -0500 To: tutor@python.org Subject: [Tutor] C mailing list *** Off Topic *** Where can I find a good C mailing list for beginners. All the best, Isr _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -------------------------------------------------------------------- mail2web - Check your email from the web at http://mail2web.com/ . From kent37 at tds.net Wed Nov 10 11:50:03 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Nov 10 11:50:13 2004 Subject: [Tutor] Would an OOP approach be simpler? In-Reply-To: <00dd01c4c6d3$ad2e7a80$db5428cf@JSLAPTOP> References: <00dd01c4c6d3$ad2e7a80$db5428cf@JSLAPTOP> Message-ID: <4191F25B.2020107@tds.net> Jacob S. wrote: > Hi all! > > >>def checkIfDoesExist(weekstart): >> if os.path.exists('./archives/wb%s' % weekstart): >> done=file('./archives/wb%s/got.lst' %weekstart, 'rb') >> donelist=done.readlines() >> done.close() >> list=donelist[0].split('/') >> return (list, 1) >> else: >> return (None, 0) > > > Okay, three things. > > 1) Does this section of code do the same thing? > > def checkIfDoesExist(weekstart): > a = './archives/wb%s' % weekstart > if os.path.exists(a): > li = file(a,'rb').readlines()[0].split('/') > return (li,1) > else: > return (None,0) > It opens a different file - wbweekstart vs wbweekstart/got.lst As you noted, it doesn't explicitly close the file. This is common - Python will close the file when it exits. I recommend you explicitly close files that you write, don't worry about it for files you open for read. > 2) Do any of you advise against/for my modified code block? It's short and sweet. BTW you could use readline().split('/') instead of readlines()[0].split() - there is no need to read the whole file when you just need the first line. Kent > 3) Does li automatically close? The file seems accessible even though I > haven't explicitly closed it. > > Thanks for answering these when you get around to it. > Jacob Schmidt > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From sundragon at cogeco.ca Wed Nov 10 14:24:13 2004 From: sundragon at cogeco.ca (SunDragon) Date: Wed Nov 10 14:24:18 2004 Subject: [Tutor] New function and 3 line program not working? Message-ID: <00d401c4c728$92566010$6500a8c0@cdca1h1bro1> This is my first post, so HI all! and Thank You for you help! Below is a tutorial that I am trying to complete, but I can not duplicate this exercise in either the IDLE gui or command line. (ver 2.3.4) Tutorial says to do this.... define the new function---- I go to IDLE gui and define the function.... def newLine(): print write the 3 line program---- I go open another IDLE window and like in the tutorial type this 3 line program.... print "First Line." newLine() print "Second Line." I save it as line.py Now I am to see this output result upon running it.... First line. Second line. But I dont get the output I should, I get the First Line. printed and a syntax error >>> First Line. Traceback (most recent call last): File "C:/Python23/newLine.py", line 2, in -toplevel- newLine() NameError: name 'newLine' is not defined >>> What have I inputed or done wrong? complete lesson below 3.6 Adding new functions So far, we have only been using the functions that come with Python, but it is also possible to add new functions. Creating new functions to solve your particular problems is one of the most useful things about a general-purpose programming language. In the context of programming, a function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition. The functions we have been using so far have been defined for us, and these definitions have been hidden. This is a good thing, because it allows us to use the functions without worrying about the details of their definitions. The syntax for a function definition is: def NAME( LIST OF PARAMETERS ): STATEMENTS You can make up any names you want for the functions you create, except that you can't use a name that is a Python keyword. The list of parameters specifies what information, if any, you have to provide in order to use the new function. There can be any number of statements inside the function, but they have to be indented from the left margin. In the examples in this book, we will use an indentation of two spaces. The first couple of functions we are going to write have no parameters, so the syntax looks like this: def newLine(): print This function is named newLine. The empty parentheses indicate that it has no parameters. It contains only a single statement, which outputs a newline character. (That's what happens when you use a printcommand without any arguments.) The syntax for calling the new function is the same as the syntax for built-in functions: print "First Line." newLine() print "Second Line." The output of this program is: First line. Second line. Notice the extra space between the two lines. What if we wanted more space between the lines? We could call the same function repeatedly: print "First Line." newLine() newLine() newLine() print "Second Line." Or we could write a new function named threeLines that prints three new lines: def threeLines(): newLine() newLine() newLine() print "First Line." threeLines() print "Second Line." This function contains three statements, all of which are indented by two spaces. Since the next statement is not indented, Python knows that it is not part of the function. You should notice a few things about this program: 1. You can call the same procedure repeatedly. In fact, it is quite common and useful to do so. 2. You can have one function call another function; in this case threeLines calls newLine. So far, it may not be clear why it is worth the trouble to create all of these new functions. Actually, there are a lot of reasons, but this example demonstrates two: * Creating a new function gives you an opportunity to name a group of statements. Functions can simplify a program by hiding a complex computation behind a single command and by using English words in place of arcane code. * Creating a new function can make a program smaller by eliminating repetitive code. For example, a short way to print nine consecutive new lines is to call threeLines three times. As an exercise, write a function called nineLines that uses threeLines to print nine blank lines. How would you print twenty-seven new lines? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041110/8ad4d068/attachment.html From cyresse at gmail.com Wed Nov 10 14:34:56 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Nov 10 14:35:01 2004 Subject: [Tutor] New function and 3 line program not working? In-Reply-To: <00d401c4c728$92566010$6500a8c0@cdca1h1bro1> References: <00d401c4c728$92566010$6500a8c0@cdca1h1bro1> Message-ID: You need to have in your file line.py the def newLine(): print before the next one. If you just do it in IDLE, IDLE executes it, but it doesn't save it anywhere your programme can access it, so your programme line.py has no idea what newLine() is. So, line.py should look like this - def newLine(): print return print First Line." newLine() print "Second Line." Hope that helps. Liam Clarke On Wed, 10 Nov 2004 08:24:13 -0500, SunDragon wrote: > > > This is my first post, so HI all! and Thank You for you help! > > Below is a tutorial that I am trying to complete, but I can not duplicate > this exercise in either the IDLE gui or command line. (ver 2.3.4) > Tutorial says to do this.... > > define the new function---- I go to IDLE gui and define the function.... > > def newLine(): > print > > > write the 3 line program---- I go open another IDLE window and like in the > tutorial type this 3 line program.... > > print "First Line." > newLine() > print "Second Line." > > I save it as line.py > > Now I am to see this output result upon running it.... > > First line. > > Second line. > > But I dont get the output I should, I get the First Line. printed and a > syntax error > > >>> > First Line. > > Traceback (most recent call last): > File "C:/Python23/newLine.py", line 2, in -toplevel- > newLine() > NameError: name 'newLine' is not defined > -- '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 cyresse at gmail.com Wed Nov 10 14:49:13 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Nov 10 14:49:17 2004 Subject: [Tutor] python email forwarder via postfix In-Reply-To: <200411092235.49743.xcentric@unixgeek.net> References: <200411092235.49743.xcentric@unixgeek.net> Message-ID: Just poke around email.Parser, it's a standard library. Here's some code of mine - for msgnum in range(len(names)): f = email.Parser.Parser() msg = f.parsestr(msgdata) That should get you a parsed RFC 822 compliant email. To parse from a file as opposed to a string, you just use msg = f.parse(msgdata) Good luck, Liam Clarke On Tue, 9 Nov 2004 22:35:49 -0500, xcentric@unixgeek.net wrote: > Hi there, > I'm posting this here, because I'm a bit green and I'd prefer not to reinvent > the wheel if possible. Can someone please point me in the right direction on > parsing emails w/ Python? My goal is to read in an email that is piped in > from postfix and then forward the message (whole) based an arbitrary system. > > Thanks, > Mike > _______________________________________________ > 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 Nov 10 19:37:28 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 10 19:37:41 2004 Subject: [Tutor] C mailing list In-Reply-To: <262870-220041131010409261@M2W035.mail2web.com> Message-ID: On Wed, 10 Nov 2004, nvettese@pdistributors.com wrote: > *** Off Topic *** > > Where can I find a good C mailing list for beginners. Hello, The comp.lang.c and comp.lang.c++ newsgroups are probably a better place to ask for C tutorial mailing lists. I think most of the C tutorial traffic goes through newsgroups instead of mailing lists. Here's a quick link to a browsable interface: http://groups.google.com/groups?group=comp.lang.c Good luck to you. From isrgish at fastem.com Wed Nov 10 20:57:58 2004 From: isrgish at fastem.com (Isr Gish) Date: Wed Nov 10 20:58:18 2004 Subject: [Tutor] C mailing list Message-ID: <20041110195816.DFA4D1E4002@bag.python.org> Thanks Liam. All the best, Isr -----Original Message----- >From: "Liam Clarke" >Sent: 11/9/04 10:02:15 PM >To: "Isr Gish", "Python Tutor" >Subject: Re: [Tutor] C mailing list >Try the following link > >http://www.google.co.nz/search?hl=en&q=c+beginners+mailing+list&btnG=Google+Search&meta= > > >Works a treat every time. > >Regards, > >Liam Clarke > >On Tue, 9 Nov 2004 19:10:10 -0500, Isr Gish wrote: >> *** Off Topic *** >> >> Where can I find a good C mailing list for beginners. >> >> All the best, >> Isr >> >> _______________________________________________ >> 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 marilyn at deliberate.com Wed Nov 10 21:40:43 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Nov 10 21:40:46 2004 Subject: [Tutor] C mailing list In-Reply-To: <20041110195816.DFA4D1E4002@bag.python.org> Message-ID: I couldn't find a beginner's C list from Googling. I didn't spend much time because I've looked before. As far as I know, this list is the only nice place for beginners. So Isr, if you find anything, please report back. Marilyn Davis From dyoo at hkn.eecs.berkeley.edu Wed Nov 10 22:15:04 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 10 22:17:03 2004 Subject: [Tutor] script hangs when attempting to read Popen3 output In-Reply-To: <41918348.8030303@tds.net> Message-ID: On Tue, 9 Nov 2004, Kent Johnson wrote: > I think there are deadlock issues with popen. Yes, we have to be sorta careful when doing popen-ish stuff. Take a look at: http://www.python.org/doc/lib/popen2-flow-control.html which explains some of the difficulties. > > the script hangs when I try to read the command output. It seems I can > > provide multi-line input, but I cant read any lines from the output of a > > command that is still recieving input. I have to close the input before > > reading any output. That doesnt seem very "pipe-ish" to me. Am I doing > > something wrong, or just expecting the wrong behavior? Expecting wrong behavior. *grin* You may need to close the input stream. Some Unix commands, like 'cat', might not start sending stuff out until either their buffers fill up, or until the input stream closes down. It's very funny how reinvention works: I had just finished writing a thin process-executing wrapper yesterday! *grin* It simulates the 'tee' utility, except that it also captures standard error. If you're interested, here's a link to it: http://aztec.stanford.edu/svn/repos/personal/dyoo/scratch/2004/python/wrap_shell_command.py Good luck to you! From wallison1 at sc.rr.com Wed Nov 10 23:22:45 2004 From: wallison1 at sc.rr.com (William Allison) Date: Wed Nov 10 23:21:17 2004 Subject: [Tutor] C mailing list In-Reply-To: References: Message-ID: <419294B5.50504@sc.rr.com> Marilyn Davis wrote: >I couldn't find a beginner's C list from Googling. I didn't spend >much time because I've looked before. > >As far as I know, this list is the only nice place for beginners. > >So Isr, if you find anything, please report back. > >Marilyn Davis > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > http://groups.google.com/groups?hl=en&lr=&group=alt.comp.lang.learn.c-c%2B%2B From renx99 at gmail.com Wed Nov 10 23:46:02 2004 From: renx99 at gmail.com (Rene Lopez) Date: Wed Nov 10 23:46:11 2004 Subject: [Tutor] C mailing list In-Reply-To: <419294B5.50504@sc.rr.com> References: <419294B5.50504@sc.rr.com> Message-ID: <57edb4ce04111014467468e258@mail.gmail.com> I would have to agree... This list the best programming list I've ever been on. The people on this list are actually helpful, and don't seem to look down upon the newbies like me... where as I don't get that sort of feeling from a lot the C++ lists I've taken a look at. So all of you guys on this list, give yourself a pat on the back, you guys rock. Rene On Wed, 10 Nov 2004 17:22:45 -0500, William Allison wrote: > Marilyn Davis wrote: > > > > >I couldn't find a beginner's C list from Googling. I didn't spend > >much time because I've looked before. > > > >As far as I know, this list is the only nice place for beginners. > > > >So Isr, if you find anything, please report back. > > > >Marilyn Davis > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > http://groups.google.com/groups?hl=en&lr=&group=alt.comp.lang.learn.c-c%2B%2B > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Rene From alan.gauld at freenet.co.uk Thu Nov 11 00:46:44 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Nov 11 00:45:55 2004 Subject: [Tutor] New function and 3 line program not working? References: <00d401c4c728$92566010$6500a8c0@cdca1h1bro1> Message-ID: <004801c4c77f$8985fc50$833c8651@xp> > define the new function---- I go to IDLE gui and define the function.... > > def newLine(): > print > > write the 3 line program---- > I go open another IDLE window and like in the tutorial type this 3 line program.... And here is the mistake, you must type the program *in the same window* as the function definition. The reason is that Pyton only knows about your function in the session where you defined it, once you go to a new session that instance of Python knows nothing about your function. > print "First Line." > newLine() > print "Second Line." > >I save it as line.py BUT you are saving it as a file not, as I first thought using a second interactive >>> prompt. Now if you did the same thing with your function definition, saving it into newline.py say, you could add a line from newline import newLine at the start of your line.py file and it would work. This is because by importing the function your new instance of Python now knows about the function definition. > Traceback (most recent call last): > File "C:/Python23/newLine.py", line 2, in -toplevel- > newLine() > NameError: name 'newLine' is not defined That's Python's way of telling you what I just said, the instance of Python running your line.py file cannot see the function definition anywhere. More etails omn using functions and modsules in my tutorial topic of the same name. 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 Thu Nov 11 00:49:55 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Nov 11 00:49:02 2004 Subject: [Tutor] C mailing list References: Message-ID: <005101c4c77f$fb2e0e10$833c8651@xp> > I couldn't find a beginner's C list from Googling. I didn't spend > much time because I've looked before. There used to be a beginner's mailing list specifically for the Borland C++Builder tool. I didn't stay on it long because I knew C++ and only needed tips on the tool. I don't know if it's still around but try googling for C++ Builder and Borland mailing lists and you might find it. The same server also had lists for Borlands Delphi and JBuilder too. Alan G From Dragonfirebane at aol.com Thu Nov 11 06:05:51 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Thu Nov 11 06:06:01 2004 Subject: [Tutor] *OFF-TOPIC* Good Java mailing list/Java StackOverflowError Message-ID: <1e9.2e7a9127.2ec44d2f@aol.com> Hello all, I recently began learning Java and was wondering what the generally best-thought-of java mailing list was. On the other hand, if anyone on this list has some knowledge of Java, please keep reading. I am trying to write a program to convert numbers (floating and negative, too) from the given base to base 10. As this is part of a larger project, what i have already written will no doubt appear as overkill, but the code in question can be found at http://rafb.net/paste/results/YDpaXH25.html (the relevant section is bounded by 5 lines of asterisk comments on top and bottom). In any case, though the current code has no syntax errors, a runtime error does occur when i try to call it like so; // java code public class BasemathInterface { public static void main(String[] args) { Basemath a = new Basemath(); a.convertBase(10, 23.4, false); } } //end java code a StackOverflowError: Exception in thread "main" java.lang.StackOverflowError Press any key to continue . . . I suspect this has something to do with line 88, where the second "half" of floating-point numbers are handled, since I've heard StackOverflowErrors are often caused by infinite loops, though i'm not sure how the current code would set up such a loop. Any help would be appreciated. Thanks in advance, Orri Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041111/01ffad0a/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Nov 11 07:30:31 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 11 07:30:36 2004 Subject: [Tutor] *OFF-TOPIC* Good Java mailing list/Java StackOverflowError In-Reply-To: <1e9.2e7a9127.2ec44d2f@aol.com> Message-ID: On Thu, 11 Nov 2004 Dragonfirebane@aol.com wrote: > I recently began learning Java and was wondering what the generally > best-thought-of java mailing list was. Hi Dragonfirebane, Try the official Java forums: http://forum.java.sun.com/ Their forums are very active, so I'm sure you can get some good support from the folks there as you're learning Java. > On the other hand, if anyone on this list has some knowledge of Java, > please keep reading. [text cut] > I am trying to write a program to convert numbers (floating and > negative, too) from the given base to base 10. [text cut] Hmmm... Try asking that on the Java forums. It's not that I have an overt anti-Java bias here. But I'm starting to worry about this off-topic thread is really starting to go way off topic. Remember, this is foremost a Python-tutor mailing list. *grin* The folks on the Java forums seem pretty helpful: give them a go first. (And if you find some kind of ecunumical forum for beginning programmers in many languages, let us know; I'd love to be involved.) Just as a note: if you see StackOverflowError, that's symptomatic of a runaway recursion. In Python, the analogous problem shows up as a RuntimeError: ### >>> def fact(x): ... if x == 0: ... return 1 ... return x * fact(x-1) ... >>> fact(5) 120 >>> fact(-1) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in fact File "", line 4, in fact File "", line 4, in fact File "", line 4, in fact File "", line 4, in fact File "", line 4, in fact [... lots and lots of text cut] RuntimeError: maximum recursion depth exceeded ### So something similar may be responsible for the bug in the Java code. Good luck to you! From cyresse at gmail.com Thu Nov 11 08:27:37 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Nov 11 08:27:40 2004 Subject: Fwd: [Tutor] New function and 3 line program not working? In-Reply-To: <002701c4c7af$ed5177c0$6500a8c0@cdca1h1bro1> References: <00d401c4c728$92566010$6500a8c0@cdca1h1bro1> <002701c4c7af$ed5177c0$6500a8c0@cdca1h1bro1> Message-ID: Sweet as, Using reply all replies to the list also. : ) ---------- Forwarded message ---------- From: SunDragon Date: Thu, 11 Nov 2004 00:33:07 -0500 Subject: Re: [Tutor] New function and 3 line program not working? To: Liam Clarke Liam, Thank You for your repy. I think I have found the solution to my problem. When I first start up the IDLE gui, it is titled "Python Shell" and I was attempting to enter everything here and I kept getting >>> after each line I typed and it would not work. But, I learned that if I open a new window from the "Python Shell" and then enter everything, then save, it would work just fine. Thank you again for your help Tim Moffatt ----- Original Message ----- From: "Liam Clarke" To: "SunDragon" ; "Python Tutor" Sent: Wednesday, November 10, 2004 8:34 AM Subject: Re: [Tutor] New function and 3 line program not working? > You need to have in your file line.py the > > def newLine(): > print > > before the next one. If you just do it in IDLE, IDLE executes it, but > it doesn't save it anywhere your programme can access it, so your > programme line.py has no idea what newLine() is. > > > So, line.py should look like this - > > def newLine(): > print > return > > print First Line." > newLine() > print "Second Line." > > > Hope that helps. > > Liam Clarke > On Wed, 10 Nov 2004 08:24:13 -0500, SunDragon wrote: > > > > > > This is my first post, so HI all! and Thank You for you help! > > > > Below is a tutorial that I am trying to complete, but I can not duplicate > > this exercise in either the IDLE gui or command line. (ver 2.3.4) > > Tutorial says to do this.... > > > > define the new function---- I go to IDLE gui and define the function.... > > > > def newLine(): > > print > > > > > > write the 3 line program---- I go open another IDLE window and like in the > > tutorial type this 3 line program.... > > > > print "First Line." > > newLine() > > print "Second Line." > > > > I save it as line.py > > > > Now I am to see this output result upon running it.... > > > > First line. > > > > Second line. > > > > But I dont get the output I should, I get the First Line. printed and a > > syntax error > > > > >>> > > First Line. > > > > Traceback (most recent call last): > > File "C:/Python23/newLine.py", line 2, in -toplevel- > > newLine() > > NameError: name 'newLine' is not defined > > > > -- > '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. -- '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 sundragon at cogeco.ca Thu Nov 11 10:22:18 2004 From: sundragon at cogeco.ca (SunDragon) Date: Thu Nov 11 10:22:25 2004 Subject: [Tutor] Re: New function and 3 line program not working? Message-ID: <009601c4c7cf$f13c8710$6500a8c0@cdca1h1bro1> I would like to Thank! Alan Gauld Liam Clarke Looking at two responses I recieved and combineing the info, I have solved the problem. When I first start up the IDLE gui, it is titled "Python Shell" and I was attempting to enter everything here and I kept getting >>> after each line I typed, and it would not work. IDLE 1.0.3 >>> def newLine(): print >>> print "First Line" First Line >>> newLine() >>> print "Second Line" Second Line But, I learned that if I open a new window from the "Python Shell" and then enter everything, then save, it would work just fine. It was well described by Alan Gauld. "Thats correct. The interactive shell is intended for trying thingsout. For example you can define your function there and play with it to make sure it works before transferring it into your program proper - this is how most Python programmers work in practice. Experiment in the >>> shell then once it works transfer to the final program in a file." SunDragon -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041111/6c1ee655/attachment-0001.html From jkmacman at yahoo.com Thu Nov 11 17:10:45 2004 From: jkmacman at yahoo.com (Jim Kelly) Date: Thu Nov 11 17:12:22 2004 Subject: [Tutor] Re: Tutor Digest, Vol 9, Issue 32 In-Reply-To: <20041110211707.45AD31E400C@bag.python.org> Message-ID: <20041111161045.91111.qmail@web50001.mail.yahoo.com> why not try this print "First Line.\n" print "Second Line." ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 10 Nov 2004 08:24:13 -0500 > From: "SunDragon" > Subject: [Tutor] New function and 3 line program not > working? > To: > Message-ID: > <00d401c4c728$92566010$6500a8c0@cdca1h1bro1> > Content-Type: text/plain; charset="iso-8859-1" > > This is my first post, so HI all! and Thank You for > you help! > > Below is a tutorial that I am trying to complete, > but I can not duplicate this exercise in either the > IDLE gui or command line. (ver 2.3.4) > Tutorial says to do this.... > > define the new function---- I go to IDLE gui and > define the function.... > > def newLine(): > print > > > write the 3 line program---- I go open another IDLE > window and like in the tutorial type this 3 line > program.... > > print "First Line." > newLine() > print "Second Line." > > I save it as line.py > > Now I am to see this output result upon running > it.... > > First line. > > Second line. > > But I dont get the output I should, I get the First > Line. printed and a syntax error > > >>> > First Line. > > Traceback (most recent call last): > File "C:/Python23/newLine.py", line 2, in -toplevel- > newLine() > NameError: name 'newLine' is not defined > >>> > > What have I inputed or done wrong? > > > complete lesson below > > > 3.6 Adding new functions > > So far, we have only been using the functions that > come with Python, but it is also possible to add new > functions. Creating new functions to solve your > particular problems is one of the most useful things > about a general-purpose programming language. > > In the context of programming, a function is a named > sequence of statements that performs a desired > operation. This operation is specified in a function > definition. The functions we have been using so far > have been defined for us, and these definitions have > been hidden. This is a good thing, because it allows > us to use the functions without worrying about the > details of their definitions. > > The syntax for a function definition is: > > def NAME( LIST OF PARAMETERS ): > STATEMENTS > > You can make up any names you want for the functions > you create, except that you can't use a name that is > a Python keyword. The list of parameters specifies > what information, if any, you have to provide in > order to use the new function. > > There can be any number of statements inside the > function, but they have to be indented from the left > margin. In the examples in this book, we will use an > indentation of two spaces. > > The first couple of functions we are going to write > have no parameters, so the syntax looks like this: > > def newLine(): > print > > This function is named newLine. The empty > parentheses indicate that it has no parameters. It > contains only a single statement, which outputs a > newline character. (That's what happens when you use > a printcommand without any arguments.) > > The syntax for calling the new function is the same > as the syntax for built-in functions: > > print "First Line." > newLine() > print "Second Line." > > The output of this program is: > > First line. > > Second line. > > Notice the extra space between the two lines. What > if we wanted more space between the lines? We could > call the same function repeatedly: > > print "First Line." > newLine() > newLine() > newLine() > print "Second Line." > > Or we could write a new function named threeLines > that prints three new lines: > > def threeLines(): > newLine() > newLine() > newLine() > > print "First Line." > threeLines() > print "Second Line." > > This function contains three statements, all of > which are indented by two spaces. Since the next > statement is not indented, Python knows that it is > not part of the function. > > You should notice a few things about this program: > > 1. You can call the same procedure repeatedly. In > fact, it is quite common and useful to do so. > 2. You can have one function call another function; > in this case threeLines calls newLine. > > So far, it may not be clear why it is worth the > trouble to create all of these new functions. > Actually, there are a lot of reasons, but this > example demonstrates two: > > * Creating a new function gives you an opportunity > to name a group of statements. Functions can > simplify a program by hiding a complex computation > behind a single command and by using English words > in place of arcane code. > * Creating a new function can make a program smaller > by eliminating repetitive code. For example, a short > way to print nine consecutive new lines is to call > threeLines three times. > === message truncated === __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From andre.roberge at ns.sympatico.ca Thu Nov 11 21:54:04 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Thu Nov 11 21:54:03 2004 Subject: [Tutor] help needed with using exec Message-ID: <4193D16C.3040100@ns.sympatico.ca> Dear Tutors, Suppose I have in file test.py a single line: move() which is a function define in otherApp.py After reading the content of "test.py" into the string named code, I would like to do "exec code" and have it execute move() as it is defined in otherApp from myApp Within myApp, I have instance = otherApp() I have tried hardcoding the following in myApp: == move = instance.move move() == and it workd. I then tried == exec code == by itself and it didn't work. I also tried == exec code in myApp.__dict__ == and it didn't work either. Suggestions would be greatly appreciated. Andr? From kent37 at tds.net Thu Nov 11 22:38:02 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Nov 11 22:38:07 2004 Subject: [Tutor] help needed with using exec In-Reply-To: <4193D16C.3040100@ns.sympatico.ca> References: <4193D16C.3040100@ns.sympatico.ca> Message-ID: <4193DBBA.4010503@tds.net> Andr? Roberge wrote: > Dear Tutors, > > Suppose I have in file test.py a single line: > move() > > which is a function define in otherApp.py > > After reading the content of "test.py" into > the string named code, I would like to do > > "exec code" > > and have it execute move() as it is defined > in otherApp from myApp > > Within myApp, I have > instance = otherApp() > > I have tried hardcoding the following in myApp: > == > move = instance.move > move() > == > and it workd. > > I then tried > == > exec code > == > by itself and it didn't work. what about this? move = instance.move exec code If that doesn't work, please post a short, complete program and the exact error message you are getting when you run it. Kent From klas.martelleur at telia.com Thu Nov 11 22:45:27 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Thu Nov 11 22:45:30 2004 Subject: [Tutor] My new web tutor launched In-Reply-To: <004d01c4c4c7$029917a0$1fcb8751@xp> References: <004d01c4c4c7$029917a0$1fcb8751@xp> Message-ID: <200411112245.27911.klas.martelleur@telia.com> Alan Is it possible to buy your latest tutor as a book? Klas s?ndagen den 7 november 2004 13.40 skrev Alan Gauld: > Its taken much longer than expected but my all-new, all-singin' > all-dancin' web tutor is officially launched! > > Thanks to all those who submitted comments on the drafts. > > A quick summary of the new features: > > - Uses Python 2.3 as the main language > Not all features but where there have been changes in preferred > approach these are adopted, for example string methods etc. > - Uses VBScript and JavaScript as comparison languages > Wheras Tcl and QBASIC were strictly used for comparisons and only > given > about 25% of the coverage of Python VBScript and JavaScript now > get > around 75% of Python's coverage. I believe you could actually > learn > these languages from the tutor now. > - Has new chapters on text processing and regular expressions > The text processing was very thin, there is much more on using > string methods and a whole intro to regular expressions, basically > reproducing the regex chapter from my book. > - has many more examples > This was one comon criticism, hopefully the increased code count > will keep folks happy. There will inevitably be bugs so if you > find any please let me know so i can fix 'em! > - has much more detailed explanations - overall its about 50% bigger > > My priorities for the immediate future are getting two new > translations > loaded onto the site - an update of the Czech one based on the new > material, and a brand new Polish edition also based on the new > material. > > After that I'll be starting a series of new topics focused on > practical > applications: using os, path, CGI, sockets, xml etc... > > Enjoy, and as ever send that feedback to me. > > Alan G. > http://www.freenetpages.co.uk/hp/alan.gauld/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From jinlin555 at msn.com Thu Nov 11 23:43:03 2004 From: jinlin555 at msn.com (Lin Jin) Date: Thu Nov 11 23:44:06 2004 Subject: [Tutor] a question about list Message-ID: i am new to python.i have a question about list.if i have two list: a=[a,b,c,d,e,f,g] b=[1,2,4] and i want to remove the element of a using b,that is i want a=[a,d,f,g],my code is like this: >>>for i in b: >>> del a[b] but it is not working, it can't remove the correct items.what should i do to make it correct?thx _________________________________________________________________ Ãâ·ÑÏÂÔØ MSN Explorer: http://explorer.msn.com/lccn/ From carroll at tjc.com Fri Nov 12 00:17:14 2004 From: carroll at tjc.com (Terry Carroll) Date: Fri Nov 12 00:17:18 2004 Subject: [Tutor] a question about list In-Reply-To: Message-ID: On Fri, 12 Nov 2004, Lin Jin wrote: > i am new to python.i have a question about list.if i have two list: > a=[a,b,c,d,e,f,g] > b=[1,2,4] > and i want to remove the element of a using b,that is i want a=[a,d,f,g],my > code is like this: > >>>for i in b: > >>> del a[b] That del statement was supposed to be "del a[i]", right? Anyway, you're forgetting that every time you delete an entry in the list, every subsequent entry's position will be one less. For example, on the first run-through, a = [A, B, C, D, E, F, G] (I'm avoiding the oddity of a being used to represent both the list and the member of the list; I assume that was an oversight in constructing your post. First iteration is del a[1], leaving a as [A, C, D, E, F, G] Second iteration is del a[2]. But now, element 2 is D, not the C you wanted deleted, leaving a = [A, C, E, F, G] Third iteration is del a[3]. Element 3 is F, leaaving a = [A, C, E, G]. A kludge would be to delete in right-to-left order instead: b_rev = b b_rev.sort() # b = [1, 2, 4] ; sorted just to be sure b_rev.reverse() # b = [4, 2, 1] for i in b_rev: del a[i] But that's pretty ugly. I'll bet someone has responded with a far more pythonic way of doing this as I've been typing. From pythonTutor at venix.com Fri Nov 12 00:17:50 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Nov 12 00:17:55 2004 Subject: [Tutor] a question about list In-Reply-To: References: Message-ID: <1100215069.18761.86.camel@laptop.venix.com> a=[a,b,c,d,e,f,g] b=[1,2,4] # so you want to delete b,c,e del a[1] a=[a,c,d,e,f,g] del a[2] a=[a,c,e,f,g] del a[4] a=[a,c,e,f] When you lay it out, you can see what is happening. As the list gets smaller, the index for an item changes. The best solution depends upon what you are really trying to do. You could make list_a into a dictionary with the index numbers as keys to the values. This gets around the renumbering. You could be careful to delete from list_a using the largest remaining index value. This would avoid changing the index numbers of your future deletions. So long as all of the index number values are known before you start deleting, that is a viable strategy. On Thu, 2004-11-11 at 17:43, Lin Jin wrote: > i am new to python.i have a question about list.if i have two list: > a=[a,b,c,d,e,f,g] > b=[1,2,4] > and i want to remove the element of a using b,that is i want a=[a,d,f,g],my > code is like this: > >>>for i in b: > >>> del a[b] > > but it is not working, it can't remove the correct items.what should i do > to make it correct?thx > > _________________________________________________________________ > ???? MSN Explorer: http://explorer.msn.com/lccn/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From jinlin555 at msn.com Fri Nov 12 00:24:50 2004 From: jinlin555 at msn.com (Lin Jin) Date: Fri Nov 12 00:25:09 2004 Subject: [Tutor] question about list Message-ID: > i am new to python.i have a question about list.if i have two list: > a=[a,b,c,d,e,f,g] > b=[1,2,4] > and i want to remove the element of a using b,that is i want a=[a,d,f,g],my > code is like this: > >>>for i in b: > >>> del a[i] > > but it is not working, it can't remove the correct items.what should i do > to make it correct?thx _________________________________________________________________ Ãâ·ÑÏÂÔØ MSN Explorer: http://explorer.msn.com/lccn/ From maxnoel_fr at yahoo.fr Fri Nov 12 00:33:02 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Nov 12 00:33:06 2004 Subject: [Tutor] a question about list In-Reply-To: References: Message-ID: <07C250B9-343A-11D9-A4DC-000393CBC88E@yahoo.fr> On Nov 11, 2004, at 23:17, Terry Carroll wrote: > A kludge would be to delete in right-to-left order instead: > > b_rev = b > b_rev.sort() # b = [1, 2, 4] ; sorted just to be sure > b_rev.reverse() # b = [4, 2, 1] > for i in b_rev: > del a[i] > > But that's pretty ugly. I'll bet someone has responded with a far more > pythonic way of doing this as I've been typing. a = [element for index, element in enumerate(a) if index not in b] Looks a bit more Pythonic to me. I also think it's faster. However, it uses more memory: in the "worst" case, you'll find yourself with a copy of a in memory for a short moment. Probably not a big deal, though, unless a is already occupying more than half your computer's memory. -- 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 carroll at tjc.com Fri Nov 12 00:43:20 2004 From: carroll at tjc.com (Terry Carroll) Date: Fri Nov 12 00:43:24 2004 Subject: [Tutor] a question about list In-Reply-To: <07C250B9-343A-11D9-A4DC-000393CBC88E@yahoo.fr> Message-ID: On Thu, 11 Nov 2004, Max Noel wrote: > a = [element for index, element in enumerate(a) if index not in b] Damn, and I thought I was starting to get list comprehensions; but this is impenetrable to me. That's not a criticism; more a statement on my inability to get list comprehensions. Would you mind unwrapping and explaining this a bit? I'd like to understand it better. From kalle at lysator.liu.se Fri Nov 12 00:58:51 2004 From: kalle at lysator.liu.se (Kalle Svensson) Date: Fri Nov 12 00:58:12 2004 Subject: [Tutor] a question about list In-Reply-To: References: <07C250B9-343A-11D9-A4DC-000393CBC88E@yahoo.fr> Message-ID: <20041111235851.GO29531@i92.ryd.student.liu.se> [Terry Carroll] > On Thu, 11 Nov 2004, Max Noel wrote: > > > a = [element for index, element in enumerate(a) if index not in b] [...] > Would you mind unwrapping and explaining this a bit? I'd like to > understand it better. a = [element # pick element for index, element in enumerate(a) # from each index, element # tuple returned by # enumerate(a) if index not in b] # if the index is not in b The key thing here is that "for index, element in enumerate(a)" contains an implicit tuple assignment (like "a, b = c, d"). Making the tuple more explicit might be a good idea: a = [element for (index, element) in enumerate(a) if index not in b] is, in my mind, perhaps a bit clearer. Peace, Kalle -- http://juckapan.org/~kalle/ http://laxmasteriet.se/04-05/ http://www.baljan.studorg.liu.se/ From tim at johnsons-web.com Fri Nov 12 01:03:25 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Fri Nov 12 01:03:21 2004 Subject: [Tutor] mod_python - script revisions? Message-ID: <20041112000325.GA17056@johnsons-web.com> I have python scripts running as cgi. mod_python will soon be employed on that server. To run those python scripts thru mod_python, will I need to make any revisions to my code? Pointers to documentation are welcome. thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From maxnoel_fr at yahoo.fr Fri Nov 12 01:06:54 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Nov 12 01:06:58 2004 Subject: [Tutor] a question about list In-Reply-To: References: Message-ID: On Nov 11, 2004, at 23:43, Terry Carroll wrote: > On Thu, 11 Nov 2004, Max Noel wrote: > >> a = [element for index, element in enumerate(a) if index not in b] > > Damn, and I thought I was starting to get list comprehensions; but > this is > impenetrable to me. > > That's not a criticism; more a statement on my inability to get list > comprehensions. > > Would you mind unwrapping and explaining this a bit? I'd like to > understand it better. Sure, no problems. The cornerstone of this list comprehension is enumerate(a). This is basically an iterator that yields (index, element) tuples. In other words, >>> blah = ['a', 'b', 'c', 'd'] >>> for index, element in enumerate(foo): ... print "%s -> %s" % (index, element) ... 0 -> a 1 -> b 2 -> c 3 -> d So if my list comprehension were: a = [element for index, element in enumerate(a)] It would be equivalent to assigning to a a copy of itself. However, the great thing about list comprehensions is that you can specify a condition that an element has to match to be added to the list, some sort of filter. Here's an example: >>> foo = [0, 1, 2, 0, 3, 0, 4, 0, 5] >>> bar = [element for element in foo if element != 0] >>> bar [1, 2, 3, 4, 5] If element is equal to zero, it is not added to the resulting list. Still following (I know, I'm not very good at explaining)? If so, you should be starting to get my original list comprehension, which is: a = [element for index, element in enumerate(a) if index not in b] Here, I'm iterating over two variables: for each element of the original list a, index contains its index and element contains the value of the element itself (yeah, I like to use explicit names). Besides, b contains the indexes of the elements which we want to delete from a, i.e. the indexes of the elements which we don't want in the resulting list. Therefore, the condition if index not in b filters out the elements whose indexes are elements of b. In the original example, b = [1, 2, 4]. Thus, the elements in a whose indexes are 1, 2 or 4 are filtered out. Did that help? -- 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 carroll at tjc.com Fri Nov 12 01:07:50 2004 From: carroll at tjc.com (Terry Carroll) Date: Fri Nov 12 01:07:53 2004 Subject: [Tutor] a question about list In-Reply-To: <20041111235851.GO29531@i92.ryd.student.liu.se> Message-ID: On Fri, 12 Nov 2004, Kalle Svensson wrote: > a = [element # pick element > for index, element in enumerate(a) # from each index, element > # tuple returned by > # enumerate(a) > if index not in b] # if the index is not in b kewl, thanks. From andre.roberge at ns.sympatico.ca Fri Nov 12 01:08:08 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Fri Nov 12 01:08:06 2004 Subject: [Tutor] Solved! was Re: help needed with using exec Message-ID: <4193FEE8.1000407@ns.sympatico.ca> Andr? Roberge wrote: > Dear Tutors, > > Suppose I have in file test.py a single line: > move() > [snip] I was doing as Kent was suggesting below (I just wasn't explaining it well). The problem was that my test file move did NOT contain only one line but was as follows: ---begin-- move() ---end-- i.e. it had two blank lines tagged at the end. When I tried to reproduce my problem with 4 short interconnected programs (as is the case in my complete program), including a test.py file with only ONE line ... I couldn't do it. Two hours later, by removing functions after functions from my bigger app, converting it from a wxPython GUI application to simpler scripts ... I eventually reduced it to something identical to the short 4 scripts mentioned in the paragraph above. So.... the only thing left to look at was the file test.py.... Sure enough.... I'm reporting this to the list in the hope that it might help someone else, sometime... =========== Kent wrote: what about this? move = instance.move exec code If that doesn't work, please post a short, complete program and the exact error message you are getting when you run it. Kent From cyresse at gmail.com Fri Nov 12 01:26:07 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 12 01:26:11 2004 Subject: [Tutor] question about list In-Reply-To: References: Message-ID: Hi Lin, I ran into this problem myself once, and I forgot how I fixed it. I can, however, tell you what's going wrong - a=['a','b','c','d','e','f','g'] b=[1,2,4] for in in b: del a[i] Watch this for i in b: del a[1] a becomes ['a','c','d','e','f','g'] next one around del a[2] a[2] is now 'd' ! so a becomes ['a','c','e','f','g'] del a[4] a[4] is now 'g' so you are going to get - a=['a','c','e','f'] So that's what's going wrong for you. I worked around this once by the following - but bear in mind that all my workarounds are messy, and there will be a better way, which hopefully someone will post shortly, because I'm curious also. work-around - a=['a','b','c','d','e','f','g'] b=[1,2,4] for i in b: a[i]="XX" <-- this makes a=['a','XX','XX','d','XX','f','g'] while a.count("XX"): While the number of occurences of 'XX' in a are above zero, do this... a.remove("XX") Remove the first occurrence of 'XX' found which gives you a=['a', 'd', 'f', 'g'] But like I said, there'll be an easier way. Hope it helps, Liam Clarke On Fri, 12 Nov 2004 07:24:50 +0800, Lin Jin wrote: > > i am new to python.i have a question about list.if i have two list: > > a=[a,b,c,d,e,f,g] > > b=[1,2,4] > > and i want to remove the element of a using b,that is i want > a=[a,d,f,g],my > > code is like this: > > >>>for i in b: > > >>> del a[i] > > > > but it is not working, it can't remove the correct items.what should i do > > > to make it correct?thx > > _________________________________________________________________ > ???? MSN Explorer: http://explorer.msn.com/lccn/ > > _______________________________________________ > 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 bill.mill at gmail.com Fri Nov 12 01:59:09 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Nov 12 01:59:15 2004 Subject: [Tutor] question about list In-Reply-To: References: Message-ID: <797fe3d40411111659200766ea@mail.gmail.com> Lin, b.sort() for i in b: del a[i] b = [element-1 for element in b] Peace Bill Mill On Fri, 12 Nov 2004 07:24:50 +0800, Lin Jin wrote: > > i am new to python.i have a question about list.if i have two list: > > a=[a,b,c,d,e,f,g] > > b=[1,2,4] > > and i want to remove the element of a using b,that is i want > a=[a,d,f,g],my > > code is like this: > > >>>for i in b: > > >>> del a[i] > > > > but it is not working, it can't remove the correct items.what should i do > > > to make it correct?thx > > _________________________________________________________________ > ???? MSN Explorer: http://explorer.msn.com/lccn/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Fri Nov 12 03:26:14 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 12 03:26:17 2004 Subject: [Tutor] question about list In-Reply-To: <797fe3d40411111659200766ea@mail.gmail.com> References: <797fe3d40411111659200766ea@mail.gmail.com> Message-ID: Heh, If you don't mind, could you explain how that works? Especially the b=[element..] part. Day by day, I learn that I have so much more to learn. Sheesh. Thanks, Liam Clarke On Thu, 11 Nov 2004 19:59:09 -0500, Bill Mill wrote: > Lin, > > b.sort() > for i in b: > del a[i] > b = [element-1 for element in b] > > Peace > Bill Mill > > > > > On Fri, 12 Nov 2004 07:24:50 +0800, Lin Jin wrote: > > > i am new to python.i have a question about list.if i have two list: > > > a=[a,b,c,d,e,f,g] > > > b=[1,2,4] > > > and i want to remove the element of a using b,that is i want > > a=[a,d,f,g],my > > > code is like this: > > > >>>for i in b: > > > >>> del a[i] > > > > > > but it is not working, it can't remove the correct items.what should i do > > > > > to make it correct?thx > > > > _________________________________________________________________ > > ???? MSN Explorer: http://explorer.msn.com/lccn/ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > 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 bill.mill at gmail.com Fri Nov 12 04:01:43 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Nov 12 04:01:48 2004 Subject: [Tutor] question about list In-Reply-To: References: <797fe3d40411111659200766ea@mail.gmail.com> Message-ID: <797fe3d4041111190136f8aff5@mail.gmail.com> Liam, Sure. Sorry I was kinda short, I was in a rush earlier. Now, I got time. In [1]: a = [1,2,3,4,5,6] In [2]: idx = [1,2,4] Now, what we want to do is delete the first, second and fourth elements (we'll let 1 be the 'zeroth' element, for convenience) of 'a'. I've renamed 'b' to 'idx', meaning index. When we delete the first element of 'a', we have a problem - what does a look like now? In [3]: del a[idx[0]] In [4]: a Out[4]: [1, 3, 4, 5, 6] We've removed the first element, but the second and fourth elements have now become the first and third elements. Thus, we need to subtract one from every element of 'idx'. I accomplished this with a list comprehension: In [5]: idx = [elt-1 for elt in idx] In [6]: idx Out[6]: [0, 1, 3] To read list comprehensions, read from the right. The first clause is "for elt in idx" which works exactly like a for loop. The second clause is "elt-1", which tells python to subtract one from the current element. So, overall, the list comprehension tells python "make a list composed of elt-1 for each elt in idx". Does that make sense? Try playing around with them in the interpreter for a while. If you still don't understand what's going on (they're hard), send a new message to the list and I'll try to give a more detailed explanation of what's going on. Now, to continue, when we do: In [7]: del a[idx[1]] In [8]: a Out[8]: [1, 4, 5, 6] We delete the correct element. However, again, the third element has become the second element, so we have to update idx, and so on until we're done. Now, looking at this with more time has given me a better idea. If we start removing entries from the back, instead of the front, the order of the elements we want to remove won't change. Thus, this code: a = [1,2,3,4,5,6] idx = [1,2,4] idx.sort() idx.reverse() for i in idx: del a[i] Which works much more nicely, and very likely more efficiently, since it doesn't have to iterate through the entire idx list every time it deletes an element of a. Does it make sense now? If not, feel free to drop me more questions. I've been doing it for a while, so I tend to miss newbie mistakes. Peace Bill Mill On Fri, 12 Nov 2004 15:26:14 +1300, Liam Clarke wrote: > Heh, > > If you don't mind, could you explain how that works? > > Especially the b=[element..] part. > > Day by day, I learn that I have so much more to learn. Sheesh. > > Thanks, > > Liam Clarke > > > On Thu, 11 Nov 2004 19:59:09 -0500, Bill Mill wrote: > > Lin, > > > > b.sort() > > for i in b: > > del a[i] > > b = [element-1 for element in b] > > > > Peace > > Bill Mill > > > > > > > > > > On Fri, 12 Nov 2004 07:24:50 +0800, Lin Jin wrote: > > > > i am new to python.i have a question about list.if i have two list: > > > > a=[a,b,c,d,e,f,g] > > > > b=[1,2,4] > > > > and i want to remove the element of a using b,that is i want > > > a=[a,d,f,g],my > > > > code is like this: > > > > >>>for i in b: > > > > >>> del a[i] > > > > > > > > but it is not working, it can't remove the correct items.what should i do > > > > > > > to make it correct?thx > > > > > > _________________________________________________________________ > > > ???? MSN Explorer: http://explorer.msn.com/lccn/ > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > > 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. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Nov 12 04:19:12 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 12 04:19:17 2004 Subject: [Tutor] a question about list In-Reply-To: <07C250B9-343A-11D9-A4DC-000393CBC88E@yahoo.fr> References: <07C250B9-343A-11D9-A4DC-000393CBC88E@yahoo.fr> Message-ID: <41942BB0.7040502@tds.net> Max Noel wrote: > > On Nov 11, 2004, at 23:17, Terry Carroll wrote: > a = [element for index, element in enumerate(a) if index not in b] > > Looks a bit more Pythonic to me. I also think it's faster. Regular readers of this list know I can't resist an optimization challenge :-) Also I was suspicious of Max's claim, as this method is clearly O(len(a) * len(b)) at least - for each element of a, the list b is searched for the index. Terry Carroll proposed: > b_rev = b Note: if you want to copy b, use b_rev = b[:] > b_rev.sort() # b = [1, 2, 4] ; sorted just to be sure > b_rev.reverse() # b = [4, 2, 1] > for i in b_rev: > del a[i] At first glance this seems more promising, as it skips the searching through b. But the del a[i] step requires copying all the elements of a after location i, so it is O(len(a)) and this method also seems to be O(len(a) * len(b)) - that is, the time taken will be proportional to the length of a times the length of b. Liam Clarke proposed > for i in b: > a[i]="XX" <-- this makes a=['a','XX','XX','d','XX','f','g'] > > while a.count("XX"): While the number of occurences of 'XX' in a are above zero, do this... > a.remove("XX") Remove the first occurrence of 'XX' found This doesn't strike me as too promising because removing the 'XX' values requires _two_ searches through a for _each_ removal. But the removal could be done with a list comprehension which would make it work with a single pass over a: a = [ element for element in a if element != 'XX' ] Of course this requires that 'XX' does not appear in a, which could be a problem. A way around that is to make a unique sentinel and use it instead: class Sentinel: pass s = Sentinel() This algorithm appears to be O(len(a) + len(b)) which could be a significant advantage for large a and b. So, those are the three contenders. Here is a program to test them. It removes every fourth element from a list of 10000 integers: ################## import random, timeit a = range(10000) b = range(0, 10000, 4) random.shuffle(b) # Make the sort do some work def remove1(a, b): b = b[:] b.sort() b.reverse() for i in b: del a[i] def remove2(a, b): a[:] = [ element for i, element in enumerate(a) if i not in b ] def remove3(a, b): class Sentinel: pass s = Sentinel() for i in b: a[i] = s a[:] = [elem for elem in a if elem is not s] def timeOne(fn): setup = "from __main__ import " + fn.__name__ + ',a,b' stmt = fn.__name__ + '(a[:], b[:])' t = timeit.Timer(stmt, setup) secs = min(t.repeat(3, 1)) print '%s: %f secs' % (fn.__name__, secs) # Make sure they all give the same answer a1=a[:] b1 = b[:] remove1(a1, b1) a2=a[:] b2 = b[:] remove2(a2, b2) a3=a[:] b3 = b[:] remove3(a3, b3) assert a1 == a2 assert a3 == a2 timeOne(remove1) timeOne(remove2) timeOne(remove3) ################ Here are my results: remove1: 0.023205 secs remove2: 1.262509 secs remove3: 0.004119 secs So with large a and b, the algorithm with the sentinel is a clear winner. The enumerate algorithm is far slower than the one with del a[i]; my guess this is because the del does a block move of memory, which can be very fast, while the enumerate version has to actually search. What about for small a and b? Here are my results with a = range(100) b = range(0, 100, 4) remove1: 0.000032 secs remove2: 0.000181 secs remove3: 0.000052 secs Now the del version wins; I think the very fast built-in list operations take the prize here. Of course with small a and b, these are all very fast and the enumerate version has the advantage of being concise and readable. Kent From keridee at jayco.net Fri Nov 12 04:18:31 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Nov 12 04:19:22 2004 Subject: [Tutor] Would an OOP approach be simpler? References: <00dd01c4c6d3$ad2e7a80$db5428cf@JSLAPTOP> <4191F25B.2020107@tds.net> Message-ID: <005801c4c866$59b2b580$6c5328cf@JSLAPTOP> Thanks to Kent and Chad for answering! BTW, readlines()[0] was a brain fart. I should have seen that. Thanks. Jacob Schmidt From keridee at jayco.net Fri Nov 12 04:27:18 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Nov 12 04:27:48 2004 Subject: [Tutor] Amazed Message-ID: <006401c4c867$87a30110$6c5328cf@JSLAPTOP> Wow! I'm amazed that several people are having trouble with list comprehensions. I must think in that style or something. I've come up with odd uses for them. This one threw me for a while... newlist = [] powers = [] a = 'x**2+sin(x)+2*x' a = a.split("+") powers = [newlist.append(x) for x in a if x.count('**') >= 1] print powers #Code yields [None] Since this is embeded deep in sloppy code, it took me a bit to realize that I was really wanting newlist. So... >>> print newlist ['x**2'] Just thought I'd share an odd usage of list comprehensions with you all. Jacob Schmidt From kent37 at tds.net Fri Nov 12 04:37:01 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 12 04:37:06 2004 Subject: [Tutor] Amazed In-Reply-To: <006401c4c867$87a30110$6c5328cf@JSLAPTOP> References: <006401c4c867$87a30110$6c5328cf@JSLAPTOP> Message-ID: <41942FDD.3030105@tds.net> Jacob S. wrote: > newlist = [] > powers = [] > a = 'x**2+sin(x)+2*x' > a = a.split("+") > powers = [newlist.append(x) for x in a if x.count('**') >= 1] This is bizarre, to append to another list instead of just letting the list comprehension do its thing! It could be powers = [x for x in a if x.count('**') >= 1] or how about powers = [x for x in a if '**' in x] Kent From bill.mill at gmail.com Fri Nov 12 06:40:16 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Nov 12 06:40:18 2004 Subject: [Tutor] Amazed In-Reply-To: <006401c4c867$87a30110$6c5328cf@JSLAPTOP> References: <006401c4c867$87a30110$6c5328cf@JSLAPTOP> Message-ID: <797fe3d404111121401462d5fd@mail.gmail.com> Jacob, I think it's a readability problem - it's too easy to abuse list comprehensions to turn a 2 or 3 line for loop into a difficult to understand one-liner. Today I found myself doing: [myset.add(x) for x in thingToIterate where x] instead of: for x in thingToIterate: if x: myset.add(x) which is much more readable, and doesn't eat the memory of creating an unnecessary list full of 'None'. I immediately fixed my mistake, but it made me realize how addictive list comprehensions are; they're like Python crack. Peace Bill Mill bill.mill@gmail.com On Thu, 11 Nov 2004 22:27:18 -0500, Jacob S. wrote: > Wow! > > I'm amazed that several people are having trouble with list > comprehensions. I must think in that style or something. I've come up with > odd uses for them. This one threw me for a while... > > newlist = [] > powers = [] > a = 'x**2+sin(x)+2*x' > a = a.split("+") > powers = [newlist.append(x) for x in a if x.count('**') >= 1] > print powers > > #Code yields > > [None] > > Since this is embeded deep in sloppy code, it took me a bit to realize > that I was really wanting newlist. > So... > > >>> print newlist > ['x**2'] > > Just thought I'd share an odd usage of list comprehensions with you all. > Jacob Schmidt > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Fri Nov 12 06:56:04 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Nov 12 06:56:07 2004 Subject: [Tutor] a question about list In-Reply-To: <41942BB0.7040502@tds.net> References: <07C250B9-343A-11D9-A4DC-000393CBC88E@yahoo.fr> <41942BB0.7040502@tds.net> Message-ID: <797fe3d4041111215655e44a8@mail.gmail.com> On Thu, 11 Nov 2004 22:19:12 -0500, Kent Johnson wrote: > Max Noel wrote: > > > > On Nov 11, 2004, at 23:17, Terry Carroll wrote: > > a = [element for index, element in enumerate(a) if index not in b] > > > > Looks a bit more Pythonic to me. I also think it's faster. > > Regular readers of this list know I can't resist an optimization > challenge :-) Also I was suspicious of Max's claim, as this method is > clearly O(len(a) * len(b)) at least - for each element of a, the list b > is searched for the index. > Well, as you all probably know, I can't resist one either, and I think I found a way to one-up all the given functions. I replaced remove2 since it was the loser and I'm lazy: ###### #snip the top of Kent's file def remove2(a, b): b.sort() b.reverse() for i in b: a.pop(i) #snip the bottom of it too ####### And the results: In [7]: @run test remove1: 0.028097 secs remove4: 0.026908 secs remove3: 0.004299 secs So, the builtin list.pop method appears to be the fastest. By the by, the built-in list.remove function is horribly slow for this task, I found. I *guess* it's because a.remove(a[i]) has an extra list access, but that doesn't explain a time of .7 secs on this test. Anybody got a guess why? Peace Bill Mill bill.mill at gmail.com From bill.mill at gmail.com Fri Nov 12 06:57:24 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Nov 12 06:57:27 2004 Subject: [Tutor] a question about list In-Reply-To: <797fe3d4041111215655e44a8@mail.gmail.com> References: <07C250B9-343A-11D9-A4DC-000393CBC88E@yahoo.fr> <41942BB0.7040502@tds.net> <797fe3d4041111215655e44a8@mail.gmail.com> Message-ID: <797fe3d404111121573124ccef@mail.gmail.com> > In [7]: @run test > remove1: 0.028097 secs > remove4: 0.026908 secs > remove3: 0.004299 secs > Doh! that should read remove2, not remove4... Peace Bill Mill bill.mill at gmail.com From cyresse at gmail.com Fri Nov 12 09:21:42 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 12 09:21:44 2004 Subject: [Tutor] question about list In-Reply-To: <797fe3d4041111190136f8aff5@mail.gmail.com> References: <797fe3d40411111659200766ea@mail.gmail.com> <797fe3d4041111190136f8aff5@mail.gmail.com> Message-ID: This is fantastic - a = [1,2,3,4,5,6] idx = [1,2,4] idx.sort() idx.reverse() for i in idx: del a[i] It's so simple once you know the answer. Like a cryptic crossword, you slap your forehead and say 'of course.' Cheers Bill. Liam Clarke On Thu, 11 Nov 2004 22:01:43 -0500, Bill Mill wrote: > Liam, > > Sure. Sorry I was kinda short, I was in a rush earlier. Now, I got time. > > In [1]: a = [1,2,3,4,5,6] > > In [2]: idx = [1,2,4] > > Now, what we want to do is delete the first, second and fourth > elements (we'll let 1 be the 'zeroth' element, for convenience) of > 'a'. I've renamed 'b' to 'idx', meaning index. When we delete the > first element of 'a', we have a problem - what does a look like now? > > In [3]: del a[idx[0]] > > In [4]: a > Out[4]: [1, 3, 4, 5, 6] > > We've removed the first element, but the second and fourth elements > have now become the first and third elements. Thus, we need to > subtract one from every element of 'idx'. I accomplished this with a > list comprehension: > > In [5]: idx = [elt-1 for elt in idx] > > In [6]: idx > Out[6]: [0, 1, 3] > > To read list comprehensions, read from the right. The first clause is > "for elt in idx" which works exactly like a for loop. The second > clause is "elt-1", which tells python to subtract one from the current > element. So, overall, the list comprehension tells python "make a list > composed of elt-1 for each elt in idx". > Does that make sense? Try playing around with them in the interpreter > for a while. If you still don't understand what's going on (they're > hard), send a new message to the list and I'll try to give a more > detailed explanation of what's going on. > > Now, to continue, when we do: > > In [7]: del a[idx[1]] > > In [8]: a > Out[8]: [1, 4, 5, 6] > > We delete the correct element. However, again, the third element has > become the second element, so we have to update idx, and so on until > we're done. > > Now, looking at this with more time has given me a better idea. If we > start removing entries from the back, instead of the front, the order > of the elements we want to remove won't change. Thus, this code: > > a = [1,2,3,4,5,6] > idx = [1,2,4] > idx.sort() > idx.reverse() > for i in idx: > del a[i] > > Which works much more nicely, and very likely more efficiently, since > it doesn't have to iterate through the entire idx list every time it > deletes an element of a. > > Does it make sense now? If not, feel free to drop me more questions. > I've been doing it for a while, so I tend to miss newbie mistakes. > > > > Peace > Bill Mill > > On Fri, 12 Nov 2004 15:26:14 +1300, Liam Clarke wrote: > > Heh, > > > > If you don't mind, could you explain how that works? > > > > Especially the b=[element..] part. > > > > Day by day, I learn that I have so much more to learn. Sheesh. > > > > Thanks, > > > > Liam Clarke > > > > > > On Thu, 11 Nov 2004 19:59:09 -0500, Bill Mill wrote: > > > Lin, > > > > > > b.sort() > > > for i in b: > > > del a[i] > > > b = [element-1 for element in b] > > > > > > Peace > > > Bill Mill > > > > > > > > > > > > > > > On Fri, 12 Nov 2004 07:24:50 +0800, Lin Jin wrote: > > > > > i am new to python.i have a question about list.if i have two list: > > > > > a=[a,b,c,d,e,f,g] > > > > > b=[1,2,4] > > > > > and i want to remove the element of a using b,that is i want > > > > a=[a,d,f,g],my > > > > > code is like this: > > > > > >>>for i in b: > > > > > >>> del a[i] > > > > > > > > > > but it is not working, it can't remove the correct items.what should i do > > > > > > > > > to make it correct?thx > > > > > > > > _________________________________________________________________ > > > > ???? MSN Explorer: http://explorer.msn.com/lccn/ > > > > > > > > _______________________________________________ > > > > Tutor maillist - Tutor@python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > > > 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. > > _______________________________________________ > > 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 Fri Nov 12 11:56:06 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 12 11:56:13 2004 Subject: [Tutor] a question about list In-Reply-To: <797fe3d4041111215655e44a8@mail.gmail.com> References: <07C250B9-343A-11D9-A4DC-000393CBC88E@yahoo.fr> <41942BB0.7040502@tds.net> <797fe3d4041111215655e44a8@mail.gmail.com> Message-ID: <419496C6.6060807@tds.net> Bill Mill wrote: > On Thu, 11 Nov 2004 22:19:12 -0500, Kent Johnson wrote: > ###### > #snip the top of Kent's file > > def remove2(a, b): > b.sort() > b.reverse() > for i in b: > a.pop(i) > > #snip the bottom of it too > ####### > > And the results: > > In [7]: @run test > remove1: 0.028097 secs > remove4: 0.026908 secs > remove3: 0.004299 secs > > So, the builtin list.pop method appears to be the fastest. Strange, in my testing it is slower to use a.pop(i) than del a[i]; i.e. your remove2 above is slower than my remove1. I tried both Python 2.3.4 and Python 2.4 on Win2k. Are you sure you read the results correctly? (When the function name in the results is different from the name in the presented code I have to wonder...) > By the by, the built-in list.remove function is horribly slow for this > task, I found. I *guess* it's because a.remove(a[i]) has an extra list > access, but that doesn't explain a time of .7 secs on this test. > Anybody got a guess why? a.remove(a[i]) is removing by _value_, not by index. So it has to search the list for the value to be removed. This is very slow compared to del a[i] which goes right to the correct spot in the list. Kent > > Peace > Bill Mill > bill.mill at gmail.com > From rdm at rcblue.com Fri Nov 12 14:06:54 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Nov 12 14:07:31 2004 Subject: [Tutor] how do i use p2exe In-Reply-To: <00e701c4c6d9$ac052e00$db5428cf@JSLAPTOP> References: <1033bb7f041109191055f46aee@mail.gmail.com> <00e701c4c6d9$ac052e00$db5428cf@JSLAPTOP> Message-ID: <6.1.2.0.2.20041112042711.08269eb0@rcblue.com> Am I the only one having trouble with this? Here's what I did, and what happens. I'm running Win XP and Python 2.3.4. I installed py2exe from http://starship.python.net/crew/theller/py2exe/ . I created setup.py. But in order to have it run I changed the 3rd line of lookdir() to if look.lower() == "y": I created the batch file, which I named test.bat. I used the line cd\python23 as is, because that's where my python23 is. When I run test.bat I get "Current directory is: C:\Python23 Do you wish to see what's in directory?" If I answer "y" I'm correctly shown what's in Python23, and asked, "What is the file you want as an executable? (Type 'quit' to break out of loop) ?" I type "weekday.py" a script I have in Python23. The "DOS" (consol?) window closes immediately. That's it. No creation of weekday.exe. Have I done something wrong. Or what? Thanks, tutors. Dick Moores rdm@rcblue.com At 19:59 11/9/2004, Jacob S. wrote: >This is what I did. >I'm using Windows XP, but it would work for any other windows version... > >1) Take code below and copy into file named "setup.py". > >### Start of Code ### >from distutils.core import setup >import py2exe >import os > > >def lookdir(): > print "Current directory is: %s" % os.getcwd() > look = raw_input('Do you wish to see what\'s in directory? ') > if look.lower() in m: > print "\n".join(os.listdir(os.getcwd())) > >def changedir(): > m = ['y','ye','yes','yep','okay','affirmative','sure'] > ask = 'y' > lookdir() > while ask not in m: > di = raw_input('What directory do you want? ') > os.chdir(di) > lookdir() > ask = raw_input('Do you want this directory? ') > >changedir() >listed = [] >while 1: > ask = raw_input('What is the file you want as an executable? (Type >\'quit\' to break out of loop) ') > if ask == 'quit' or ask == 'stop' or ask == '': > break > else: > listed.append(os.path.join(desktop,ask)) > >setup(console = listed) >### End of Code ### > >2) Take following code and save as a batch file. You will have to change the >second line to change the directory to your python dir > >rem Start of Code >@echo off >cd\python23 >start python setup.py py2exe >rem End of Code > >3) Run the batch file. It will ask you which directory the script file is >in. That would be the file that you're trying to make and executable. Then, >when you decide which directory it is in, it will ask you the name of the >file. You type in the name. If you want more than one file, you can type in >another file name in the next prompt, else you can type in 'quit' or 'stop' >or just hit enter. When all is done and the shell window closes, you can >check out the directory that you chose. In that directory, there will be two >new folders. One is labeled build. That folder is not necessary to run your >executable and can be deleted. I usually delete it. The other is labeled >dist. It contains the files needed for your program. Your program will have >the same name, just with a exe extension instead of a py extension. Send the >whole folder on to your students, and they can double-click on the exe file, >and it will run your script as if you double-clicked it in Windows Explorer. > >Also, in your code (which I will try to rewrite for fun on my own (no >offense)) you might try this instead: > >print "".join(["\t","\\"*7," ","\\"*4," ","\\"*6," ","\\"*7," ","\\"*2," >","\\"*10," ","\\"*2," ","\\"*8,"\n"]) > >Ignore the underline and blue if it shows up in your email thing. >This just shows that you can multiply a particular string by an integer to >copy it. > >Hope all this helps, >Jacob Schmidt From bill.mill at gmail.com Fri Nov 12 15:16:21 2004 From: bill.mill at gmail.com (Bill Mill) Date: Fri Nov 12 15:16:28 2004 Subject: [Tutor] a question about list In-Reply-To: <419496C6.6060807@tds.net> References: <07C250B9-343A-11D9-A4DC-000393CBC88E@yahoo.fr> <41942BB0.7040502@tds.net> <797fe3d4041111215655e44a8@mail.gmail.com> <419496C6.6060807@tds.net> Message-ID: <797fe3d4041112061664b2f6f5@mail.gmail.com> Kent, > > Strange, in my testing it is slower to use a.pop(i) than del a[i]; i.e. > your remove2 above is slower than my remove1. I tried both Python 2.3.4 > and Python 2.4 on Win2k. Are you sure you read the results correctly? > (When the function name in the results is different from the name in the > presented code I have to wonder...) > Yup, I fail it. I'm not getting those results anymore - it was late last night. That's my excuse and I'm sticking to it. > > By the by, the built-in list.remove function is horribly slow for this > > task, I found. I *guess* it's because a.remove(a[i]) has an extra list > > access, but that doesn't explain a time of .7 secs on this test. > > Anybody got a guess why? > > a.remove(a[i]) is removing by _value_, not by index. So it has to search > the list for the value to be removed. This is very slow compared to del > a[i] which goes right to the correct spot in the list. > Seems to make sense. Peace Bill Mill bill.mill at gmail.com From cyresse at gmail.com Fri Nov 12 16:00:02 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 12 16:00:05 2004 Subject: [Tutor] Globals? Message-ID: Hi all, Having trouble with something, it is 3:30am in the morning, so this may be a dumb problem, if so, I apologise. In my prog, there's two variables created right at the get go - import imaplib import email.Parser import os import os.path import datetime import md5 from pause import * badUserList=[] badConnectCycle=0 as I want them to be global within this module, so that another module can pick them out easily. Now, I just added badConnectCycle, badUserList has been there awhile, and it's used in the function connectToImap which is called by getReturns which is called by main(), and my other module can get it no problem, so badUserList is fine. badConnectCycle... is giving me errors - badConnectCycle is used in getReturns, as so - if session == "NoConnect" : badConnectCycle += 1 continue function getReturns ends as follows - if badConnectCycle == len(user) and badConnectCycle > 0: return ("NoConnect","") if badUserList and not sender: return ('NoLogin',"") if matchindex[0] and not sender: return ('NoNew', '') if not sender: return ("NoMatch","") return (sender, msgdata) and it's at that line if badConnectCycle == len(user) and badConnectCycle > 0: that I get this error: UnboundLocalError: local variable 'badConnectCycle' referenced before assignment. Which is confusing me because badUserList is used within a function called by getReturns, and I've had no problem with it. Help anyone? Much appreciated if you can. Regards, Liam Clarke -- '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 Fri Nov 12 16:02:07 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 12 16:09:10 2004 Subject: [Tutor] Globals? In-Reply-To: References: Message-ID: <4194D06F.1090904@tds.net> Liam, When you make any assignment to a variable inside a function, Python assumes that the variable is local to the function. Then any use of the variable before it's first assignment is an error. To force a variable in a function to be global, put a 'global' statement in the function. You need to add global badConnectCycle to your function getReturns If you don't make any assignment to a variable, then the global (module) namespace is searched. That is why badUserList works fine - you never assign it, you just access the list methods. Kent Liam Clarke wrote: > Hi all, > > Having trouble with something, it is 3:30am in the morning, so this > may be a dumb problem, if so, I apologise. > > In my prog, there's two variables created right at the get go - > > import imaplib > import email.Parser > import os > import os.path > import datetime > import md5 > from pause import * > > badUserList=[] > badConnectCycle=0 > > as I want them to be global within this module, so that another module > can pick them out easily. > > Now, I just added badConnectCycle, badUserList has been there awhile, > and it's used in > > the function connectToImap which is called by getReturns which is > called by main(), and my other module can get it no problem, so > badUserList is fine. > > badConnectCycle... is giving me errors - > > badConnectCycle is used in getReturns, as so - > > if session == "NoConnect" : > badConnectCycle += 1 > continue > > > function getReturns ends as follows - > > if badConnectCycle == len(user) and badConnectCycle > 0: return ("NoConnect","") > if badUserList and not sender: return ('NoLogin',"") > if matchindex[0] and not sender: return ('NoNew', '') > if not sender: return ("NoMatch","") > return (sender, msgdata) > > and it's at that line > > if badConnectCycle == len(user) and badConnectCycle > 0: > > that I get this error: > > UnboundLocalError: local variable 'badConnectCycle' referenced before > assignment. > > Which is confusing me because badUserList is used within a function > called by getReturns, and I've had no problem with it. > > Help anyone? Much appreciated if you can. > > Regards, > > Liam Clarke From kapiladhanvi at gmail.com Fri Nov 12 16:44:15 2004 From: kapiladhanvi at gmail.com (Mr. Dhanvi Kapila) Date: Fri Nov 12 16:44:20 2004 Subject: [Tutor] VB + python? Message-ID: <35ccaa9904111207446885629c@mail.gmail.com> Hi, I was developing a GUI application and was curious as to whether Python modules can be called from within VB. Is there any way in which this can be achieved ? GUI creation is simple in VB and scripts writing is a breeze in Python so I wanted to combine the 2 to create an application. Awaiting your replies. Thanks for the replies. Sincerely Dhanvi -- ?v? kapila * .dhanvi 2.0.0 /(_)\ http://kapiladhanvi.myensim.net ^ ^ the good ones may be taken.. but the best are still waiting for me LinUX From flaxeater at yahoo.com Fri Nov 12 17:14:12 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Nov 12 17:14:16 2004 Subject: [Tutor] VB + python? Message-ID: <20041112161413.85040.qmail@web54302.mail.yahoo.com> Mr. Dhanvi Kapila wrote: >Hi, > > I was developing a GUI application and was curious as to whether > >Python modules can be called from within VB. Is there any way in > >which this can be achieved ? > > GUI creation is simple in VB and scripts writing is a breeze in > >Python so I wanted to combine the 2 to create an application. > > Awaiting your replies. Thanks for the replies. > > > >Sincerely > >Dhanvi > > > I've ran across this before I have however not followed the instructions. http://www.hps1.demon.co.uk/users/andy/pyvb/ Good Luck __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kapiladhanvi at gmail.com Fri Nov 12 17:35:53 2004 From: kapiladhanvi at gmail.com (Mr. Dhanvi Kapila) Date: Fri Nov 12 17:35:58 2004 Subject: [Tutor] VB + python? In-Reply-To: <20041112161413.85040.qmail@web54302.mail.yahoo.com> References: <20041112161413.85040.qmail@web54302.mail.yahoo.com> Message-ID: <35ccaa99041112083525f44c02@mail.gmail.com> Hey buddy, Thanks!. That was what I was looking for .. Dhanvi On Fri, 12 Nov 2004 08:14:12 -0800 (PST), Chad Crabtree wrote: > Mr. Dhanvi Kapila wrote: > >Hi, > > > > I was developing a GUI application and was curious as to whether > > > >Python modules can be called from within VB. Is there any way in > > > >which this can be achieved ? > > > > GUI creation is simple in VB and scripts writing is a breeze in > > > >Python so I wanted to combine the 2 to create an application. > > > > Awaiting your replies. Thanks for the replies. > > > > > > > >Sincerely > > > >Dhanvi > > > > > > > I've ran across this before I have however not followed the > instructions. > > http://www.hps1.demon.co.uk/users/andy/pyvb/ > > Good Luck > -- ?v? kapila * .dhanvi 2.0.0 /(_)\ http://kapiladhanvi.myensim.net ^ ^ the good ones may be taken.. but the best are still waiting for me LinUX From kbond at free.fr Sat Nov 13 02:03:19 2004 From: kbond at free.fr (kbond) Date: Fri Nov 12 20:03:32 2004 Subject: [Tutor] urllib2 with a proxy Message-ID: <41955D57.9040804@free.fr> Kent, I did test your suggestion but unfortunatly it is still not working. Somehow I do not understand why it is so complex to go trough my proxy. I do not have any trouble if I use firefox or mozilla. I am completely stuck by this tiny detail. If someone on this list has clear and simple explanation about what is realm and host in "add_password('realm', 'host', 'username', 'password')" that will also help me a lot. Thank you for your help any pointer or code sample are more than welcome. *code** * import urllib2 # set up authentication info authinfo = urllib2.HTTPBasicAuthHandler() #add_password('realm', 'host', 'username', 'password') authinfo.add_password(None, "http://google.com", 'username', 'pwd') proxy_support = urllib2.ProxyHandler({"http" : "http//:proxy:8080"}) # build a new opener that adds authentication and caching FTP handlers opener = urllib2.build_opener(proxy_support, authinfo,urllib2.CacheFTPHandler()) # install it urllib2.install_opener(opener) f = urllib2.urlopen('http://google.com') buf = f.read() print buf f.close() *error* Traceback (most recent call last): File "testProxy.py", line 12, in ? f = urllib2.urlopen('http://google.com') File "E:\users\install\Python\lib\urllib2.py", line 129, in urlopen return _opener.open(url, data) File "E:\users\install\Python\lib\urllib2.py", line 326, in open '_open', req) File "E:\users\install\Python\lib\urllib2.py", line 306, in _call_chain result = func(*args) File "E:\users\install\Python\lib\urllib2.py", line 491, in lambda r, proxy=url, type=type, meth=self.proxy_open: \ File "E:\users\install\Python\lib\urllib2.py", line 498, in proxy_open if '@' in host: TypeError: iterable argument required kbond wrote: > Thank you for your help kent. > Already the second time that you are helping me. > In fact I face this proxy trouble right after your first answer I was > about to try your suggestion to solve the clientForm trouble when this > proxy came into the danse. > > When I started my project I was far to imagine that talking to the > world wide web was that difficult by script. > Unfortunatly I will not be able to test before monday because I do not > use a proxy at home. > Do you have an idea of what are realm and host in the add_password() > method? > I am making the assomption that host stand for the host I want to > contact but I do not have any idea of what realm is? > Do you know how I can get it? Why firefox don't need this information > to go out? > > You will find below the code I will try on monday. > Thank you for your help > > *Code* > import urllib2 > # set up authentication info > authinfo = urllib2.HTTPBasicAuthHandler() > #add_password('realm', 'host', 'username', 'password') > authinfo.add_password(None, "http://google.com", 'userName', 'pwd') > proxy_support = urllib2.ProxyHandler({"http" : "http//:proxy:8080"}) > # build a new opener that adds authentication and caching FTP handlers > opener = urllib2.build_opener(proxy_support, > authinfo,urllib2.CacheFTPHandler()) > # install it > urllib2.install_opener(opener) > f = urllib2.urlopen('http://google.com') > buf = f.read() > print buf > f.close() > > Kent Johnson wrote: > >> I'm not familiar with this library but looking at your code and the >> docs I can make some guesses where the problem might be: >> - The second argument to ProxyHandler should be a complete URL, e.g. >> 'http://proxy:8080'. This is the cause of the exception you are seeing. >> - Try using a HTTPBasicAuthHandler instead of a HTTPDigestAuthHandler >> unless you are sure your proxy uses digest authentication >> - You should pass an instance of CacheFTPHandler to build_opener, not >> the class itself. In other words, pass CacheFTPHandler() with >> parentheses. >> >> HTH >> Kent >> >> At 10:56 AM 11/6/2004 -0500, kbond wrote: >> >>> hello, >>> >>> I am trying to get access an internet page using urllib2. I am able >>> to do so form home where I do not have proxy but for some reason I >>> am unable to do it form my company. >>> >>> I found many ressource on the internet explaining how to do it but I >>> was unable to apply it to my contexte. The interesting thing is that >>> I did manage to configure Firefox (my fovourite browser) so I guess >>> I should have all the information to do it by script. >>> I think I am doing something is the usage of "add_password". Could >>> you please explain me what realm and host are? and how can I get them? >>> >>> You will find bellow my firefox configuration. >>> It would be great If someone can help me to put all this together. >>> Thank you for your help >>> >>> *Code* >>> import urllib2 >>> # set up authentication info >>> authinfo = urllib2.HTTPDigestAuthHandler() >>> #proxy_auth_handler.add_password('realm', 'host', 'username', >>> 'password') >>> authinfo.add_password(None, "http://google.com", 'userName', 'pwd') >>> * * >>> proxy_support = urllib2.ProxyHandler({"http" : "proxy:8080"}) >>> # build a new opener that adds authentication and caching FTP handlers >>> opener = urllib2.build_opener(proxy_support, >>> authinfo,urllib2.CacheFTPHandler) >>> # install it >>> urllib2.install_opener(opener) >>> f = urllib2.urlopen('http://google.com') >>> buf = f.read() >>> print buf >>> f.close() >>> >>> *Error Message* >>> >>> Traceback (most recent call last): >>> File "test.py", line 18, in ? >>> f = urllib2.urlopen('http://google.com') >>> File "E:\users\install\Python\lib\urllib2.py", line 129, in urlopen >>> return _opener.open(url, data) >>> File "E:\users\install\Python\lib\urllib2.py", line 326, in open >>> '_open', req) >>> File "E:\users\install\Python\lib\urllib2.py", line 306, in >>> _call_chain >>> result = func(*args) >>> File "E:\users\install\Python\lib\urllib2.py", line 491, in >>> lambda r, proxy=url, type=type, meth=self.proxy_open: \ >>> File "E:\users\install\Python\lib\urllib2.py", line 498, in proxy_open >>> if '@' in host: >>> TypeError: iterable argument required >>> >>> *Firefox configuration* >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> >> _______________________________________________ >> 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 kent37 at tds.net Fri Nov 12 20:39:17 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 12 20:39:21 2004 Subject: [Tutor] urllib2 with a proxy In-Reply-To: <41955D57.9040804@free.fr> References: <41955D57.9040804@free.fr> Message-ID: <41951165.2010504@tds.net> Try this (untested and I don't know what I'm talking about but maybe it will work): import urllib2 passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm() passmgr.add_password(None, 'http://proxy:8080', 'username', 'password') authinfo = urllib2.ProxyBasicAuthHandler(passmgr) proxy_support = urllib2.ProxyHandler({"http" : "http://proxy:8080"}) opener = urllib2.build_opener(proxy_support, authinfo) urllib2.install_opener(opener) f = urllib2.urlopen('http://www.google.com') buf = f.read() print buf f.close() The host for the password manager is probably the host you are authenticating against (http://proxy:8080). The realm is the authentication realm on the proxy; this is part of the auth headers returned from the proxy. Note: in your code below, I think you need a ProxyBasicAuthHandler, not an HTTPBasicAuthHandler; you have misspelled 'http://proxy:8080'. HTH Kent kbond wrote: > Kent, > > I did test your suggestion but unfortunatly it is still not working. > Somehow I do not understand why it is so complex to go trough my > proxy. I do not have any trouble if I use firefox or mozilla. > I am completely stuck by this tiny detail. > If someone on this list has clear and simple explanation about what is > realm and host in "add_password('realm', 'host', 'username', > 'password')" that will also help me a lot. > > Thank you for your help any pointer or code sample are more than welcome. > > *code** * > import urllib2 > # set up authentication info > authinfo = urllib2.HTTPBasicAuthHandler() > #add_password('realm', 'host', 'username', 'password') > authinfo.add_password(None, "http://google.com", 'username', 'pwd') > proxy_support = urllib2.ProxyHandler({"http" : "http//:proxy:8080"}) > # build a new opener that adds authentication and caching FTP handlers > opener = urllib2.build_opener(proxy_support, > authinfo,urllib2.CacheFTPHandler()) > # install it > urllib2.install_opener(opener) > f = urllib2.urlopen('http://google.com') > buf = f.read() > print buf > f.close() > > > *error* > > Traceback (most recent call last): > File "testProxy.py", line 12, in ? > f = urllib2.urlopen('http://google.com') > File "E:\users\install\Python\lib\urllib2.py", line 129, in urlopen > return _opener.open(url, data) > File "E:\users\install\Python\lib\urllib2.py", line 326, in open > '_open', req) > File "E:\users\install\Python\lib\urllib2.py", line 306, in _call_chain > result = func(*args) > File "E:\users\install\Python\lib\urllib2.py", line 491, in > lambda r, proxy=url, type=type, meth=self.proxy_open: \ > File "E:\users\install\Python\lib\urllib2.py", line 498, in proxy_open > if '@' in host: > TypeError: iterable argument required > > > > kbond wrote: > >> Thank you for your help kent. >> Already the second time that you are helping me. >> In fact I face this proxy trouble right after your first answer I was >> about to try your suggestion to solve the clientForm trouble when this >> proxy came into the danse. >> When I started my project I was far to imagine that talking to the >> world wide web was that difficult by script. >> Unfortunatly I will not be able to test before monday because I do not >> use a proxy at home. >> Do you have an idea of what are realm and host in the add_password() >> method? >> I am making the assomption that host stand for the host I want to >> contact but I do not have any idea of what realm is? >> Do you know how I can get it? Why firefox don't need this information >> to go out? >> >> You will find below the code I will try on monday. >> Thank you for your help >> >> *Code* >> import urllib2 >> # set up authentication info >> authinfo = urllib2.HTTPBasicAuthHandler() >> #add_password('realm', 'host', 'username', 'password') >> authinfo.add_password(None, "http://google.com", 'userName', 'pwd') >> proxy_support = urllib2.ProxyHandler({"http" : "http//:proxy:8080"}) >> # build a new opener that adds authentication and caching FTP handlers >> opener = urllib2.build_opener(proxy_support, >> authinfo,urllib2.CacheFTPHandler()) >> # install it >> urllib2.install_opener(opener) >> f = urllib2.urlopen('http://google.com') >> buf = f.read() >> print buf >> f.close() >> >> Kent Johnson wrote: >> >>> I'm not familiar with this library but looking at your code and the >>> docs I can make some guesses where the problem might be: >>> - The second argument to ProxyHandler should be a complete URL, e.g. >>> 'http://proxy:8080'. This is the cause of the exception you are seeing. >>> - Try using a HTTPBasicAuthHandler instead of a HTTPDigestAuthHandler >>> unless you are sure your proxy uses digest authentication >>> - You should pass an instance of CacheFTPHandler to build_opener, not >>> the class itself. In other words, pass CacheFTPHandler() with >>> parentheses. >>> >>> HTH >>> Kent >>> >>> At 10:56 AM 11/6/2004 -0500, kbond wrote: >>> >>>> hello, >>>> >>>> I am trying to get access an internet page using urllib2. I am able >>>> to do so form home where I do not have proxy but for some reason I >>>> am unable to do it form my company. >>>> >>>> I found many ressource on the internet explaining how to do it but I >>>> was unable to apply it to my contexte. The interesting thing is that >>>> I did manage to configure Firefox (my fovourite browser) so I guess >>>> I should have all the information to do it by script. >>>> I think I am doing something is the usage of "add_password". Could >>>> you please explain me what realm and host are? and how can I get them? >>>> >>>> You will find bellow my firefox configuration. >>>> It would be great If someone can help me to put all this together. >>>> Thank you for your help >>>> >>>> *Code* >>>> import urllib2 >>>> # set up authentication info >>>> authinfo = urllib2.HTTPDigestAuthHandler() >>>> #proxy_auth_handler.add_password('realm', 'host', 'username', >>>> 'password') >>>> authinfo.add_password(None, "http://google.com", 'userName', 'pwd') >>>> * * >>>> proxy_support = urllib2.ProxyHandler({"http" : "proxy:8080"}) >>>> # build a new opener that adds authentication and caching FTP handlers >>>> opener = urllib2.build_opener(proxy_support, >>>> authinfo,urllib2.CacheFTPHandler) >>>> # install it >>>> urllib2.install_opener(opener) >>>> f = urllib2.urlopen('http://google.com') >>>> buf = f.read() >>>> print buf >>>> f.close() >>>> >>>> *Error Message* >>>> >>>> Traceback (most recent call last): >>>> File "test.py", line 18, in ? >>>> f = urllib2.urlopen('http://google.com') >>>> File "E:\users\install\Python\lib\urllib2.py", line 129, in urlopen >>>> return _opener.open(url, data) >>>> File "E:\users\install\Python\lib\urllib2.py", line 326, in open >>>> '_open', req) >>>> File "E:\users\install\Python\lib\urllib2.py", line 306, in >>>> _call_chain >>>> result = func(*args) >>>> File "E:\users\install\Python\lib\urllib2.py", line 491, in >>>> lambda r, proxy=url, type=type, meth=self.proxy_open: \ >>>> File "E:\users\install\Python\lib\urllib2.py", line 498, in proxy_open >>>> if '@' in host: >>>> TypeError: iterable argument required >>>> >>>> *Firefox configuration* >>>> >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor@python.org >>>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> _______________________________________________ >> 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 pythonTutor at venix.com Fri Nov 12 20:49:51 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Nov 12 20:49:57 2004 Subject: [Tutor] urllib2 with a proxy In-Reply-To: <41955D57.9040804@free.fr> References: <41955D57.9040804@free.fr> Message-ID: <1100288990.20028.23.camel@laptop.venix.com> The realm is defined by the host you connect to. A URL consists of (protocol)://(host)/(resource)?(parameters) Each resource can be assigned to a security realm by the system administrator on the host. When the host wants to check to see if you should be allowed access to the resource, it sends a response back to your browser: HTTP/1.0 401 Unauthorized WWW-Authenticate: Basic realm="Some string which is the realm name" Your browser will ask you for your username and password and remember them along with the realm name. Then whenever the host returns Unauthorized for that realm, the browser will supply your username and password. Looking below: "http//:proxy:8080" should be: "http://proxy:8080" On Fri, 2004-11-12 at 20:03, kbond wrote: > Kent, > > I did test your suggestion but unfortunatly it is still not working. > Somehow I do not understand why it is so complex to go trough my > proxy. I do not have any trouble if I use firefox or mozilla. > I am completely stuck by this tiny detail. > If someone on this list has clear and simple explanation about what is > realm and host in "add_password('realm', 'host', 'username', > 'password')" that will also help me a lot. > > Thank you for your help any pointer or code sample are more than welcome. > > *code** * > import urllib2 > # set up authentication info > authinfo = urllib2.HTTPBasicAuthHandler() > #add_password('realm', 'host', 'username', 'password') > authinfo.add_password(None, "http://google.com", 'username', 'pwd') > proxy_support = urllib2.ProxyHandler({"http" : "http//:proxy:8080"}) > # build a new opener that adds authentication and caching FTP handlers > opener = urllib2.build_opener(proxy_support, > authinfo,urllib2.CacheFTPHandler()) > # install it > urllib2.install_opener(opener) > f = urllib2.urlopen('http://google.com') > buf = f.read() > print buf > f.close() > > > *error* > > Traceback (most recent call last): > File "testProxy.py", line 12, in ? > f = urllib2.urlopen('http://google.com') > File "E:\users\install\Python\lib\urllib2.py", line 129, in urlopen > return _opener.open(url, data) > File "E:\users\install\Python\lib\urllib2.py", line 326, in open > '_open', req) > File "E:\users\install\Python\lib\urllib2.py", line 306, in _call_chain > result = func(*args) > File "E:\users\install\Python\lib\urllib2.py", line 491, in > lambda r, proxy=url, type=type, meth=self.proxy_open: \ > File "E:\users\install\Python\lib\urllib2.py", line 498, in proxy_open > if '@' in host: > TypeError: iterable argument required > > > > kbond wrote: > > > Thank you for your help kent. > > Already the second time that you are helping me. > > In fact I face this proxy trouble right after your first answer I was > > about to try your suggestion to solve the clientForm trouble when this > > proxy came into the danse. > > > > When I started my project I was far to imagine that talking to the > > world wide web was that difficult by script. > > Unfortunatly I will not be able to test before monday because I do not > > use a proxy at home. > > Do you have an idea of what are realm and host in the add_password() > > method? > > I am making the assomption that host stand for the host I want to > > contact but I do not have any idea of what realm is? > > Do you know how I can get it? Why firefox don't need this information > > to go out? > > > > You will find below the code I will try on monday. > > Thank you for your help > > > > *Code* > > import urllib2 > > # set up authentication info > > authinfo = urllib2.HTTPBasicAuthHandler() > > #add_password('realm', 'host', 'username', 'password') > > authinfo.add_password(None, "http://google.com", 'userName', 'pwd') > > proxy_support = urllib2.ProxyHandler({"http" : "http//:proxy:8080"}) > > # build a new opener that adds authentication and caching FTP handlers > > opener = urllib2.build_opener(proxy_support, > > authinfo,urllib2.CacheFTPHandler()) > > # install it > > urllib2.install_opener(opener) > > f = urllib2.urlopen('http://google.com') > > buf = f.read() > > print buf > > f.close() > > > > Kent Johnson wrote: > > > >> I'm not familiar with this library but looking at your code and the > >> docs I can make some guesses where the problem might be: > >> - The second argument to ProxyHandler should be a complete URL, e.g. > >> 'http://proxy:8080'. This is the cause of the exception you are seeing. > >> - Try using a HTTPBasicAuthHandler instead of a HTTPDigestAuthHandler > >> unless you are sure your proxy uses digest authentication > >> - You should pass an instance of CacheFTPHandler to build_opener, not > >> the class itself. In other words, pass CacheFTPHandler() with > >> parentheses. > >> > >> HTH > >> Kent > >> > >> At 10:56 AM 11/6/2004 -0500, kbond wrote: > >> > >>> hello, > >>> > >>> I am trying to get access an internet page using urllib2. I am able > >>> to do so form home where I do not have proxy but for some reason I > >>> am unable to do it form my company. > >>> > >>> I found many ressource on the internet explaining how to do it but I > >>> was unable to apply it to my contexte. The interesting thing is that > >>> I did manage to configure Firefox (my fovourite browser) so I guess > >>> I should have all the information to do it by script. > >>> I think I am doing something is the usage of "add_password". Could > >>> you please explain me what realm and host are? and how can I get them? > >>> > >>> You will find bellow my firefox configuration. > >>> It would be great If someone can help me to put all this together. > >>> Thank you for your help > >>> > >>> *Code* > >>> import urllib2 > >>> # set up authentication info > >>> authinfo = urllib2.HTTPDigestAuthHandler() > >>> #proxy_auth_handler.add_password('realm', 'host', 'username', > >>> 'password') > >>> authinfo.add_password(None, "http://google.com", 'userName', 'pwd') > >>> * * > >>> proxy_support = urllib2.ProxyHandler({"http" : "proxy:8080"}) > >>> # build a new opener that adds authentication and caching FTP handlers > >>> opener = urllib2.build_opener(proxy_support, > >>> authinfo,urllib2.CacheFTPHandler) > >>> # install it > >>> urllib2.install_opener(opener) > >>> f = urllib2.urlopen('http://google.com') > >>> buf = f.read() > >>> print buf > >>> f.close() > >>> > >>> *Error Message* > >>> > >>> Traceback (most recent call last): > >>> File "test.py", line 18, in ? > >>> f = urllib2.urlopen('http://google.com') > >>> File "E:\users\install\Python\lib\urllib2.py", line 129, in urlopen > >>> return _opener.open(url, data) > >>> File "E:\users\install\Python\lib\urllib2.py", line 326, in open > >>> '_open', req) > >>> File "E:\users\install\Python\lib\urllib2.py", line 306, in > >>> _call_chain > >>> result = func(*args) > >>> File "E:\users\install\Python\lib\urllib2.py", line 491, in > >>> lambda r, proxy=url, type=type, meth=self.proxy_open: \ > >>> File "E:\users\install\Python\lib\urllib2.py", line 498, in proxy_open > >>> if '@' in host: > >>> TypeError: iterable argument required > >>> > >>> *Firefox configuration* > >>> > >>> > >>> _______________________________________________ > >>> Tutor maillist - Tutor@python.org > >>> http://mail.python.org/mailman/listinfo/tutor > >> > >> > >> > >> > >> _______________________________________________ > >> Tutor maillist - Tutor@python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > >> > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From cyresse at gmail.com Sat Nov 13 01:04:51 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sat Nov 13 01:04:54 2004 Subject: [Tutor] Re: Globals? In-Reply-To: References: Message-ID: Hi all, Thanks Kent - I had a niggling suspicion in the back of mind it was something to do with that, although as it was late at night (which, just like Bill, is my excuse and I'm sticking to it), I couldn't express it coherently. Regards, Liam Clarke From alan.gauld at freenet.co.uk Sat Nov 13 01:11:06 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Nov 13 01:11:11 2004 Subject: [Tutor] My new web tutor launched References: <004d01c4c4c7$029917a0$1fcb8751@xp> <200411112245.27911.klas.martelleur@telia.com> Message-ID: <004c01c4c915$4586e0e0$43bb8651@xp> > Is it possible to buy your latest tutor as a book? Nope. Once I get the new material written I might ask Addison Wesley if they want to do a second edition of the original book, but for now the new version is only on-line. The new version incorporates most of the extra features that were in the original book as well as a lot of new material based on FAQs from this list. Alan G. From kent37 at tds.net Sat Nov 13 18:26:53 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Nov 13 18:26:58 2004 Subject: [Tutor] Amazed In-Reply-To: <797fe3d404111121401462d5fd@mail.gmail.com> References: <006401c4c867$87a30110$6c5328cf@JSLAPTOP> <797fe3d404111121401462d5fd@mail.gmail.com> Message-ID: <419643DD.4040705@tds.net> I share your feelings about list comprehensions - I like the conciseness, and they seem to fit better with how I think, but using one purely for the side effects seems like abuse. Here are a couple of different ways to do what you have below, assuming that myset is a sets.Set (or set builtin from Python 2.4): myset.update( [ x for x in thingToIterate if x ] ) Set.update() takes any iterable as an argument, not just another set. In Python 2.4 you can use a generator expression to avoid creating the intermediate list at all. A generator expression is like a list comprehension but its value is an iterator instead of a list: myset.update(x for x in thingToIterate if x) Sweet! You can do something similar in Python 2.3 using itertools.ifilter: import itertools myset.update(itertools.ifilter(None, thingToIterate)) Cheers Kent Bill Mill wrote: > Jacob, > > I think it's a readability problem - it's too easy to abuse list > comprehensions to turn a 2 or 3 line for loop into a difficult to > understand one-liner. Today I found myself doing: > > [myset.add(x) for x in thingToIterate where x] > > instead of: > > for x in thingToIterate: > if x: > myset.add(x) > > which is much more readable, and doesn't eat the memory of creating an > unnecessary list full of 'None'. I immediately fixed my mistake, but > it made me realize how addictive list comprehensions are; they're like > Python crack. > From orbitz at ezabel.com Sat Nov 13 20:07:07 2004 From: orbitz at ezabel.com (orbitz) Date: Sat Nov 13 20:07:13 2004 Subject: [Tutor] Globals? In-Reply-To: <4194D06F.1090904@tds.net> References: <4194D06F.1090904@tds.net> Message-ID: <41965B5B.7010802@ezabel.com> In my opinion, this behavior really sucks too. Like when it comes to closures. As far as I know, Python does not *really* support closures, like you would get with something like lisp. Correct me if I'm wrong. This means code like: def fn(x): def _(): x += 1 return x return _ Will not work, which can be a pain in the ass. Kent Johnson wrote: > Liam, > > When you make any assignment to a variable inside a function, Python > assumes that the variable is local to the function. Then any use of > the variable before it's first assignment is an error. > > To force a variable in a function to be global, put a 'global' > statement in the function. You need to add > global badConnectCycle > to your function getReturns > > If you don't make any assignment to a variable, then the global > (module) namespace is searched. That is why badUserList works fine - > you never assign it, you just access the list methods. > > Kent > > Liam Clarke wrote: > >> Hi all, >> Having trouble with something, it is 3:30am in the morning, so this >> may be a dumb problem, if so, I apologise. >> >> In my prog, there's two variables created right at the get go - >> >> import imaplib >> import email.Parser >> import os >> import os.path >> import datetime >> import md5 >> from pause import * >> >> badUserList=[] >> badConnectCycle=0 >> >> as I want them to be global within this module, so that another module >> can pick them out easily. >> >> Now, I just added badConnectCycle, badUserList has been there awhile, >> and it's used in >> >> the function connectToImap which is called by getReturns which is >> called by main(), and my other module can get it no problem, so >> badUserList is fine. >> >> badConnectCycle... is giving me errors - >> >> badConnectCycle is used in getReturns, as so - >> if session == "NoConnect" : badConnectCycle += 1 >> continue >> >> >> function getReturns ends as follows - >> if badConnectCycle == len(user) and badConnectCycle > 0: return >> ("NoConnect","") >> if badUserList and not sender: return ('NoLogin',"") >> if matchindex[0] and not sender: return ('NoNew', '') >> if not sender: return ("NoMatch","") >> return (sender, msgdata) >> >> and it's at that line >> >> if badConnectCycle == len(user) and badConnectCycle > 0: >> >> that I get this error: >> >> UnboundLocalError: local variable 'badConnectCycle' referenced before >> assignment. >> >> Which is confusing me because badUserList is used within a function >> called by getReturns, and I've had no problem with it. >> >> Help anyone? Much appreciated if you can. >> >> Regards, >> >> Liam Clarke > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pythonTutor at venix.com Sat Nov 13 21:29:00 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Nov 13 21:29:18 2004 Subject: [Tutor] Globals? In-Reply-To: <41965B5B.7010802@ezabel.com> References: <4194D06F.1090904@tds.net> <41965B5B.7010802@ezabel.com> Message-ID: <1100377740.21480.43.camel@laptop.venix.com> It DOES work in current versions of Python, exactly as you coded it. In older Pythons (e.g. 1.52) you would have had to specifying the enclosing variables explicitly def _(x=x): A lot of old critiques are still present on the web. wikipedia has a terrific article describing Python that is current (at least 2.3.3). http://en.wikipedia.org/wiki/Python_programming_language On Sat, 2004-11-13 at 14:07, orbitz wrote: > In my opinion, this behavior really sucks too. Like when it comes to > closures. As far as I know, Python does not *really* support closures, > like you would get with something like lisp. Correct me if I'm wrong. > This means code like: > > def fn(x): > def _(): > x += 1 > return x > return _ > > Will not work, which can be a pain in the ass. > > > Kent Johnson wrote: > > > Liam, > > > > When you make any assignment to a variable inside a function, Python > > assumes that the variable is local to the function. Then any use of > > the variable before it's first assignment is an error. > > > > To force a variable in a function to be global, put a 'global' > > statement in the function. You need to add > > global badConnectCycle > > to your function getReturns > > > > If you don't make any assignment to a variable, then the global > > (module) namespace is searched. That is why badUserList works fine - > > you never assign it, you just access the list methods. > > > > Kent > > > > Liam Clarke wrote: > > > >> Hi all, > >> Having trouble with something, it is 3:30am in the morning, so this > >> may be a dumb problem, if so, I apologise. > >> > >> In my prog, there's two variables created right at the get go - > >> > >> import imaplib > >> import email.Parser > >> import os > >> import os.path > >> import datetime > >> import md5 > >> from pause import * > >> > >> badUserList=[] > >> badConnectCycle=0 > >> > >> as I want them to be global within this module, so that another module > >> can pick them out easily. > >> > >> Now, I just added badConnectCycle, badUserList has been there awhile, > >> and it's used in > >> > >> the function connectToImap which is called by getReturns which is > >> called by main(), and my other module can get it no problem, so > >> badUserList is fine. > >> > >> badConnectCycle... is giving me errors - > >> > >> badConnectCycle is used in getReturns, as so - > >> if session == "NoConnect" : badConnectCycle += 1 > >> continue > >> > >> > >> function getReturns ends as follows - > >> if badConnectCycle == len(user) and badConnectCycle > 0: return > >> ("NoConnect","") > >> if badUserList and not sender: return ('NoLogin',"") > >> if matchindex[0] and not sender: return ('NoNew', '') > >> if not sender: return ("NoMatch","") > >> return (sender, msgdata) > >> > >> and it's at that line > >> > >> if badConnectCycle == len(user) and badConnectCycle > 0: > >> > >> that I get this error: > >> > >> UnboundLocalError: local variable 'badConnectCycle' referenced before > >> assignment. > >> > >> Which is confusing me because badUserList is used within a function > >> called by getReturns, and I've had no problem with it. > >> > >> Help anyone? Much appreciated if you can. > >> > >> Regards, > >> > >> Liam Clarke > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From jfabiani at yolo.com Sat Nov 13 21:34:17 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sat Nov 13 21:34:46 2004 Subject: [Tutor] Property questions Message-ID: <200411131234.17987.jfabiani@yolo.com> Hi, First how does python know which method to use as in: size = property(getsize,setsize,delsize,'test doc') I just have not seen anything/example that uses the dele of the "property". so: "size = something" # would call the getsize method because of the '=' sign? "size" # would call the setsize because of what? "dele size" # would call the delete method ??????? is that right? And how does one call the comment part?? "size.__doc__" Thanks From kent37 at tds.net Sat Nov 13 21:57:13 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Nov 13 21:57:22 2004 Subject: [Tutor] Globals? In-Reply-To: <1100377740.21480.43.camel@laptop.venix.com> References: <4194D06F.1090904@tds.net> <41965B5B.7010802@ezabel.com> <1100377740.21480.43.camel@laptop.venix.com> Message-ID: <41967529.1090305@tds.net> I think the idea is that x in the enclosing scope should be changed when _ is called. To closure purists :-) a language doesn't have closures if it can't do this. Python will bind the *values* of variables in an enclosing scope into a closure, which is good enough for many uses :-) Personally I haven't found much need for 'true' closures. orbitz, can you say why this is such a pain? How would you use a true closure? A workaround is to store the variable in a list, but it's a bit ugly: x = [3] def fn(x): def _(): x[0] += 1 return x[0] return _ Kent Lloyd Kvam wrote: > It DOES work in current versions of Python, exactly as you coded it. > > In older Pythons (e.g. 1.52) you would have had to specifying the > enclosing variables explicitly > def _(x=x): > > A lot of old critiques are still present on the web. wikipedia has a > terrific article describing Python that is current (at least 2.3.3). > > http://en.wikipedia.org/wiki/Python_programming_language > > > > On Sat, 2004-11-13 at 14:07, orbitz wrote: > >>In my opinion, this behavior really sucks too. Like when it comes to >>closures. As far as I know, Python does not *really* support closures, >>like you would get with something like lisp. Correct me if I'm wrong. >>This means code like: >> >>def fn(x): >> def _(): >> x += 1 >> return x >> return _ >> >>Will not work, which can be a pain in the ass. >> >> >>Kent Johnson wrote: >> >> >>>Liam, >>> >>>When you make any assignment to a variable inside a function, Python >>>assumes that the variable is local to the function. Then any use of >>>the variable before it's first assignment is an error. >>> >>>To force a variable in a function to be global, put a 'global' >>>statement in the function. You need to add >>> global badConnectCycle >>>to your function getReturns >>> >>>If you don't make any assignment to a variable, then the global >>>(module) namespace is searched. That is why badUserList works fine - >>>you never assign it, you just access the list methods. >>> >>>Kent >>> >>>Liam Clarke wrote: >>> >>> >>>>Hi all, >>>>Having trouble with something, it is 3:30am in the morning, so this >>>>may be a dumb problem, if so, I apologise. >>>> >>>>In my prog, there's two variables created right at the get go - >>>> >>>>import imaplib >>>>import email.Parser >>>>import os >>>>import os.path >>>>import datetime >>>>import md5 >>>>from pause import * >>>> >>>>badUserList=[] >>>>badConnectCycle=0 >>>> >>>>as I want them to be global within this module, so that another module >>>>can pick them out easily. >>>> >>>>Now, I just added badConnectCycle, badUserList has been there awhile, >>>>and it's used in >>>> >>>>the function connectToImap which is called by getReturns which is >>>>called by main(), and my other module can get it no problem, so >>>>badUserList is fine. >>>> >>>>badConnectCycle... is giving me errors - >>>> >>>>badConnectCycle is used in getReturns, as so - >>>>if session == "NoConnect" : badConnectCycle += 1 >>>> continue >>>> >>>> >>>>function getReturns ends as follows - >>>>if badConnectCycle == len(user) and badConnectCycle > 0: return >>>>("NoConnect","") >>>>if badUserList and not sender: return ('NoLogin',"") >>>>if matchindex[0] and not sender: return ('NoNew', '') >>>>if not sender: return ("NoMatch","") >>>>return (sender, msgdata) >>>> >>>>and it's at that line >>>> >>>> if badConnectCycle == len(user) and badConnectCycle > 0: >>>> >>>>that I get this error: >>>> >>>>UnboundLocalError: local variable 'badConnectCycle' referenced before >>>>assignment. >>>> >>>>Which is confusing me because badUserList is used within a function >>>>called by getReturns, and I've had no problem with it. >>>> >>>>Help anyone? Much appreciated if you can. >>>> >>>>Regards, >>>> >>>>Liam Clarke >>> >>>_______________________________________________ >>>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 dleigh0 at carolina.rr.com Sat Nov 13 22:06:26 2004 From: dleigh0 at carolina.rr.com (Diana Furr) Date: Sat Nov 13 22:04:46 2004 Subject: [Tutor] multidemisional arrays Message-ID: <000601c4c9c4$a53196c0$121c8645@oemcomputer> Please someone help me. I don't know where else to look. I have tried everything I've seen to get this to work right but I must be doing something wrong. This is the program: i=0 howMany=input('How many artists will you enter? ') paintings=[]#painting artists=[]#artist values=[]#value for i in range(0,howMany,1): painting=raw_input('Painting Name ') artist=raw_input('Artist Name ') value=input('Painting Value ') paintings+=[painting] artists+=[artist] values+=[value] artists=zip(artists,paintings,values) artists.sort() i=i+1 n=0 for n in range(0,howMany,1): print artists[n] I need the program to sort the artists alphabetically. I can do that but I'm having trouble with the other lists. When I print it needs to look like this: Artist Painting Value Alecia Flowers 10 Diana Apples 15 When I print it looks like this: ('Alecia', 'Flowers', 10) (('Diana', 'Apples', 15), 'Apples', 15) Why does the , 'Apples', 15) print and how can I loose the parenthesis and quotation marks. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041113/15abb875/attachment.html From pythonTutor at venix.com Sat Nov 13 22:32:05 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Nov 13 22:32:11 2004 Subject: [Tutor] Globals? In-Reply-To: <41967529.1090305@tds.net> References: <4194D06F.1090904@tds.net> <41965B5B.7010802@ezabel.com> <1100377740.21480.43.camel@laptop.venix.com> <41967529.1090305@tds.net> Message-ID: <1100381525.21480.66.camel@laptop.venix.com> But integers are immutable. If names could be rebound as a side-effect of a function call, you would be creating some difficult to debug connections in your program. If you are deliberately creating a special environment for communicating between functions sharing that environment (closures), it probably makes sense to use a dictionary or class to separate those variable names from the "general" variables. A list works, since it is mutable. I guess I'm not a closure purist. On Sat, 2004-11-13 at 15:57, Kent Johnson wrote: > I think the idea is that x in the enclosing scope should be changed when > _ is called. To closure purists :-) a language doesn't have closures if > it can't do this. > > Python will bind the *values* of variables in an enclosing scope into a > closure, which is good enough for many uses :-) > > Personally I haven't found much need for 'true' closures. orbitz, can > you say why this is such a pain? How would you use a true closure? > > A workaround is to store the variable in a list, but it's a bit ugly: > > x = [3] > def fn(x): > def _(): > x[0] += 1 > return x[0] > return _ > > Kent > > Lloyd Kvam wrote: > > It DOES work in current versions of Python, exactly as you coded it. > > > > In older Pythons (e.g. 1.52) you would have had to specifying the > > enclosing variables explicitly > > def _(x=x): > > > > A lot of old critiques are still present on the web. wikipedia has a > > terrific article describing Python that is current (at least 2.3.3). > > > > http://en.wikipedia.org/wiki/Python_programming_language > > > > > > > > On Sat, 2004-11-13 at 14:07, orbitz wrote: > > > >>In my opinion, this behavior really sucks too. Like when it comes to > >>closures. As far as I know, Python does not *really* support closures, > >>like you would get with something like lisp. Correct me if I'm wrong. > >>This means code like: > >> > >>def fn(x): > >> def _(): > >> x += 1 > >> return x > >> return _ > >> > >>Will not work, which can be a pain in the ass. > >> > >> > >>Kent Johnson wrote: > >> > >> > >>>Liam, > >>> > >>>When you make any assignment to a variable inside a function, Python > >>>assumes that the variable is local to the function. Then any use of > >>>the variable before it's first assignment is an error. > >>> > >>>To force a variable in a function to be global, put a 'global' > >>>statement in the function. You need to add > >>> global badConnectCycle > >>>to your function getReturns > >>> > >>>If you don't make any assignment to a variable, then the global > >>>(module) namespace is searched. That is why badUserList works fine - > >>>you never assign it, you just access the list methods. > >>> > >>>Kent > >>> > >>>Liam Clarke wrote: > >>> > >>> > >>>>Hi all, > >>>>Having trouble with something, it is 3:30am in the morning, so this > >>>>may be a dumb problem, if so, I apologise. > >>>> > >>>>In my prog, there's two variables created right at the get go - > >>>> > >>>>import imaplib > >>>>import email.Parser > >>>>import os > >>>>import os.path > >>>>import datetime > >>>>import md5 > >>>>from pause import * > >>>> > >>>>badUserList=[] > >>>>badConnectCycle=0 > >>>> > >>>>as I want them to be global within this module, so that another module > >>>>can pick them out easily. > >>>> > >>>>Now, I just added badConnectCycle, badUserList has been there awhile, > >>>>and it's used in > >>>> > >>>>the function connectToImap which is called by getReturns which is > >>>>called by main(), and my other module can get it no problem, so > >>>>badUserList is fine. > >>>> > >>>>badConnectCycle... is giving me errors - > >>>> > >>>>badConnectCycle is used in getReturns, as so - > >>>>if session == "NoConnect" : badConnectCycle += 1 > >>>> continue > >>>> > >>>> > >>>>function getReturns ends as follows - > >>>>if badConnectCycle == len(user) and badConnectCycle > 0: return > >>>>("NoConnect","") > >>>>if badUserList and not sender: return ('NoLogin',"") > >>>>if matchindex[0] and not sender: return ('NoNew', '') > >>>>if not sender: return ("NoMatch","") > >>>>return (sender, msgdata) > >>>> > >>>>and it's at that line > >>>> > >>>> if badConnectCycle == len(user) and badConnectCycle > 0: > >>>> > >>>>that I get this error: > >>>> > >>>>UnboundLocalError: local variable 'badConnectCycle' referenced before > >>>>assignment. > >>>> > >>>>Which is confusing me because badUserList is used within a function > >>>>called by getReturns, and I've had no problem with it. > >>>> > >>>>Help anyone? Much appreciated if you can. > >>>> > >>>>Regards, > >>>> > >>>>Liam Clarke > >>> > >>>_______________________________________________ > >>>Tutor maillist - Tutor@python.org > >>>http://mail.python.org/mailman/listinfo/tutor > >>> > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From bill.mill at gmail.com Sat Nov 13 22:36:49 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sat Nov 13 22:36:53 2004 Subject: [Tutor] multidemisional arrays In-Reply-To: <000601c4c9c4$a53196c0$121c8645@oemcomputer> References: <000601c4c9c4$a53196c0$121c8645@oemcomputer> Message-ID: <797fe3d4041113133619415b2@mail.gmail.com> Diana, The tutorial's section on output formatting might help you out: http://docs.python.org/tut/node9.html#SECTION009100000000000000000 Peace Bill Mill bill.mill at gmail.com On Sat, 13 Nov 2004 16:06:26 -0500, Diana Furr wrote: > > Please someone help me. I don't know where else to look. I have tried > everything I've seen to get this to work right but I must be doing something > wrong. > This is the program: > > i=0 > howMany=input('How many artists will you enter? ') > paintings=[]#painting > artists=[]#artist > values=[]#value > for i in range(0,howMany,1): > painting=raw_input('Painting Name ') > artist=raw_input('Artist Name ') > value=input('Painting Value ') > paintings+=[painting] > artists+=[artist] > values+=[value] > artists=zip(artists,paintings,values) > artists.sort() > i=i+1 > n=0 > for n in range(0,howMany,1): > print artists[n] > > I need the program to sort the artists alphabetically. I can do that but I'm > having trouble with the other lists. When I print it needs to look like > this: > Artist Painting Value > Alecia Flowers 10 > Diana Apples 15 > > When I print it looks like this: > ('Alecia', 'Flowers', 10) > (('Diana', 'Apples', 15), 'Apples', 15) > > Why does the , 'Apples', 15) print and how can I loose the parenthesis and > quotation marks. > Thanks in advance. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From pythonTutor at venix.com Sat Nov 13 22:39:12 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Nov 13 22:39:19 2004 Subject: [Tutor] multidemisional arrays In-Reply-To: <000601c4c9c4$a53196c0$121c8645@oemcomputer> References: <000601c4c9c4$a53196c0$121c8645@oemcomputer> Message-ID: <1100381951.21480.73.camel@laptop.venix.com> On Sat, 2004-11-13 at 16:06, Diana Furr wrote: > Please someone help me. I don't know where else to look. I have tried > everything I've seen to get this to work right but I must be doing > something wrong. > This is the program: > > i=0 > howMany=input('How many artists will you enter? ') > paintings=[]#painting > artists=[]#artist > values=[]#value > for i in range(0,howMany,1): > painting=raw_input('Painting Name ') > artist=raw_input('Artist Name ') > value=input('Painting Value ') > paintings+=[painting] > artists+=[artist] > values+=[value] You are doing this step too soon. These next two lines should be deferred until you have finished collecting all of your data. Notice that you are using artists to store a list of artist names. And then you use artists to store the (artist,painting,value) tuples that you create using zip. > artists=zip(artists,paintings,values) > artists.sort() > i=i+1 (Put them here) artists=zip(artists,paintings,values) artists.sort() > > n=0 > for n in range(0,howMany,1): > print artists[n] > > I need the program to sort the artists alphabetically. I can do that > but I'm having trouble with the other lists. When I print it needs to > look like this: > Artist Painting Value > Alecia Flowers 10 > Diana Apples 15 > > When I print it looks like this: > ('Alecia', 'Flowers', 10) > (('Diana', 'Apples', 15), 'Apples', 15) > > Why does the , 'Apples', 15) print and how can I loose the parenthesis > and quotation marks. > Thanks in advance. > > > ______________________________________________________________________ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From kent37 at tds.net Sat Nov 13 22:49:13 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Nov 13 22:49:22 2004 Subject: [Tutor] Property questions In-Reply-To: <200411131234.17987.jfabiani@yolo.com> References: <200411131234.17987.jfabiani@yolo.com> Message-ID: <41968159.2050601@tds.net> John Fabiani wrote: > Hi, > > First how does python know which method to use as in: > > size = property(getsize,setsize,delsize,'test doc') > > I just have not seen anything/example that uses the dele of the "property". > > so: > > "size = something" # would call the getsize method because of the '=' sign? No, this would call setsize because it is setting a new value for size > "size" # would call the setsize because of what? This calls getsize because it is getting the value > > "dele size" # would call the delete method ??????? is that right? del size > > And how does one call the comment part?? > "size.__doc__" Note that all of these require an instance specifier, e.g. myObj.size. Here is an example. Suppose you have a class Props defined like this: class Props(object): def __init__(self): self._x = 0 def _getx(self): print '_getx' return self._x def _setx(self, x): print '_setx' self._x = x def _delx(self): print '_delx' del self._x x = property(_getx, _setx, _delx, 'This is the "x" property') Then you can use it like this: >>> p=Props() Access x through _getx: >>> p.x _getx 0 Set x through _setx: >>> p.x = 3 _setx >>> p.x _getx 3 Access the doc string. You have to do this on the attribute of the *class*, not the instance >>> Props.x.__doc__ 'This is the "x" property' Delete the attribute: >>> del p.x _delx Now it's gone: >>> p.x _getx Traceback (most recent call last): File "", line 1, in ? File "Property.py", line 7, in _getx return self._x AttributeError: 'Props' object has no attribute '_x' A good, though technical, guide to properties and descriptors is here: http://users.rcn.com/python/download/Descriptor.htm Kent From orbitz at ezabel.com Sat Nov 13 22:51:20 2004 From: orbitz at ezabel.com (orbitz) Date: Sat Nov 13 22:51:30 2004 Subject: [Tutor] Globals? In-Reply-To: <1100381525.21480.66.camel@laptop.venix.com> References: <4194D06F.1090904@tds.net> <41965B5B.7010802@ezabel.com> <1100377740.21480.43.camel@laptop.venix.com> <41967529.1090305@tds.net> <1100381525.21480.66.camel@laptop.venix.com> Message-ID: <419681D8.7010402@ezabel.com> Kent, If i follow what you are saying here, I think you are confusing dynamic scope with lexical scope in here. Dynamic scoping tends to be icky for debugging and usage purposes, and lexical scoping is generally preferred. If I'm not following what you are saying here properly please correct me Lloyd Kvam wrote: >But integers are immutable. > >If names could be rebound as a side-effect of a function call, you would >be creating some difficult to debug connections in your program. > >If you are deliberately creating a special environment for communicating >between functions sharing that environment (closures), it probably makes >sense to use a dictionary or class to separate those variable names from >the "general" variables. A list works, since it is mutable. > >I guess I'm not a closure purist. > >On Sat, 2004-11-13 at 15:57, Kent Johnson wrote: > > >>I think the idea is that x in the enclosing scope should be changed when >>_ is called. To closure purists :-) a language doesn't have closures if >>it can't do this. >> >>Python will bind the *values* of variables in an enclosing scope into a >>closure, which is good enough for many uses :-) >> >>Personally I haven't found much need for 'true' closures. orbitz, can >>you say why this is such a pain? How would you use a true closure? >> >>A workaround is to store the variable in a list, but it's a bit ugly: >> >>x = [3] >>def fn(x): >> def _(): >> x[0] += 1 >> return x[0] >> return _ >> >>Kent >> >>Lloyd Kvam wrote: >> >> >>>It DOES work in current versions of Python, exactly as you coded it. >>> >>>In older Pythons (e.g. 1.52) you would have had to specifying the >>>enclosing variables explicitly >>> def _(x=x): >>> >>>A lot of old critiques are still present on the web. wikipedia has a >>>terrific article describing Python that is current (at least 2.3.3). >>> >>>http://en.wikipedia.org/wiki/Python_programming_language >>> >>> >>> >>>On Sat, 2004-11-13 at 14:07, orbitz wrote: >>> >>> >>> >>>>In my opinion, this behavior really sucks too. Like when it comes to >>>>closures. As far as I know, Python does not *really* support closures, >>>>like you would get with something like lisp. Correct me if I'm wrong. >>>>This means code like: >>>> >>>>def fn(x): >>>> def _(): >>>> x += 1 >>>> return x >>>> return _ >>>> >>>>Will not work, which can be a pain in the ass. >>>> >>>> >>>>Kent Johnson wrote: >>>> >>>> >>>> >>>> >>>>>Liam, >>>>> >>>>>When you make any assignment to a variable inside a function, Python >>>>>assumes that the variable is local to the function. Then any use of >>>>>the variable before it's first assignment is an error. >>>>> >>>>>To force a variable in a function to be global, put a 'global' >>>>>statement in the function. You need to add >>>>> global badConnectCycle >>>>>to your function getReturns >>>>> >>>>>If you don't make any assignment to a variable, then the global >>>>>(module) namespace is searched. That is why badUserList works fine - >>>>>you never assign it, you just access the list methods. >>>>> >>>>>Kent >>>>> >>>>>Liam Clarke wrote: >>>>> >>>>> >>>>> >>>>> >>>>>>Hi all, >>>>>>Having trouble with something, it is 3:30am in the morning, so this >>>>>>may be a dumb problem, if so, I apologise. >>>>>> >>>>>>In my prog, there's two variables created right at the get go - >>>>>> >>>>>>import imaplib >>>>>>import email.Parser >>>>>>import os >>>>>>import os.path >>>>>>import datetime >>>>>>import md5 >>>>>> >>>>>> >>>>>>from pause import * >>>>> >>>>> >>>>>>badUserList=[] >>>>>>badConnectCycle=0 >>>>>> >>>>>>as I want them to be global within this module, so that another module >>>>>>can pick them out easily. >>>>>> >>>>>>Now, I just added badConnectCycle, badUserList has been there awhile, >>>>>>and it's used in >>>>>> >>>>>>the function connectToImap which is called by getReturns which is >>>>>>called by main(), and my other module can get it no problem, so >>>>>>badUserList is fine. >>>>>> >>>>>>badConnectCycle... is giving me errors - >>>>>> >>>>>>badConnectCycle is used in getReturns, as so - >>>>>>if session == "NoConnect" : badConnectCycle += 1 >>>>>> continue >>>>>> >>>>>> >>>>>>function getReturns ends as follows - >>>>>>if badConnectCycle == len(user) and badConnectCycle > 0: return >>>>>>("NoConnect","") >>>>>>if badUserList and not sender: return ('NoLogin',"") >>>>>>if matchindex[0] and not sender: return ('NoNew', '') >>>>>>if not sender: return ("NoMatch","") >>>>>>return (sender, msgdata) >>>>>> >>>>>>and it's at that line >>>>>> >>>>>>if badConnectCycle == len(user) and badConnectCycle > 0: >>>>>> >>>>>>that I get this error: >>>>>> >>>>>>UnboundLocalError: local variable 'badConnectCycle' referenced before >>>>>>assignment. >>>>>> >>>>>>Which is confusing me because badUserList is used within a function >>>>>>called by getReturns, and I've had no problem with it. >>>>>> >>>>>>Help anyone? Much appreciated if you can. >>>>>> >>>>>>Regards, >>>>>> >>>>>>Liam Clarke >>>>>> >>>>>> >>>>>_______________________________________________ >>>>>Tutor maillist - Tutor@python.org >>>>>http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>>> >>>>_______________________________________________ >>>>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 kent37 at tds.net Sat Nov 13 23:00:53 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Nov 13 23:00:59 2004 Subject: [Tutor] Globals? In-Reply-To: <419681D8.7010402@ezabel.com> References: <4194D06F.1090904@tds.net> <41965B5B.7010802@ezabel.com> <1100377740.21480.43.camel@laptop.venix.com> <41967529.1090305@tds.net> <1100381525.21480.66.camel@laptop.venix.com> <419681D8.7010402@ezabel.com> Message-ID: <41968415.2090003@tds.net> The issue is whether a closure can rebind a variable in the enclosing scope. Python does not allow this except in the special case where the enclosing scope is the global scope - then you can use the global keyword to rebind it. But I was responding to the message where you said, > In my opinion, this behavior really sucks too. Like when it comes to closures. As far as I know, Python does not *really* support closures, like you would get with something like lisp. Correct me if I'm wrong. This means code like: > > def fn(x): > def _(): > x += 1 > return x > return _ > > Will not work, which can be a pain in the ass. Could you explain what behavior you would like to see from this program and why it sucks not to get it? My guess is that the problem is that x += 1 only rebinds x in the scope of _(), not in the scope of fn(), so the change to x is not persistent. Kent orbitz wrote: > Kent, If i follow what you are saying here, I think you are confusing > dynamic scope with lexical scope in here. Dynamic scoping tends to be > icky for debugging and usage purposes, and lexical scoping is generally > preferred. > > If I'm not following what you are saying here properly please correct me > > > Lloyd Kvam wrote: > >> But integers are immutable. >> >> If names could be rebound as a side-effect of a function call, you would >> be creating some difficult to debug connections in your program. >> If you are deliberately creating a special environment for communicating >> between functions sharing that environment (closures), it probably makes >> sense to use a dictionary or class to separate those variable names from >> the "general" variables. A list works, since it is mutable. >> >> I guess I'm not a closure purist. >> >> On Sat, 2004-11-13 at 15:57, Kent Johnson wrote: >> >> >>> I think the idea is that x in the enclosing scope should be changed >>> when _ is called. To closure purists :-) a language doesn't have >>> closures if it can't do this. >>> >>> Python will bind the *values* of variables in an enclosing scope into >>> a closure, which is good enough for many uses :-) >>> >>> Personally I haven't found much need for 'true' closures. orbitz, can >>> you say why this is such a pain? How would you use a true closure? >>> >>> A workaround is to store the variable in a list, but it's a bit ugly: >>> >>> x = [3] >>> def fn(x): >>> def _(): >>> x[0] += 1 >>> return x[0] >>> return _ >>> >>> Kent >>> >>> Lloyd Kvam wrote: >>> >>> >>>> It DOES work in current versions of Python, exactly as you coded it. >>>> >>>> In older Pythons (e.g. 1.52) you would have had to specifying the >>>> enclosing variables explicitly >>>> def _(x=x): >>>> >>>> A lot of old critiques are still present on the web. wikipedia has a >>>> terrific article describing Python that is current (at least 2.3.3). >>>> >>>> http://en.wikipedia.org/wiki/Python_programming_language >>>> >>>> >>>> >>>> On Sat, 2004-11-13 at 14:07, orbitz wrote: >>>> >>>> >>>> >>>>> In my opinion, this behavior really sucks too. Like when it comes >>>>> to closures. As far as I know, Python does not *really* support >>>>> closures, like you would get with something like lisp. Correct me >>>>> if I'm wrong. This means code like: >>>>> >>>>> def fn(x): >>>>> def _(): >>>>> x += 1 >>>>> return x >>>>> return _ >>>>> >>>>> Will not work, which can be a pain in the ass. >>>>> >>>>> >>>>> Kent Johnson wrote: >>>>> >>>>> >>>>> >>>>> >>>>>> Liam, >>>>>> >>>>>> When you make any assignment to a variable inside a function, >>>>>> Python assumes that the variable is local to the function. Then >>>>>> any use of the variable before it's first assignment is an error. >>>>>> >>>>>> To force a variable in a function to be global, put a 'global' >>>>>> statement in the function. You need to add >>>>>> global badConnectCycle >>>>>> to your function getReturns >>>>>> >>>>>> If you don't make any assignment to a variable, then the global >>>>>> (module) namespace is searched. That is why badUserList works fine >>>>>> - you never assign it, you just access the list methods. >>>>>> >>>>>> Kent >>>>>> >>>>>> Liam Clarke wrote: >>>>>> >>>>>> >>>>>> >>>>>> >>>>>>> Hi all, >>>>>>> Having trouble with something, it is 3:30am in the morning, so this >>>>>>> may be a dumb problem, if so, I apologise. >>>>>>> >>>>>>> In my prog, there's two variables created right at the get go - >>>>>>> >>>>>>> import imaplib >>>>>>> import email.Parser >>>>>>> import os >>>>>>> import os.path >>>>>>> import datetime >>>>>>> import md5 >>>>>>> >>>>>>> from pause import * >>>>>> >>>>>> >>>>>> >>>>>>> badUserList=[] >>>>>>> badConnectCycle=0 >>>>>>> >>>>>>> as I want them to be global within this module, so that another >>>>>>> module >>>>>>> can pick them out easily. >>>>>>> >>>>>>> Now, I just added badConnectCycle, badUserList has been there >>>>>>> awhile, >>>>>>> and it's used in >>>>>>> >>>>>>> the function connectToImap which is called by getReturns which is >>>>>>> called by main(), and my other module can get it no problem, so >>>>>>> badUserList is fine. >>>>>>> >>>>>>> badConnectCycle... is giving me errors - >>>>>>> >>>>>>> badConnectCycle is used in getReturns, as so - >>>>>>> if session == "NoConnect" : badConnectCycle += 1 >>>>>>> continue >>>>>>> >>>>>>> >>>>>>> function getReturns ends as follows - >>>>>>> if badConnectCycle == len(user) and badConnectCycle > 0: return >>>>>>> ("NoConnect","") >>>>>>> if badUserList and not sender: return ('NoLogin',"") >>>>>>> if matchindex[0] and not sender: return ('NoNew', '') >>>>>>> if not sender: return ("NoMatch","") >>>>>>> return (sender, msgdata) >>>>>>> >>>>>>> and it's at that line >>>>>>> >>>>>>> if badConnectCycle == len(user) and badConnectCycle > 0: >>>>>>> >>>>>>> that I get this error: >>>>>>> >>>>>>> UnboundLocalError: local variable 'badConnectCycle' referenced >>>>>>> before >>>>>>> assignment. >>>>>>> >>>>>>> Which is confusing me because badUserList is used within a function >>>>>>> called by getReturns, and I've had no problem with it. >>>>>>> >>>>>>> Help anyone? Much appreciated if you can. >>>>>>> >>>>>>> Regards, >>>>>>> >>>>>>> Liam Clarke >>>>>>> >>>>>> >>>>>> _______________________________________________ >>>>>> Tutor maillist - Tutor@python.org >>>>>> http://mail.python.org/mailman/listinfo/tutor >>>>>> >>>>>> >>>>> >>>>> _______________________________________________ >>>>> 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 orbitz at ezabel.com Sat Nov 13 23:23:11 2004 From: orbitz at ezabel.com (orbitz) Date: Sat Nov 13 23:23:22 2004 Subject: [Tutor] Globals? In-Reply-To: <41968415.2090003@tds.net> References: <4194D06F.1090904@tds.net> <41965B5B.7010802@ezabel.com> <1100377740.21480.43.camel@laptop.venix.com> <41967529.1090305@tds.net> <1100381525.21480.66.camel@laptop.venix.com> <419681D8.7010402@ezabel.com> <41968415.2090003@tds.net> Message-ID: <4196894F.9080709@ezabel.com> The change doesn't happen at all actually: >>> def fn(x): ... def _(): ... x += 1 ... return x ... return _ ... >>> blah = fn(2) >>> blah() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in _ UnboundLocalError: local variable 'x' referenced before assignment Here is a CL equiv of what I *think* should happen, unelss someone has a godo reason for it not to belike this: (defun foo (n) (lambda (i) (incf n i))) Kent Johnson wrote: > The issue is whether a closure can rebind a variable in the enclosing > scope. Python does not allow this except in the special case where the > enclosing scope is the global scope - then you can use the global > keyword to rebind it. > > But I was responding to the message where you said, > >> In my opinion, this behavior really sucks too. Like when it comes to >> closures. As far as I know, Python does not *really* support >> closures, like you would get with something like lisp. Correct me if >> I'm wrong. This means code like: >> >> def fn(x): >> def _(): >> x += 1 >> return x >> return _ >> >> Will not work, which can be a pain in the ass. > > > Could you explain what behavior you would like to see from this > program and why it sucks not to get it? My guess is that the problem > is that > x += 1 > only rebinds x in the scope of _(), not in the scope of fn(), so the > change to x is not persistent. > > Kent > > orbitz wrote: > >> Kent, If i follow what you are saying here, I think you are confusing >> dynamic scope with lexical scope in here. Dynamic scoping tends to >> be icky for debugging and usage purposes, and lexical scoping is >> generally preferred. >> >> If I'm not following what you are saying here properly please correct me >> >> >> Lloyd Kvam wrote: >> >>> But integers are immutable. >>> >>> If names could be rebound as a side-effect of a function call, you >>> would >>> be creating some difficult to debug connections in your program. If >>> you are deliberately creating a special environment for communicating >>> between functions sharing that environment (closures), it probably >>> makes >>> sense to use a dictionary or class to separate those variable names >>> from >>> the "general" variables. A list works, since it is mutable. >>> >>> I guess I'm not a closure purist. >>> >>> On Sat, 2004-11-13 at 15:57, Kent Johnson wrote: >>> >>> >>>> I think the idea is that x in the enclosing scope should be changed >>>> when _ is called. To closure purists :-) a language doesn't have >>>> closures if it can't do this. >>>> >>>> Python will bind the *values* of variables in an enclosing scope >>>> into a closure, which is good enough for many uses :-) >>>> >>>> Personally I haven't found much need for 'true' closures. orbitz, >>>> can you say why this is such a pain? How would you use a true closure? >>>> >>>> A workaround is to store the variable in a list, but it's a bit ugly: >>>> >>>> x = [3] >>>> def fn(x): >>>> def _(): >>>> x[0] += 1 >>>> return x[0] >>>> return _ >>>> >>>> Kent >>>> >>>> Lloyd Kvam wrote: >>>> >>>> >>>>> It DOES work in current versions of Python, exactly as you coded it. >>>>> >>>>> In older Pythons (e.g. 1.52) you would have had to specifying the >>>>> enclosing variables explicitly >>>>> def _(x=x): >>>>> >>>>> A lot of old critiques are still present on the web. wikipedia has a >>>>> terrific article describing Python that is current (at least 2.3.3). >>>>> >>>>> http://en.wikipedia.org/wiki/Python_programming_language >>>>> >>>>> >>>>> >>>>> On Sat, 2004-11-13 at 14:07, orbitz wrote: >>>>> >>>>> >>>>> >>>>>> In my opinion, this behavior really sucks too. Like when it comes >>>>>> to closures. As far as I know, Python does not *really* support >>>>>> closures, like you would get with something like lisp. Correct me >>>>>> if I'm wrong. This means code like: >>>>>> >>>>>> def fn(x): >>>>>> def _(): >>>>>> x += 1 >>>>>> return x >>>>>> return _ >>>>>> >>>>>> Will not work, which can be a pain in the ass. >>>>>> >>>>>> >>>>>> Kent Johnson wrote: >>>>>> >>>>>> >>>>>> >>>>>> >>>>>>> Liam, >>>>>>> >>>>>>> When you make any assignment to a variable inside a function, >>>>>>> Python assumes that the variable is local to the function. Then >>>>>>> any use of the variable before it's first assignment is an error. >>>>>>> >>>>>>> To force a variable in a function to be global, put a 'global' >>>>>>> statement in the function. You need to add >>>>>>> global badConnectCycle >>>>>>> to your function getReturns >>>>>>> >>>>>>> If you don't make any assignment to a variable, then the global >>>>>>> (module) namespace is searched. That is why badUserList works >>>>>>> fine - you never assign it, you just access the list methods. >>>>>>> >>>>>>> Kent >>>>>>> >>>>>>> Liam Clarke wrote: >>>>>>> >>>>>>> >>>>>>> >>>>>>> >>>>>>>> Hi all, >>>>>>>> Having trouble with something, it is 3:30am in the morning, so >>>>>>>> this >>>>>>>> may be a dumb problem, if so, I apologise. >>>>>>>> >>>>>>>> In my prog, there's two variables created right at the get go - >>>>>>>> >>>>>>>> import imaplib >>>>>>>> import email.Parser >>>>>>>> import os >>>>>>>> import os.path >>>>>>>> import datetime >>>>>>>> import md5 >>>>>>>> from pause import * >>>>>>> >>>>>>> >>>>>>> >>>>>>> >>>>>>>> badUserList=[] >>>>>>>> badConnectCycle=0 >>>>>>>> >>>>>>>> as I want them to be global within this module, so that another >>>>>>>> module >>>>>>>> can pick them out easily. >>>>>>>> >>>>>>>> Now, I just added badConnectCycle, badUserList has been there >>>>>>>> awhile, >>>>>>>> and it's used in >>>>>>>> >>>>>>>> the function connectToImap which is called by getReturns which is >>>>>>>> called by main(), and my other module can get it no problem, so >>>>>>>> badUserList is fine. >>>>>>>> >>>>>>>> badConnectCycle... is giving me errors - >>>>>>>> >>>>>>>> badConnectCycle is used in getReturns, as so - >>>>>>>> if session == "NoConnect" : badConnectCycle += 1 >>>>>>>> continue >>>>>>>> >>>>>>>> >>>>>>>> function getReturns ends as follows - >>>>>>>> if badConnectCycle == len(user) and badConnectCycle > 0: return >>>>>>>> ("NoConnect","") >>>>>>>> if badUserList and not sender: return ('NoLogin',"") >>>>>>>> if matchindex[0] and not sender: return ('NoNew', '') >>>>>>>> if not sender: return ("NoMatch","") >>>>>>>> return (sender, msgdata) >>>>>>>> >>>>>>>> and it's at that line >>>>>>>> >>>>>>>> if badConnectCycle == len(user) and badConnectCycle > 0: >>>>>>>> >>>>>>>> that I get this error: >>>>>>>> >>>>>>>> UnboundLocalError: local variable 'badConnectCycle' referenced >>>>>>>> before >>>>>>>> assignment. >>>>>>>> >>>>>>>> Which is confusing me because badUserList is used within a >>>>>>>> function >>>>>>>> called by getReturns, and I've had no problem with it. >>>>>>>> >>>>>>>> Help anyone? Much appreciated if you can. >>>>>>>> >>>>>>>> Regards, >>>>>>>> >>>>>>>> Liam Clarke >>>>>>>> >>>>>>> >>>>>>> >>>>>>> _______________________________________________ >>>>>>> Tutor maillist - Tutor@python.org >>>>>>> http://mail.python.org/mailman/listinfo/tutor >>>>>>> >>>>>>> >>>>>> >>>>>> >>>>>> _______________________________________________ >>>>>> Tutor maillist - Tutor@python.org >>>>>> http://mail.python.org/mailman/listinfo/tutor >>>>>> >>>>> >>>> >>>> _______________________________________________ >>>> 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 orbitz at ezabel.com Sat Nov 13 23:29:29 2004 From: orbitz at ezabel.com (orbitz) Date: Sat Nov 13 23:29:37 2004 Subject: [Tutor] Globals? In-Reply-To: <41968415.2090003@tds.net> References: <4194D06F.1090904@tds.net> <41965B5B.7010802@ezabel.com> <1100377740.21480.43.camel@laptop.venix.com> <41967529.1090305@tds.net> <1100381525.21480.66.camel@laptop.venix.com> <419681D8.7010402@ezabel.com> <41968415.2090003@tds.net> Message-ID: <41968AC9.8030007@ezabel.com> Err, that CL example does something slightly different, but same idea. Kent Johnson wrote: > The issue is whether a closure can rebind a variable in the enclosing > scope. Python does not allow this except in the special case where the > enclosing scope is the global scope - then you can use the global > keyword to rebind it. > > But I was responding to the message where you said, > >> In my opinion, this behavior really sucks too. Like when it comes to >> closures. As far as I know, Python does not *really* support >> closures, like you would get with something like lisp. Correct me if >> I'm wrong. This means code like: >> >> def fn(x): >> def _(): >> x += 1 >> return x >> return _ >> >> Will not work, which can be a pain in the ass. > > > Could you explain what behavior you would like to see from this > program and why it sucks not to get it? My guess is that the problem > is that > x += 1 > only rebinds x in the scope of _(), not in the scope of fn(), so the > change to x is not persistent. > > Kent > > orbitz wrote: > >> Kent, If i follow what you are saying here, I think you are confusing >> dynamic scope with lexical scope in here. Dynamic scoping tends to >> be icky for debugging and usage purposes, and lexical scoping is >> generally preferred. >> >> If I'm not following what you are saying here properly please correct me >> >> >> Lloyd Kvam wrote: >> >>> But integers are immutable. >>> >>> If names could be rebound as a side-effect of a function call, you >>> would >>> be creating some difficult to debug connections in your program. If >>> you are deliberately creating a special environment for communicating >>> between functions sharing that environment (closures), it probably >>> makes >>> sense to use a dictionary or class to separate those variable names >>> from >>> the "general" variables. A list works, since it is mutable. >>> >>> I guess I'm not a closure purist. >>> >>> On Sat, 2004-11-13 at 15:57, Kent Johnson wrote: >>> >>> >>>> I think the idea is that x in the enclosing scope should be changed >>>> when _ is called. To closure purists :-) a language doesn't have >>>> closures if it can't do this. >>>> >>>> Python will bind the *values* of variables in an enclosing scope >>>> into a closure, which is good enough for many uses :-) >>>> >>>> Personally I haven't found much need for 'true' closures. orbitz, >>>> can you say why this is such a pain? How would you use a true closure? >>>> >>>> A workaround is to store the variable in a list, but it's a bit ugly: >>>> >>>> x = [3] >>>> def fn(x): >>>> def _(): >>>> x[0] += 1 >>>> return x[0] >>>> return _ >>>> >>>> Kent >>>> >>>> Lloyd Kvam wrote: >>>> >>>> >>>>> It DOES work in current versions of Python, exactly as you coded it. >>>>> >>>>> In older Pythons (e.g. 1.52) you would have had to specifying the >>>>> enclosing variables explicitly >>>>> def _(x=x): >>>>> >>>>> A lot of old critiques are still present on the web. wikipedia has a >>>>> terrific article describing Python that is current (at least 2.3.3). >>>>> >>>>> http://en.wikipedia.org/wiki/Python_programming_language >>>>> >>>>> >>>>> >>>>> On Sat, 2004-11-13 at 14:07, orbitz wrote: >>>>> >>>>> >>>>> >>>>>> In my opinion, this behavior really sucks too. Like when it comes >>>>>> to closures. As far as I know, Python does not *really* support >>>>>> closures, like you would get with something like lisp. Correct me >>>>>> if I'm wrong. This means code like: >>>>>> >>>>>> def fn(x): >>>>>> def _(): >>>>>> x += 1 >>>>>> return x >>>>>> return _ >>>>>> >>>>>> Will not work, which can be a pain in the ass. >>>>>> >>>>>> >>>>>> Kent Johnson wrote: >>>>>> >>>>>> >>>>>> >>>>>> >>>>>>> Liam, >>>>>>> >>>>>>> When you make any assignment to a variable inside a function, >>>>>>> Python assumes that the variable is local to the function. Then >>>>>>> any use of the variable before it's first assignment is an error. >>>>>>> >>>>>>> To force a variable in a function to be global, put a 'global' >>>>>>> statement in the function. You need to add >>>>>>> global badConnectCycle >>>>>>> to your function getReturns >>>>>>> >>>>>>> If you don't make any assignment to a variable, then the global >>>>>>> (module) namespace is searched. That is why badUserList works >>>>>>> fine - you never assign it, you just access the list methods. >>>>>>> >>>>>>> Kent >>>>>>> >>>>>>> Liam Clarke wrote: >>>>>>> >>>>>>> >>>>>>> >>>>>>> >>>>>>>> Hi all, >>>>>>>> Having trouble with something, it is 3:30am in the morning, so >>>>>>>> this >>>>>>>> may be a dumb problem, if so, I apologise. >>>>>>>> >>>>>>>> In my prog, there's two variables created right at the get go - >>>>>>>> >>>>>>>> import imaplib >>>>>>>> import email.Parser >>>>>>>> import os >>>>>>>> import os.path >>>>>>>> import datetime >>>>>>>> import md5 >>>>>>>> from pause import * >>>>>>> >>>>>>> >>>>>>> >>>>>>> >>>>>>>> badUserList=[] >>>>>>>> badConnectCycle=0 >>>>>>>> >>>>>>>> as I want them to be global within this module, so that another >>>>>>>> module >>>>>>>> can pick them out easily. >>>>>>>> >>>>>>>> Now, I just added badConnectCycle, badUserList has been there >>>>>>>> awhile, >>>>>>>> and it's used in >>>>>>>> >>>>>>>> the function connectToImap which is called by getReturns which is >>>>>>>> called by main(), and my other module can get it no problem, so >>>>>>>> badUserList is fine. >>>>>>>> >>>>>>>> badConnectCycle... is giving me errors - >>>>>>>> >>>>>>>> badConnectCycle is used in getReturns, as so - >>>>>>>> if session == "NoConnect" : badConnectCycle += 1 >>>>>>>> continue >>>>>>>> >>>>>>>> >>>>>>>> function getReturns ends as follows - >>>>>>>> if badConnectCycle == len(user) and badConnectCycle > 0: return >>>>>>>> ("NoConnect","") >>>>>>>> if badUserList and not sender: return ('NoLogin',"") >>>>>>>> if matchindex[0] and not sender: return ('NoNew', '') >>>>>>>> if not sender: return ("NoMatch","") >>>>>>>> return (sender, msgdata) >>>>>>>> >>>>>>>> and it's at that line >>>>>>>> >>>>>>>> if badConnectCycle == len(user) and badConnectCycle > 0: >>>>>>>> >>>>>>>> that I get this error: >>>>>>>> >>>>>>>> UnboundLocalError: local variable 'badConnectCycle' referenced >>>>>>>> before >>>>>>>> assignment. >>>>>>>> >>>>>>>> Which is confusing me because badUserList is used within a >>>>>>>> function >>>>>>>> called by getReturns, and I've had no problem with it. >>>>>>>> >>>>>>>> Help anyone? Much appreciated if you can. >>>>>>>> >>>>>>>> Regards, >>>>>>>> >>>>>>>> Liam Clarke >>>>>>>> >>>>>>> >>>>>>> >>>>>>> _______________________________________________ >>>>>>> Tutor maillist - Tutor@python.org >>>>>>> http://mail.python.org/mailman/listinfo/tutor >>>>>>> >>>>>>> >>>>>> >>>>>> >>>>>> _______________________________________________ >>>>>> Tutor maillist - Tutor@python.org >>>>>> http://mail.python.org/mailman/listinfo/tutor >>>>>> >>>>> >>>> >>>> _______________________________________________ >>>> 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 pythonTutor at venix.com Sat Nov 13 23:33:39 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Nov 13 23:33:44 2004 Subject: [Tutor] Globals? In-Reply-To: <419685CE.902@ezabel.com> References: <4194D06F.1090904@tds.net> <41965B5B.7010802@ezabel.com> <1100377740.21480.43.camel@laptop.venix.com> <41967C89.4090208@ezabel.com> <1100382419.21480.78.camel@laptop.venix.com> <4196830E.1020101@ezabel.com> <1100383413.21480.86.camel@laptop.venix.com> <419685CE.902@ezabel.com> Message-ID: <1100385219.21480.107.camel@laptop.venix.com> x = 2 def _(): x += 1 _() Traceback (most recent call last): File "/home/lkvam/aa.py", line 6, in -toplevel- _() File "/home/lkvam/aa.py", line 4, in _ x += 1 UnboundLocalError: local variable 'x' referenced before assignment What is happening is not a closure issue. Any function that attempts to assign to a non-local variable will get that error. x = 2 def _(): global x x += 1 return x print _() >>> 3 This works because we now explicitly reference the variable as a global. I'd hate to think that using global in a closure allows it to change the global x in whatever namespace where it was run, or that the closure would fail if it were run in a namespace that did NOT have a global x. I'll leave that investigation to others. On Sat, 2004-11-13 at 17:08, orbitz wrote: > I'm modifying the variable which references it though. Which *should* be > fine, but Pythons scoping rules and closures are hella messed up. > It should work fine, and it can simplify code. Generally you have to > make a nested class and return a reference to a method of an instance. > > > Lloyd Kvam wrote: > > >I should have said, > >It is the attempt to change a non-local IMMUTABLE variable. > > > >I still think that is a feature. If you are trying to change variables > >out side of your local scope, Python requires that they be mutable. > > > >(So I am not a closure purist as Kent pointed out.) > > > >On Sat, 2004-11-13 at 16:56, orbitz wrote: > > > > > >>I know, which is the weakness of python closure's I was pointing out. > >> > >>Lloyd Kvam wrote: > >> > >> > >> > >>>It is the attempt to change a non-local variable. > >>>def _(): > >>> return x+1 > >>> > >>>will work. > >>> > >>>On Sat, 2004-11-13 at 16:28, orbitz wrote: > >>> > >>> > >>> > >>> > >>>>Hrm, it does not work like there here: > >>>> > >>>>Python 2.3.3 (#2, Mar 19 2004, 19:14:13) > >>>>[GCC 3.2.1 [FreeBSD] 20021119 (release)] on freebsd5 > >>>>Type "help", "copyright", "credits" or "license" for more information. > >>>> > >>>> > >>>>>>>def fn(x): > >>>>>>> > >>>>>>> > >>>>... def _(): > >>>>... x += 1 > >>>>... return x > >>>>... return _ > >>>>... > >>>> > >>>> > >>>>>>>blah = fn(2) > >>>>>>>blah() > >>>>>>> > >>>>>>> > >>>>Traceback (most recent call last): > >>>> File "", line 1, in ? > >>>> File "", line 3, in _ > >>>>UnboundLocalError: local variable 'x' referenced before assignment > >>>> > >>>>And doing def _(x = x) does not fix the trick either. > >>>> > >>>> > >>>> > >>>>>>>blah = fn(2) > >>>>>>>blah() > >>>>>>> > >>>>>>> > >>>>3 > >>>> > >>>> > >>>>>>>blah() > >>>>>>> > >>>>>>> > >>>>3 > >>>> > >>>> > >>>>>>>blah() > >>>>>>> > >>>>>>> > >>>>3 > >>>> > >>>>Do real closures exist in 2.4? > >>>> > >>>>Lloyd Kvam wrote: > >>>> > >>>> > >>>> > >>>> > >>>> > >>>>>It DOES work in current versions of Python, exactly as you coded it. > >>>>> > >>>>>In older Pythons (e.g. 1.52) you would have had to specifying the > >>>>>enclosing variables explicitly > >>>>> def _(x=x): > >>>>> > >>>>>A lot of old critiques are still present on the web. wikipedia has a > >>>>>terrific article describing Python that is current (at least 2.3.3). > >>>>> > >>>>>http://en.wikipedia.org/wiki/Python_programming_language > >>>>> > >>>>> > >>>>> > >>>>>On Sat, 2004-11-13 at 14:07, orbitz wrote: > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>>>In my opinion, this behavior really sucks too. Like when it comes to > >>>>>>closures. As far as I know, Python does not *really* support closures, > >>>>>>like you would get with something like lisp. Correct me if I'm wrong. > >>>>>>This means code like: > >>>>>> > >>>>>>def fn(x): > >>>>>> def _(): > >>>>>> x += 1 > >>>>>> return x > >>>>>> return _ > >>>>>> > >>>>>>Will not work, which can be a pain in the ass. > >>>>>> > >>>>>> > >>>>>>Kent Johnson wrote: > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>>>Liam, > >>>>>>> > >>>>>>>When you make any assignment to a variable inside a function, Python > >>>>>>>assumes that the variable is local to the function. Then any use of > >>>>>>>the variable before it's first assignment is an error. > >>>>>>> > >>>>>>>To force a variable in a function to be global, put a 'global' > >>>>>>>statement in the function. You need to add > >>>>>>>global badConnectCycle > >>>>>>>to your function getReturns > >>>>>>> > >>>>>>>If you don't make any assignment to a variable, then the global > >>>>>>>(module) namespace is searched. That is why badUserList works fine - > >>>>>>>you never assign it, you just access the list methods. > >>>>>>> > >>>>>>>Kent > >>>>>>> > >>>>>>>Liam Clarke wrote: > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>>>Hi all, > >>>>>>>>Having trouble with something, it is 3:30am in the morning, so this > >>>>>>>>may be a dumb problem, if so, I apologise. > >>>>>>>> > >>>>>>>>In my prog, there's two variables created right at the get go - > >>>>>>>> > >>>>>>>>import imaplib > >>>>>>>>import email.Parser > >>>>>>>>import os > >>>>>>>>import os.path > >>>>>>>>import datetime > >>>>>>>>import md5 > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>>from pause import * > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>>>badUserList=[] > >>>>>>>>badConnectCycle=0 > >>>>>>>> > >>>>>>>>as I want them to be global within this module, so that another module > >>>>>>>>can pick them out easily. > >>>>>>>> > >>>>>>>>Now, I just added badConnectCycle, badUserList has been there awhile, > >>>>>>>>and it's used in > >>>>>>>> > >>>>>>>>the function connectToImap which is called by getReturns which is > >>>>>>>>called by main(), and my other module can get it no problem, so > >>>>>>>>badUserList is fine. > >>>>>>>> > >>>>>>>>badConnectCycle... is giving me errors - > >>>>>>>> > >>>>>>>>badConnectCycle is used in getReturns, as so - > >>>>>>>>if session == "NoConnect" : badConnectCycle += 1 > >>>>>>>> continue > >>>>>>>> > >>>>>>>> > >>>>>>>>function getReturns ends as follows - > >>>>>>>>if badConnectCycle == len(user) and badConnectCycle > 0: return > >>>>>>>>("NoConnect","") > >>>>>>>>if badUserList and not sender: return ('NoLogin',"") > >>>>>>>>if matchindex[0] and not sender: return ('NoNew', '') > >>>>>>>>if not sender: return ("NoMatch","") > >>>>>>>>return (sender, msgdata) > >>>>>>>> > >>>>>>>>and it's at that line > >>>>>>>> > >>>>>>>>if badConnectCycle == len(user) and badConnectCycle > 0: > >>>>>>>> > >>>>>>>>that I get this error: > >>>>>>>> > >>>>>>>>UnboundLocalError: local variable 'badConnectCycle' referenced before > >>>>>>>>assignment. > >>>>>>>> > >>>>>>>>Which is confusing me because badUserList is used within a function > >>>>>>>>called by getReturns, and I've had no problem with it. > >>>>>>>> > >>>>>>>>Help anyone? Much appreciated if you can. > >>>>>>>> > >>>>>>>>Regards, > >>>>>>>> > >>>>>>>>Liam Clarke > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>_______________________________________________ > >>>>>>>Tutor maillist - Tutor@python.org > >>>>>>>http://mail.python.org/mailman/listinfo/tutor > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>_______________________________________________ > >>>>>>Tutor maillist - Tutor@python.org > >>>>>>http://mail.python.org/mailman/listinfo/tutor > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> -- Lloyd Kvam Venix Corp From pythonTutor at venix.com Sun Nov 14 00:05:50 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sun Nov 14 00:06:05 2004 Subject: [Tutor] Globals? In-Reply-To: <41968D1A.7010904@ezabel.com> References: <4194D06F.1090904@tds.net> <41965B5B.7010802@ezabel.com> <1100377740.21480.43.camel@laptop.venix.com> <41967C89.4090208@ezabel.com> <1100382419.21480.78.camel@laptop.venix.com> <4196830E.1020101@ezabel.com> <1100383413.21480.86.camel@laptop.venix.com> <419685CE.902@ezabel.com> <1100384926.21480.104.camel@laptop.venix.com> <41968D1A.7010904@ezabel.com> Message-ID: <1100387149.21480.129.camel@laptop.venix.com> Well, the behavior that you are looking for is quite deliberately not supported in Python. I would have described closures as allowing you to set policy for future execution. A decision can be made once and then packaged as a piece of executable code which is used else where. I gather that closure purists would expect that code to have the ability to also rebind variables that lie outside of that executable block. On Sat, 2004-11-13 at 17:39, orbitz wrote: > With closures that will work correctly. Since that is the problem they > solve (more or less) > > > Lloyd Kvam wrote: > > >x = 2 > >def _(): > > x += 1 > >_() > > > >Traceback (most recent call last): > > File "/home/lkvam/aa.py", line 6, in -toplevel- > > _() > > File "/home/lkvam/aa.py", line 4, in _ > > x += 1 > >UnboundLocalError: local variable 'x' referenced before assignment > > > >What is happening is not a closure issue. Any function that attempts to > >assign to a non-local variable will get that error. > > > >x = 2 > >def _(): > > global x > > x += 1 > > return x > >print _() > > > > > >3 > > > >This works because we now explicitly reference the variable as a global. > > > >I'd hate to think that using global in a closure allows it to change the > >global x in whatever namespace where it was run, or that the closure > >would fail if it were run in a namespace that did NOT have a global x. > >I'll leave that investigation to others. > > > > > > > >On Sat, 2004-11-13 at 17:08, orbitz wrote: > > > > > >>I'm modifying the variable which references it though. Which *should* be > >>fine, but Pythons scoping rules and closures are hella messed up. > >>It should work fine, and it can simplify code. Generally you have to > >>make a nested class and return a reference to a method of an instance. > >> > >> > >>Lloyd Kvam wrote: > >> > >> > >> > >>>I should have said, > >>>It is the attempt to change a non-local IMMUTABLE variable. > >>> > >>>I still think that is a feature. If you are trying to change variables > >>>out side of your local scope, Python requires that they be mutable. > >>> > >>>(So I am not a closure purist as Kent pointed out.) > >>> > >>>On Sat, 2004-11-13 at 16:56, orbitz wrote: > >>> > >>> > >>> > >>> > >>>>I know, which is the weakness of python closure's I was pointing out. > >>>> > >>>>Lloyd Kvam wrote: > >>>> > >>>> > >>>> > >>>> > >>>> > >>>>>It is the attempt to change a non-local variable. > >>>>>def _(): > >>>>> return x+1 > >>>>> > >>>>>will work. > >>>>> > >>>>>On Sat, 2004-11-13 at 16:28, orbitz wrote: > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>>>Hrm, it does not work like there here: > >>>>>> > >>>>>>Python 2.3.3 (#2, Mar 19 2004, 19:14:13) > >>>>>>[GCC 3.2.1 [FreeBSD] 20021119 (release)] on freebsd5 > >>>>>>Type "help", "copyright", "credits" or "license" for more information. > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>>>>>def fn(x): > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>... def _(): > >>>>>>... x += 1 > >>>>>>... return x > >>>>>>... return _ > >>>>>>... > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>>>>>blah = fn(2) > >>>>>>>>>blah() > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>Traceback (most recent call last): > >>>>>>File "", line 1, in ? > >>>>>>File "", line 3, in _ > >>>>>>UnboundLocalError: local variable 'x' referenced before assignment > >>>>>> > >>>>>>And doing def _(x = x) does not fix the trick either. > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>>>>>blah = fn(2) > >>>>>>>>>blah() > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>3 > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>>>>>blah() > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>3 > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>>>>>blah() > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>3 > >>>>>> > >>>>>>Do real closures exist in 2.4? > >>>>>> > >>>>>>Lloyd Kvam wrote: > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>>>It DOES work in current versions of Python, exactly as you coded it. > >>>>>>> > >>>>>>>In older Pythons (e.g. 1.52) you would have had to specifying the > >>>>>>>enclosing variables explicitly > >>>>>>> def _(x=x): > >>>>>>> > >>>>>>>A lot of old critiques are still present on the web. wikipedia has a > >>>>>>>terrific article describing Python that is current (at least 2.3.3). > >>>>>>> > >>>>>>>http://en.wikipedia.org/wiki/Python_programming_language > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>>On Sat, 2004-11-13 at 14:07, orbitz wrote: > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>>>In my opinion, this behavior really sucks too. Like when it comes to > >>>>>>>>closures. As far as I know, Python does not *really* support closures, > >>>>>>>>like you would get with something like lisp. Correct me if I'm wrong. > >>>>>>>>This means code like: > >>>>>>>> > >>>>>>>>def fn(x): > >>>>>>>> def _(): > >>>>>>>> x += 1 > >>>>>>>> return x > >>>>>>>> return _ > >>>>>>>> > >>>>>>>>Will not work, which can be a pain in the ass. > >>>>>>>> > >>>>>>>> > >>>>>>>>Kent Johnson wrote: > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>>>Liam, > >>>>>>>>> > >>>>>>>>>When you make any assignment to a variable inside a function, Python > >>>>>>>>>assumes that the variable is local to the function. Then any use of > >>>>>>>>>the variable before it's first assignment is an error. > >>>>>>>>> > >>>>>>>>>To force a variable in a function to be global, put a 'global' > >>>>>>>>>statement in the function. You need to add > >>>>>>>>>global badConnectCycle > >>>>>>>>>to your function getReturns > >>>>>>>>> > >>>>>>>>>If you don't make any assignment to a variable, then the global > >>>>>>>>>(module) namespace is searched. That is why badUserList works fine - > >>>>>>>>>you never assign it, you just access the list methods. > >>>>>>>>> > >>>>>>>>>Kent > >>>>>>>>> > >>>>>>>>>Liam Clarke wrote: > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>>>Hi all, > >>>>>>>>>>Having trouble with something, it is 3:30am in the morning, so this > >>>>>>>>>>may be a dumb problem, if so, I apologise. > >>>>>>>>>> > >>>>>>>>>>In my prog, there's two variables created right at the get go - > >>>>>>>>>> > >>>>>>>>>>import imaplib > >>>>>>>>>>import email.Parser > >>>>>>>>>>import os > >>>>>>>>>>import os.path > >>>>>>>>>>import datetime > >>>>>>>>>>import md5 > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>>from pause import * > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>>>badUserList=[] > >>>>>>>>>>badConnectCycle=0 > >>>>>>>>>> > >>>>>>>>>>as I want them to be global within this module, so that another module > >>>>>>>>>>can pick them out easily. > >>>>>>>>>> > >>>>>>>>>>Now, I just added badConnectCycle, badUserList has been there awhile, > >>>>>>>>>>and it's used in > >>>>>>>>>> > >>>>>>>>>>the function connectToImap which is called by getReturns which is > >>>>>>>>>>called by main(), and my other module can get it no problem, so > >>>>>>>>>>badUserList is fine. > >>>>>>>>>> > >>>>>>>>>>badConnectCycle... is giving me errors - > >>>>>>>>>> > >>>>>>>>>>badConnectCycle is used in getReturns, as so - > >>>>>>>>>>if session == "NoConnect" : badConnectCycle += 1 > >>>>>>>>>> continue > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>>function getReturns ends as follows - > >>>>>>>>>>if badConnectCycle == len(user) and badConnectCycle > 0: return > >>>>>>>>>>("NoConnect","") > >>>>>>>>>>if badUserList and not sender: return ('NoLogin',"") > >>>>>>>>>>if matchindex[0] and not sender: return ('NoNew', '') > >>>>>>>>>>if not sender: return ("NoMatch","") > >>>>>>>>>>return (sender, msgdata) > >>>>>>>>>> > >>>>>>>>>>and it's at that line > >>>>>>>>>> > >>>>>>>>>>if badConnectCycle == len(user) and badConnectCycle > 0: > >>>>>>>>>> > >>>>>>>>>>that I get this error: > >>>>>>>>>> > >>>>>>>>>>UnboundLocalError: local variable 'badConnectCycle' referenced before > >>>>>>>>>>assignment. > >>>>>>>>>> > >>>>>>>>>>Which is confusing me because badUserList is used within a function > >>>>>>>>>>called by getReturns, and I've had no problem with it. > >>>>>>>>>> > >>>>>>>>>>Help anyone? Much appreciated if you can. > >>>>>>>>>> > >>>>>>>>>>Regards, > >>>>>>>>>> > >>>>>>>>>>Liam Clarke > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>_______________________________________________ > >>>>>>>>>Tutor maillist - Tutor@python.org > >>>>>>>>>http://mail.python.org/mailman/listinfo/tutor > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>_______________________________________________ > >>>>>>>>Tutor maillist - Tutor@python.org > >>>>>>>>http://mail.python.org/mailman/listinfo/tutor > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> -- Lloyd Kvam Venix Corp From alan.gauld at freenet.co.uk Sun Nov 14 00:44:35 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Nov 14 00:44:31 2004 Subject: [Tutor] Globals? References: <4194D06F.1090904@tds.net> <41965B5B.7010802@ezabel.com> <1100377740.21480.43.camel@laptop.venix.com> <41967529.1090305@tds.net> <1100381525.21480.66.camel@laptop.venix.com> <419681D8.7010402@ezabel.com><41968415.2090003@tds.net> <4196894F.9080709@ezabel.com> Message-ID: <010b01c4c9da$bb88ba50$43bb8651@xp> PMFJI, > Here is a CL equiv of what I *think* should happen, unelss someone has a > godo reason for it not to belike this: > > (defun foo (n) (lambda (i) (incf n i))) But this is not really equivalrent to what you posted in Python since you pass the increment value to the lambda. If we allow the lambda to take parameters we must surely allow the default value trick too? So the nearest equivalent in Python, which seems to do what I think the CL does... is this: >>> def f(n): ... def g(i, x=n): ... x = x + i ... return x ... return g ... >>> b = f(2) >>> b(3) 5 >>> b(9) 11 >>> c = f(7) >>> c(4) 11 >>> c(22) 29 >>> So by passing the outer parameter into the scope of the returned function as a default value we get very near to true closure behaviour. What are you still missing? Alan G. From jfabiani at yolo.com Sun Nov 14 01:57:49 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sun Nov 14 01:58:18 2004 Subject: [Tutor] Property questions In-Reply-To: <41968159.2050601@tds.net> References: <200411131234.17987.jfabiani@yolo.com> <41968159.2050601@tds.net> Message-ID: <200411131657.49644.jfabiani@yolo.com> On Saturday 13 November 2004 13:49, Kent Johnson wrote: > John Fabiani wrote: > > Hi, > > > > First how does python know which method to use as in: > > > > size = property(getsize,setsize,delsize,'test doc') > > > > I just have not seen anything/example that uses the dele of the > > "property". > > > > so: > > > > "size = something" # would call the getsize method because of the '=' > > sign? > > No, this would call setsize because it is setting a new value for size > > > "size" # would call the setsize because of what? > > This calls getsize because it is getting the value > > > "dele size" # would call the delete method ??????? is that right? > > del size > > > And how does one call the comment part?? > > "size.__doc__" > > Note that all of these require an instance specifier, e.g. myObj.size. > > Here is an example. Suppose you have a class Props defined like this: > class Props(object): > def __init__(self): > self._x = 0 > > def _getx(self): > print '_getx' > return self._x > > def _setx(self, x): > print '_setx' > self._x = x > > def _delx(self): > print '_delx' > del self._x > > x = property(_getx, _setx, _delx, 'This is the "x" property') > > Then you can use it like this: > >>> p=Props() > > Access x through _getx: > >>> p.x > > _getx > 0 > > Set x through _setx: > >>> p.x = 3 > > _setx > > >>> p.x > > _getx > 3 > > Access the doc string. You have to do this on the attribute of the > *class*, not the instance > > >>> Props.x.__doc__ > > 'This is the "x" property' > > Delete the attribute: > >>> del p.x > > _delx > > Now it's gone: > >>> p.x > > _getx > Traceback (most recent call last): > File "", line 1, in ? > File "Property.py", line 7, in _getx > return self._x > AttributeError: 'Props' object has no attribute '_x' > > A good, though technical, guide to properties and descriptors is here: > http://users.rcn.com/python/download/Descriptor.htm Thanks I think understand and will check the link.. John From kent37 at tds.net Sun Nov 14 02:53:21 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Nov 14 02:53:25 2004 Subject: [Tutor] Globals? In-Reply-To: <1100387149.21480.129.camel@laptop.venix.com> References: <4194D06F.1090904@tds.net> <41965B5B.7010802@ezabel.com> <1100377740.21480.43.camel@laptop.venix.com> <41967C89.4090208@ezabel.com> <1100382419.21480.78.camel@laptop.venix.com> <4196830E.1020101@ezabel.com> <1100383413.21480.86.camel@laptop.venix.com> <419685CE.902@ezabel.com> <1100384926.21480.104.camel@laptop.venix.com> <41968D1A.7010904@ezabel.com> <1100387149.21480.129.camel@laptop.venix.com> Message-ID: <4196BA91.4040404@tds.net> Lloyd Kvam wrote: > Well, the behavior that you are looking for is quite deliberately not > supported in Python. I would have described closures as allowing you to > set policy for future execution. A decision can be made once and then > packaged as a piece of executable code which is used else where. > > I gather that closure purists would expect that code to have the ability > to also rebind variables that lie outside of that executable block. That's my understanding of the issue. Here are a couple of references: http://groups.google.com/groups?hl=en&lr=&c2coff=1&selm=tyfwu15v85j.fsf%40pcepsft001.cern.ch http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/67666 This page has orbitz' CL example and a Python version using a class whose instance is callable. http://www.paulgraham.com/accgen.html Kent From jinlin555 at msn.com Sun Nov 14 02:59:54 2004 From: jinlin555 at msn.com (Lin Jin) Date: Sun Nov 14 03:00:09 2004 Subject: [Tutor] how to take user input to form a list? Message-ID: hello,all: if i want to make a function that takes user input to form a list,how i could do that? it's run like: >>>Enter 4 letters: >>>a >>>b >>>c >>>d >>>[a,b,c,d] and i write a code like this which is not working: def list(let1,let2,let3,let4): let1,let2,let3,let4=raw_input("enter 4 letters:") list=[let1,let2,let3,let4] print list anyone could help me on this? thx _________________________________________________________________ Ãâ·ÑÏÂÔØ MSN Explorer: http://explorer.msn.com/lccn/ From bill.mill at gmail.com Sun Nov 14 03:16:25 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sun Nov 14 03:16:31 2004 Subject: [Tutor] how to take user input to form a list? In-Reply-To: References: Message-ID: <797fe3d404111318162236d602@mail.gmail.com> Lin, In [6]: count = 0 In [7]: nums = [] In [8]: while count < 4: ...: n = input('Number: ') ...: nums.append(n) ...: count += 1 ...: Number: 1 Number: 2 Number: 3 Number: 4 In [9]: print nums [1, 2, 3, 4] On Sun, 14 Nov 2004 09:59:54 +0800, Lin Jin wrote: > hello,all: > if i want to make a function that takes user input to form a list,how i > could do that? > it's run like: > >>>Enter 4 letters: > >>>a > >>>b > >>>c > >>>d > >>>[a,b,c,d] > and i write a code like this which is not working: > def list(let1,let2,let3,let4): > let1,let2,let3,let4=raw_input("enter 4 letters:") > list=[let1,let2,let3,let4] > print list > > anyone could help me on this? thx > > _________________________________________________________________ > ???? MSN Explorer: http://explorer.msn.com/lccn/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Sun Nov 14 04:13:19 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Nov 14 04:14:18 2004 Subject: [Tutor] how do i use p2exe Message-ID: <6.1.2.0.2.20041113191107.055d07e0@rcblue.com> This is my second attempt to get some help. I'd REALLY like to be able to use py2exe: Am I the only one having trouble with this? Here's what I did, and what happens. I'm running Win XP and Python 2.3.4. I installed py2exe from http://starship.python.net/crew/theller/py2exe/ . I created setup.py. But in order to have it run I changed the 3rd line of lookdir() to if look.lower() == "y": I created the batch file, which I named test.bat. I used the line cd\python23 as is, because that's where my python23 is. When I run test.bat I get "Current directory is: C:\Python23 Do you wish to see what's in directory?" If I answer "y" I'm correctly shown what's in Python23, and asked, "What is the file you want as an executable? (Type 'quit' to break out of loop) ?" I type "weekday.py" a script I have in Python23. The "DOS" (consol?) window closes immediately. That's it. No creation of weekday.exe. Have I done something wrong. Or what? Thanks, tutors. Dick Moores rdm@rcblue.com At 19:59 11/9/2004, Jacob S. wrote: >This is what I did. >I'm using Windows XP, but it would work for any other windows version... > >1) Take code below and copy into file named "setup.py". > >### Start of Code ### >from distutils.core import setup >import py2exe >import os > > >def lookdir(): > print "Current directory is: %s" % os.getcwd() > look = raw_input('Do you wish to see what\'s in directory? ') > if look.lower() in m: > print "\n".join(os.listdir(os.getcwd())) > >def changedir(): > m = ['y','ye','yes','yep','okay','affirmative','sure'] > ask = 'y' > lookdir() > while ask not in m: > di = raw_input('What directory do you want? ') > os.chdir(di) > lookdir() > ask = raw_input('Do you want this directory? ') > >changedir() >listed = [] >while 1: > ask = raw_input('What is the file you want as an executable? (Type >\'quit\' to break out of loop) ') > if ask == 'quit' or ask == 'stop' or ask == '': > break > else: > listed.append(os.path.join(desktop,ask)) > >setup(console = listed) >### End of Code ### > >2) Take following code and save as a batch file. You will have to change the >second line to change the directory to your python dir > >rem Start of Code >@echo off >cd\python23 >start python setup.py py2exe >rem End of Code > >3) Run the batch file. It will ask you which directory the script file is >in. That would be the file that you're trying to make and executable. Then, >when you decide which directory it is in, it will ask you the name of the >file. You type in the name. If you want more than one file, you can type in >another file name in the next prompt, else you can type in 'quit' or 'stop' >or just hit enter. When all is done and the shell window closes, you can >check out the directory that you chose. In that directory, there will be two >new folders. One is labeled build. That folder is not necessary to run your >executable and can be deleted. I usually delete it. The other is labeled >dist. It contains the files needed for your program. Your program will have >the same name, just with a exe extension instead of a py extension. Send the >whole folder on to your students, and they can double-click on the exe file, >and it will run your script as if you double-clicked it in Windows Explorer. > >Also, in your code (which I will try to rewrite for fun on my own (no >offense)) you might try this instead: > >print "".join(["\t","\\"*7," ","\\"*4," ","\\"*6," ","\\"*7," ","\\"*2," >","\\"*10," ","\\"*2," ","\\"*8,"\n"]) > >Ignore the underline and blue if it shows up in your email thing. >This just shows that you can multiply a particular string by an integer to >copy it. > >Hope all this helps, >Jacob Schmidt _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sun Nov 14 04:47:21 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Nov 14 04:47:30 2004 Subject: [Tutor] how do i use p2exe In-Reply-To: <6.1.2.0.2.20041113191107.055d07e0@rcblue.com> References: <6.1.2.0.2.20041113191107.055d07e0@rcblue.com> Message-ID: <4196D549.3080107@tds.net> Dick, The script you are using is an attempt to automate the use of py2exe so you don't have to create setup.py for each script. I suggest you try a manual approach. I downloaded and installed py2exe. I opened a DOS console to C:\Python23\Lib\site-packages\py2exe\samples\simple and typed > python setup.py py2exe This created a dist directory with two executables - a console program and a wxPython program. Does this work for you? If it does, the next step is to copy setup.py from the samples dir to the dir where your program is, and modify it appropriately. It's a pretty simple file, this isn't be hard. If you can't get that to work, you might want to ask on the py2exe mailing list, we don't seem to have any experts here. Kent Dick Moores wrote: > This is my second attempt to get some help. I'd REALLY like to be able > to use py2exe: > > > Am I the only one having trouble with this? Here's what I did, and what > happens. > I'm running Win XP and Python 2.3.4. > > I installed py2exe from http://starship.python.net/crew/theller/py2exe/ . > > I created setup.py. But in order to have it run I changed the 3rd line > of lookdir() to if look.lower() == "y": > > I created the batch file, which I named test.bat. I used the line > cd\python23 as is, because that's where my python23 is. > > When I run test.bat I get > "Current directory is: C:\Python23 > Do you wish to see what's in directory?" > > If I answer "y" I'm correctly shown what's in Python23, and asked, > "What is the file you want as an executable? (Type 'quit' to break out > of loop) ?" > > I type "weekday.py" a script I have in Python23. > > The "DOS" (consol?) window closes immediately. > > That's it. No creation of weekday.exe. > > Have I done something wrong. Or what? > > Thanks, tutors. > > Dick Moores > rdm@rcblue.com > > > At 19:59 11/9/2004, Jacob S. wrote: > >> This is what I did. >> I'm using Windows XP, but it would work for any other windows version... >> >> 1) Take code below and copy into file named "setup.py". >> >> ### Start of Code ### >> from distutils.core import setup >> import py2exe >> import os >> >> >> def lookdir(): >> print "Current directory is: %s" % os.getcwd() >> look = raw_input('Do you wish to see what\'s in directory? ') >> if look.lower() in m: >> print "\n".join(os.listdir(os.getcwd())) >> >> def changedir(): >> m = ['y','ye','yes','yep','okay','affirmative','sure'] >> ask = 'y' >> lookdir() >> while ask not in m: >> di = raw_input('What directory do you want? ') >> os.chdir(di) >> lookdir() >> ask = raw_input('Do you want this directory? ') >> >> changedir() >> listed = [] >> while 1: >> ask = raw_input('What is the file you want as an executable? (Type >> \'quit\' to break out of loop) ') >> if ask == 'quit' or ask == 'stop' or ask == '': >> break >> else: >> listed.append(os.path.join(desktop,ask)) >> >> setup(console = listed) >> ### End of Code ### >> >> 2) Take following code and save as a batch file. You will have to >> change the >> second line to change the directory to your python dir >> >> rem Start of Code >> @echo off >> cd\python23 >> start python setup.py py2exe >> rem End of Code >> >> 3) Run the batch file. It will ask you which directory the script file is >> in. That would be the file that you're trying to make and executable. >> Then, >> when you decide which directory it is in, it will ask you the name of the >> file. You type in the name. If you want more than one file, you can >> type in >> another file name in the next prompt, else you can type in 'quit' or >> 'stop' >> or just hit enter. When all is done and the shell window closes, you can >> check out the directory that you chose. In that directory, there will >> be two >> new folders. One is labeled build. That folder is not necessary to run >> your >> executable and can be deleted. I usually delete it. The other is labeled >> dist. It contains the files needed for your program. Your program will >> have >> the same name, just with a exe extension instead of a py extension. >> Send the >> whole folder on to your students, and they can double-click on the exe >> file, >> and it will run your script as if you double-clicked it in Windows >> Explorer. >> >> Also, in your code (which I will try to rewrite for fun on my own (no >> offense)) you might try this instead: >> >> print "".join(["\t","\\"*7," ","\\"*4," ","\\"*6," ","\\"*7," ","\\"*2," >> ","\\"*10," ","\\"*2," ","\\"*8,"\n"]) >> >> Ignore the underline and blue if it shows up in your email thing. >> This just shows that you can multiply a particular string by an >> integer to >> copy it. >> >> Hope all this helps, >> Jacob Schmidt > > > > _______________________________________________ > 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 rdm at rcblue.com Sun Nov 14 06:20:06 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Nov 14 06:20:25 2004 Subject: [Tutor] how do i use p2exe In-Reply-To: <4196D549.3080107@tds.net> References: <6.1.2.0.2.20041113191107.055d07e0@rcblue.com> <4196D549.3080107@tds.net> Message-ID: <6.1.2.0.2.20041113202140.0483a190@rcblue.com> Thanks, Kent. I've gotten to the point where I can create an exe in Python23/dist of a script in Python23. For example, from weekday1.py I've created weekday1.exe. When I double-click on Python/dist/weekday1.exe, it works fine in a consol window. But when I copy weekday1.exe to my desktop, all I get is a flash of a console window opening and closing when I execute it. Here's weekday1.py: And setup.py: Can you tell me what's wrong? Thanks, Dick Kent Johnson wrote at 19:47 11/13/2004: >Dick, > >The script you are using is an attempt to automate the use of py2exe so >you don't have to create setup.py for each script. I suggest you try a >manual approach. > >I downloaded and installed py2exe. I opened a DOS console to >C:\Python23\Lib\site-packages\py2exe\samples\simple and typed > > python setup.py py2exe > >This created a dist directory with two executables - a console program >and a wxPython program. > >Does this work for you? >If it does, the next step is to copy setup.py from the samples dir to >the dir where your program is, and modify it appropriately. It's a >pretty simple file, this isn't be hard. > >If you can't get that to work, you might want to ask on the py2exe >mailing list, we don't seem to have any experts here. > >Kent > >Dick Moores wrote: >>This is my second attempt to get some help. I'd REALLY like to be able >>to use py2exe: >> >>Am I the only one having trouble with this? Here's what I did, and what >>happens. >>I'm running Win XP and Python 2.3.4. >>I installed py2exe from http://starship.python.net/crew/theller/py2exe/ . >>I created setup.py. But in order to have it run I changed the 3rd line >>of lookdir() to if look.lower() == "y": >>I created the batch file, which I named test.bat. I used the line >>cd\python23 as is, because that's where my python23 is. >>When I run test.bat I get >>"Current directory is: C:\Python23 >>Do you wish to see what's in directory?" >>If I answer "y" I'm correctly shown what's in Python23, and asked, >>"What is the file you want as an executable? (Type 'quit' to break out >>of loop) ?" >>I type "weekday.py" a script I have in Python23. >>The "DOS" (consol?) window closes immediately. >>That's it. No creation of weekday.exe. >>Have I done something wrong. Or what? >>Thanks, tutors. >>Dick Moores >>rdm@rcblue.com >> >>At 19:59 11/9/2004, Jacob S. wrote: >> >>>This is what I did. >>>I'm using Windows XP, but it would work for any other windows version... >>> >>>1) Take code below and copy into file named "setup.py". >>> >>>### Start of Code ### >>>from distutils.core import setup >>>import py2exe >>>import os >>> >>> >>>def lookdir(): >>> print "Current directory is: %s" % os.getcwd() >>> look = raw_input('Do you wish to see what\'s in directory? ') >>> if look.lower() in m: >>> print "\n".join(os.listdir(os.getcwd())) >>> >>>def changedir(): >>> m = ['y','ye','yes','yep','okay','affirmative','sure'] >>> ask = 'y' >>> lookdir() >>> while ask not in m: >>> di = raw_input('What directory do you want? ') >>> os.chdir(di) >>> lookdir() >>> ask = raw_input('Do you want this directory? ') >>> >>>changedir() >>>listed = [] >>>while 1: >>> ask = raw_input('What is the file you want as an executable? (Type >>>\'quit\' to break out of loop) ') >>> if ask == 'quit' or ask == 'stop' or ask == '': >>> break >>> else: >>> listed.append(os.path.join(desktop,ask)) >>> >>>setup(console = listed) >>>### End of Code ### >>> >>>2) Take following code and save as a batch file. You will have to >>>change the >>>second line to change the directory to your python dir >>> >>>rem Start of Code >>>@echo off >>>cd\python23 >>>start python setup.py py2exe >>>rem End of Code >>> >>>3) Run the batch file. It will ask you which directory the script file is >>>in. That would be the file that you're trying to make and executable. >>>Then, >>>when you decide which directory it is in, it will ask you the name of the >>>file. You type in the name. If you want more than one file, you can >>>type in >>>another file name in the next prompt, else you can type in 'quit' or >>>'stop' >>>or just hit enter. When all is done and the shell window closes, you can >>>check out the directory that you chose. In that directory, there will >>>be two >>>new folders. One is labeled build. That folder is not necessary to run >>>your >>>executable and can be deleted. I usually delete it. The other is labeled >>>dist. It contains the files needed for your program. Your program will >>>have >>>the same name, just with a exe extension instead of a py extension. >>>Send the >>>whole folder on to your students, and they can double-click on the exe >>>file, >>>and it will run your script as if you double-clicked it in Windows >>>Explorer. >>> >>>Also, in your code (which I will try to rewrite for fun on my own (no >>>offense)) you might try this instead: >>> >>>print "".join(["\t","\\"*7," ","\\"*4," ","\\"*6," ","\\"*7," ","\\"*2," >>>","\\"*10," ","\\"*2," ","\\"*8,"\n"]) >>> >>>Ignore the underline and blue if it shows up in your email thing. >>>This just shows that you can multiply a particular string by an integer to >>>copy it. >>> >>>Hope all this helps, >>>Jacob Schmidt >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >>_______________________________________________ >>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 alan.gauld at freenet.co.uk Sun Nov 14 09:08:42 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Nov 14 09:08:32 2004 Subject: [Tutor] how to take user input to form a list? References: Message-ID: <012401c4ca21$288bf950$43bb8651@xp> > and i write a code like this which is not working: > def list(let1,let2,let3,let4): > let1,let2,let3,let4=raw_input("enter 4 letters:") raw_input always returns a single string. You need to separate, or parse, out the individual components. So: def getList(): s = raw_input('Enter 4 comma separated letters') lst = s.split(',') return lst Of course you would probably need a lot more error detection than that in reality, to ensure there were only 4 letters, that they were comme separated etc. THe other thing to watch is that you should not use Python reserved words like list as variable names because if you do you will not be able to use the Python functions of the same name! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sun Nov 14 12:58:25 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Nov 14 12:58:30 2004 Subject: [Tutor] how do i use p2exe In-Reply-To: <6.1.2.0.2.20041113202140.0483a190@rcblue.com> References: <6.1.2.0.2.20041113191107.055d07e0@rcblue.com> <4196D549.3080107@tds.net> <6.1.2.0.2.20041113202140.0483a190@rcblue.com> Message-ID: <41974861.6060101@tds.net> Ah. py2exe doesn't actually create a single-file executable. You need everything else in the dist folder to go with the .exe. If you want a single file exe, Google for 'py2exe single file' to find some discussions. If you want the exe on your desktop, just make a shortcut. A more general tip - when a console-based program is failing, if you run it by double-clicking the exe you will often see just the flash of the console opening and closing. You can get more information by opening a console yourself to the directory and running the exe from the command line. With weekday1.exe, if I copy it to a new directory and run it from the command line I get this: D:\Personal\Tutor\weekday>weekday1 Traceback (most recent call last): File "C:\Python23\lib\site-packages\py2exe\boot_common.py", line 69, in ? import linecache ImportError: No module named linecache Traceback (most recent call last): File "weekday1.py", line 8, in ? import datetime ImportError: No module named datetime which might not have been enough for you to figure out the problem but it is at least a clue in the right direction. Kent Dick Moores wrote: > Thanks, Kent. I've gotten to the point where I can create an exe in > Python23/dist of a script in Python23. For example, from weekday1.py > I've created weekday1.exe. When I double-click on > Python/dist/weekday1.exe, it works fine in a consol window. But when I > copy weekday1.exe to my desktop, all I get is a flash of a console > window opening and closing when I execute it. > > Here's weekday1.py: > And setup.py: > > Can you tell me what's wrong? > > Thanks, > > Dick > > Kent Johnson wrote at 19:47 11/13/2004: > >> Dick, >> >> The script you are using is an attempt to automate the use of py2exe >> so you don't have to create setup.py for each script. I suggest you >> try a manual approach. >> >> I downloaded and installed py2exe. I opened a DOS console to >> C:\Python23\Lib\site-packages\py2exe\samples\simple and typed >> > python setup.py py2exe >> >> This created a dist directory with two executables - a console program >> and a wxPython program. >> >> Does this work for you? >> If it does, the next step is to copy setup.py from the samples dir to >> the dir where your program is, and modify it appropriately. It's a >> pretty simple file, this isn't be hard. >> >> If you can't get that to work, you might want to ask on the py2exe >> mailing list, we don't seem to have any experts here. >> >> Kent >> >> Dick Moores wrote: >> >>> This is my second attempt to get some help. I'd REALLY like to be >>> able to use py2exe: >>> >>> Am I the only one having trouble with this? Here's what I did, and >>> what happens. >>> I'm running Win XP and Python 2.3.4. >>> I installed py2exe from >>> http://starship.python.net/crew/theller/py2exe/ . >>> I created setup.py. But in order to have it run I changed the 3rd >>> line of lookdir() to if look.lower() == "y": >>> I created the batch file, which I named test.bat. I used the line >>> cd\python23 as is, because that's where my python23 is. >>> When I run test.bat I get >>> "Current directory is: C:\Python23 >>> Do you wish to see what's in directory?" >>> If I answer "y" I'm correctly shown what's in Python23, and asked, >>> "What is the file you want as an executable? (Type 'quit' to break >>> out of loop) ?" >>> I type "weekday.py" a script I have in Python23. >>> The "DOS" (consol?) window closes immediately. >>> That's it. No creation of weekday.exe. >>> Have I done something wrong. Or what? >>> Thanks, tutors. >>> Dick Moores >>> rdm@rcblue.com >>> >>> At 19:59 11/9/2004, Jacob S. wrote: >>> >>>> This is what I did. >>>> I'm using Windows XP, but it would work for any other windows >>>> version... >>>> >>>> 1) Take code below and copy into file named "setup.py". >>>> >>>> ### Start of Code ### >>>> from distutils.core import setup >>>> import py2exe >>>> import os >>>> >>>> >>>> def lookdir(): >>>> print "Current directory is: %s" % os.getcwd() >>>> look = raw_input('Do you wish to see what\'s in directory? ') >>>> if look.lower() in m: >>>> print "\n".join(os.listdir(os.getcwd())) >>>> >>>> def changedir(): >>>> m = ['y','ye','yes','yep','okay','affirmative','sure'] >>>> ask = 'y' >>>> lookdir() >>>> while ask not in m: >>>> di = raw_input('What directory do you want? ') >>>> os.chdir(di) >>>> lookdir() >>>> ask = raw_input('Do you want this directory? ') >>>> >>>> changedir() >>>> listed = [] >>>> while 1: >>>> ask = raw_input('What is the file you want as an executable? (Type >>>> \'quit\' to break out of loop) ') >>>> if ask == 'quit' or ask == 'stop' or ask == '': >>>> break >>>> else: >>>> listed.append(os.path.join(desktop,ask)) >>>> >>>> setup(console = listed) >>>> ### End of Code ### >>>> >>>> 2) Take following code and save as a batch file. You will have to >>>> change the >>>> second line to change the directory to your python dir >>>> >>>> rem Start of Code >>>> @echo off >>>> cd\python23 >>>> start python setup.py py2exe >>>> rem End of Code >>>> >>>> 3) Run the batch file. It will ask you which directory the script >>>> file is >>>> in. That would be the file that you're trying to make and >>>> executable. Then, >>>> when you decide which directory it is in, it will ask you the name >>>> of the >>>> file. You type in the name. If you want more than one file, you can >>>> type in >>>> another file name in the next prompt, else you can type in 'quit' or >>>> 'stop' >>>> or just hit enter. When all is done and the shell window closes, you >>>> can >>>> check out the directory that you chose. In that directory, there >>>> will be two >>>> new folders. One is labeled build. That folder is not necessary to >>>> run your >>>> executable and can be deleted. I usually delete it. The other is >>>> labeled >>>> dist. It contains the files needed for your program. Your program >>>> will have >>>> the same name, just with a exe extension instead of a py extension. >>>> Send the >>>> whole folder on to your students, and they can double-click on the >>>> exe file, >>>> and it will run your script as if you double-clicked it in Windows >>>> Explorer. >>>> >>>> Also, in your code (which I will try to rewrite for fun on my own (no >>>> offense)) you might try this instead: >>>> >>>> print "".join(["\t","\\"*7," ","\\"*4," ","\\"*6," ","\\"*7," >>>> ","\\"*2," >>>> ","\\"*10," ","\\"*2," ","\\"*8,"\n"]) >>>> >>>> Ignore the underline and blue if it shows up in your email thing. >>>> This just shows that you can multiply a particular string by an >>>> integer to >>>> copy it. >>>> >>>> Hope all this helps, >>>> Jacob Schmidt >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >> >> _______________________________________________ >> 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 pythontut at pusspaws.net Sun Nov 14 14:34:27 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Nov 14 14:41:30 2004 Subject: [Tutor] demon / app I/F better way ? Message-ID: <41975EE3.3070809@pusspaws.net> Hi there, I am planning a python app but have hit a dilemma. I have a time critical python app that will be running constantly as a demon, checking a data web page for updates & archiving any changes. When a change occurs it needs to signal another python app that new data has arrived. OK this is the way I am planning to do this, if there is a neater way please shout :-D the demon dumps data in /data/data_new & also changes the state of a flag /data/data_flag to true when it has found new changes my main app when it is ready to accept data checks the status of /data/data_flag every second, if it changes to a true state reads in /data/data_new & sets /data/data_flag to false, performs processing then checks /data/data_flag ... This will work (I think ;-) ) but seems a bit clunky, anyone got a more elegant solution? Dave From kent37 at tds.net Sun Nov 14 15:29:54 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Nov 14 15:30:02 2004 Subject: [Tutor] demon / app I/F better way ? In-Reply-To: <41975EE3.3070809@pusspaws.net> References: <41975EE3.3070809@pusspaws.net> Message-ID: <41976BE2.4000204@tds.net> What about running the demon as a separate thread in the main app? Use a Queue to send data from the demon to the main app. The app checks for data in the queue every second. Or, use a socket connection between the demon and the main app... Kent Dave S wrote: > Hi there, > > I am planning a python app but have hit a dilemma. > > I have a time critical python app that will be running constantly as a > demon, checking a data web page for updates & archiving any changes. > When a change occurs it needs to signal another python app that new data > has arrived. > > > OK this is the way I am planning to do this, if there is a neater way > please shout :-D > > the demon dumps data in /data/data_new & also changes the state of a > flag /data/data_flag to true when it has found new changes > > my main app when it is ready to accept data checks the status of > /data/data_flag every second, if it changes to a true state reads in > /data/data_new & sets /data/data_flag to false, performs processing then > checks /data/data_flag ... > > > This will work (I think ;-) ) but seems a bit clunky, anyone got a more > elegant solution? > > Dave > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pythontut at pusspaws.net Sun Nov 14 16:47:59 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Nov 14 16:48:10 2004 Subject: [Tutor] demon / app I/F better way ? In-Reply-To: <41976BE2.4000204@tds.net> References: <41975EE3.3070809@pusspaws.net> <41976BE2.4000204@tds.net> Message-ID: <41977E2F.1080807@pusspaws.net> Kent Johnson wrote: > What about running the demon as a separate thread in the main app? Use > a Queue to send data from the demon to the main app. The app checks > for data in the queue every second. > > Or, use a socket connection between the demon and the main app... > > Kent Running the demon as a seperate thread is a good idea, I had not thought of that, I was going to 'demon.py &' it - which must be pretty inefficient. Queueing the data, like a FIFO buffer, that negates the need for /data/data_flag, if its read, its gone - thats elegent - I like that :-) . I could write a script that implements a FIFO function - or maybe I will find one in the vaults. As to using a socket, I have only encounterd passing references to them mainly when tweeking the linux kernel , Can you point me in the direction of how you can use them in Python ... ? Cheers Dave From pythontut at pusspaws.net Sun Nov 14 17:05:57 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Nov 14 17:06:09 2004 Subject: [Tutor] demon / app I/F better way ? In-Reply-To: <41977E2F.1080807@pusspaws.net> References: <41975EE3.3070809@pusspaws.net> <41976BE2.4000204@tds.net> <41977E2F.1080807@pusspaws.net> Message-ID: <41978265.8080804@pusspaws.net> > Running the demon as a seperate thread is a good idea, I had not > thought of that, I was going to 'demon.py &' it - which must be pretty > inefficient. > > Queueing the data, like a FIFO buffer, that negates the need for > /data/data_flag, if its read, its gone - thats elegent - I like that > :-) . I could write a script that implements a FIFO function - or > maybe I will find one in the vaults. Just found one, and an interesting thread http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68436 > > As to using a socket, I have only encounterd passing references to > them mainly when tweeking the linux kernel , Can you point me in the > direction of how you can use them in Python ... ? > > Cheers > Dave From kent37 at tds.net Sun Nov 14 17:07:18 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Nov 14 17:07:23 2004 Subject: [Tutor] demon / app I/F better way ? In-Reply-To: <41977E2F.1080807@pusspaws.net> References: <41975EE3.3070809@pusspaws.net> <41976BE2.4000204@tds.net> <41977E2F.1080807@pusspaws.net> Message-ID: <419782B6.8030305@tds.net> Dave S wrote: > Running the demon as a seperate thread is a good idea, I had not thought > of that, I was going to 'demon.py &' it - which must be pretty inefficient. > > Queueing the data, like a FIFO buffer, that negates the need for > /data/data_flag, if its read, its gone - thats elegent - I like that > :-) . I could write a script that implements a FIFO function - or maybe > I will find one in the vaults. See the Queue module in the standard library > As to using a socket, I have only encounterd passing references to them > mainly when tweeking the linux kernel , Can you point me in the > direction of how you can use them in Python ... ? See the socket module to start, or the socket programming HOW-TO: http://www.amk.ca/python/howto/sockets/ There are others on this list with more experience than me with socket programming, I hope they will chime in here...personally I like threads :-) Kent From keridee at jayco.net Sun Nov 14 17:12:20 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Nov 14 17:12:50 2004 Subject: [Tutor] Amazed References: <006401c4c867$87a30110$6c5328cf@JSLAPTOP> <41942FDD.3030105@tds.net> Message-ID: <001601c4ca64$bcb5ade0$065428cf@JSLAPTOP> I believe I agree with both you and Bill. 1) List comprehensions do seem addictive. However, I did not give you enough code. newlist = [] for x in something: if somethingelse == somethingelse2: [newlist.append(somethingelse) for m in ot if m % 2 == 0] elif somethingelse == somethingelse3: [newlist.append(somethingelse) for m in ot if m % 3 == 0] etc,etc,etc. This shows that newlist is appended to, not written over in each list comprehension. That's because I want all of the things in newlist throughout the whole loop, because I will do something with newlist afterwards. From pythontut at pusspaws.net Sun Nov 14 17:41:30 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Nov 14 17:41:43 2004 Subject: [Tutor] demon / app I/F better way ? In-Reply-To: <419782B6.8030305@tds.net> References: <41975EE3.3070809@pusspaws.net> <41976BE2.4000204@tds.net> <41977E2F.1080807@pusspaws.net> <419782B6.8030305@tds.net> Message-ID: <41978ABA.7000900@pusspaws.net> Kent Johnson wrote: > Dave S wrote: > >> Running the demon as a seperate thread is a good idea, I had not >> thought of that, I was going to 'demon.py &' it - which must be >> pretty inefficient. >> >> Queueing the data, like a FIFO buffer, that negates the need for >> /data/data_flag, if its read, its gone - thats elegent - I like that >> :-) . I could write a script that implements a FIFO function - or >> maybe I will find one in the vaults. > > > See the Queue module in the standard library > >> As to using a socket, I have only encounterd passing references to >> them mainly when tweeking the linux kernel , Can you point me in the >> direction of how you can use them in Python ... ? > > > See the socket module to start, or the socket programming HOW-TO: > http://www.amk.ca/python/howto/sockets/ > > There are others on this list with more experience than me with socket > programming, I hope they will chime in here...personally I like > threads :-) > > Kent ...mmm ... Now I have an idea as to what sockets are, I like threads to :-), they seem OTT for what I need. Having decided on threading the demon, and using a fifo, the queue module looks cool, I have one last dilema. One that quite often causes me problems, that scope, namespace thing ;-) If I have my demon thread running, and I define a queue, it will work fine, If I have my main app running and define a queue, it will also work fine but this defines two seperate queues which are not joined, data from one will not pass to the other. If I were to define a seperate script which handles the queue 'fifio.py' & import it to both the deamon thread & the main app, this would use the class definition as a king of global variable. Would this be the best way ? - more importantly would it work :-D ! Dave From keridee at jayco.net Sun Nov 14 17:45:32 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Nov 14 17:46:09 2004 Subject: [Tutor] how do i use p2exe References: <1033bb7f041109191055f46aee@mail.gmail.com> <00e701c4c6d9$ac052e00$db5428cf@JSLAPTOP> <6.1.2.0.2.20041112042711.08269eb0@rcblue.com> Message-ID: <002501c4ca69$62a69e40$065428cf@JSLAPTOP> Okay, I see what's wrong with my code. First, to Kent, what's wrong with trying to automate py2exe? It drives me batty to have to open the command prompt in Windows and then go to the python23 folder and type in "python setup.py py2exe" which I can't remember when I need it. Then, I always have to change setup.py every time I want to use py2exe. I think that if you can get it to work, automation would be beautiful. (It works on my machine.) Second, to Dick. There are one or two things wrong with the code I gave you. It was late. However, you did not use the raw_inputs quite as I would have expected. So, a detailed run through. First, change my setup.py to read as follows: ##Start of code ### Start of Code ### from distutils.core import setup import py2exe import os def lookdir(): m = ['y','ye','yes','yep','okay','affirmative','sure'] print "Current directory is: %s" % os.getcwd() look = raw_input('Do you wish to see what\'s in directory? ') if look.lower() in m: print "\n".join(os.listdir(os.getcwd())) def changedir(): m = ['y','ye','yes','yep','okay','affirmative','sure'] ## Here I have to define m again because of local variables. Ughh. lookdir() ask = raw_input('Do you want the current directory? ') ## Had to fix this, brain fart. while ask not in m: di = raw_input('What directory do you want? ') os.chdir(di) lookdir() ask = raw_input('Do you want this directory? ') changedir() listed = [] while 1: ask = raw_input('What is the file you want as an executable? (Type \'quit\' to break out of loop) ') if ask == 'quit' or ask == 'stop' or ask == '': break else: listed.append(os.path.join(os.getcwd(),ask)) setup(console = listed) ### End of Code ### Okay, the batch file should be okay... But just in case... rem Start of Code @echo off cd\python23 rem Change this line to your python directory start python setup.py py2exe rem End of Code I made a couple of changes to the code above. Okay, a complete walkthrough. 1) Copy setup.py code to file in python directory 2) Copy batch file code to any convenient directory. 3) Run batch file 4) You should get a python console program. 5) Okay the nitty-gritty, cross your fingers, hope I have it right this time. 6) It should show current directory, ask you if you want to see what's in it 7) It should ask you whether you want the current dir 8) If you say no, then it will ask you for a new directory. It will run through steps 6-8 until you say that you want the current directory 9) It will ask you what file you want until you type in quit. This is for multiple file executables. Each thing you type in other than quit will be thought of as a file in the current directory. '' '' '' '' '' '' '' '' '' '' put in the executable directory. 10) When you type quit in step 9, it will make executables for every other thing you typed in. 11) Python console should disappear. 12) In the directory that the files are in, you should have two folders, build and dist. 13) Dist is the folder that you are looking for, build is another helper folder that doesn't really do anything as far as I can tell. It can be deleted. 14) Run each executable in the dist folder. The ones that have the same names as the files you typed in should all work. (There is another executable in there that doesn't stand alone. It's part of the stuff.) 15) You can rename the dist folder anything you want. 16) You have to leave everything in the dist folder intact. 17) You should probably put shortcuts to the programs in a more convenient place 18) That should be it. If it doesn't work now, I should be very unhappy and I would like to know why it doesn't work! I hope this will help someone, Jacob Schmidt From glingl at aon.at Sun Nov 14 17:52:27 2004 From: glingl at aon.at (Gregor Lingl) Date: Sun Nov 14 17:52:08 2004 Subject: [Tutor] how to take user input to form a list? In-Reply-To: References: Message-ID: <41978D4B.2070302@aon.at> Lin Jin schrieb: > hello,all: > if i want to make a function that takes user input to form a list,how > i could do that? > it's run like: > >>>> Enter 4 letters: >>>> a >>>> b >>>> c >>>> d >>>> [a,b,c,d] >>> > and i write a code like this which is not working: > def list(let1,let2,let3,let4): > let1,let2,let3,let4=raw_input("enter 4 letters:") > list=[let1,let2,let3,let4] > print list > Hi Lin! In priciple your code should work. But you should tell us, how you want to call your function list. You have to supply 4 arguments, which - however - will not be used, when your function is executed. The values of your parameters will be overwritten immediately by the result of the raw_input call. I did this, for instance: >>> def list(let1,let2,let3,let4): let1,let2,let3,let4=raw_input("enter 4 letters:") list=[let1,let2,let3,let4] print list >>> list(1,2,3,4) enter 4 letters:abcd ['a', 'b', 'c', 'd'] >>> list(None,None,None,None) enter 4 letters:xyz! ['x', 'y', 'z', '!'] >>> So you could define as well: >>> def list(): let1,let2,let3,let4=raw_input("enter 4 letters:") list=[let1,let2,let3,let4] print list >>> list() enter 4 letters:1234 ['1', '2', '3', '4'] >>> Moreover it is not a good idea do name a userdefined function 'list' as this is the name of a built-in datatype/function of Python, which you will not be able to use anymore after your definition is executed: >>> list >>> >>> def list(): let1,let2,let3,let4=raw_input("enter 4 letters:") list=[let1,let2,let3,let4] print list >>> list Aaah! This reminds me, that you can use the original Python-list-type to accomplish your task (in a freshly started Python): Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. ... >>> list("abcd") ['a', 'b', 'c', 'd'] >>> def makecharlist(): return list(raw_input("Enter (4) characters: ")) >>> makecharlist() Enter (4) characters: pqrs ['p', 'q', 'r', 's'] >>> makecharlist() Enter (4) characters: pqrstuvw!!!! ['p', 'q', 'r', 's', 't', 'u', 'v', 'w', '!', '!', '!', '!'] >>> I think, that Alan in his reply missed, that splitting will be done by "sequence-unpacking" in your code. But it will work only with exactly four characters entered, while the code he proposed will work for strings with arbitrary length (and produce lists of that length). Hope that helps Gregor > anyone could help me on this? thx > > _________________________________________________________________ > Ãâ·ÑÏÂÔØ MSN Explorer: http://explorer.msn.com/lccn/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Sun Nov 14 18:14:38 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Nov 14 18:14:43 2004 Subject: [Tutor] how do i use p2exe In-Reply-To: <002501c4ca69$62a69e40$065428cf@JSLAPTOP> References: <1033bb7f041109191055f46aee@mail.gmail.com> <00e701c4c6d9$ac052e00$db5428cf@JSLAPTOP> <6.1.2.0.2.20041112042711.08269eb0@rcblue.com> <002501c4ca69$62a69e40$065428cf@JSLAPTOP> Message-ID: <4197927E.1010401@tds.net> Jacob S. wrote: > Okay, > > I see what's wrong with my code. First, to Kent, what's wrong with trying to > automate py2exe? In principle, nothing at all. But when the automation is broken it's not too helpful :-) Dick was having trouble with something that should be pretty basic. He wasn't getting any help. I don't know py2exe or distutils but I was willing to give it a shot. So going back to basics seemed like a good approach - I wanted to address the fundamental problem, not figure out what your script was doing. Once Dick has that working he can come back to your script with better understanding. Kent From orbitz at ezabel.com Sun Nov 14 18:14:48 2004 From: orbitz at ezabel.com (orbitz) Date: Sun Nov 14 18:15:04 2004 Subject: [Tutor] demon / app I/F better way ? In-Reply-To: <41977E2F.1080807@pusspaws.net> References: <41975EE3.3070809@pusspaws.net> <41976BE2.4000204@tds.net> <41977E2F.1080807@pusspaws.net> Message-ID: <41979288.8010404@ezabel.com> What is time critical about this? Checking a website for updates takes eons longer than doing some calculations. Do you have control of both of these apps code? If so it might just be more efficient in the long run to rewrite them so that they are one application using something like nonblocking sockets to do multiple things. Just a thought. Dave S wrote: > Kent Johnson wrote: > >> What about running the demon as a separate thread in the main app? >> Use a Queue to send data from the demon to the main app. The app >> checks for data in the queue every second. >> >> Or, use a socket connection between the demon and the main app... >> >> Kent > > > Running the demon as a seperate thread is a good idea, I had not > thought of that, I was going to 'demon.py &' it - which must be pretty > inefficient. > > Queueing the data, like a FIFO buffer, that negates the need for > /data/data_flag, if its read, its gone - thats elegent - I like that > :-) . I could write a script that implements a FIFO function - or > maybe I will find one in the vaults. > > As to using a socket, I have only encounterd passing references to > them mainly when tweeking the linux kernel , Can you point me in the > direction of how you can use them in Python ... ? > > Cheers > Dave > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Nov 14 18:20:37 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Nov 14 18:20:42 2004 Subject: [Tutor] demon / app I/F better way ? In-Reply-To: <41978ABA.7000900@pusspaws.net> References: <41975EE3.3070809@pusspaws.net> <41976BE2.4000204@tds.net> <41977E2F.1080807@pusspaws.net> <419782B6.8030305@tds.net> <41978ABA.7000900@pusspaws.net> Message-ID: <419793E5.9010604@tds.net> I would put make a class to hold the demon thread. The main program can create the queue and pass it to the demon. Here is a simple example of a Worker thread that passes work back to a main program: from threading import Thread from Queue import Queue, Empty from time import sleep class Worker(Thread): ''' Every two seconds put some work in the queue ''' def __init__(self, queue): Thread.__init__(self) self.queue = queue self.setDaemon(True) def run(self): while True: self.queue.put('Work') sleep(2) def main(): fifo = Queue() Worker(fifo).start() # Monitor the work queue from the Worker thread while True: sleep(0.5) try: work = fifo.get(False) print work except Empty: print 'Nothing to do' main() Kent Dave S wrote: > Kent Johnson wrote: > >> Dave S wrote: > ...mmm ... Now I have an idea as to what sockets are, I like threads to > :-), they seem OTT for what I need. > > Having decided on threading the demon, and using a fifo, the queue > module looks cool, I have one last dilema. One that quite often causes > me problems, that scope, namespace thing ;-) > > If I have my demon thread running, and I define a queue, it will work > fine, If I have my main app running and define a queue, it will also > work fine but this defines two seperate queues which are not joined, > data from one will not pass to the other. > > If I were to define a seperate script which handles the queue > 'fifio.py' & import it to both the deamon thread & the main app, this > would use the class definition as a king of global variable. Would this > be the best way ? - more importantly would it work :-D ! > > Dave > From alan.gauld at freenet.co.uk Sun Nov 14 18:54:55 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Nov 14 18:54:29 2004 Subject: [Tutor] demon / app I/F better way ? References: <41975EE3.3070809@pusspaws.net> Message-ID: <014701c4ca73$0cd211c0$43bb8651@xp> > my main app when it is ready to accept data checks the status of > /data/data_flag every second, if it changes to a true state reads in > /data/data_new & sets /data/data_flag to false, performs processing then > checks /data/data_flag ... > > This will work (I think ;-) ) but seems a bit clunky, anyone got a more > elegant solution? There are several other solutions including launching the second app from the first but your way will work for most cases. Be careful about the effect of the second app locking the files for the first app - either have a fallback strategy to write to a second file or just dump the data in dev/null. Another option you might consider is to use different files for each data dump, timestamped perhaps then your processing app simply deletes the files as it processes them. This also covers the locking problem and allows you to process multiple files at once if updates are frequent... Finally it makes manual recovery of errors much easier. And of course you should se an environment variable or config file to set the data path to get round potential system file structure changes between machines/operating systems etc. 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 Nov 14 19:00:24 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Nov 14 19:00:29 2004 Subject: [Tutor] demon / app I/F better way ? References: <41975EE3.3070809@pusspaws.net> <41976BE2.4000204@tds.net><41977E2F.1080807@pusspaws.net> <419782B6.8030305@tds.net> Message-ID: <015201c4ca73$d1492ca0$43bb8651@xp> > See the socket module to start, or the socket programming HOW-TO: > http://www.amk.ca/python/howto/sockets/ > > There are others on this list with more experience than me with socket > programming, I hope they will chime in here...personally I like threads :-) But if both your processes are on the same machine you can use a pipe which is even easier than a socket albeit less flexible. But a pipe just looks like a file you read from - the popenX() family is the function set to look at. But your file processing solution is a perfectly valid way of working, especially for large data volumes. Its how almost every mainframe application in existence works! The big win is ease of data and/or job recovery in the event of a crash. Alan G. From ps_python at yahoo.com Sun Nov 14 19:05:45 2004 From: ps_python at yahoo.com (kumar s) Date: Sun Nov 14 19:05:48 2004 Subject: [Tutor] Function calls Message-ID: <20041114180545.86332.qmail@web53701.mail.yahoo.com> Dear group, i have been practising some function examples: here is a function i wrote: def min3(*args): tmp = list(args) tmp.sort() return tmp[0] >>> min3(1,3,4,5,6,[1,3,4,0]) 1 >>> min3(1,2,3,4,5,(1,0)) 1 Why isnt it showing '0' as the minimun value. this function should report min value irrespective of a list or a tuple passed to an argument as a call. Can any one help me understand please. thank you. regards, kumar __________________________________ Do you Yahoo!? Check out the new Yahoo! Front Page. www.yahoo.com From alan.gauld at freenet.co.uk Sun Nov 14 19:15:10 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Nov 14 19:14:46 2004 Subject: [Tutor] demon / app I/F better way ? References: <41975EE3.3070809@pusspaws.net><41976BE2.4000204@tds.net> <41977E2F.1080807@pusspaws.net><419782B6.8030305@tds.net> <41978ABA.7000900@pusspaws.net> Message-ID: <015901c4ca75$e11f5d50$43bb8651@xp> > Having decided on threading the demon, and using a fifo, the queue > module looks cool, I have one last dilema. One that quite often causes > me problems, that scope, namespace thing ;-) To be honest the risks of deadlocks and race conditions using multiple threads accessing a common queue are such that I would tend to have the data collection thread writing to a separate queue (out of a pool of queues) from the processing thread. I'd then switch queues on each data change leaving the processor reading a queue which has no risk of being overwritten by the collector thread. I'd keep a status map of the queues such that the collector marks them as full and the processor marks them as empty. This way they avoid trampling on each other and if the pool gets to the state of all full you can flag an error and stop processing or dump it to a file before restarting or whatever... One advantage of using two processes linked by sockets or pipes is that the queing is all handled for you implicitly by the comms mechanism - the pipe/socket is inherently fifo in nature.. The danger in that case is data overflowing the available buffer size. The best decision in all of this depends on: 1) How often the data changes 2) how much data changes each time 3) how critical is data recovery on error conditions If the data only changes occasionally, the changed data size is small and you can afford to drop a data change once in a while then any solution will do. If volumes of data are small but changes are frequent sockets or pipes are probably best. If changes are frequent and volumes large either fifo queues or files is the best solution. If changes are infrequent but the volumes large or if error detection/correction is needed then the original files approach is best. Good design is always a matter of trading off one set of compromises against the others to get a best match. Alan G. From orbitz at ezabel.com Sun Nov 14 19:23:44 2004 From: orbitz at ezabel.com (orbitz) Date: Sun Nov 14 19:23:52 2004 Subject: [Tutor] Function calls In-Reply-To: <20041114180545.86332.qmail@web53701.mail.yahoo.com> References: <20041114180545.86332.qmail@web53701.mail.yahoo.com> Message-ID: <4197A2B0.3080302@ezabel.com> Because you are the value is not 0 it is [1,3,4,0] in the first and(1, 0) in the second. This is a list and a tuple respectively, 0 is an integer. kumar s wrote: >Dear group, > i have been practising some function examples: > >here is a function i wrote: > > >def min3(*args): > tmp = list(args) > tmp.sort() > return tmp[0] > > > >>>>min3(1,3,4,5,6,[1,3,4,0]) >>>> >>>> >1 > > >>>>min3(1,2,3,4,5,(1,0)) >>>> >>>> >1 > > >Why isnt it showing '0' as the minimun value. this >function should report min value irrespective of a >list or a tuple passed to an argument as a call. > >Can any one help me understand please. > >thank you. > >regards, >kumar > > > >__________________________________ >Do you Yahoo!? >Check out the new Yahoo! Front Page. >www.yahoo.com > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From pan at uchicago.edu Sun Nov 14 19:27:07 2004 From: pan at uchicago.edu (pan@uchicago.edu) Date: Sun Nov 14 19:28:52 2004 Subject: [Tutor] unittest: unbound method? In-Reply-To: <20041110211707.1E83E1E400A@bag.python.org> References: <20041110211707.1E83E1E400A@bag.python.org> Message-ID: <1100456827.4197a37be313c@webmail.uchicago.edu> I have a class Ini that load a dictionary and save to a config (ini) file. I was trying to write a test using unittest (this is the first time I use it): ==== code starts ===== from panTools import Ini class TestIni(unittest.TestCase): def setUp(self): self.name = {'First': 'runsun', 'Last' : 'pan'} def test_loadDict(self): Ini.load(self.name) #<=========== if __name__ == '__main__': unittest.main() ==== code ends ==== When executed, it resulted in an error: in test_loadDict #x=Ini.load(self.name) TypeError: unbound method load() must be called with Ini instance as first argument (got dict instance instead) I read several unittest tutorials and they all use class.method, not instance.method. What's going wrong in my code? Thx in advance. pan From pythontut at pusspaws.net Sun Nov 14 19:31:55 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Nov 14 19:32:05 2004 Subject: [Tutor] demon / app I/F better way ? In-Reply-To: <014701c4ca73$0cd211c0$43bb8651@xp> References: <41975EE3.3070809@pusspaws.net> <014701c4ca73$0cd211c0$43bb8651@xp> Message-ID: <4197A49B.8010404@pusspaws.net> Thank you all so much, Ive got a ton of options and its made me think a lot more about the data rates vs reliabilty vs simplicity. File locking was something I had not even considerd as a problem. Co-incidently my demon app dumps all its data to an archive file, time and date stamped, so as you suggested Alan I could simply use that. (I like that idea :-) ) The data rate being a few KBs at exact syncronised 5 mins intervals, the timing of the data readings being paramount otherwise syncronisation with server data updates is lost. Processing is a whole other ballgame. Kents suggestion is an interesting one, and being still a relative Python newbe, It got me thinking as well. Phew, well better fire up eric & start codeing Cheers Guys Dave From alan.gauld at freenet.co.uk Sun Nov 14 19:36:31 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Nov 14 19:36:28 2004 Subject: [Tutor] how to take user input to form a list? References: <41978D4B.2070302@aon.at> Message-ID: <016c01c4ca78$dc9f9a30$43bb8651@xp> > I think, that Alan in his reply missed, that > splitting will be done by "sequence-unpacking" in > your code. But it will work only with exactly four > characters entered, while the code he proposed will work > for strings with arbitrary length (and produce lists > of that length). Exactly so, the sequence unpacking requires that 4 characters be entered *without* seperators. Thus 1234 will be unpacked but 1,2,3,4 will not. Similarly trying to enter numbers greater than 9 will cause errors. Sequence unpacking from raw_input is usually the wrong way to go IMHO. Alan G. From alan.gauld at freenet.co.uk Sun Nov 14 19:40:53 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Nov 14 19:40:27 2004 Subject: [Tutor] Function calls References: <20041114180545.86332.qmail@web53701.mail.yahoo.com> Message-ID: <017901c4ca79$78a920e0$43bb8651@xp> > >>> min3(1,3,4,5,6,[1,3,4,0]) > 1 > >>> min3(1,2,3,4,5,(1,0)) > 1 > > > Why isnt it showing '0' as the minimun value. this > function should report min value irrespective of a > list or a tuple passed to an argument as a call. In both cases there are only 6 elements to be sorted, sort does not unpack nested lists/tuples. Python's sorting algorithm for lists considers a single item element to be less than a multi item element. This is an arbitrary choice (although it makes some sense to me!) and the author culd have gone the other way but didn't. HTH, Alan G From alan.gauld at freenet.co.uk Sun Nov 14 19:46:42 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Nov 14 19:46:56 2004 Subject: [Tutor] unittest: unbound method? References: <20041110211707.1E83E1E400A@bag.python.org> <1100456827.4197a37be313c@webmail.uchicago.edu> Message-ID: <018201c4ca7a$48eeb1c0$43bb8651@xp> > from panTools import Ini > class TestIni(unittest.TestCase): > ... > def test_loadDict(self): > Ini.load(self.name) #<=========== > > in test_loadDict > #x=Ini.load(self.name) > TypeError: unbound method load() must be called with Ini instance as first > argument (got dict instance instead) > > I read several unittest tutorials and they all use class.method, > not instance.method. What's going wrong in my code? The error is with Ini which is a class you imported from panTools. You need to use an instance of Ini in your class method: def test_loadDict(self): i = Ini() # create instance i.load(self.name) # use instance instead of class. Personally I usually test new classes at the >>> prompt rather than writing test harnesses using unittest. The >>> prompt is much more immediate. Once your individual classes work you can use unittest to check the bigger picture combinations of classes. Alan G. From kent37 at tds.net Sun Nov 14 20:13:37 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Nov 14 20:13:42 2004 Subject: [Tutor] demon / app I/F better way ? In-Reply-To: <015901c4ca75$e11f5d50$43bb8651@xp> References: <41975EE3.3070809@pusspaws.net><41976BE2.4000204@tds.net> <41977E2F.1080807@pusspaws.net><419782B6.8030305@tds.net> <41978ABA.7000900@pusspaws.net> <015901c4ca75$e11f5d50$43bb8651@xp> Message-ID: <4197AE61.9010909@tds.net> I don't think any of the complications Alan suggests are needed. The Queue module takes care of the necessary locking semantics. It is specifically intended for inter-thread communication. From the docs: The Queue module implements a multi-producer, multi-consumer FIFO queue. It is especially useful in threads programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. On a side note... I'm starting to think there is a cultural bias against threads in the python community. I came to Python from Java where threads are commonly used. For example the Jetty web server is a threaded web server that is used in many production environments. I'm not sure there are any industrial-strength Python web servers that use a threading model - they are either based on asyncore or forking. This is the second time I have suggested a threaded solution to a problem posted on this list. Each time someone has fired back a reply about the difficulties of threading. The replies surprise me because in my experience, simple uses of threads can be, well, simple. Yes, there are dangers, and certainly it can be hard to wrap your head around a threaded app, but with a little care and the help of some library classes you can get a lot done easily. I'm not sure where I'm going with this except maybe, "Hey, guys, lighten up a little! Threads can be your friends!" Kent Alan Gauld wrote: >>Having decided on threading the demon, and using a fifo, the queue >>module looks cool, I have one last dilema. One that quite often > > causes > >>me problems, that scope, namespace thing ;-) > > > To be honest the risks of deadlocks and race conditions using > multiple threads accessing a common queue are such that I would > tend to have the data collection thread writing to a separate > queue (out of a pool of queues) from the processing thread. > I'd then switch queues on each data change leaving the processor > reading a queue which has no risk of being overwritten by the > collector thread. I'd keep a status map of the queues such that > the collector marks them as full and the processor marks them > as empty. This way they avoid trampling on each other and if > the pool gets to the state of all full you can flag an error > and stop processing or dump it to a file before restarting > or whatever... > From rdm at rcblue.com Mon Nov 15 00:45:25 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Nov 15 00:51:15 2004 Subject: [Tutor] how do i use p2exe In-Reply-To: <41974861.6060101@tds.net> References: <6.1.2.0.2.20041113191107.055d07e0@rcblue.com> <4196D549.3080107@tds.net> <6.1.2.0.2.20041113202140.0483a190@rcblue.com> <41974861.6060101@tds.net> Message-ID: <6.1.2.0.2.20041114150350.050cc3e0@rcblue.com> Thanks, Kent. That was dumb of me. Yeah, when I copy the dist folder to my desktop, weekday1.exe runs fine. So now I assume I could email the whole folder to a friend running Win98 (but with no Python), and he could use weekday1.exe. That's what I wanted. Thanks for sticking with me. Dick Kent Johnson wrote at 03:58 11/14/2004: >Ah. py2exe doesn't actually create a single-file executable. You need >everything else in the dist folder to go with the .exe. > >If you want a single file exe, Google for 'py2exe single file' to find >some discussions. > >If you want the exe on your desktop, just make a shortcut. > >A more general tip - when a console-based program is failing, if you run >it by double-clicking the exe you will often see just the flash of the >console opening and closing. You can get more information by opening a >console yourself to the directory and running the exe from the command line. > >With weekday1.exe, if I copy it to a new directory and run it from the >command line I get this: >D:\Personal\Tutor\weekday>weekday1 >Traceback (most recent call last): > File "C:\Python23\lib\site-packages\py2exe\boot_common.py", line 69, in ? > import linecache >ImportError: No module named linecache >Traceback (most recent call last): > File "weekday1.py", line 8, in ? > import datetime >ImportError: No module named datetime > >which might not have been enough for you to figure out the problem but >it is at least a clue in the right direction. > >Kent > > >Dick Moores wrote: >>Thanks, Kent. I've gotten to the point where I can create an exe in >>Python23/dist of a script in Python23. For example, from weekday1.py >>I've created weekday1.exe. When I double-click on >>Python/dist/weekday1.exe, it works fine in a consol window. But when I >>copy weekday1.exe to my desktop, all I get is a flash of a console >>window opening and closing when I execute it. >>Here's weekday1.py: >>And setup.py: >>Can you tell me what's wrong? >>Thanks, >>Dick >>Kent Johnson wrote at 19:47 11/13/2004: >> >>>Dick, >>> >>>The script you are using is an attempt to automate the use of py2exe >>>so you don't have to create setup.py for each script. I suggest you >>>try a manual approach. >>> >>>I downloaded and installed py2exe. I opened a DOS console to >>>C:\Python23\Lib\site-packages\py2exe\samples\simple and typed >>> > python setup.py py2exe >>> >>>This created a dist directory with two executables - a console program >>>and a wxPython program. >>> >>>Does this work for you? >>>If it does, the next step is to copy setup.py from the samples dir to >>>the dir where your program is, and modify it appropriately. It's a >>>pretty simple file, this isn't be hard. >>> >>>If you can't get that to work, you might want to ask on the py2exe >>>mailing list, we don't seem to have any experts here. >>> >>>Kent >>> >>>Dick Moores wrote: >>> >>>>This is my second attempt to get some help. I'd REALLY like to be >>>>able to use py2exe: >>>> >>>>Am I the only one having trouble with this? Here's what I did, and >>>>what happens. >>>>I'm running Win XP and Python 2.3.4. >>>>I installed py2exe from http://starship.python.net/crew/theller/py2exe/ . >>>>I created setup.py. But in order to have it run I changed the 3rd >>>>line of lookdir() to if look.lower() == "y": >>>>I created the batch file, which I named test.bat. I used the line >>>>cd\python23 as is, because that's where my python23 is. >>>>When I run test.bat I get >>>>"Current directory is: C:\Python23 >>>>Do you wish to see what's in directory?" >>>>If I answer "y" I'm correctly shown what's in Python23, and asked, >>>>"What is the file you want as an executable? (Type 'quit' to break >>>>out of loop) ?" >>>>I type "weekday.py" a script I have in Python23. >>>>The "DOS" (consol?) window closes immediately. >>>>That's it. No creation of weekday.exe. >>>>Have I done something wrong. Or what? >>>>Thanks, tutors. >>>>Dick Moores >>>>rdm@rcblue.com >>>> >>>>At 19:59 11/9/2004, Jacob S. wrote: >>>> >>>>>This is what I did. >>>>>I'm using Windows XP, but it would work for any other windows version... >>>>> >>>>>1) Take code below and copy into file named "setup.py". >>>>> >>>>>### Start of Code ### >>>>>from distutils.core import setup >>>>>import py2exe >>>>>import os >>>>> >>>>> >>>>>def lookdir(): >>>>> print "Current directory is: %s" % os.getcwd() >>>>> look = raw_input('Do you wish to see what\'s in directory? ') >>>>> if look.lower() in m: >>>>> print "\n".join(os.listdir(os.getcwd())) >>>>> >>>>>def changedir(): >>>>> m = ['y','ye','yes','yep','okay','affirmative','sure'] >>>>> ask = 'y' >>>>> lookdir() >>>>> while ask not in m: >>>>> di = raw_input('What directory do you want? ') >>>>> os.chdir(di) >>>>> lookdir() >>>>> ask = raw_input('Do you want this directory? ') >>>>> >>>>>changedir() >>>>>listed = [] >>>>>while 1: >>>>> ask = raw_input('What is the file you want as an executable? (Type >>>>>\'quit\' to break out of loop) ') >>>>> if ask == 'quit' or ask == 'stop' or ask == '': >>>>> break >>>>> else: >>>>> listed.append(os.path.join(desktop,ask)) >>>>> >>>>>setup(console = listed) >>>>>### End of Code ### >>>>> >>>>>2) Take following code and save as a batch file. You will have to >>>>>change the >>>>>second line to change the directory to your python dir >>>>> >>>>>rem Start of Code >>>>>@echo off >>>>>cd\python23 >>>>>start python setup.py py2exe >>>>>rem End of Code >>>>> >>>>>3) Run the batch file. It will ask you which directory the script >>>>>file is >>>>>in. That would be the file that you're trying to make and >>>>>executable. Then, >>>>>when you decide which directory it is in, it will ask you the name >>>>>of the >>>>>file. You type in the name. If you want more than one file, you can >>>>>type in >>>>>another file name in the next prompt, else you can type in 'quit' or >>>>>'stop' >>>>>or just hit enter. When all is done and the shell window closes, you can >>>>>check out the directory that you chose. In that directory, there >>>>>will be two >>>>>new folders. One is labeled build. That folder is not necessary to >>>>>run your >>>>>executable and can be deleted. I usually delete it. The other is labeled >>>>>dist. It contains the files needed for your program. Your program >>>>>will have >>>>>the same name, just with a exe extension instead of a py extension. >>>>>Send the >>>>>whole folder on to your students, and they can double-click on the >>>>>exe file, >>>>>and it will run your script as if you double-clicked it in Windows >>>>>Explorer. >>>>> >>>>>Also, in your code (which I will try to rewrite for fun on my own (no >>>>>offense)) you might try this instead: >>>>> >>>>>print "".join(["\t","\\"*7," ","\\"*4," ","\\"*6," ","\\"*7," ","\\"*2," >>>>>","\\"*10," ","\\"*2," ","\\"*8,"\n"]) >>>>> >>>>>Ignore the underline and blue if it shows up in your email thing. >>>>>This just shows that you can multiply a particular string by an >>>>>integer to >>>>>copy it. >>>>> >>>>>Hope all this helps, >>>>>Jacob Schmidt >>>> >>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >> >>_______________________________________________ >>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 crasch at openknowledge.org Mon Nov 15 04:40:30 2004 From: crasch at openknowledge.org (Christopher rasch) Date: Mon Nov 15 04:40:40 2004 Subject: [Tutor] Python interpreter with command history? Message-ID: <18E06576-36B8-11D9-B59B-00039366A582@openknowledge.org> The default Python interpreter on Mac OS X doesn't seem to have a command history (such as you get in bash or tcsh). Any ideas how to turn such a thing on? The python documentation says that some interpreters have such a feature, but I haven't yet been able to locate a command line interpreter with such a feature. Anyone recommend alternative interpreters? Thanks for any suggestions! Chris From huw.davies at kerberos.davies.net.au Mon Nov 15 06:39:29 2004 From: huw.davies at kerberos.davies.net.au (Huw Davies) Date: Mon Nov 15 06:39:36 2004 Subject: [Tutor] Python interpreter with command history? In-Reply-To: <18E06576-36B8-11D9-B59B-00039366A582@openknowledge.org> References: <18E06576-36B8-11D9-B59B-00039366A582@openknowledge.org> Message-ID: On 15/11/2004, at 2:40 PM, Christopher rasch wrote: > The default Python interpreter on Mac OS X doesn't seem to have a > command history (such as you get in bash or tcsh). Any ideas how to > turn such a thing on? The python documentation says that some > interpreters have such a feature, but I haven't yet been able to > locate a command line interpreter with such a feature. Anyone > recommend alternative interpreters? Interesting - I have fink installed and use the python in /sw/bin/fink and it has command recall but as you point out the "default" OS X python (/usr/bin/python) seems to built without it. If you already have fink setup, I guess the easiest solution might be to install python from it. I suspect that the only way to get command recall will be to recompile python. Huw Davies | e-mail: Huw.Davies@kerberos.davies.net.au Melbourne | "If soccer was meant to be played in the Australia | air, the sky would be painted green" From cmeesters at ucdavis.edu Mon Nov 15 06:40:03 2004 From: cmeesters at ucdavis.edu (Christian Meesters) Date: Mon Nov 15 06:39:47 2004 Subject: [Tutor] object orientation Message-ID: Hi These days I was reading a discussion between "Ruby-people" and "Python-people" (us) on pros and cons of each language. Such discussions aren't very meaningful, of course, but sometimes interesting. One of the arguments was about the realization of the OO-approach in the languages. And this leads me to my question: Though I like the Python syntax and actually prefer it above Ruby's, I wanted to know why we write len(x) instead of x.len() (x being a string for instance). Does anybody know an essay / link about why this approach was chosen? It makes sense within Python, of course, but for now I'm merely interested in the history. My own screenings of the web didn't bring up anything useful about this topic. Thanks in advance, Cheers Christian From johan at accesstel.co.za Mon Nov 15 07:30:58 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon Nov 15 07:32:00 2004 Subject: [Tutor] PYC files Message-ID: <1100500258.4518.10.camel@KMA.accesstel> Hi, I have pyc files and would like to know how to decompile them for reading? Any suggestions will be welcome. Thanks -- Johan -- Message has been scanned. Enjoy Your Day. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041115/7bd509e0/attachment.htm From bill.mill at gmail.com Mon Nov 15 07:36:49 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Nov 15 07:36:52 2004 Subject: [Tutor] PYC files In-Reply-To: <1100500258.4518.10.camel@KMA.accesstel> References: <1100500258.4518.10.camel@KMA.accesstel> Message-ID: <797fe3d404111422362cd0255a@mail.gmail.com> Johan, GIYF http://docs.python.org/lib/module-dis.html Peace Bill Mill bill.mill at gmail.com On Mon, 15 Nov 2004 08:30:58 +0200, Johan Geldenhuys wrote: > Hi, > I have pyc files and would like to know how to decompile them for reading? > Any suggestions will be welcome. > > Thanks > > -- Johan > -- > Message has been scanned > Enjoy your day > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From bill.mill at gmail.com Mon Nov 15 07:41:17 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Nov 15 07:41:20 2004 Subject: [Tutor] object orientation In-Reply-To: References: Message-ID: <797fe3d404111422416eaae242@mail.gmail.com> Christian, A little creative googling brought up Andrew Kuchling on the topic: http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/91470f975bc85485/b725ce946cd1584c?_done=%2Fgroup%2Fcomp.lang.python%2Fsearch%3Fgroup%3Dcomp.lang.python%26q%3D%22len(x)%22+%22x.len()%22%26qt_g%3D1%26searchnow%3DSearch+this+group%26&_doneTitle=Back+to+Search&&d#b725ce946cd1584c It gets asked on the newsgroup all the time, but basically he gives the answer minus all the bull you'll hear on said newsgroup discussions. Peace Bill Mill bill.mill at gmail.com On Sun, 14 Nov 2004 21:40:03 -0800, Christian Meesters wrote: > Hi > > These days I was reading a discussion between "Ruby-people" and > "Python-people" (us) on pros and cons of each language. Such > discussions aren't very meaningful, of course, but sometimes > interesting. One of the arguments was about the realization of the > OO-approach in the languages. And this leads me to my question: Though > I like the Python syntax and actually prefer it above Ruby's, I wanted > to know why we write len(x) instead of x.len() (x being a string for > instance). Does anybody know an essay / link about why this approach > was chosen? It makes sense within Python, of course, but for now I'm > merely interested in the history. My own screenings of the web didn't > bring up anything useful about this topic. > > Thanks in advance, > Cheers > Christian > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Mon Nov 15 08:01:30 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Nov 15 08:00:59 2004 Subject: [Tutor] demon / app I/F better way ? References: <41975EE3.3070809@pusspaws.net><41976BE2.4000204@tds.net> <41977E2F.1080807@pusspaws.net><419782B6.8030305@tds.net><41978ABA.7000900@pusspaws.net> <015901c4ca75$e11f5d50$43bb8651@xp> <4197AE61.9010909@tds.net> Message-ID: <019a01c4cae0$ef46b4d0$43bb8651@xp> > I don't think any of the complications Alan suggests are needed. The > Queue module takes care of the necessary locking semantics. It is > specifically intended for inter-thread communication. From the docs: I've never usd the psarticular Queue module you refer to and it may well solve the problems. Indeed the socket/pipe approach also caters for all of those issues. I was talking in general terms and most of the isses apply to any inter-process comms mechanism. > I'm starting to think there is a cultural bias against threads in the > python community. I came to Python from Java where threads are commonly > used. And cause lots of problems. The correct and safe use of threads in any language is fraught with difficulty. I spend a fair amount of any given year disentangling problems brought about by over zealous use of threads in designs (mostly in Java). When used properly threads are immensely powerful tools but to be safe you do need to consider very carefully all theramifications of state, locking and resilience/failover. But used correctly they are great. I built a telephone exchange system several years ago which was fully threaded in operation - each call was a thread - and it handled huge volumes without a hickup. I certainly wish Microsoft would use more threading than they do in Windows - it would reduce the number of application hangups I get! But for beginners threads are a difficult concept to grok and can be a nightmare to debug and on that basis I usually look for simpler options before recommending them to beginners. Like somebody in the XP movement once said, always pick the simplest thing that will work. > This is the second time I have suggested a threaded solution to a > problem posted on this list. Each time someone has fired back a reply > about the difficulties of threading. The replies surprise me because in > my experience, simple uses of threads can be, well, simple. Simple uses can be, but unfortunately there are very few simple uses of threads. > are dangers, and certainly it can be hard to wrap your head around a > threaded app, but with a little care and the help of some library > classes you can get a lot done easily. Absolutely, and it is good to include threads as an option. Often they are the best solution. But on this list, aimed at beginners, its worth having a variety of options to pick from. Alan G From alan.gauld at freenet.co.uk Mon Nov 15 08:05:42 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Nov 15 08:05:14 2004 Subject: [Tutor] object orientation References: Message-ID: <01a301c4cae1$85a2fc40$43bb8651@xp> > to know why we write len(x) instead of x.len() There was a thread about this a fw weeks ago - either here or comp.lang.python. I think history is the real answer. When Guido first built Python not everything (strings, ints, floats etc) were first class objects so making len() a function meant it was more generally useful. Nowadays len() could just as well be an object method. Alan G. From godoy at ieee.org Mon Nov 15 07:39:37 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon Nov 15 08:38:30 2004 Subject: [Tutor] Re: PYC files References: <1100500258.4518.10.camel@KMA.accesstel> Message-ID: Johan Geldenhuys writes: > > > > > > > > Hi, > I have pyc files and would like to know how to decompile them for reading? Any suggestions will be welcome. > > Thanks http://www.google.com.br/search?q=python+pyc+disassemble+decompile The few hits here tell you what you should look for and why. Be seeing you, -- Godoy. From glingl at aon.at Mon Nov 15 08:44:18 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Nov 15 08:43:59 2004 Subject: [Tutor] object orientation In-Reply-To: <01a301c4cae1$85a2fc40$43bb8651@xp> References: <01a301c4cae1$85a2fc40$43bb8651@xp> Message-ID: <41985E52.4020203@aon.at> Alan Gauld schrieb: >>to know why we write len(x) instead of x.len() >> >> > >There was a thread about this a fw weeks ago >- either here or comp.lang.python. > >I think history is the real answer. When Guido first built Python >not everything (strings, ints, floats etc) were first class >objects so making len() a function meant it was more generally >useful. Nowadays len() could just as well be an object method. > > And, in fact, behind the scene it is: >>> "abc".__len__() 3 >>> [].__len__() 0 >>> Regards, Gregor >Alan G. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From rdm at rcblue.com Mon Nov 15 08:51:50 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Nov 15 08:52:27 2004 Subject: [Tutor] how do i use p2exe In-Reply-To: <002501c4ca69$62a69e40$065428cf@JSLAPTOP> References: <1033bb7f041109191055f46aee@mail.gmail.com> <00e701c4c6d9$ac052e00$db5428cf@JSLAPTOP> <6.1.2.0.2.20041112042711.08269eb0@rcblue.com> <002501c4ca69$62a69e40$065428cf@JSLAPTOP> Message-ID: <6.1.2.0.2.20041114234942.04cc5eb0@rcblue.com> Thanks for fixing it Jacob. Works fine now. With batch file, too. Very handy. Dick Jacob S. wrote at 08:45 11/14/2004: >Okay, > >I see what's wrong with my code. First, to Kent, what's wrong with trying to >automate py2exe? It drives me batty to have to open the command prompt in >Windows and then go to the python23 folder and type in "python setup.py >py2exe" which I can't remember when I need it. Then, I always have to change >setup.py every time I want to use py2exe. I think that if you can get it to >work, automation would be beautiful. (It works on my machine.) > Second, to Dick. >There are one or two things wrong with the code I gave you. It was late. >However, you did not use the raw_inputs quite as I would have expected. So, >a detailed run through. > >First, change my setup.py to read as follows: > >##Start of code >### Start of Code ### >from distutils.core import setup >import py2exe >import os > > >def lookdir(): > m = ['y','ye','yes','yep','okay','affirmative','sure'] > print "Current directory is: %s" % os.getcwd() > look = raw_input('Do you wish to see what\'s in directory? ') > if look.lower() in m: > print "\n".join(os.listdir(os.getcwd())) > >def changedir(): > m = ['y','ye','yes','yep','okay','affirmative','sure'] > ## Here I have to define m again because of local variables. Ughh. > lookdir() > ask = raw_input('Do you want the current directory? ') ## Had to fix >this, brain fart. > while ask not in m: > di = raw_input('What directory do you want? ') > os.chdir(di) > lookdir() > ask = raw_input('Do you want this directory? ') > >changedir() >listed = [] >while 1: > ask = raw_input('What is the file you want as an executable? (Type >\'quit\' to break out of loop) ') > if ask == 'quit' or ask == 'stop' or ask == '': > break > else: > listed.append(os.path.join(os.getcwd(),ask)) > >setup(console = listed) >### End of Code ### > >Okay, the batch file should be okay... >But just in case... > >rem Start of Code >@echo off >cd\python23 rem Change this line to your python directory >start python setup.py py2exe >rem End of Code > >I made a couple of changes to the code above. >Okay, a complete walkthrough. > >1) Copy setup.py code to file in python directory >2) Copy batch file code to any convenient directory. >3) Run batch file >4) You should get a python console program. >5) Okay the nitty-gritty, cross your fingers, hope I have it right this >time. >6) It should show current directory, ask you if you want to see what's in it >7) It should ask you whether you want the current dir >8) If you say no, then it will ask you for a new directory. It will run >through steps 6-8 > until you say that you want the current directory >9) It will ask you what file you want until you type in quit. This is for >multiple file executables. > Each thing you type in other than quit will be thought of as a file in >the current directory. > '' '' '' '' '' '' '' '' '' '' >put in the executable directory. >10) When you type quit in step 9, it will make executables for every other >thing you typed in. >11) Python console should disappear. >12) In the directory that the files are in, you should have two folders, >build and dist. >13) Dist is the folder that you are looking for, build is another helper >folder that doesn't really do anything as far as I can tell. It can >be deleted. >14) Run each executable in the dist folder. The ones that have the same >names as the files you typed in should all work. (There is >another executable in there that doesn't stand alone. It's part of the >stuff.) >15) You can rename the dist folder anything you want. >16) You have to leave everything in the dist folder intact. >17) You should probably put shortcuts to the programs in a more convenient >place >18) That should be it. If it doesn't work now, I should be very unhappy and >I would like to know why it doesn't work! > >I hope this will help someone, >Jacob Schmidt > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From andreas at kostyrka.org Mon Nov 15 10:39:04 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon Nov 15 11:12:09 2004 Subject: [Tutor] object orientation In-Reply-To: References: Message-ID: <20041115093904.GA31746@kostyrka.org> On Sun, Nov 14, 2004 at 09:40:03PM -0800, Christian Meesters wrote: > Hi > > These days I was reading a discussion between "Ruby-people" and > "Python-people" (us) on pros and cons of each language. Such > discussions aren't very meaningful, of course, but sometimes > interesting. One of the arguments was about the realization of the > OO-approach in the languages. And this leads me to my question: Though > I like the Python syntax and actually prefer it above Ruby's, I wanted > to know why we write len(x) instead of x.len() (x being a string for > instance). Does anybody know an essay / link about why this approach > was chosen? It makes sense within Python, of course, but for now I'm > merely interested in the history. My own screenings of the web didn't > bring up anything useful about this topic. Basically historical, but if you prefer the object oriented approach: >>> [].__len__() 0 >>> "ABC".__len__() 3 >>> (1,2,3).__len__() 3 Andreas From kent37 at tds.net Mon Nov 15 12:06:25 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Nov 15 12:06:31 2004 Subject: [Tutor] object orientation In-Reply-To: References: Message-ID: <41988DB1.8030602@tds.net> There was recently a long thread on this topic on comp.lang.python. Many people argued that this is a desirable feature of python, not an historical accident, because it lets the runtime try different methods to resolve an operation. This post by Alex Martelli spells out the argument at length: http://groups.google.com/groups?hl=en&lr=&c2coff=1&selm=1gm05gb.1251x8o3h0barN%25aleaxit%40yahoo.com&rnum=6 Kent Christian Meesters wrote: > Hi > > These days I was reading a discussion between "Ruby-people" and > "Python-people" (us) on pros and cons of each language. Such discussions > aren't very meaningful, of course, but sometimes interesting. One of the > arguments was about the realization of the OO-approach in the languages. > And this leads me to my question: Though I like the Python syntax and > actually prefer it above Ruby's, I wanted to know why we write len(x) > instead of x.len() (x being a string for instance). Does anybody know an > essay / link about why this approach was chosen? It makes sense within > Python, of course, but for now I'm merely interested in the history. My > own screenings of the web didn't bring up anything useful about this topic. > > Thanks in advance, > Cheers > Christian > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From maxnoel_fr at yahoo.fr Mon Nov 15 13:15:37 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon Nov 15 13:15:47 2004 Subject: Fwd: [Tutor] Python interpreter with command history? Message-ID: <0EE63798-3700-11D9-A720-000393CBC88E@yahoo.fr> Begin forwarded message: > From: Christopher rasch > Date: November 15, 2004 06:06:46 GMT > To: Max Noel > Subject: Re: [Tutor] Python interpreter with command history? > > Hi > On Nov 14, 2004, at 10:54 PM, Max Noel wrote: > >> >> On Nov 15, 2004, at 03:40, Christopher rasch wrote: >> >>> The default Python interpreter on Mac OS X doesn't seem to have a >>> command history (such as you get in bash or tcsh). Any ideas how to >>> turn such a thing on? The python documentation says that some >>> interpreters have such a feature, but I haven't yet been able to >>> locate a command line interpreter with such a feature. Anyone >>> recommend alternative interpreters? >>> >>> Thanks for any suggestions! >>> >>> Chris >> >> Go there: http://homepages.cwi.nl/~jack/macpython/download.html >> Download the "MacPython for Panther addons" disk image. Install the >> software it contains. Among this is a Package Manager. Launch it, >> then use it to install the GNU Readline-related enhancements. Your >> Python interactive interpreter should now have command history. >> I never understood why Apple hadn't included is in their standard >> distribution (because of this, the same problem exists with irb)... >> >> -- 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?" >> >> > > Hi Max, > > Thanks! I did as you instructed, and installed the "MacPython for > Panther addons" . However, when I tried to launch the PackageManager, > it appeared to start to launch, then immediately shut down. Same with > the other applications. I'm guessing it's a permissions problem, but > I'm not sure what I should change if that's the case. > > Any ideas? > > Thanks! > > Chris > > -- 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 amonroe at columbus.rr.com Mon Nov 15 14:40:12 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon Nov 15 14:40:30 2004 Subject: [Tutor] Can anybody explain this unusual behavior? Apparent variable corruption? Message-ID: <968371362.20041115084012@columbus.rr.com> Here are the relevant parts of the program in question: ---- locationid = sys.argv[1] def runupdate(querystring): global mycurs log(querystring) mycurs.execute(querystring) if newregion != oldregion or newsite != oldsite or len(changeddepts)>0: log("Filling new ztmps over old for this location") runupdate("UPDATE mylocation set region=ztmpnewregion, site=ztmpnewsite, department=ztmpnewdepartment where location_id='%s' and status=0" % (locationid,)) ---- My log (per second line of the runupdate function) contains: Sat Nov 13 08:44:17 2004 UPDATE mylocation set region=ztmpnewregion, site=ztmpnewsite, department=ztmpnewdepartment where location_id='000380' and status=0 At no point do I ever re-assign the value of locationid, but somehow I get this error back, in about 20ish cases out of the 3000 or so times the script gets executed: 2004/11/13 08:11:21.389 0 4 Executing command line 'python.exe E:\\updatelocationsProd.py 000380 \"WV\" \"EXAMPLE_CITY\"'... 2004/11/13 08:44:28.857 1 1 (-53) Traceback (most recent call last):\r\n File \"E:\\updatelocationsProd.py\", line 282, in ?\r\n runupdate(\"UPDATE mylocation set region=ztmpnewregion, site=ztmpnewsite, department=ztmpnewdepartment where location_id='?L$\x14??????T$\x18?D$\x1CR?L$\x14P?F,Q?T$ I am trying to install a python application and it fails, because it wants "distutils.xxxx". What and where do I get this? -- Johan -- Message has been scanned. Enjoy Your Day. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041115/e18fa1ba/attachment.htm From pythonTutor at venix.com Mon Nov 15 18:25:22 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Nov 15 18:25:27 2004 Subject: [Tutor] demon / app I/F better way ? In-Reply-To: <4197AE61.9010909@tds.net> References: <41975EE3.3070809@pusspaws.net><41976BE2.4000204@tds.net> <41977E2F.1080807@pusspaws.net><419782B6.8030305@tds.net> <41978ABA.7000900@pusspaws.net> <015901c4ca75$e11f5d50$43bb8651@xp> <4197AE61.9010909@tds.net> Message-ID: <1100539522.2861.40.camel@laptop.venix.com> Eric Raymond in "The Art of Unix Programming" claims that UNIX developers tend to dislike threads. He cites the Ousterhout article: http://www.cs.utah.edu/~regehr/research/ouster.pdf as an argument against threads. Martelli in "Python in a Nutshell" provides detailed threading recommendations. These parallel Kent's recommendations of using the Queue module and if carefully followed should give you a reliable program. I have to confess that I tend to avoid threads myself. On Sun, 2004-11-14 at 14:13, Kent Johnson wrote: > I don't think any of the complications Alan suggests are needed. The > Queue module takes care of the necessary locking semantics. It is > specifically intended for inter-thread communication. From the docs: > > The Queue module implements a multi-producer, multi-consumer FIFO queue. > It is especially useful in threads programming when information must be > exchanged safely between multiple threads. The Queue class in this > module implements all the required locking semantics. > > On a side note... > I'm starting to think there is a cultural bias against threads in the > python community. I came to Python from Java where threads are commonly > used. For example the Jetty web server is a threaded web server that is > used in many production environments. I'm not sure there are any > industrial-strength Python web servers that use a threading model - they > are either based on asyncore or forking. > > This is the second time I have suggested a threaded solution to a > problem posted on this list. Each time someone has fired back a reply > about the difficulties of threading. The replies surprise me because in > my experience, simple uses of threads can be, well, simple. Yes, there > are dangers, and certainly it can be hard to wrap your head around a > threaded app, but with a little care and the help of some library > classes you can get a lot done easily. > > I'm not sure where I'm going with this except maybe, "Hey, guys, lighten > up a little! Threads can be your friends!" > > Kent > > Alan Gauld wrote: > >>Having decided on threading the demon, and using a fifo, the queue > >>module looks cool, I have one last dilema. One that quite often > > > > causes > > > >>me problems, that scope, namespace thing ;-) > > > > > > To be honest the risks of deadlocks and race conditions using > > multiple threads accessing a common queue are such that I would > > tend to have the data collection thread writing to a separate > > queue (out of a pool of queues) from the processing thread. > > I'd then switch queues on each data change leaving the processor > > reading a queue which has no risk of being overwritten by the > > collector thread. I'd keep a status map of the queues such that > > the collector marks them as full and the processor marks them > > as empty. This way they avoid trampling on each other and if > > the pool gets to the state of all full you can flag an error > > and stop processing or dump it to a file before restarting > > or whatever... > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Mon Nov 15 19:21:10 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 15 19:21:16 2004 Subject: [Tutor] Function calls In-Reply-To: <017901c4ca79$78a920e0$43bb8651@xp> Message-ID: On Sun, 14 Nov 2004, Alan Gauld wrote: > > >>> min3(1,3,4,5,6,[1,3,4,0]) > > 1 > > >>> min3(1,2,3,4,5,(1,0)) > > 1 > > > > > > Why isnt it showing '0' as the minimun value. this > > function should report min value irrespective of a > > list or a tuple passed to an argument as a call. > > In both cases there are only 6 elements to be sorted, > sort does not unpack nested lists/tuples. Yes, Python does not do any list flattening by itself: if you need it, you need to write it explicitely. This is a point that may be slightly confusing to people coming from a Perl background, so maybe we should show it: ### >>> stuff = [1, 2, [3, 4]] >>> stuff[0] 1 >>> stuff[1] 2 >>> stuff[2] [3, 4] >>> list(stuff) [1, 2, [3, 4]] ### If we want a list to get flattened, we can look at: http://aspn.activestate.com/ASPN/Mail/Message/python-list/453883 Hope this helps! From bgailer at alum.rpi.edu Mon Nov 15 19:57:01 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Nov 15 19:55:19 2004 Subject: [Tutor] Can anybody explain this unusual behavior? Apparent variable corruption? In-Reply-To: <968371362.20041115084012@columbus.rr.com> References: <968371362.20041115084012@columbus.rr.com> Message-ID: <6.1.2.0.0.20041115115603.02848d48@mail.mric.net> At 06:40 AM 11/15/2004, R. Alan Monroe wrote: >Here are the relevant parts of the program in question: > >---- >locationid = sys.argv[1] > >def runupdate(querystring): > global mycurs An aside: global is not needed here. Only needed if you want to re-assign to mycurs. > log(querystring) > mycurs.execute(querystring) > >if newregion != oldregion or newsite != oldsite or len(changeddepts)>0: > log("Filling new ztmps over old for this location") > runupdate("UPDATE mylocation set region=ztmpnewregion, > site=ztmpnewsite, department=ztmpnewdepartment where > location_id='%s' and status=0" % (locationid,)) >---- > >My log (per second line of the runupdate function) contains: > >Sat Nov 13 08:44:17 2004 UPDATE mylocation set region=ztmpnewregion, >site=ztmpnewsite, department=ztmpnewdepartment where >location_id='000380' and status=0 > > >At no point do I ever re-assign the value of locationid, but somehow I >get this error back, in about 20ish cases out of the 3000 or so times >the script gets executed: > > >2004/11/13 08:11:21.389 0 4 Executing command line 'python.exe >E:\\updatelocationsProd.py 000380 >\"WV\" \"EXAMPLE_CITY\"'... > >2004/11/13 08:44:28.857 1 1 (-53) Traceback (most recent call >last):\r\n File >\"E:\\updatelocationsProd.py\", >line 282, in ?\r\n runupdate(\"UPDATE mylocation set >region=ztmpnewregion, site=ztmpnewsite, department=ztmpnewdepartment >where location_id='?L$\x14??????T$\x18?D$\x1CR?L$\x14P?F,Q?T$status=0\" (locationid,))\r\n File >\"E:\\updatelocationsProd.py\", >line 48, in runupdate\r\n >remcurs.execute(querystring)\r\ndbi.integrity-error: >[Oracle][ODBC][Ora]ORA-00001: unique constraint >(ARADMIN.I476_200000012_1) violated\r\n in EXEC\r\n > > >Where on earth did "?L$\x14..." come from? > >I'm using Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit >(Intel)] on win32 > >Any ideas? > >Alan > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From carroll at tjc.com Mon Nov 15 20:05:19 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon Nov 15 20:05:22 2004 Subject: [Tutor] object orientation In-Reply-To: <797fe3d404111422416eaae242@mail.gmail.com> Message-ID: On Mon, 15 Nov 2004, Bill Mill wrote: > A little creative googling brought up Andrew Kuchling on the topic: > > http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/91470f975bc85485/b725ce946cd1584c?_done=%2Fgroup%2Fcomp.lang.python%2Fsearch%3Fgroup%3Dcomp.lang.python%26q%3D%22len(x)%22+%22x.len()%22%26qt_g%3D1%26searchnow%3DSearch+this+group%26&_doneTitle=Back+to+Search&&d#b725ce946cd1584c Yow. A little easier: http://tinyurl.com/6u8ga From rdm at rcblue.com Mon Nov 15 20:19:46 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Nov 15 20:19:56 2004 Subject: [Tutor] What is "distutils"? In-Reply-To: <1100528120.4518.37.camel@KMA.accesstel> References: <1100528120.4518.37.camel@KMA.accesstel> Message-ID: <6.1.2.0.2.20041115111845.08b32430@rcblue.com> Maybe this will help: Dick Johan Geldenhuys wrote at 06:15 11/15/2004: >I am trying to install a python application and it fails, because it >wants "distutils.xxxx". >What and where do I get this? > >-- > Johan From adeleinandjeremy at yahoo.com Mon Nov 15 20:57:49 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Mon Nov 15 20:57:52 2004 Subject: [Tutor] What is "distutils"? In-Reply-To: <6.1.2.0.2.20041115111845.08b32430@rcblue.com> Message-ID: <20041115195749.78589.qmail@web54706.mail.yahoo.com> --- Dick Moores wrote: > Maybe this will help: > > > Dick > > Johan Geldenhuys wrote at 06:15 11/15/2004: > >I am trying to install a python application and it fails, because > it > >wants "distutils.xxxx". > >What and where do I get this? > > > >-- > > Johan Are we sure that the problem is with the Python module? I am not so sure. After all, it's standard with Python 2.3. What OS are we talking about? Which Python version? What is the Python application? What are all of the steps leading to the error/requirement report? When I install Python apps I do tar -zxv .tgz and then python to run it. Which app are we discussing, and where can I get it so that I can look at the source to learn how to write installation script(s)? - Jeremy __________________________________ Do you Yahoo!? The all-new My Yahoo! - Get yours free! http://my.yahoo.com From davholla2002 at yahoo.co.uk Mon Nov 15 21:30:44 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Mon Nov 15 21:30:48 2004 Subject: [Tutor] Sort dictionaries In-Reply-To: <20041115191956.D372C1E400D@bag.python.org> Message-ID: <20041115203044.70992.qmail@web25407.mail.ukl.yahoo.com> Is there a built command to sort a dictionary keys or values by their length or do I have to write a function to do it myself ? David --- tutor-request@python.org wrote: > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, > visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body > 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-owner@python.org > > When replying, please edit your Subject line so it > is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: object orientation (Kent Johnson) > 2. Fwd: [Tutor] Python interpreter with command > history? (Max Noel) > 3. Can anybody explain this unusual behavior? > Apparent variable > corruption? (R. Alan Monroe) > 4. What is "distutils"? (Johan Geldenhuys) > 5. Re: demon / app I/F better way ? (Lloyd Kvam) > 6. Re: Function calls (Danny Yoo) > 7. Re: Can anybody explain this unusual behavior? > Apparent > variable corruption? (Bob Gailer) > 8. Re: object orientation (Terry Carroll) > 9. Re: What is "distutils"? (Dick Moores) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 15 Nov 2004 06:06:25 -0500 > From: Kent Johnson > Subject: Re: [Tutor] object orientation > To: tutor@python.org > Message-ID: <41988DB1.8030602@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; > format=flowed > > There was recently a long thread on this topic on > comp.lang.python. Many > people argued that this is a desirable feature of > python, not an > historical accident, because it lets the runtime try > different methods > to resolve an operation. This post by Alex Martelli > spells out the > argument at length: > http://groups.google.com/groups?hl=en&lr=&c2coff=1&selm=1gm05gb.1251x8o3h0barN%25aleaxit%40yahoo.com&rnum=6 > > Kent > > > Christian Meesters wrote: > > Hi > > > > These days I was reading a discussion between > "Ruby-people" and > > "Python-people" (us) on pros and cons of each > language. Such discussions > > aren't very meaningful, of course, but sometimes > interesting. One of the > > arguments was about the realization of the > OO-approach in the languages. > > And this leads me to my question: Though I like > the Python syntax and > > actually prefer it above Ruby's, I wanted to know > why we write len(x) > > instead of x.len() (x being a string for > instance). Does anybody know an > > essay / link about why this approach was chosen? > It makes sense within > > Python, of course, but for now I'm merely > interested in the history. My > > own screenings of the web didn't bring up anything > useful about this topic. > > > > Thanks in advance, > > Cheers > > Christian > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > ------------------------------ > > Message: 2 > Date: Mon, 15 Nov 2004 12:15:37 +0000 > From: Max Noel > Subject: Fwd: [Tutor] Python interpreter with > command history? > To: Python Tutor List > Message-ID: > <0EE63798-3700-11D9-A720-000393CBC88E@yahoo.fr> > Content-Type: text/plain; charset=US-ASCII; > format=flowed > > > > Begin forwarded message: > > > From: Christopher rasch > > Date: November 15, 2004 06:06:46 GMT > > To: Max Noel > > Subject: Re: [Tutor] Python interpreter with > command history? > > > > Hi > > On Nov 14, 2004, at 10:54 PM, Max Noel wrote: > > > >> > >> On Nov 15, 2004, at 03:40, Christopher rasch > wrote: > >> > >>> The default Python interpreter on Mac OS X > doesn't seem to have a > >>> command history (such as you get in bash or > tcsh). Any ideas how to > >>> turn such a thing on? The python documentation > says that some > >>> interpreters have such a feature, but I haven't > yet been able to > >>> locate a command line interpreter with such a > feature. Anyone > >>> recommend alternative interpreters? > >>> > >>> Thanks for any suggestions! > >>> > >>> Chris > >> > >> Go there: > http://homepages.cwi.nl/~jack/macpython/download.html > >> Download the "MacPython for Panther addons" disk > image. Install the > >> software it contains. Among this is a Package > Manager. Launch it, > >> then use it to install the GNU Readline-related > enhancements. Your > >> Python interactive interpreter should now have > command history. > >> I never understood why Apple hadn't included is > in their standard > >> distribution (because of this, the same problem > exists with irb)... > >> > >> -- 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?" > >> > >> > > > > Hi Max, > > > > Thanks! I did as you instructed, and installed > the "MacPython for > > Panther addons" . However, when I tried to launch > the PackageManager, > > it appeared to start to launch, then immediately > shut down. Same with > > the other applications. I'm guessing it's a > permissions problem, but > > I'm not sure what I should change if that's the > case. > > > > Any ideas? > > > > Thanks! > > > > Chris > > > > > -- > 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?" > > > > ------------------------------ > > Message: 3 > Date: Mon, 15 Nov 2004 08:40:12 -0500 > From: "R. Alan Monroe" > === message truncated === ___________________________________________________________ Win a castle for NYE with your mates and Yahoo! Messenger http://uk.messenger.yahoo.com From dyoo at hkn.eecs.berkeley.edu Mon Nov 15 22:28:25 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 15 22:28:30 2004 Subject: [Tutor] Sort dictionaries In-Reply-To: <20041115203044.70992.qmail@web25407.mail.ukl.yahoo.com> Message-ID: On Mon, 15 Nov 2004, David Holland wrote: > Is there a built command to sort a dictionary keys or values by their > length or do I have to write a function to do it myself ? Hi David, You might find the Sorting HOWTO helpful; here's a link to it: http://www.amk.ca/python/howto/sorting/sorting.html Dictionaries themselves can't be sorted, but their keys and values can be. You might need to define your own comparison function. The HOWTO link above shows how to get the sort to work by other criteria. If you have more questions, please feel free to ask! From kent37 at tds.net Mon Nov 15 22:32:46 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Nov 15 22:32:51 2004 Subject: [Tutor] Sort dictionaries In-Reply-To: <20041115203044.70992.qmail@web25407.mail.ukl.yahoo.com> References: <20041115203044.70992.qmail@web25407.mail.ukl.yahoo.com> Message-ID: <4199207E.50708@tds.net> David Holland wrote: > Is there a built command to sort a dictionary keys or > values by their length or do I have to write a > function to do it myself ? In Python 2.4 you can use sort with the builtin len as the key: >>> d = dict(aaa='aaa', bb='bb', c='c') >>> d {'c': 'c', 'aaa': 'aaa', 'bb': 'bb'} >>> k=d.keys() >>> k ['c', 'aaa', 'bb'] >>> k.sort(key=len) >>> k ['c', 'bb', 'aaa'] In Python 2.3 the usual way to do this is with the 'decorate-sort-undecorate' idiom: Make a helper list containing tuples. The first element of the tuple is what you want to sort on, the second element is the actual data: >>> l = [ (len(key), key) for key in d.keys() ] >>> l [(1, 'c'), (3, 'aaa'), (2, 'bb')] Sort the helper list: >>> l.sort() >>> l [(1, 'c'), (2, 'bb'), (3, 'aaa')] Extract the original list: >>> [ key for (keylen, key) in l] ['c', 'bb', 'aaa'] You could also write a comparison function and pass it to the sort, but that is not recommended in general, it is much slower than DSU. BTW this is really a question about lists, not dictionaries - d.keys() is a list, as are d.values() and d.items(). Kent From davholla2002 at yahoo.co.uk Mon Nov 15 22:35:15 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Mon Nov 15 22:35:17 2004 Subject: [Tutor] Sort dictionaries In-Reply-To: Message-ID: <20041115213515.52058.qmail@web25403.mail.ukl.yahoo.com> Thanks a lot that is very helpful. --- Danny Yoo wrote: > > > On Mon, 15 Nov 2004, David Holland wrote: > > > Is there a built command to sort a dictionary keys > or values by their > > length or do I have to write a function to do it > myself ? > > Hi David, > > > You might find the Sorting HOWTO helpful; here's a > link to it: > > > http://www.amk.ca/python/howto/sorting/sorting.html > > > Dictionaries themselves can't be sorted, but their > keys and values can be. > > You might need to define your own comparison > function. The HOWTO link > above shows how to get the sort to work by other > criteria. > > > If you have more questions, please feel free to ask! > > ___________________________________________________________ Moving house? Beach bar in Thailand? New Wardrobe? Win ?10k with Yahoo! Mail to make your dream a reality. Get Yahoo! Mail www.yahoo.co.uk/10k From carroll at tjc.com Mon Nov 15 22:42:37 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon Nov 15 22:42:40 2004 Subject: [Tutor] Threads (was: demon / app I/F better way ? In-Reply-To: <4197AE61.9010909@tds.net> Message-ID: On Sun, 14 Nov 2004, Kent Johnson wrote: > I'm starting to think there is a cultural bias against threads in the > python community. I think there's a bias against threads in the tutorial mailing list, which is kind of understandable. It's a big leap in writing and debugging. I suspect that most programmers who are looking for help, and who are proficient enough to use threads, would probably be hitting the comp.lang.python newsgroup, rather than python-tutor. I'm toying with using threads for an app I have in mind. The Queue module you point out looks like just the ticket for what I'm thinking of. One question I do have on threads, though. In my app, a finite number (12-50) requests including URLs would be put on the queue, and multiple (2-4) consumer threads would pick things off the queue to process. But what's the mechanism to tell those consumer threads that there will be nothing more to consume? It's not just an empty queue, because that could happen whenever the consumers outpace the producer. I was toying with a special-purpose element to add to the queue, as a sentinel to say "that's it, show's over; you can shut down now!" But that would take care only of the thread that happens to pull that element off the queue; the other threads would just see an empty queue and have no basis for knowing that this is the big final empty. I suppose I could ass that "shutdown element" multiple times, once for each consumer thread spawned, but that seems so inelegant. Another technique would be to pass, in addition to the queue, a Shutdown flag, so that when the queue is empty and the shutdown flag is set, the thread shouts down. But the problem with this is that Queue.empty() is documented as not reliable. I suppose I could do a get with a timeout, and check the Shutdown flag; but I can imagine there are synch issues there. What's the ordinary way of telling a thread that it's no longer needed? From op73418 at mail.telepac.pt Mon Nov 15 22:52:17 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Nov 15 22:49:06 2004 Subject: [Tutor] Sort dictionaries In-Reply-To: <20041115203044.70992.qmail@web25407.mail.ukl.yahoo.com> References: <20041115203044.70992.qmail@web25407.mail.ukl.yahoo.com> Message-ID: <41992511.4020908@mail.telepac.pt> David Holland wrote: > Is there a built command to sort a dictionary keys or > values by their length or do I have to write a > function to do it myself ? > > David Dictionaries have no inherent concept of order so you cannot sort them. If you have a collection of objects, sorting them means that you put your objects in 1-1 correspondence with {0,...,n} where n is the number of objects in the collection: in Python terms, you need a list. So suppose you have a dictionary: >>> dct = {(1, 2 , 3) : "ahab", ... (0,) : [], ... ("a", "test") : 3} >>> dct {(0,): [], ('a', 'test'): 3, (1, 2, 3): 'ahab'} And you want to sort your keys by length: One way to do this, is to first extract a list of keys and then you "decorate" them with theior length, >>> pairs = [] >>> for key in dct.keys(): ... pairs.append((len(key), key)) ... >>> pairs [(1, (0,)), (2, ('a', 'test')), (3, (1, 2, 3))] Here we just extracted the keys via the dictionary keys method that returns a list and formed a list of 2-tuples where the *first* item (your sort criteria) is the length of the key and the second item is the key itself. Now that we have a list, we just sort it: >>> pairs.sort() >>> pairs [(1, (0,)), (2, ('a', 'test')), (3, (1, 2, 3))] >>> This works because there is a natural order on tuples: the lexicographic order. First you compare the first item, if they are equal you compare the second item, etc. I hope you can see how this procedure (btw it is called the decorate-sort-undecorate, or DSU for short, pattern) can be applied to your specific setting. With my best regards, G. Rodrigues P.S: There is an hidden assumption in the code above: the keys must be comparable. If they are not, you have to write your own compare function. From op73418 at mail.telepac.pt Mon Nov 15 23:00:26 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Nov 15 22:57:15 2004 Subject: [Tutor] Threads In-Reply-To: References: Message-ID: <419926FA.1030406@mail.telepac.pt> Terry Carroll wrote: > On Sun, 14 Nov 2004, Kent Johnson wrote: > > >>I'm starting to think there is a cultural bias against threads in the >>python community. > > > I think there's a bias against threads in the tutorial mailing list, which > is kind of understandable. It's a big leap in writing and debugging. I > suspect that most programmers who are looking for help, and who are > proficient enough to use threads, would probably be hitting the > comp.lang.python newsgroup, rather than python-tutor. > Agreed. Threads can seem simple but they have associated all the shenanigans of synchronization and deadlocking, starvation, race conditions, etc. And all these problems can be *very* hard to debug. [snip] > What's the ordinary way of telling a thread that it's no longer needed? > Use the queue to pass an object that the thread can recognize as an order to shut down. Upon reception the thread can gracefully shut down, releasing all resources, etc. There is no way of this moment to kill threads from the outside (which is always a last option anyway -- a sort of "look, if you don't behave I'll kill you ok?") so you must build your framework with this kind of cooperation in mind. With my best regards, G. Rodrigues From carroll at tjc.com Mon Nov 15 23:08:06 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon Nov 15 23:08:15 2004 Subject: [Tutor] Threads In-Reply-To: <419926FA.1030406@mail.telepac.pt> Message-ID: On Mon, 15 Nov 2004, Gon?alo Rodrigues wrote: > Terry Carroll wrote: > > > What's the ordinary way of telling a thread that it's no longer needed? > > Use the queue to pass an object that the thread can recognize as an > order to shut down. Okay, but that was one possibility I'd mentioned. The problem is where you have multiple consumer threads reading the Queue. Only the first consumer will get the magic shutdown object. What's the solution? Keep count of the number of consumer threads and enqueue one shutdown object per consumer? (Seems icky; there has to be a less smelly way.) From kent37 at tds.net Mon Nov 15 23:22:12 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Nov 15 23:22:16 2004 Subject: [Tutor] Threads In-Reply-To: References: Message-ID: <41992C14.5090904@tds.net> Terry Carroll wrote: > I'm toying with using threads for an app I have in mind. The Queue module > you point out looks like just the ticket for what I'm thinking of. > > One question I do have on threads, though. In my app, a finite number > (12-50) requests including URLs would be put on the queue, and multiple > (2-4) consumer threads would pick things off the queue to process. > > But what's the mechanism to tell those consumer threads that there will be > nothing more to consume? It's not just an empty queue, because that could > happen whenever the consumers outpace the producer. > > I was toying with a special-purpose element to add to the queue, as a > sentinel to say "that's it, show's over; you can shut down now!" But that > would take care only of the thread that happens to pull that element off > the queue; the other threads would just see an empty queue and have no > basis for knowing that this is the big final empty. > > I suppose I could ass that "shutdown element" multiple times, once for > each consumer thread spawned, but that seems so inelegant. Simple and effective, though, as long as you know how many consumers there are. > > Another technique would be to pass, in addition to the queue, a Shutdown > flag, so that when the queue is empty and the shutdown flag is set, the > thread shouts down. But the problem with this is that Queue.empty() is > documented as not reliable. I suppose I could do a get with a timeout, > and check the Shutdown flag; but I can imagine there are synch issues > there. This a the typical approach in Java - the worker thread checks a flag and returns when the flag is set. You could use a threading.Event() as the flag. What happens if you just leave the consumer threads blocked on the empty queue? If you will need them again, or if the entire process is short-lived, this is a simple solution. Just mark the consumers as daemon threads so the app will exit while they are still alive. You might be interested in these recipes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/196618 Kent From kent37 at tds.net Mon Nov 15 23:30:38 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Nov 15 23:30:42 2004 Subject: [Tutor] Threads In-Reply-To: <419926FA.1030406@mail.telepac.pt> References: <419926FA.1030406@mail.telepac.pt> Message-ID: <41992E0E.1080902@tds.net> OK, maybe there is something for me to learn here. How would you implement a single-producer, multi-consumer system like the OP described without threads? Kent Gon?alo Rodrigues wrote: > Terry Carroll wrote: > >> On Sun, 14 Nov 2004, Kent Johnson wrote: >> >> >>> I'm starting to think there is a cultural bias against threads in the >>> python community. >> >> I think there's a bias against threads in the tutorial mailing list, >> which is kind of understandable. It's a big leap in writing and >> debugging. I suspect that most programmers who are looking for help, >> and who are proficient enough to use threads, would probably be >> hitting the comp.lang.python newsgroup, rather than python-tutor. >> > > Agreed. Threads can seem simple but they have associated all the > shenanigans of synchronization and deadlocking, starvation, race > conditions, etc. And all these problems can be *very* hard to debug. From orbitz at ezabel.com Mon Nov 15 23:37:23 2004 From: orbitz at ezabel.com (orbitz) Date: Mon Nov 15 23:37:30 2004 Subject: [Tutor] Threads In-Reply-To: References: Message-ID: <41992FA3.9070604@ezabel.com> Why waste your time using threads for this? Network I/O is so dang slow using threads will not make the downloading any faster. Using async/non-blocking sockets should be fine and easier to program, less worry of deadlock's and easier to debug IMO. Terry Carroll wrote: >On Sun, 14 Nov 2004, Kent Johnson wrote: > > > >>I'm starting to think there is a cultural bias against threads in the >>python community. >> >> > >I think there's a bias against threads in the tutorial mailing list, which >is kind of understandable. It's a big leap in writing and debugging. I >suspect that most programmers who are looking for help, and who are >proficient enough to use threads, would probably be hitting the >comp.lang.python newsgroup, rather than python-tutor. > >I'm toying with using threads for an app I have in mind. The Queue module >you point out looks like just the ticket for what I'm thinking of. > >One question I do have on threads, though. In my app, a finite number >(12-50) requests including URLs would be put on the queue, and multiple >(2-4) consumer threads would pick things off the queue to process. > >But what's the mechanism to tell those consumer threads that there will be >nothing more to consume? It's not just an empty queue, because that could >happen whenever the consumers outpace the producer. > >I was toying with a special-purpose element to add to the queue, as a >sentinel to say "that's it, show's over; you can shut down now!" But that >would take care only of the thread that happens to pull that element off >the queue; the other threads would just see an empty queue and have no >basis for knowing that this is the big final empty. > >I suppose I could ass that "shutdown element" multiple times, once for >each consumer thread spawned, but that seems so inelegant. > >Another technique would be to pass, in addition to the queue, a Shutdown >flag, so that when the queue is empty and the shutdown flag is set, the >thread shouts down. But the problem with this is that Queue.empty() is >documented as not reliable. I suppose I could do a get with a timeout, >and check the Shutdown flag; but I can imagine there are synch issues >there. > >What's the ordinary way of telling a thread that it's no longer needed? > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From kent37 at tds.net Mon Nov 15 23:58:12 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Nov 15 23:58:19 2004 Subject: [Tutor] Threads In-Reply-To: <41992FA3.9070604@ezabel.com> References: <41992FA3.9070604@ezabel.com> Message-ID: <41993484.2080403@tds.net> orbitz wrote: > Why waste your time using threads for this? Network I/O is so dang slow > using threads will not make the downloading any faster. Using > async/non-blocking sockets should be fine and easier to program, less > worry of deadlock's and easier to debug IMO. Would you use asyncore or asynchat and raw socket IO, then? How would you deal with redirects and other complications of HTTP? Or is there a way to use non-blocking sockets with urllib? Really trying to understand this time... Kent > > > Terry Carroll wrote: >> I'm toying with using threads for an app I have in mind. The Queue >> module you point out looks like just the ticket for what I'm thinking of. >> >> One question I do have on threads, though. In my app, a finite number >> (12-50) requests including URLs would be put on the queue, and >> multiple (2-4) consumer threads would pick things off the queue to >> process. From orbitz at ezabel.com Tue Nov 16 00:11:31 2004 From: orbitz at ezabel.com (orbitz) Date: Tue Nov 16 00:11:40 2004 Subject: [Tutor] Threads In-Reply-To: <41993484.2080403@tds.net> References: <41992FA3.9070604@ezabel.com> <41993484.2080403@tds.net> Message-ID: <419937A3.9000301@ezabel.com> I'm fairly biased, but I suggest twisted. It has an HTTP client, although it isn't 1.1 compliant (or have anything with 1.1 as far as I know). Asyncore isn't very good from what I hear, which is why the author has gone on to make 2 other async libraries. Kent Johnson wrote: > orbitz wrote: > >> Why waste your time using threads for this? Network I/O is so dang >> slow using threads will not make the downloading any faster. Using >> async/non-blocking sockets should be fine and easier to program, less >> worry of deadlock's and easier to debug IMO. > > > Would you use asyncore or asynchat and raw socket IO, then? How would > you deal with redirects and other complications of HTTP? Or is there a > way to use non-blocking sockets with urllib? > > Really trying to understand this time... > Kent > >> >> >> Terry Carroll wrote: >> >>> I'm toying with using threads for an app I have in mind. The Queue >>> module you point out looks like just the ticket for what I'm >>> thinking of. >>> >>> One question I do have on threads, though. In my app, a finite >>> number (12-50) requests including URLs would be put on the queue, >>> and multiple (2-4) consumer threads would pick things off the queue >>> to process. >> > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From carroll at tjc.com Tue Nov 16 00:23:49 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Nov 16 00:23:53 2004 Subject: [Tutor] Threads In-Reply-To: <41992FA3.9070604@ezabel.com> Message-ID: On Mon, 15 Nov 2004, orbitz wrote: > Why waste your time using threads for this? Network I/O is so dang slow > using threads will not make the downloading any faster. Using > async/non-blocking sockets should be fine and easier to program, less > worry of deadlock's and easier to debug IMO. Boy, I see the network I/O slowness as a reason to use threads. If one file takes, say, 1 minute to download, then doing 12 downloads serially will take 12 minutes. But if I can have four threads running, I can have each thread do 3 downloads, total time 3 minutes. I'm assuming that the reason for the slowness is not saturation of the network, but rather is a throttle on the web server. From carroll at tjc.com Tue Nov 16 00:36:45 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Nov 16 00:36:48 2004 Subject: [Tutor] Threads In-Reply-To: <41992C14.5090904@tds.net> Message-ID: On Mon, 15 Nov 2004, Kent Johnson wrote: > Terry Carroll wrote: > > > I suppose I could [add] that "shutdown element" multiple times, once for > > each consumer thread spawned, but that seems so inelegant. > > Simple and effective, though, as long as you know how many consumers > there are. I just thought of a hybrid solution; have a lock object that's required to be held to reference both the Queue and the Shutdown flag. Each thread would do something like this: get_lock() if shutdown_flag == 'y': self.shutdown='y' else: request=Queue.get() if request.type = "shutdown" self.shutdown='y' shutdown_flag='y' # tell the others else: [normal processing] release_lock() if self.shutdown ='y': [shutdown stuff] > What happens if you just leave the consumer threads blocked on the empty > queue? If you will need them again, or if the entire process is > short-lived, this is a simple solution. Just mark the consumers as > daemon threads so the app will exit while they are still alive. I won't need them again. Can the app exit with the threads still blocked? Will Python kill off all the threads then? > You might be interested in these recipes: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/196618 Thanks; they look interesting. I'll take a closer look. From orbitz at ezabel.com Tue Nov 16 00:39:13 2004 From: orbitz at ezabel.com (orbitz) Date: Tue Nov 16 00:39:19 2004 Subject: [Tutor] Threads In-Reply-To: References: Message-ID: <41993E21.6080808@ezabel.com> I guess you didn't read what I said. I suggested using async/non-blocking sockets so you may have multiple downloads going. Feel free to google what they are. Terry Carroll wrote: >On Mon, 15 Nov 2004, orbitz wrote: > > > >>Why waste your time using threads for this? Network I/O is so dang slow >>using threads will not make the downloading any faster. Using >>async/non-blocking sockets should be fine and easier to program, less >>worry of deadlock's and easier to debug IMO. >> >> > >Boy, I see the network I/O slowness as a reason to use threads. > >If one file takes, say, 1 minute to download, then doing 12 downloads >serially will take 12 minutes. But if I can have four threads running, I >can have each thread do 3 downloads, total time 3 minutes. > >I'm assuming that the reason for the slowness is not saturation of the >network, but rather is a throttle on the web server. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From carroll at tjc.com Tue Nov 16 00:56:51 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Nov 16 00:56:54 2004 Subject: [Tutor] Threads In-Reply-To: <41993E21.6080808@ezabel.com> Message-ID: On Mon, 15 Nov 2004, orbitz wrote: > I guess you didn't read what I said. I suggested using > async/non-blocking sockets so you may have multiple downloads going. > Feel free to google what they are. I read it; I misunderstood it. Sad to see this mailing list taking the far-too-typical turn toward incivility. From amonroe at columbus.rr.com Tue Nov 16 01:04:06 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Nov 16 01:04:25 2004 Subject: [Tutor] Threads In-Reply-To: References: Message-ID: <24105804879.20041115190406@columbus.rr.com> > On Mon, 15 Nov 2004, Kent Johnson wrote: >> Terry Carroll wrote: >> >> > I suppose I could [add] that "shutdown element" multiple times, once for >> > each consumer thread spawned, but that seems so inelegant. >> >> Simple and effective, though, as long as you know how many consumers >> there are. Can your consumers write to the queue? If so, they could bucket brigade the shutdown element. When the first thread gets the shutdown token, it eats it and puts a new one on the queue, then shuts down. Alan From carroll at tjc.com Tue Nov 16 01:08:06 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Nov 16 01:08:09 2004 Subject: [Tutor] Threads In-Reply-To: <24105804879.20041115190406@columbus.rr.com> Message-ID: On Mon, 15 Nov 2004, R. Alan Monroe wrote: > Can your consumers write to the queue? If so, they could bucket brigade > the shutdown element. When the first thread gets the shutdown token, > it eats it and puts a new one on the queue, then shuts down. That's a cool idea, There's the slight aesthetic thing that there would be one element left on the Queue after the last one goes away, but since that's the last thing to occur before the app as a whole shuts down, I could live with that. From orbitz at ezabel.com Tue Nov 16 01:08:12 2004 From: orbitz at ezabel.com (orbitz) Date: Tue Nov 16 01:08:24 2004 Subject: [Tutor] Threads In-Reply-To: References: Message-ID: <419944EC.7090203@ezabel.com> Naw, I'm just a big ass. I'm used to it by now though so I don't notice :) Terry Carroll wrote: >On Mon, 15 Nov 2004, orbitz wrote: > > > >>I guess you didn't read what I said. I suggested using >>async/non-blocking sockets so you may have multiple downloads going. >>Feel free to google what they are. >> >> > >I read it; I misunderstood it. Sad to see this mailing list taking the >far-too-typical turn toward incivility. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From kent37 at tds.net Tue Nov 16 01:08:30 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Nov 16 01:08:37 2004 Subject: [Tutor] Threads In-Reply-To: References: Message-ID: <419944FE.60901@tds.net> Terry Carroll wrote: > I just thought of a hybrid solution; have a lock object that's required to > be held to reference both the Queue and the Shutdown flag. Each thread > would do something like this: > > get_lock() > if shutdown_flag == 'y': > self.shutdown='y' > else: > request=Queue.get() > if request.type = "shutdown" > self.shutdown='y' > shutdown_flag='y' # tell the others > else: > [normal processing] > release_lock() > if self.shutdown ='y': > [shutdown stuff] I think it can be as simple as this: while not stopevent.isSet(): try: task = producerQueue.get(True, 0.1) # process task except Queue.Empty: pass where stopevent is a Queue.Event and producerQueue is a Queue.Queue. >>What happens if you just leave the consumer threads blocked on the empty >>queue? If you will need them again, or if the entire process is >>short-lived, this is a simple solution. Just mark the consumers as >>daemon threads so the app will exit while they are still alive. > > > I won't need them again. Can the app exit with the threads still blocked? > Will Python kill off all the threads then? If the threads are marked as daemon threads (call thread.setDaemon(True)) then Python will exit even if the thread is still alive. Kent From kent37 at tds.net Tue Nov 16 01:46:23 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Nov 16 01:46:30 2004 Subject: [Tutor] Threads In-Reply-To: <419944FE.60901@tds.net> References: <419944FE.60901@tds.net> Message-ID: <41994DDF.8040807@tds.net> OK, here is a simple threaded app. It uses worker threads to fetch data from URLs. There are two queues - one to pass jobs (URLs) to the worker threads, another to return results to the main program. The main program keeps a count of how many requests are outstanding; when there are none left it exits. The worker threads are marked as daemon threads so they don't have to be killed. IMO short and sweet, and it just uses standard Python. Kent #################################### import Queue, threading, urllib2 # jobQ passes URLs to the worker threads jobQ = Queue.Queue() # resultsQ returns results to the main thread. A result is a triple of # - the original URL # - a boolean indicating success or failure # - for success, the contents of the url # - for failure, an error message resultsQ = Queue.Queue() urls = [ 'http://www.google.com', 'http://www.python.org', 'http://www.apple.com', 'http://www.kentsjohnson.com', 'http://www.foobarbaz.com/' ] class Worker(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.setDaemon(True) def run(self): while True: url = jobQ.get() try: data = urllib2.urlopen(url).read() except urllib2.URLError, msg: resultsQ.put( (url, False, msg) ) else: resultsQ.put( (url, True, data) ) def main(): # Start two worker threads Worker().start() Worker().start() # Push jobs on the job queue for url in urls: jobQ.put(url) # Read results from the results queue count = len(urls) while count > 0: url, flag, msg = resultsQ.get() if flag: print url, 'read', len(msg), 'bytes' else: print "Couldn't read from", url, msg count -= 1 main() From david at zettazebra.com Tue Nov 16 02:10:29 2004 From: david at zettazebra.com (David Clymer) Date: Tue Nov 16 02:11:42 2004 Subject: [Tutor] Modulus wierdness? Message-ID: <1100567429.5997.14.camel@localhost> Just for fun & practice, I'm implementing a character rotation cypher (e.g. rot13) script. I'm trying to use modulus to wrap the characters' ordinal's around, but I seem to be getting really weird results. When I try the operation in a python shell, it all works fine...so I think i'm misunderstanding something. Does modulus work diffently on variables than it does on literals? The example script is below. -davidc #! /usr/bin/python import sys def rot(text,rotation): textchars = list(text) min_ord=32 max_ord=126 index=0 for c in textchars: if ord(c) < min_ord or ord(c) > max_ord: continue else: num = ord(c) + rotation print '%i + %i = %i' % (ord(c), rotation, num) if num > max_ord: num = min_ord + (num % max_ord) # this shows really wacky modulus results print '%i + (%i / %i)[%i] = %i' % (min_ord, num, max_ord, num % max_ord, num2) textchars[index] = chr(num) index += 1 return ''.join(textchars) if __name__ == '__main__': if len(sys.argv) > 1: if len(sys.argv) > 2: print rot(sys.argv[1],int(sys.argv[2])) else: print rot(sys.argv[1],13) From dyoo at hkn.eecs.berkeley.edu Tue Nov 16 02:23:55 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 16 02:24:22 2004 Subject: [Tutor] Threads In-Reply-To: Message-ID: On Mon, 15 Nov 2004, Terry Carroll wrote: > On Mon, 15 Nov 2004, orbitz wrote: > > > I guess you didn't read what I said. I suggested using > > async/non-blocking sockets so you may have multiple downloads going. > > Feel free to google what they are. > > I read it; I misunderstood it. Hi everyone, [text cut] I have to admit: I haven't done too much asynchronous stuff myself yet. A learning experience! *grin* Let's look at an example of doing something like asynchronous http downloads, using the socket.select() call. It sounds like the problem is to try retrieving a bunch of pages by url simulaneously. We try doing things in parallel to improve network throughput, and to account for certain web pages coming off slower than others. We can use urllib.urlopen() to grab a bunch of web pages. Since that object looks just like a file, we can using it as part of a 'select' event loop. For example: ### >>> import urllib >>> import select >>> f = urllib.urlopen("http://python.org") >>> ready_in, ready_out, ready_exc = select.select([f], [], []) ### When we use a select.select(), what comes back are the file objects that are ready to be read(). select.select() is useful because it returns us all the files that have some content to read. Here's some demonstration code of using select together with the file-like objects that come off of urlopen(): ###### """A small demonstration on grabbing pages asynchronously. Danny Yoo (dyoo@hkn.eecs.berkeley.edu) urllib.urlopen() provides a file-like object, but we can still get at the underlying socket. """ import select import sys import urllib class PageGrabber: def __init__(self): self._urls = {} self._inFiles = {} self._outFiles = {} def add(self, url, outputFile): """Adds a new url to be grabbed. We start writing the output to the outputFile.""" openedFile = urllib.urlopen(url) fileno = openedFile.fileno() self._inFiles[fileno] = openedFile self._urls[fileno] = url self._outFiles[fileno] = outputFile def writeOutAllPages(self): """Waits until all the url streams are written out to their respective outFiles.""" while self._urls: ins, outs, errs = select.select(self._inFiles.keys(), [], []) for in_fileno in ins: all_done = self._writeBlock(in_fileno) if all_done: self._dropUrl(in_fileno) def _dropUrl(self, in_fileno): del self._urls[in_fileno] self._inFiles[in_fileno].close() del self._inFiles[in_fileno] del self._outFiles[in_fileno] def _writeBlock(self, in_fileno, block_size=1024): """Write out the next block. If no more blocks are available, returns True. Else, returns false.""" next_block = self._inFiles[in_fileno].read(block_size) self._outFiles[in_fileno].write(next_block) if next_block: return False else: return True ###################################################################### ## The rest here is just test code. I really should be using unittest ## but I got impatient. *grin* class TracedFile: """A small file just to trace when things are getting written. Used just for debugging purposes""" def __init__(self, name, file): self.name = name self.file = file def write(self, bytes): sys.stderr.write("%s is writing.\n" % self.name) self.file.write(bytes) if __name__ == '__main__': p = PageGrabber() p.add("http://python.org", TracedFile("python.org", sys.stdout)) p.add("http://www.pythonware.com/daily/", TracedFile("daily python url", sys.stdout)) p.writeOutAllPages() ###### The code is really rough and not factored well yet, but it's a starting point. I hope this helps! From kent37 at tds.net Tue Nov 16 02:27:18 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Nov 16 02:27:24 2004 Subject: [Tutor] Modulus wierdness? In-Reply-To: <1100567429.5997.14.camel@localhost> References: <1100567429.5997.14.camel@localhost> Message-ID: <41995776.2080207@tds.net> You are re-assigning num, then trying to use its original value again in the print. Try this: num2 = min_ord + (num % max_ord) # this shows really wacky modulus results print '%i + (%i / %i)[%i] = %i' % (min_ord, num, max_ord, num % max_ord, num2) num = num2 David Clymer wrote: > Just for fun & practice, I'm implementing a character rotation cypher > (e.g. rot13) script. I'm trying to use modulus to wrap the characters' > ordinal's around, but I seem to be getting really weird results. When I > try the operation in a python shell, it all works fine...so I think i'm > misunderstanding something. Does modulus work diffently on variables > than it does on literals? > > The example script is below. > > -davidc > > #! /usr/bin/python > > import sys > > def rot(text,rotation): > textchars = list(text) > min_ord=32 > max_ord=126 > > index=0 > for c in textchars: > if ord(c) < min_ord or ord(c) > max_ord: > continue > else: > num = ord(c) + rotation > print '%i + %i = %i' % (ord(c), rotation, num) > if num > max_ord: > num = min_ord + (num % max_ord) > > # this shows really wacky modulus results > print '%i + (%i / %i)[%i] = %i' % (min_ord, num, max_ord, num % > max_ord, num2) > > textchars[index] = chr(num) > > index += 1 > > return ''.join(textchars) > > > if __name__ == '__main__': > if len(sys.argv) > 1: > if len(sys.argv) > 2: > print rot(sys.argv[1],int(sys.argv[2])) > else: > print rot(sys.argv[1],13) > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From x.ultimate at verizon.net Tue Nov 16 02:28:53 2004 From: x.ultimate at verizon.net (Joe Chiocchi) Date: Tue Nov 16 02:28:58 2004 Subject: [Tutor] Python Timer Message-ID: <20041115202853.5f9c789c.x.ultimate@verizon.net> Hello, I was wondering if it were possible to make a timer in the console. It would be a simple timer just to count down seconds. The only timers I found were made with Tkinter and I am in need of one that prints to the console. Thanks From carroll at tjc.com Tue Nov 16 02:50:36 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Nov 16 02:50:42 2004 Subject: [Tutor] Threads In-Reply-To: <419944FE.60901@tds.net> Message-ID: On Mon, 15 Nov 2004, Kent Johnson wrote: > Terry Carroll wrote: > > I won't need them again. Can the app exit with the threads still blocked? > > Will Python kill off all the threads then? > > If the threads are marked as daemon threads (call > thread.setDaemon(True)) then Python will exit even if the thread is > still alive. That's what I thought. That's the opposite of what I want to have happen. I want the app to exit, and the threads it started to go away; they're done. From tim.peters at gmail.com Tue Nov 16 03:21:29 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue Nov 16 03:21:32 2004 Subject: [Tutor] Threads In-Reply-To: References: <419944FE.60901@tds.net> Message-ID: <1f7befae0411151821716a0d07@mail.gmail.com> [Kent Johnson] >> If the threads are marked as daemon threads (call >> thread.setDaemon(True)) then Python will exit even if the thread is >> still alive. [Terry Carroll] > That's what I thought. That's the opposite of what I want to have > happen. I want the app to exit, and the threads it started to go away; > they're done. That's probably what *will* happen. Since Python exits in this case, it has no more say about what the threads do. Whether the threads die too is then up to the platform (operating system + thread libraries). Under most OSes, when the main thread goes away, child threads are automatically killed too. There's a bit about this in the Python docs for the thread module: When the main thread exits, it is system defined whether the other threads survive. On SGI IRIX using the native thread implementation, they survive. On most other systems, they are killed without executing try ... finally clauses or executing object destructors. But even if you can get away with it, it's generally a better idea to do a controlled shutdown yourself. For example, some day you're going to want those threads to write a summary of what they accomplished to a log file -- or something. It's *always* something . From carroll at tjc.com Tue Nov 16 03:34:11 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Nov 16 03:34:13 2004 Subject: [Tutor] Threads In-Reply-To: <1f7befae0411151821716a0d07@mail.gmail.com> Message-ID: On Mon, 15 Nov 2004, Tim Peters wrote: > [Kent Johnson] > >> If the threads are marked as daemon threads (call > >> thread.setDaemon(True)) then Python will exit even if the thread is > >> still alive. > > [Terry Carroll] > > That's what I thought. That's the opposite of what I want to have > > happen. I want the app to exit, and the threads it started to go away; > > they're done. > > That's probably what *will* happen. If that's what happens, great. I just don't want either the threads to stay around (if I make them daemons) or for the application to hang rather than exit. I suppose I could just write an app that starts a thread and exits without shutting it down, to see if it hangs, huh? From tim.peters at gmail.com Tue Nov 16 04:06:51 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue Nov 16 04:07:45 2004 Subject: [Tutor] Threads In-Reply-To: References: <1f7befae0411151821716a0d07@mail.gmail.com> Message-ID: <1f7befae04111519063a3a3bcf@mail.gmail.com> [Terry Carroll] [Terry Carroll] >>> .... I want the app to exit, and the threads it started to go away; > > > they're done. [Tim Peters] >> That's probably what *will* happen [depending on OS]. > [Terry] > If that's what happens, great. I just don't want either the threads to > stay around (if I make them daemons) or for the application to hang > rather than exit. > > I suppose I could just write an app that starts a thread and exits > without shutting it down, to see if it hangs, huh? If you're talking about a threading.Thread, it will hang unless you marked the thread as a daemon thread. If you're talking about a "raw thread" created by the low-level thread module, don't -- use threading.Thread instead. If you do mark a threading.Thread as daemonic, the program will not hang at exit regardless of whether the OS kills the thread. To determine whether your OS kills a daemon thread when Python exits, try something like this: """ import threading import time class Worker(threading.Thread): def run(self): while True: print "thread still running" time.sleep(1) t = Worker() t.setDaemon(True) t.start() time.sleep(3) # let the thread get started print "main thread going away now" """ If you see an unending parade of "thread still running" lines after you see "main thread going away now", then your OS is not killing the thread. From carroll at tjc.com Tue Nov 16 07:24:48 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Nov 16 07:24:53 2004 Subject: [Tutor] Threads In-Reply-To: <1f7befae04111519063a3a3bcf@mail.gmail.com> Message-ID: On Mon, 15 Nov 2004, Tim Peters wrote: > To determine whether your OS kills a daemon thread when Python exits, > try something like this: [thread-fu example deleted for brevity] > If you see an unending parade of "thread still running" lines after > you see "main thread going away now", then your OS is not killing the > thread. Thanks for this. It looks like my OS kills the thread. And, as you know doubt knew, if I don't make it a daemon, it won't exit. From olli.s.rajala at tut.fi Tue Nov 16 12:34:16 2004 From: olli.s.rajala at tut.fi (Olli Rajala) Date: Tue Nov 16 12:34:19 2004 Subject: [Tutor] Simpler way to do this (for-loop)? Message-ID: <20041116113416.GA23503@students.cc.tut.fi> Okay, I've been coding my own photogallery and in admin-site I have this kind of code. Well, to put it short, it works but is anything but goodlooking... And I have no idea how to make it better, so I thought to ask here. So, 'categories' is just a list with names of categories and I'd like to set the default value of the select in html the value found in 'category'. Sorry the not so good English. :( So, any ideas how to refactor that part of code? ************************************************************ print 'Category:
' ************************************************************ TIA, -- <>< "Quite normal guy" Olli Rajala From maxnoel_fr at yahoo.fr Tue Nov 16 13:47:44 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Nov 16 13:47:49 2004 Subject: [Tutor] object orientation In-Reply-To: <01a301c4cae1$85a2fc40$43bb8651@xp> References: <01a301c4cae1$85a2fc40$43bb8651@xp> Message-ID: On Nov 15, 2004, at 07:05, Alan Gauld wrote: >> to know why we write len(x) instead of x.len() > > There was a thread about this a fw weeks ago > - either here or comp.lang.python. It was here, starring me as "The Ruby Guy" (and no, I still can't decide which of the two languages I like best ^^). -- 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 op73418 at mail.telepac.pt Tue Nov 16 13:56:10 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Nov 16 13:52:59 2004 Subject: [Tutor] Threads In-Reply-To: References: Message-ID: <4199F8EA.9070606@mail.telepac.pt> Terry Carroll wrote: > On Mon, 15 Nov 2004, Gon?alo Rodrigues wrote: > > >>Terry Carroll wrote: >> >> >>>What's the ordinary way of telling a thread that it's no longer needed? >> >>Use the queue to pass an object that the thread can recognize as an >>order to shut down. > > > Okay, but that was one possibility I'd mentioned. The problem is where > you have multiple consumer threads reading the Queue. Only the first > consumer will get the magic shutdown object. > > What's the solution? Keep count of the number of consumer threads and > enqueue one shutdown object per consumer? (Seems icky; there has to be a > less smelly way.) > After I replied I went to sleep and the thread seems to have gained much life -- my inbox has a lot of Re: Threads posts!. I think it was Alan Munroe that talked of one solution - once a Thread gets a shutdown event it pushes another into the queue and then proceeds obediently and orderly to shutdown. If you are ready to code just a little bit more, add one extra level of indirection. Have all your Thread's waiting on their own private queue. This way you can send messages to any Thread in particular. To organize work among a bunch of these threads you can have an extra Thread that acts like a post mail, it receives "packets of work" and distributes them among the worker threads. Queues are really wonderful and if you can shoehorn your thread framework by using them you are saving yourself a lot of trouble. With my best regards, G. Rodrigues From op73418 at mail.telepac.pt Tue Nov 16 14:07:03 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Nov 16 14:03:50 2004 Subject: [Tutor] Threads In-Reply-To: <41992E0E.1080902@tds.net> References: <419926FA.1030406@mail.telepac.pt> <41992E0E.1080902@tds.net> Message-ID: <4199FB77.1010409@mail.telepac.pt> Kent Johnson wrote: > OK, maybe there is something for me to learn here. How would you > implement a single-producer, multi-consumer system like the OP described > without threads? > > Kent > Threads can be the right soluition for such a system. And using Queue and some "smart" event system goes a long way in solving the problem without all the hassles that usually come with threads. But it's not the only solution. Asynchronous systems (like Twisted for network related stuff) can also do the job. It depends. And since I'm not such an expert on the field I'll leave the matter here. As a learning experience there is cookbook recipe (or D. Mertz charming python column -- I forgot which) that uses generators to build a cooperating micro-thread framework. With my best regards, G. Rodrigues From project5 at redrival.net Tue Nov 16 16:13:39 2004 From: project5 at redrival.net (Andrei) Date: Tue Nov 16 16:13:45 2004 Subject: [Tutor] Re: Simpler way to do this (for-loop)? References: <20041116113416.GA23503@students.cc.tut.fi> Message-ID: Olli Rajala tut.fi> writes: > how to refactor: > if not category: > print '' > for line in categories: > print '\n' % (line) > else: > print '' > for line in categories: > if line == category: > print '\n' % (line) > else: > print '\n' % (line) When refactoring, always look for duplicate code in different if-statements and such. In this case, you see that the "Choose the category" thing appears in both parts of the if statement and also the printing of non-selected options. Simply remove the outer if-condition - it serves no purpose. The else part of the condition already automatically covers the case of an unspecified category; it will not display anything as selected, given the fact that line will never match an empty category. You could also move the format string into a separate variable and get the selected status from a dictionary, though I'm not sure that is an improvement over using the if-statement inside the loop. print '' s = '%s\n' d = {True: ' selected', False: ''} for line in categories: print s % (d[line==category], line) Yours, Andrei From andreas at kostyrka.org Tue Nov 16 17:11:38 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue Nov 16 17:14:09 2004 Subject: [Tutor] What is "distutils"? In-Reply-To: <1100528120.4518.37.camel@KMA.accesstel> References: <1100528120.4518.37.camel@KMA.accesstel> Message-ID: <1100620720.2736.16.camel@andi-lap> Am Mo, den 15.11.2004 schrieb Johan Geldenhuys um 15:15: > I am trying to install a python application and it fails, because it > wants "distutils.xxxx". > What and where do I get this? Well, it depends upon xxxx, because certain modules are supplied by external modules, e.g. Pyrex. But assuming it refers to the core modules, I'd guess that you are on a Linux system, and the development package (python-dev, python-devel, depending upon your distribution) isn't installed. Andreas > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20041116/9044d28a/attachment.pgp From andreas at kostyrka.org Tue Nov 16 17:12:18 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue Nov 16 17:14:45 2004 Subject: [Tutor] What is "distutils"? In-Reply-To: <1100528120.4518.37.camel@KMA.accesstel> References: <1100528120.4518.37.camel@KMA.accesstel> Message-ID: <1100620720.2736.16.camel@andi-lap> Am Mo, den 15.11.2004 schrieb Johan Geldenhuys um 15:15: > I am trying to install a python application and it fails, because it > wants "distutils.xxxx". > What and where do I get this? Well, it depends upon xxxx, because certain modules are supplied by external modules, e.g. Pyrex. But assuming it refers to the core modules, I'd guess that you are on a Linux system, and the development package (python-dev, python-devel, depending upon your distribution) isn't installed. Andreas > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20041116/9044d28a/attachment-0001.pgp From andreas at kostyrka.org Tue Nov 16 17:12:20 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue Nov 16 17:14:51 2004 Subject: [Tutor] Python interpreter with command history? In-Reply-To: References: <18E06576-36B8-11D9-B59B-00039366A582@openknowledge.org> Message-ID: <1100620908.2736.17.camel@andi-lap> Am Mo, den 15.11.2004 schrieb Huw Davies um 6:39: > On 15/11/2004, at 2:40 PM, Christopher rasch wrote: > > > The default Python interpreter on Mac OS X doesn't seem to have a > > command history (such as you get in bash or tcsh). Any ideas how to > > turn such a thing on? The python documentation says that some > > interpreters have such a feature, but I haven't yet been able to > > locate a command line interpreter with such a feature. Anyone > > recommend alternative interpreters? > > Interesting - I have fink installed and use the python in /sw/bin/fink > and it has command recall but as you point out the "default" OS X > python (/usr/bin/python) seems to built without it. > > If you already have fink setup, I guess the easiest solution might be > to install python from it. I suspect that the only way to get command > recall will be to recompile python. Alternativly one might use a program that supplies that feature externaly. One that comes to mind would be emacs ;) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20041116/f6242ebe/attachment.pgp From Christian.Wyglendowski at greenville.edu Tue Nov 16 18:05:43 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Tue Nov 16 18:05:47 2004 Subject: [Tutor] Python Timer Message-ID: > -----Original Message----- > [mailto:tutor-bounces@python.org] On Behalf Of Joe Chiocchi > Subject: [Tutor] Python Timer > > Hello, I was wondering if it were possible to make a timer in > the console. It would be a simple timer just to count down seconds. > The only timers I found were made with Tkinter and I am in > need of one that prints to the console. Thanks Hi Joe, With all the great talk about threads going on, I thought it might be fun to make a simple threaded timer. Here is what I typed into the Pythonwin shell: >>> import time >>> import threading >>> class Timer(threading.Thread): #subclass Thread ... def __init__(self, seconds): #make it possible to pass the time in seconds that we want the timer to run ... self.runTime = seconds #set our runTime in seconds ... threading.Thread.__init__(self) #call the Thread's constructor ... def run(self): #define what we want our Timer thread to do ... time.sleep(self.runTime) #have it sleep for runTime seconds ... print "Buzzzz!! Time's up!" #print a message when done ... >>> t = Timer(10) >>> t.start() #ten seconds go by ... >>> Buzzzz!! Time's up! There is a very simple (and pretty useless) timer. I reread your question though and noticed that you want the timer to "print to the console". I don't know if this is the best way, but we can use the simple Timer class above to build a CountDownTimer. >>> class CountDownTimer(Timer): #inherit from our simple Timer which initializes all that we need ... def run(self): #setup our new action, overriding the simple action in Timer ... counter = self.runTime #inititialize a counter variable ... for sec in range(self.runTime): #start a loop over a range that is self.runTime elements long ... print counter #output value of counter ... time.sleep(1.0) # ZZZZzzzz... (sleep for one second) ... counter -= 1 #decrement our counter variable by 1 ... print "Done." #print this once the loop above is complete ... >>> c = CountDownTimer(10) >>> c.start() 10 >>> 9 8 7 6 5 4 3 2 1 Done. So there we have a timer that counts down the seconds and prints them to the screen. More interesting than the first timer, but not by much. Here is a final implementation that allows you to pass an action to execute at the end of the timer run. >>> class CountDownExec(CountDownTimer): #now we subclass CountDownTimer ... def __init__(self, seconds, action): #we need to accept seconds as well as an action as arguments ... self.action = action #set our timer's action ... CountDownTimer.__init__(self, seconds) #setup the rest of the timer from CountDownTimer ... def run(self): #we need to modify run to perform the action ... CountDownTimer.run(self) #first we run the standard CountDownTimer routine, as it still works ... self.action() #then we do our action ... >>> def myAction(): #we need an action, right? ... print "Performing my action..." #boring, but simple ... >>> c = CountDownExec(10, myAction) >>> c.start() 10 >>> 9 8 7 6 5 4 3 2 1 Done. Performing my action... CountDownExec could be expanded to allow for arguments to be passed to the action, but unfortunately I am out of time on this email! HTH, Christian http://www.dowski.com From Christian.Wyglendowski at greenville.edu Tue Nov 16 18:15:04 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Tue Nov 16 18:15:08 2004 Subject: [Tutor] Python Timer Message-ID: [line wrapped mess snipped] Ugh...here is my reply without the comments which wrapped and made it unreadable... (commented text file attached) ------------------------------------------------------------------------ Hi Joe, With all the great talk about threads going on, I thought it might be fun to make a simple threaded timer. Here is what I typed into the Pythonwin shell: >>> import time >>> import threading >>> class Timer(threading.Thread): ... def __init__(self, seconds): ... self.runTime = seconds ... threading.Thread.__init__(self) ... def run(self): ... time.sleep(self.runTime) ... print "Buzzzz!! Time's up!" ... >>> t = Timer(10) >>> t.start() >>> Buzzzz!! Time's up! There is a very simple (and pretty useless) timer. I reread your question though and noticed that you want the timer to "print to the console". I don't know if this is the best way, but we can use the simple Timer class above to build a CountDownTimer. >>> class CountDownTimer(Timer): ... def run(self): ... counter = self.runTime ... for sec in range(self.runTime): ... print counter ... time.sleep(1.0) ... counter -= 1 ... print "Done." ... >>> c = CountDownTimer(10) >>> c.start() 10 >>> 9 8 7 6 5 4 3 2 1 Done. So there we have a timer that counts down the seconds and prints them to the screen. More interesting than the first timer, but not by much. Here is a final implementation that allows you to pass an action to execute at the end of the timer run. >>> class CountDownExec(CountDownTimer): ... def __init__(self, seconds, action): ... self.action = action ... CountDownTimer.__init__(self, seconds) ... def run(self): ... CountDownTimer.run(self) ... self.action() ... >>> def myAction(): ... print "Performing my action..." ... >>> c = CountDownExec(10, myAction) >>> c.start() 10 >>> 9 8 7 6 5 4 3 2 1 Done. Performing my action... CountDownExec could be expanded to allow for arguments to be passed to the action, but unfortunately I am out of time on this email! HTH, Christian http://www.dowski.com -------------- next part -------------- > -----Original Message----- > [mailto:tutor-bounces@python.org] On Behalf Of Joe Chiocchi > Subject: [Tutor] Python Timer > > Hello, I was wondering if it were possible to make a timer in the > console. It would be a simple timer just to count down seconds. > The only timers I found were made with Tkinter and I am in need of one > that prints to the console. Thanks Hi Joe, With all the great talk about threads going on, I thought it might be fun to make a simple threaded timer. Here is what I typed into the Pythonwin shell: >>> import time >>> import threading >>> class Timer(threading.Thread): #subclass Thread ... def __init__(self, seconds): #make it possible to pass the time in seconds that we want the timer to run ... self.runTime = seconds #set our runTime in seconds ... threading.Thread.__init__(self) #call the Thread's constructor ... def run(self): #define what we want our Timer thread to do ... time.sleep(self.runTime) #have it sleep for runTime seconds ... print "Buzzzz!! Time's up!" #print a message when done ... >>> t = Timer(10) >>> t.start() #ten seconds go by ... >>> Buzzzz!! Time's up! There is a very simple (and pretty useless) timer. I reread your question though and noticed that you want the timer to "print to the console". I don't know if this is the best way, but we can use the simple Timer class above to build a CountDownTimer. >>> class CountDownTimer(Timer): #inherit from our simple Timer which initializes all that we need ... def run(self): #setup our new action, overriding the simple action in Timer ... counter = self.runTime #inititialize a counter variable ... for sec in range(self.runTime): #start a loop over a range that is self.runTime elements long ... print counter #output value of counter ... time.sleep(1.0) # ZZZZzzzz... (sleep for one second) ... counter -= 1 #decrement our counter variable by 1 ... print "Done." #print this once the loop above is complete ... >>> c = CountDownTimer(10) >>> c.start() 10 >>> 9 8 7 6 5 4 3 2 1 Done. So there we have a timer that counts down the seconds and prints them to the screen. More interesting than the first timer, but not by much. Here is a final implementation that allows you to pass an action to execute at the end of the timer run. >>> class CountDownExec(CountDownTimer): #now we subclass CountDownTimer ... def __init__(self, seconds, action): #we need to accept seconds as well as an action as arguments ... self.action = action #set our timer's action ... CountDownTimer.__init__(self, seconds) #setup the rest of the timer from CountDownTimer ... def run(self): #we need to modify run to perform the action ... CountDownTimer.run(self) #first we run the standard CountDownTimer routine, as it still works ... self.action() #then we do our action ... >>> def myAction(): #we need an action, right? ... print "Performing my action..." #boring, but simple ... >>> c = CountDownExec(10, myAction) >>> c.start() 10 >>> 9 8 7 6 5 4 3 2 1 Done. Performing my action... CountDownExec could be expanded to allow for arguments to be passed to the action, but unfortunately I am out of time on this email! HTH, Christian http://www.dowski.com From andreas at kostyrka.org Tue Nov 16 18:43:13 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue Nov 16 18:45:40 2004 Subject: [Tutor] Python interpreter with command history? In-Reply-To: References: <18E06576-36B8-11D9-B59B-00039366A582@openknowledge.org> Message-ID: <1100620908.2736.17.camel@andi-lap> Am Mo, den 15.11.2004 schrieb Huw Davies um 6:39: > On 15/11/2004, at 2:40 PM, Christopher rasch wrote: > > > The default Python interpreter on Mac OS X doesn't seem to have a > > command history (such as you get in bash or tcsh). Any ideas how to > > turn such a thing on? The python documentation says that some > > interpreters have such a feature, but I haven't yet been able to > > locate a command line interpreter with such a feature. Anyone > > recommend alternative interpreters? > > Interesting - I have fink installed and use the python in /sw/bin/fink > and it has command recall but as you point out the "default" OS X > python (/usr/bin/python) seems to built without it. > > If you already have fink setup, I guess the easiest solution might be > to install python from it. I suspect that the only way to get command > recall will be to recompile python. Alternativly one might use a program that supplies that feature externaly. One that comes to mind would be emacs ;) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20041116/f6242ebe/attachment-0002.pgp From andreas at kostyrka.org Tue Nov 16 18:43:15 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue Nov 16 18:45:44 2004 Subject: [Tutor] Simpler way to do this (for-loop)? In-Reply-To: <20041116113416.GA23503@students.cc.tut.fi> References: <20041116113416.GA23503@students.cc.tut.fi> Message-ID: <1100621417.2736.24.camel@andi-lap> Am Di, den 16.11.2004 schrieb Olli Rajala um 12:34: > Okay, I've been coding my own photogallery and in admin-site I have > this kind of code. Well, to put it short, it works but is anything > but goodlooking... And I have no idea how to make it better, so I > thought to ask here. > > So, 'categories' is just a list with names of categories and I'd like > to set the default value of the select in html the value found in > 'category'. Sorry the not so good English. :( > > So, any ideas how to refactor that part of code? > > ************************************************************ > print 'Category:
' > ************************************************************ Untested code: print 'Category:
' Alternativly (still untested): print 'Category:
' Important things to point out: * You can compare None in Python with any other object. It's just usually not equal ;) * You do not need to write '% (line)', either '% line' is enough, because you know that line will never ever be a tuple, or you should use '% (line, )'. The comma at the end signals it as a tuple. Andreas > > TIA, -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20041116/e4e7a152/attachment.pgp From rdm at rcblue.com Tue Nov 16 19:12:56 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Nov 16 19:13:19 2004 Subject: [Tutor] Python Timer In-Reply-To: <20041115202853.5f9c789c.x.ultimate@verizon.net> References: <20041115202853.5f9c789c.x.ultimate@verizon.net> Message-ID: <6.1.2.0.2.20041116100231.04a04100@rcblue.com> Here's mine. Wrote it some months ago with help from this list when I was even a newer newbie, and now would modularize it more. Dick Joe Chiocchi wrote at 17:28 11/15/2004: >Hello, I was wondering if it were possible to make a timer in the >console. It would be a simple timer just to count down seconds. >The only timers I found were made with Tkinter and I am in need of one >that prints to the console. Thanks >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From ps_python at yahoo.com Tue Nov 16 20:35:46 2004 From: ps_python at yahoo.com (kumar s) Date: Tue Nov 16 20:35:50 2004 Subject: [Tutor] Implementing Genetic Algorithm in Python Message-ID: <20041116193546.20372.qmail@web53708.mail.yahoo.com> Hello tutors, In a recent publication by Journal of Biological Chemistry, a group of scientists implemented gentic algorithm to cluster a set of genes based on the statistical values arising from measuring gene expression values. I am very much interested in using the identical approach on my own data to ask different questions. Is python suitable for implementing Genetic Algorithms? Are there any libraries or modules that are useful for implementing GAs. Is there any site where I can get some information. I am interested in knowing more from tutors. Thanks Kumar. __________________________________ Do you Yahoo!? The all-new My Yahoo! - Get yours free! http://my.yahoo.com From lbrannma at yahoo.com Wed Nov 17 05:45:51 2004 From: lbrannma at yahoo.com (L) Date: Tue Nov 16 20:44:18 2004 Subject: [Tutor] wxPython Message-ID: <006d01c4cc60$50cb6450$6400a8c0@mynewbox> Hi All, I sent this to the wxPython mail list but haven't seen it appear. It might be too basic for them. I'm new to GUI programming and chose wxPython (after reading many rave reviews). My several Python books cover the old version (without the wx namespace). I would like to read from a text box on one form and write some results based on the read to another form. I suppose both forms have panels (that's how I designed things, using wxGlade). The text I will write is rather lengthy so I will write to a multiline scrollable text box. My paltry attempts at a solution so far have not resulted in success. Would anyone be able to contribute a small piece of code to get me started? Thanks, Lance -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041116/4bb81c1a/attachment.htm From kent37 at tds.net Tue Nov 16 21:25:13 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Nov 16 21:25:18 2004 Subject: [Tutor] Implementing Genetic Algorithm in Python In-Reply-To: <20041116193546.20372.qmail@web53708.mail.yahoo.com> References: <20041116193546.20372.qmail@web53708.mail.yahoo.com> Message-ID: <419A6229.4080200@tds.net> Do you know about BioPython? Is that the kind of thing you are looking for? Andrew Dalke, one of the contributors to BioPython, is a regular on comp.lang.python. http://www.biopython.org/ Kent kumar s wrote: > Hello tutors, > In a recent publication by Journal of Biological > Chemistry, a group of scientists implemented gentic > algorithm to cluster a set of genes based on the > statistical values arising from measuring gene > expression values. I am very much interested in using > the identical approach on my own data to ask different > questions. > Is python suitable for implementing Genetic > Algorithms? Are there any libraries or modules that > are useful for implementing GAs. Is there any site > where I can get some information. I am interested in > knowing more from tutors. > > Thanks > Kumar. > > > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - Get yours free! > http://my.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From STEVEN.M.FAULCONER at saic.com Tue Nov 16 21:49:10 2004 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Tue Nov 16 21:49:14 2004 Subject: [Tutor] Windows Printing with separator sheets. Message-ID: <207DA77D2384D411A48B0008C7095D810152B947@us-melbourne.mail.saic.com> Hello everyone, I'm having a problem getting a stand-alone Windows system to print to a USB printer with a separator sheet using Python+COM. I posted this to the Python-Win32 list, but didn't receive any response. I hope someone on the Tutor list might have run into this before. The code is: ----code---- from win32com.client import Dispatch myWord = Dispatch( 'Word.Application' ) #myWord.Visible = 1 myDoc = myWord.Documents.Add( r"c:\docs\report.doc" ) myDoc.PrintOut() myDoc.Close() ----code---- Now, when I open that Word document (5 pages, text only) by hand and print. Everything works correctly. The separator page is first, followed by the 5 page document. Running the above code gets the separator page to print, but nothing else. If I uncomment Visible=1, I can see the instance of Word spool 5 pages. However, the printer only prints the separator sheet. Now, to ensure it wasn't my separator sheet, using one of the separator pages that comes with Windows (SYSPRINT.SEP) does exactly the same thing. Has anyone encountered something like this before? Any help would be greatly appreciated. Thanks. Steven From orbitz at ezabel.com Tue Nov 16 21:56:28 2004 From: orbitz at ezabel.com (orbitz) Date: Tue Nov 16 21:56:37 2004 Subject: [Tutor] Threads In-Reply-To: References: Message-ID: <419A697C.9080408@ezabel.com> urllib is blocking, so you can't really use it wiht non blocking code. the urlopen functio could take awhile, and then even if data is on the socket then it will still block for te read most likely which is not going to help you. One is going to have to use a non blocking url api in order to make the most of their time. Danny Yoo wrote: >On Mon, 15 Nov 2004, Terry Carroll wrote: > > > >>On Mon, 15 Nov 2004, orbitz wrote: >> >> >> >>>I guess you didn't read what I said. I suggested using >>>async/non-blocking sockets so you may have multiple downloads going. >>>Feel free to google what they are. >>> >>> >>I read it; I misunderstood it. >> >> > > >Hi everyone, > > >[text cut] > >I have to admit: I haven't done too much asynchronous stuff myself yet. >A learning experience! *grin* > > >Let's look at an example of doing something like asynchronous http >downloads, using the socket.select() call. It sounds like the problem is >to try retrieving a bunch of pages by url simulaneously. We try doing >things in parallel to improve network throughput, and to account for >certain web pages coming off slower than others. > > >We can use urllib.urlopen() to grab a bunch of web pages. Since that >object looks just like a file, we can using it as part of a 'select' event >loop. For example: > >### > > >>>>import urllib >>>>import select >>>>f = urllib.urlopen("http://python.org") >>>>ready_in, ready_out, ready_exc = select.select([f], [], []) >>>> >>>> >### > >When we use a select.select(), what comes back are the file objects that >are ready to be read(). select.select() is useful because it returns us >all the files that have some content to read. > > > > >Here's some demonstration code of using select together with the file-like >objects that come off of urlopen(): > > >###### >"""A small demonstration on grabbing pages asynchronously. > >Danny Yoo (dyoo@hkn.eecs.berkeley.edu) > >urllib.urlopen() provides a file-like object, but we can still get at >the underlying socket. > >""" > >import select >import sys >import urllib > > >class PageGrabber: > def __init__(self): > self._urls = {} > self._inFiles = {} > self._outFiles = {} > > > def add(self, url, outputFile): > """Adds a new url to be grabbed. We start writing the output > to the outputFile.""" > openedFile = urllib.urlopen(url) > fileno = openedFile.fileno() > self._inFiles[fileno] = openedFile > self._urls[fileno] = url > self._outFiles[fileno] = outputFile > > > def writeOutAllPages(self): > """Waits until all the url streams are written out to their > respective outFiles.""" > while self._urls: > ins, outs, errs = select.select(self._inFiles.keys(), [], []) > for in_fileno in ins: > all_done = self._writeBlock(in_fileno) > if all_done: > self._dropUrl(in_fileno) > > > def _dropUrl(self, in_fileno): > del self._urls[in_fileno] > self._inFiles[in_fileno].close() > del self._inFiles[in_fileno] > del self._outFiles[in_fileno] > > > > def _writeBlock(self, in_fileno, block_size=1024): > """Write out the next block. If no more blocks are available, > returns True. Else, returns false.""" > next_block = self._inFiles[in_fileno].read(block_size) > self._outFiles[in_fileno].write(next_block) > if next_block: > return False > else: > return True > > > >###################################################################### >## The rest here is just test code. I really should be using unittest >## but I got impatient. *grin* > >class TracedFile: > """A small file just to trace when things are getting written. > Used just for debugging purposes""" > def __init__(self, name, file): > self.name = name > self.file = file > > def write(self, bytes): > sys.stderr.write("%s is writing.\n" % self.name) > self.file.write(bytes) > > >if __name__ == '__main__': > p = PageGrabber() > p.add("http://python.org", > TracedFile("python.org", sys.stdout)) > p.add("http://www.pythonware.com/daily/", > TracedFile("daily python url", sys.stdout)) > p.writeOutAllPages() >###### > > >The code is really rough and not factored well yet, but it's a starting >point. I hope this helps! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From naveed48 at wol.net.pk Tue Nov 16 23:08:06 2004 From: naveed48 at wol.net.pk (Naveed Ahmed Khan) Date: Tue Nov 16 23:08:20 2004 Subject: [Tutor] dictionary command Message-ID: <200411162205.iAGM5O5w027441@svmout.wol.net.pk> Dear friends, I am using python on windows and trying the dictionary command but its not working. dict = {} This command line works alright but when I try the below: >>> dict['boolean'] = "A value which is either true or false" I get the following error message: "Object does not support the item assignment" Kindly help me out why is that so. Please note that I am new in programming Regards, NAK -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041117/40f9398a/attachment.html From carroll at tjc.com Tue Nov 16 23:44:35 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Nov 16 23:44:38 2004 Subject: [Tutor] dictionary command In-Reply-To: <200411162205.iAGM5O5w027441@svmout.wol.net.pk> Message-ID: On Wed, 17 Nov 2004, Naveed Ahmed Khan wrote: > dict = {} > > This command line works alright but when I try the below: > > > >>> dict['boolean'] = "A value which is either true or false" > > I get the following error message: > > "Object does not support the item assignment" These are in two different sessions, right? Your basic problem is that "dict" is the name of a builtin type, the dictionary. use a different name. From jfabiani at yolo.com Tue Nov 16 23:45:35 2004 From: jfabiani at yolo.com (John Fabiani) Date: Tue Nov 16 23:46:00 2004 Subject: [Tutor] wxPython In-Reply-To: <006d01c4cc60$50cb6450$6400a8c0@mynewbox> References: <006d01c4cc60$50cb6450$6400a8c0@mynewbox> Message-ID: <200411161445.35760.jfabiani@yolo.com> On Tuesday 16 November 2004 20:45, L wrote: > Hi All, > > I sent this to the wxPython mail list but haven't seen it appear. It might > be too basic for them. > > I'm new to GUI programming and chose wxPython (after reading many rave > reviews). My several Python books cover the old version (without the wx > namespace). > > I would like to read from a text box on one form and write some results > based on the read to another form. I suppose both forms have panels (that's > how I designed things, using wxGlade). The text I will write is rather > lengthy so I will write to a multiline scrollable text box. > > My paltry attempts at a solution so far have not resulted in success. Would > anyone be able to contribute a small piece of code to get me started? > > Thanks, > Lance I'm not sure I can help but I think I understand what your asking. I'll assume that you mean 'frame' when you say 'forms'. If your opening one frame (a window) and typing into the multiline text and then click a button to transfer data and open a second frame with the info then" Pass the frame1 info (first window/frame) in the EVT_BUTTON event. Something like frame = MainWindow(None,-1, "Main Window") # you set up a var in secondWindow class like #self.textinfo ='' #then in the EVT_BUTTON event say something like myframe=secondWindow(frame,-1,"second window") myframe.textinfo = the value of the text control I hope this helps. As a newbie it has been working for me anyway. John From dyoo at hkn.eecs.berkeley.edu Wed Nov 17 01:03:55 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 17 01:04:20 2004 Subject: [Tutor] Threads In-Reply-To: <419A697C.9080408@ezabel.com> Message-ID: On Tue, 16 Nov 2004, orbitz wrote: > urllib is blocking, so you can't really use it wiht non blocking code. > the urlopen functio could take awhile, and then even if data is on the > socket then it will still block for te read most likely which is not > going to help you. One is going to have to use a non blocking url api in > order to make the most of their time. Hi Orbitz, Hmmm! Yes, you're right: the sockets block by default. But, when we try to read() a block of data, select() can tell us which ones will immediately block and which ones won't. The real-world situation is actually a bit complicated. Let's do a test to make things more explicit and measurable. For this example, let's say that we have the following 'hello.py' CGI: ### #!/usr/bin/python import time import sys print "Content-type: text/plain\n\n" sys.stdout.flush() print "hello world"; time.sleep(5) print "goodbye world" ### I'll be accessing this cgi from the url "http://localhost/~dyoo/hello.py". I'm also using Apache 2.0 as my web server. Big note: there's a flush() after the content-stream header. This is intentional, and will be significant later on in this post. I then wrote the following two test programs: ### ## test1.py from grab_pages import PageGrabber from StringIO import StringIO pg = PageGrabber() f1, f2, f3 = StringIO(), StringIO(), StringIO() pg.add("http://localhost/~dyoo/hello.py", f1) pg.add("http://localhost/~dyoo/hello.py", f2) pg.add("http://localhost/~dyoo/hello.py", f3) pg.writeOutAllPages() print f1.getvalue() print f2.getvalue() print f3.getvalue() ### ### ## test2.py import urllib print urllib.urlopen("http://localhost/~dyoo/hello.py").read() print urllib.urlopen("http://localhost/~dyoo/hello.py").read() print urllib.urlopen("http://localhost/~dyoo/hello.py").read() ### test1 uses the PageGrabber class we wrote earlier, and test2 uses a straightforward approach. If we start timing the perfomance of test1.py and test2.py, we do see a difference between the two, since test1 will try to grab the pages in parallel, while test2 will do it serially: ### [dyoo@shoebox dyoo]$ time python test1.py hello world goodbye world hello world goodbye world hello world goodbye world real 0m5.106s user 0m0.043s sys 0m0.011s [dyoo@shoebox dyoo]$ time python test2.py hello world goodbye world hello world goodbye world hello world goodbye world real 0m15.107s user 0m0.044s sys 0m0.007s ### So for this particular example, we're getting good results: test1 takes about 5 seconds, while test2 takes 15. So the select() code is doing pretty ok so far, and does show improvement over the straightforward approach. Isn't this wonderful? *grin* Well, there's bad news. The problem is that, as you highlighted, the urllib.urlopen() function itself can block, and that's actually a very bad problem in practice. In particular, it blocks until it sees the end of the HTTP headers, since it depends on Python's 'httplib' module. If we take out the flush() out of our hello.py CGI: ### #!/usr/bin/python import time import sys print "Content-type: text/plain\n\n" print "hello world"; time.sleep(5) print "goodbye world" ### then suddenly things go horribly awry: ### [dyoo@shoebox dyoo]$ time python test1.py hello world goodbye world hello world goodbye world hello world goodbye world real 0m15.113s user 0m0.047s sys 0m0.006s ### And suddenly, we do no better than with the serial version! What's happening is that the web server is buffering the output of its CGI programs. Without the sys.stdout.flush(), it's likely that the web server doesn't send out anything until the whole program is complete. But because urllib.urlopen() returns only after seeing the header block from the HTTP response, it actually ends up waiting until the whole program's done. Not all CGI's have been carefully written to output its HTTP headers in a timely manner, so urllib.urlopen()'s blocking behavior is a show-stopper. This highlights the need for a framework that's built with nonblocking, event-driven code as a pervasive concept. Like... Twisted! *grin* Does anyone want to cook up an example with Twisted to show how the page-grabbing example might work? Hope this helps! From orbitz at ezabel.com Wed Nov 17 02:49:06 2004 From: orbitz at ezabel.com (orbitz) Date: Wed Nov 17 02:49:43 2004 Subject: [Tutor] Threads In-Reply-To: References: Message-ID: <419AAE12.4000206@ezabel.com> Not only is things like waiting for headers a major issue, but simply resolving the name and connecting. What if your DNS goes down in mid-download. It could take a long time to timeout while trying to connect to your DNS, and none of your sockets will be touched, select or not. So if we are going to use blocking sockets we might as well go all the way. Here is a simple twisted example of downloading 3 sites, printing them to stdout, and exiting, it probably won't make much sense but it's 100% non blocking at least:) from twisted.web import client from twisted.Internet import reactor from urllib2 import urlparse def _handlePage(result): """The result is the contents of the webpage""" global num_downloaded print result num_downloaded += 1 if num_downloaded == len(URLS) - 1: reactor.stop() URLS = ['http://www.google.com/', 'http://www.yahoo.com/', 'http://www.python.org/'] num_downloaded = 0 for i in URLS: parsed = urlparse.urlsplit(i) f = client.HTTPClientFactory(parsed[2]) f.host = parsed[1] f.deferred.addCallback(_handlePage) reactor.connectTCP(parsed[1], 80, f) reactor.run() All this does is download each page, print it out, and when that many url's has been processed, stop the program (reactor.stop). This does not handle errors or any exceptional situations. Danny Yoo wrote: >On Tue, 16 Nov 2004, orbitz wrote: > > > >>urllib is blocking, so you can't really use it wiht non blocking code. >>the urlopen functio could take awhile, and then even if data is on the >>socket then it will still block for te read most likely which is not >>going to help you. One is going to have to use a non blocking url api in >>order to make the most of their time. >> >> > > >Hi Orbitz, > > >Hmmm! Yes, you're right: the sockets block by default. But, when we try >to read() a block of data, select() can tell us which ones will >immediately block and which ones won't. > > >The real-world situation is actually a bit complicated. Let's do a test >to make things more explicit and measurable. > > >For this example, let's say that we have the following 'hello.py' CGI: > >### >#!/usr/bin/python >import time >import sys >print "Content-type: text/plain\n\n" >sys.stdout.flush() > >print "hello world"; >time.sleep(5) >print "goodbye world" >### > > >I'll be accessing this cgi from the url "http://localhost/~dyoo/hello.py". >I'm also using Apache 2.0 as my web server. Big note: there's a flush() >after the content-stream header. This is intentional, and will be >significant later on in this post. > > > >I then wrote the following two test programs: > >### >## test1.py >from grab_pages import PageGrabber >from StringIO import StringIO >pg = PageGrabber() >f1, f2, f3 = StringIO(), StringIO(), StringIO() >pg.add("http://localhost/~dyoo/hello.py", f1) >pg.add("http://localhost/~dyoo/hello.py", f2) >pg.add("http://localhost/~dyoo/hello.py", f3) >pg.writeOutAllPages() >print f1.getvalue() >print f2.getvalue() >print f3.getvalue() >### > > >### >## test2.py >import urllib >print urllib.urlopen("http://localhost/~dyoo/hello.py").read() >print urllib.urlopen("http://localhost/~dyoo/hello.py").read() >print urllib.urlopen("http://localhost/~dyoo/hello.py").read() >### > > >test1 uses the PageGrabber class we wrote earlier, and test2 uses a >straightforward approach. > > >If we start timing the perfomance of test1.py and test2.py, we do see a >difference between the two, since test1 will try to grab the pages in >parallel, while test2 will do it serially: > > >### >[dyoo@shoebox dyoo]$ time python test1.py > >hello world >goodbye world > > >hello world >goodbye world > > >hello world >goodbye world > > >real 0m5.106s >user 0m0.043s >sys 0m0.011s > >[dyoo@shoebox dyoo]$ time python test2.py > >hello world >goodbye world > > >hello world >goodbye world > > >hello world >goodbye world > > >real 0m15.107s >user 0m0.044s >sys 0m0.007s >### > > >So for this particular example, we're getting good results: test1 takes >about 5 seconds, while test2 takes 15. So the select() code is doing >pretty ok so far, and does show improvement over the straightforward >approach. Isn't this wonderful? *grin* > > >Well, there's bad news. > > >The problem is that, as you highlighted, the urllib.urlopen() function >itself can block, and that's actually a very bad problem in practice. In >particular, it blocks until it sees the end of the HTTP headers, since it >depends on Python's 'httplib' module. > >If we take out the flush() out of our hello.py CGI: > >### >#!/usr/bin/python >import time >import sys >print "Content-type: text/plain\n\n" >print "hello world"; >time.sleep(5) >print "goodbye world" >### > > >then suddenly things go horribly awry: > >### >[dyoo@shoebox dyoo]$ time python test1.py > >hello world >goodbye world > > >hello world >goodbye world > > >hello world >goodbye world > > >real 0m15.113s >user 0m0.047s >sys 0m0.006s >### > >And suddenly, we do no better than with the serial version! > > >What's happening is that the web server is buffering the output of its CGI >programs. Without the sys.stdout.flush(), it's likely that the web server >doesn't send out anything until the whole program is complete. But >because urllib.urlopen() returns only after seeing the header block from >the HTTP response, it actually ends up waiting until the whole program's >done. > > >Not all CGI's have been carefully written to output its HTTP headers in a >timely manner, so urllib.urlopen()'s blocking behavior is a show-stopper. >This highlights the need for a framework that's built with nonblocking, >event-driven code as a pervasive concept. Like... Twisted! *grin* > >Does anyone want to cook up an example with Twisted to show how the >page-grabbing example might work? > > > >Hope this helps! > > > > From orbitz at ezabel.com Wed Nov 17 03:06:44 2004 From: orbitz at ezabel.com (orbitz) Date: Wed Nov 17 03:06:57 2004 Subject: [Tutor] Threads In-Reply-To: <419AAE12.4000206@ezabel.com> References: <419AAE12.4000206@ezabel.com> Message-ID: <419AB234.5080205@ezabel.com> My apologies, should be len(URLS) not len(URLS) - 1 orbitz wrote: > Not only is things like waiting for headers a major issue, but simply > resolving the name and connecting. What if your DNS goes down in > mid-download. It could take a long time to timeout while trying to > connect to your DNS, and none of your sockets will be touched, select > or not. So if we are going to use blocking sockets we might as well > go all the way. > > Here is a simple twisted example of downloading 3 sites, printing them > to stdout, and exiting, it probably won't make much sense but it's > 100% non blocking at least:) > > from twisted.web import client > from twisted.Internet import reactor > > from urllib2 import urlparse > > def _handlePage(result): > """The result is the contents of the webpage""" > global num_downloaded > print result > num_downloaded += 1 > if num_downloaded == len(URLS) - 1: > reactor.stop() > > URLS = ['http://www.google.com/', 'http://www.yahoo.com/', > 'http://www.python.org/'] > num_downloaded = 0 > > for i in URLS: > parsed = urlparse.urlsplit(i) > f = client.HTTPClientFactory(parsed[2]) > f.host = parsed[1] > f.deferred.addCallback(_handlePage) > reactor.connectTCP(parsed[1], 80, f) > > reactor.run() > > > All this does is download each page, print it out, and when that many > url's has been processed, stop the program (reactor.stop). This does > not handle errors or any exceptional situations. > > Danny Yoo wrote: > >> On Tue, 16 Nov 2004, orbitz wrote: >> >> >> >>> urllib is blocking, so you can't really use it wiht non blocking code. >>> the urlopen functio could take awhile, and then even if data is on the >>> socket then it will still block for te read most likely which is not >>> going to help you. One is going to have to use a non blocking url >>> api in >>> order to make the most of their time. >>> >> >> >> >> Hi Orbitz, >> >> >> Hmmm! Yes, you're right: the sockets block by default. But, when we >> try >> to read() a block of data, select() can tell us which ones will >> immediately block and which ones won't. >> >> >> The real-world situation is actually a bit complicated. Let's do a test >> to make things more explicit and measurable. >> >> >> For this example, let's say that we have the following 'hello.py' CGI: >> >> ### >> #!/usr/bin/python >> import time >> import sys >> print "Content-type: text/plain\n\n" >> sys.stdout.flush() >> >> print "hello world"; >> time.sleep(5) >> print "goodbye world" >> ### >> >> >> I'll be accessing this cgi from the url >> "http://localhost/~dyoo/hello.py". >> I'm also using Apache 2.0 as my web server. Big note: there's a flush() >> after the content-stream header. This is intentional, and will be >> significant later on in this post. >> >> >> >> I then wrote the following two test programs: >> >> ### >> ## test1.py >> from grab_pages import PageGrabber >> from StringIO import StringIO >> pg = PageGrabber() >> f1, f2, f3 = StringIO(), StringIO(), StringIO() >> pg.add("http://localhost/~dyoo/hello.py", f1) >> pg.add("http://localhost/~dyoo/hello.py", f2) >> pg.add("http://localhost/~dyoo/hello.py", f3) >> pg.writeOutAllPages() >> print f1.getvalue() >> print f2.getvalue() >> print f3.getvalue() >> ### >> >> >> ### >> ## test2.py >> import urllib >> print urllib.urlopen("http://localhost/~dyoo/hello.py").read() >> print urllib.urlopen("http://localhost/~dyoo/hello.py").read() >> print urllib.urlopen("http://localhost/~dyoo/hello.py").read() >> ### >> >> >> test1 uses the PageGrabber class we wrote earlier, and test2 uses a >> straightforward approach. >> >> >> If we start timing the perfomance of test1.py and test2.py, we do see a >> difference between the two, since test1 will try to grab the pages in >> parallel, while test2 will do it serially: >> >> >> ### >> [dyoo@shoebox dyoo]$ time python test1.py >> >> hello world >> goodbye world >> >> >> hello world >> goodbye world >> >> >> hello world >> goodbye world >> >> >> real 0m5.106s >> user 0m0.043s >> sys 0m0.011s >> >> [dyoo@shoebox dyoo]$ time python test2.py >> >> hello world >> goodbye world >> >> >> hello world >> goodbye world >> >> >> hello world >> goodbye world >> >> >> real 0m15.107s >> user 0m0.044s >> sys 0m0.007s >> ### >> >> >> So for this particular example, we're getting good results: test1 takes >> about 5 seconds, while test2 takes 15. So the select() code is doing >> pretty ok so far, and does show improvement over the straightforward >> approach. Isn't this wonderful? *grin* >> >> >> Well, there's bad news. >> >> >> The problem is that, as you highlighted, the urllib.urlopen() function >> itself can block, and that's actually a very bad problem in >> practice. In >> particular, it blocks until it sees the end of the HTTP headers, >> since it >> depends on Python's 'httplib' module. >> >> If we take out the flush() out of our hello.py CGI: >> >> ### >> #!/usr/bin/python >> import time >> import sys >> print "Content-type: text/plain\n\n" >> print "hello world"; >> time.sleep(5) >> print "goodbye world" >> ### >> >> >> then suddenly things go horribly awry: >> >> ### >> [dyoo@shoebox dyoo]$ time python test1.py >> >> hello world >> goodbye world >> >> >> hello world >> goodbye world >> >> >> hello world >> goodbye world >> >> >> real 0m15.113s >> user 0m0.047s >> sys 0m0.006s >> ### >> >> And suddenly, we do no better than with the serial version! >> >> >> What's happening is that the web server is buffering the output of >> its CGI >> programs. Without the sys.stdout.flush(), it's likely that the web >> server >> doesn't send out anything until the whole program is complete. But >> because urllib.urlopen() returns only after seeing the header block from >> the HTTP response, it actually ends up waiting until the whole program's >> done. >> >> >> Not all CGI's have been carefully written to output its HTTP headers >> in a >> timely manner, so urllib.urlopen()'s blocking behavior is a >> show-stopper. >> This highlights the need for a framework that's built with nonblocking, >> event-driven code as a pervasive concept. Like... Twisted! *grin* >> >> Does anyone want to cook up an example with Twisted to show how the >> page-grabbing example might work? >> >> >> >> Hope this helps! >> >> >> >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From guillermo.fernandez.castellanos at gmail.com Wed Nov 17 03:20:38 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Wed Nov 17 03:20:45 2004 Subject: [Tutor] Implementing Genetic Algorithm in Python In-Reply-To: <20041116193546.20372.qmail@web53708.mail.yahoo.com> References: <20041116193546.20372.qmail@web53708.mail.yahoo.com> Message-ID: <7d7029e704111618204573b587@mail.gmail.com> After a quick googling, some libraries that implement genetic algorithms: http://www.scipy.org/ http://pygp.sourceforge.net/ http://geneticalgorithms.ai-depot.com/GeneticAlgorithms/1310.html http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/199121 I haven't tried them, so use at your own risk. My (little...) experience with GA comes from an implementation in python of a C++ algorithm of GP three years ago. if I remember well, it was quickly programmed but took a long time to run. I guess my code was not very optimized, and the use of one of the above libraries could speed up the process quite a bit. Regards, Guille On Tue, 16 Nov 2004 11:35:46 -0800 (PST), kumar s wrote: > Hello tutors, > In a recent publication by Journal of Biological > Chemistry, a group of scientists implemented gentic > algorithm to cluster a set of genes based on the > statistical values arising from measuring gene > expression values. I am very much interested in using > the identical approach on my own data to ask different > questions. > Is python suitable for implementing Genetic > Algorithms? Are there any libraries or modules that > are useful for implementing GAs. Is there any site > where I can get some information. I am interested in > knowing more from tutors. > > Thanks > Kumar. > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - Get yours free! > http://my.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From elrood_corrino_ii at yahoo.com Wed Nov 17 03:48:52 2004 From: elrood_corrino_ii at yahoo.com (Harov Satmandirvich) Date: Wed Nov 17 03:48:55 2004 Subject: [Tutor] Enter? Tab? Message-ID: <20041117024852.94707.qmail@web54001.mail.yahoo.com> I have been going through the Python tutorial and tried to reproduce one of its first examples: However, this didn't work. The only way I could get the prompt to display the above text like that was to hit TAB over and over again until the cursor advanced a line. Hitting ENTER, of course, enters the line as if it were a whole program and produces an error. And even when I used TAB for the spacing, the example program didn't work. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bill.mill at gmail.com Wed Nov 17 04:10:21 2004 From: bill.mill at gmail.com (Bill Mill) Date: Wed Nov 17 04:10:24 2004 Subject: [Tutor] Enter? Tab? In-Reply-To: <20041117024852.94707.qmail@web54001.mail.yahoo.com> References: <20041117024852.94707.qmail@web54001.mail.yahoo.com> Message-ID: <797fe3d40411161910734c67f7@mail.gmail.com> Where is this a python example and in what tutorial? Peace Bill Mill bill.mill at gmail.com On Tue, 16 Nov 2004 18:48:52 -0800 (PST), Harov Satmandirvich wrote: > I have been going through the Python tutorial and > tried to reproduce one of its first examples: > > > > > > > > > > However, this didn't work. The only way I could get > the prompt to display the above text like that was to > hit TAB over and over again until the cursor advanced > a line. Hitting ENTER, of course, enters the line as > if it were a whole program and produces an error. And > even when I used TAB for the spacing, the example > program didn't work. > > __________________________________________________ > 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 > From billburns at pennswoods.net Wed Nov 17 04:31:45 2004 From: billburns at pennswoods.net (Bill Burns) Date: Wed Nov 17 04:24:33 2004 Subject: [Tutor] Critique of program Message-ID: <200411162231.45730.billburns@pennswoods.net> Hello, I've written the program below and I'm wondering if anyone would be interested in taking a look at it for me? I'd like to know if I'm doing "things" correctly. I'm not a programmer. I found python several months ago and just started tooling around with it and I've not stopped yet :-) AFAIK, everything works correctly. The program does not error and the output is as expected. I'm just looking for tips on how I can improve it or for feedback if I've done something silly that should be done differently. I've only run this program on my Linux box so I have no idea if it works on Windows, sorry. I built the program using Qt Designer, PyQt and pyuic (to compile the interface). I haven't included the GUI file, I decided to drop it because my first post bounced (it was too big). I can supply the file if someone wants it or if it's necessary. You will see in the code below there are several places where I have replaced the line "if isinstance():" with "if hasattr():". After reading some posts on c.l.p, I got the feeling that it is better to use hasattr() instead of isinstance(). Is this correct?? You can find the posts I'm talking about by "googling" c.l.p for the phrase "isinstance considered harmful". Either way, I'm not really trying to check whether the object has a certain attribute that I desire, I just want to know if it's the object that I'm looking for. IOW, are you a lineEdit or are you a button, if you're a button then go away I only like lineEdits ;-) The code seems to work no matter which function I use. Also, I've commented out the report() function in my code. It's a work in progress...... I appriecate your feedback!! Thanks, Bill Burns #! /usr/bin/env python """ Pipe Volume Calc - calculates the water volume (in U.S. gallons) contained inside various types and sizes of pipe. The user selects a type of pipe, a size of pipe and then enters a length (in feet). Water volume is automatically calculated and displayed as the data is entered into the form. There's a GUI front-end which is separate from this module. I made the GUI using Qt Designer, PyQt and pyuic. The GUI is a tabbed dialog containing multiple lineEdits. Each lineEdit corresponds to a specific size of pipe, i.e., 1/2", 3/4", etc. Each tabbed page corresponds to a different type of pipe (steel, copper or PVC). The user selects the page containing the type of pipe and then enters the total footage. The first dictionary below (pipeDict) holds all the inside diameters (in inches) for the various pipes. The inside diameter (and length) are needed to calculate water volume. The lineEdit "groups" are broken out as follows: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? lineEdit1 ? -> lineEdit25 ? (standard steel pipe) ? ? ? ? lineEdit1_1 -> lineEdit25_1 (extra strong steel pipe) ? ? lineEdit1_2 -> lineEdit15_2 (type L copper pipe) ? ? ? lineEdit1_3 -> lineEdit13_3 (schedule 40 PVC pipe) ? ? ? lineEdit1_4 -> lineEdit13_4 (schedule 80 PVC pipe) """ ? ? pipeDict = \ {'lineEdit1': .622, 'lineEdit2': .824, 'lineEdit3': 1.049, 'lineEdit4': 1.38, 'lineEdit5': 1.61, 'lineEdit6': 2.067, 'lineEdit7': 2.469, 'lineEdit8': 3.068, 'lineEdit9': 3.548, 'lineEdit10': 4.026, 'lineEdit11': 5.047, 'lineEdit12': 6.065, 'lineEdit13': 7.981, 'lineEdit14': 10.02, 'lineEdit15': 12.00, 'lineEdit16': 13.25, 'lineEdit17': 15.25, 'lineEdit18': 17.25, 'lineEdit19': 19.25, 'lineEdit20': 21.25, 'lineEdit21': 23.25, 'lineEdit22': 29.25, 'lineEdit23': 35.25, 'lineEdit24': 41.25, 'lineEdit25': 47.25, 'lineEdit1_1': .546, 'lineEdit2_1': .742, 'lineEdit3_1': .957, 'lineEdit4_1': 1.278, 'lineEdit5_1': 1.50, 'lineEdit6_1': 1.939, 'lineEdit7_1': 2.323, 'lineEdit8_1': 2.90, 'lineEdit9_1': 3.364, 'lineEdit10_1': 3.826, 'lineEdit11_1': 4.813, 'lineEdit12_1': 5.761, 'lineEdit13_1': 7.625, 'lineEdit14_1': 9.75, 'lineEdit15_1': 11.75, 'lineEdit16_1': 13.00, 'lineEdit17_1': 15.00, 'lineEdit18_1': 17.00, 'lineEdit19_1': 19.00, 'lineEdit20_1': 21.00, 'lineEdit21_1': 23.00, 'lineEdit22_1': 29.00, 'lineEdit23_1': 35.00, 'lineEdit24_1': 41.00, 'lineEdit25_1': 47.50, 'lineEdit1_2': .585, 'lineEdit2_2': .830, 'lineEdit3_2': 1.075, 'lineEdit4_2': 1.32, 'lineEdit5_2': 1.565, 'lineEdit6_2': 2.055, 'lineEdit7_2': 2.545, 'lineEdit8_2': 3.035, 'lineEdit9_2': 3.525, 'lineEdit10_2': 4.015, 'lineEdit11_2': 5.00, 'lineEdit12_2': 5.985, 'lineEdit13_2': 7.925, 'lineEdit14_2': 9.875, 'lineEdit15_2': 11.845, ? 'lineEdit1_3': .731, 'lineEdit2_3': .937, 'lineEdit3_3': 1.182, 'lineEdit4_3': 1.52, 'lineEdit5_3': 1.755, 'lineEdit6_3': 2.221, 'lineEdit7_3': 2.672, 'lineEdit8_3': 3.284, 'lineEdit9_3': 4.263, 'lineEdit10_3': 6.345, 'lineEdit11_3': 8.303, 'lineEdit12_3': 10.385, 'lineEdit13_3': 12.344, 'lineEdit1_4': .693, 'lineEdit2_4': .896, 'lineEdit3_4': 1.136, 'lineEdit4_4': 1.469, 'lineEdit5_4': 1.70, 'lineEdit6_4': 2.157, 'lineEdit7_4': 2.599, 'lineEdit8_4': 3.20, 'lineEdit9_4': 4.163, 'lineEdit10_4': 6.193, 'lineEdit11_4': 8.125, 'lineEdit12_4': 10.157, 'lineEdit13_4': 12.063} """ This dictionary (sizeDict) holds all of the pipe sizes. Each size corresponds to a matching lineEdit on the GUI. I'm thinking I may use this dict to generate some kind of report. Something that the user can print out or save. I don't know if this is the right direction or not but I'll figure it out later! """ sizeDict = \ {'lineEdit1': '1/2"', 'lineEdit2': '3/4"', 'lineEdit3': '1"', 'lineEdit4': '1-1/4"', 'lineEdit5': '1-1/2"', 'lineEdit6': '2"', 'lineEdit7': '2-1/2"', 'lineEdit8': '3"', 'lineEdit9': '3-1/2"', 'lineEdit10': '4"', 'lineEdit11': '5"', 'lineEdit12': '6"', 'lineEdit13': '8"', 'lineEdit14': '10"', 'lineEdit15': '12"', 'lineEdit16': '14"', 'lineEdit17': '16"', 'lineEdit18': '18"', 'lineEdit19': '20"', 'lineEdit20': '22"', 'lineEdit21': '24"', 'lineEdit22': '30"', 'lineEdit23': '36"', 'lineEdit24': '42"', 'lineEdit25': '48"', 'lineEdit1_1': '1/2"', 'lineEdit2_1': '3/4"', 'lineEdit3_1': '1"', 'lineEdit4_1': '1-1/4"', 'lineEdit5_1': '1-1/2"', 'lineEdit6_1': '2"', 'lineEdit7_1': '2-1/2"', 'lineEdit8_1': '3"', 'lineEdit9_1': '3-1/2"', 'lineEdit10_1': '4"', 'lineEdit11_1': '5"', 'lineEdit12_1': '6"', 'lineEdit13_1': '8"', 'lineEdit14_1': '10"', 'lineEdit15_1': '12"', 'lineEdit16_1': '14"', 'lineEdit17_1': '16"', 'lineEdit18_1': '18"', 'lineEdit19_1': '20"', 'lineEdit20_1': '22"', 'lineEdit21_1': '24"', 'lineEdit22_1': '30"', 'lineEdit23_1': '36"', 'lineEdit24_1': '42"', 'lineEdit25_1': '48"', 'lineEdit1_2': '1/2"', 'lineEdit2_2': '3/4"', 'lineEdit3_2': '1"', 'lineEdit4_2': '1-1/4"', 'lineEdit5_2': '1-1/2"', 'lineEdit6_2': '2"', 'lineEdit7_2': '2-1/2"', 'lineEdit8_2': '3"', 'lineEdit9_2': '3-1/2"', 'lineEdit10_2': '4"', 'lineEdit11_2': '5"', 'lineEdit12_2': '6"', 'lineEdit13_2': '8"', 'lineEdit14_2': '10"', 'lineEdit15_2': '12"', ? 'lineEdit1_3': '1/2"', 'lineEdit2_3': '3/4"', 'lineEdit3_3': '1"', 'lineEdit4_3': '1-1/4"', 'lineEdit5_3': '1-1/2"', 'lineEdit6_3': '2"', 'lineEdit7_3': '2-1/2"', 'lineEdit8_3': '3"', 'lineEdit9_3': '4"', 'lineEdit10_3': '6"', 'lineEdit11_3': '8"', 'lineEdit12_3': '10"', 'lineEdit13_3': '12"', 'lineEdit1_4': '1/2"', 'lineEdit2_4': '3/4"', 'lineEdit3_4': '1"', 'lineEdit4_4': '1-1/4"', 'lineEdit5_4': '1-1/2"', 'lineEdit6_4': '2"', 'lineEdit7_4': '2-1/2"', 'lineEdit8_4': '3"', 'lineEdit9_4': '4"', 'lineEdit10_4': '6"', 'lineEdit11_4': '8"', 'lineEdit12_4': '10"', 'lineEdit13_4': '12"'} import sys import types from qt import * from pipeCalcGUI import PipeForm class PipeConnector(PipeForm): ? ? def __init__(self, parent=None): ? ? ? ?PipeForm.__init__(self, parent) ? ? ? ?self.connect(self.buttonClear,SIGNAL("clicked()"), self.clearLineEdits) ? ? ? ?self.connect(self.buttonExit,SIGNAL("clicked()"),self,SLOT("close()")) ? ? ? ?self.connect(self.buttonPrint,SIGNAL("clicked()"), self.report) ? ? ? ?self.lineEditTotal.setAlignment(QLineEdit.AlignRight) ? ? ? ? ? ? ? ?for name in self.__dict__: ? ? ? ? ? ?w = getattr(self, name) ? ? ? ? ? ?if name != "lineEditTotal": ? ? ? ? ? ? ? ?if hasattr(w, "displayText"): # if isinstance(w, QLineEdit): ? ? ? ? ? ? ? ? ? ?self.connect(w,SIGNAL("textChanged(const QString &)"), ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.calc) ? ? ? ? ? ? ? ? ? ?w.setAlignment(QLineEdit.AlignRight) ? ? ? ? ? ? ? ? ? ?validator=QIntValidator(0.00, 9999999.00, w) ? ? ? ? ? ? ? ? ? ?w.setValidator(validator) ? ? ? ? ? ? ? ? ? ? ? def report(self): ? ? ? ? pass ? ? ? ? """Maybe I can use some variation of this to build a dictionary ? ? ? ? ? ?that contains the values from sizeDict and the lengths that ? ? ? ? ? ?the user has entered. At some point in time, I'm going to want ? ? ? ? ? ?a nicely formatted report or print out. ? ? ? ? """ ? ? ? ? """ ? ? ? ? reportDict = {} ? ? ? ? for name in self.__dict__: ? ? ? ? ? ? w = getattr(self, name) ? ? ? ? ? ? if name != "lineEditTotal": ? ? ? ? ? ? ? ? if hasattr(w, "displayText"): # if isinstance(w, QLineEdit): ? ? ? ? ? ? ? ? ? ? length = w.displayText() ? ? ? ? ? ? ? ? ? ? if not length == "": ? ? ? ? ? ? ? ? ? ? ? ?length = int(str(length),10) ? ? ? ? ? ? ? ? ? ? ? ?#size = sizeDict[name] ? ? ? ? ? ? ? ? ? ? ? ?#reportDict[size] = length ? ? ? ? ? ? ? ? ? ? ? ?reportDict[name] = length ? ? ? ? print reportDict ? ? ? ? """ ? ? def calc(self): ? ? ? ? """First I create an empty list, then iterate through all the objects ? ? ? ? ? ?in self.__dict__, then "weed out" all of the objects / instances ? ? ? ? ? ?that are NOT lineEdits, grab the text from each lineEdit, skipping ? ? ? ? ? ?any lineEdit with and empty string, pull an inside diameter for ? ? ? ? ? ?each corresponding lineEdit from the dictionary, send that data ? ? ? ? ? ?to volCalc() to calculate gallons in the pipe, pop each gallon ? ? ? ? ? ?calculation on to the stack, send the data on the stack to add() ? ? ? ? ? ?to be summed and finally, set lineEditTotal to display the total ? ? ? ? ? ?gallons ? ? ? ? """ ? ? ? ? stack = [] ? ? ? ? for name in self.__dict__: ? ? ? ? ? ? w = getattr(self, name) ? ? ? ? ? ? if name != "lineEditTotal": ? ? ? ? ? ? ? ? if hasattr(w, "displayText"): #if isinstance(w, QLineEdit): ? ? ? ? ? ? ? ? ? ? length = w.displayText() ? ? ? ? ? ? ? ? ? ? if not length == "": ? ? ? ? ? ? ? ? ? ? ? ?length = int(str(length),10) ? ? ? ? ? ? ? ? ? ? ? ?ID = pipeDict[name] ? ? ? ? ? ? ? ? ? ? ? ?x = volCalc(ID, length) ? ? ? ? ? ? ? ? ? ? ? ?stack.append(x) ? ? ? ? total = add(stack) ? ? ? ? self.lineEditTotal.setText(total) ? ? ? def clearLineEdits(self): ? ? ? ? """Clears the data in every lineEdit ? ? ? ? """ ? ? ? ? for name in self.__dict__: ? ? ? ? ? ? w = getattr(self, name) ? ? ? ? ? ? if hasattr(w, "displayText"): # if isinstance(w, QLineEdit): ? ? ? ? ? ? ? ? w.clear() ? ? ? ? self.lineEditTotal.setText("") def volCalc(ID, length): ? ? """ Calculates the water volume inside of the pipe ? ? """ ? ? gal = ((ID*.5)**2)*3.14159265*(12*length)/(230.9429931) ? ? gal = "%0.2f" % gal ? ? return gal ? ? def add(args): ? ? """Sums all of the values on the stack ? ? """ ? ? sum = 0 ? ? for i in args: ? ? ? ? i = float(i) ? ? ? ? sum = sum + i ? ? sum = str(sum) ? ? return sum if __name__ == "__main__": ? ? app = QApplication(sys.argv) ? ? QObject.connect(app, SIGNAL("lastWindowClosed()"), ? ? ? ? ? ? ? ? ? ? app, SLOT("quit()")) ? ? win = PipeConnector() ? ? app.setMainWidget(win) ? ? win.show() ? ? app.exec_loop() From bill.mill at gmail.com Wed Nov 17 06:11:33 2004 From: bill.mill at gmail.com (Bill Mill) Date: Wed Nov 17 06:11:35 2004 Subject: [Tutor] Enter? Tab? In-Reply-To: <20041117035214.32042.qmail@web54006.mail.yahoo.com> References: <797fe3d40411161910734c67f7@mail.gmail.com> <20041117035214.32042.qmail@web54006.mail.yahoo.com> Message-ID: <797fe3d404111621112a9a873d@mail.gmail.com> Harov, That page isn't very clear. Alan, the author of that tutorial, reads this list, so I'm sure he'll jump into this discussion, but I'll offer my 2 cents. The file listed under the "javascript" heading is the javascript equivalent of this python program: ---Python code--- print "hello world" #tutorial should mention this explicitly, but doesn't --- end code --- Further below that is the VBscript equivalent of the same python program. They won't run in Python because they're not Python programs. Peace Bill Mill bill.mill at gmail.com On Tue, 16 Nov 2004 19:52:13 -0800 (PST), Harov Satmandirvich wrote: > This is the link, and it's the page called "getting > started". > > http://www.freenetpages.co.uk/hp/alan.gauld/ > > > > > --- Bill Mill wrote: > > > Where is this a python example and in what tutorial? > > > > Peace > > Bill Mill > > bill.mill at gmail.com > > > > > > On Tue, 16 Nov 2004 18:48:52 -0800 (PST), Harov > > Satmandirvich > > wrote: > > > I have been going through the Python tutorial and > > > tried to reproduce one of its first examples: > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > However, this didn't work. The only way I could > > get > > > the prompt to display the above text like that was > > to > > > hit TAB over and over again until the cursor > > advanced > > > a line. Hitting ENTER, of course, enters the line > > as > > > if it were a whole program and produces an error. > > And > > > even when I used TAB for the spacing, the example > > > program didn't work. > > > > > > __________________________________________________ > > > 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 > > > > > > > > __________________________________________________ > > > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > From naveed48 at wol.net.pk Wed Nov 17 07:07:26 2004 From: naveed48 at wol.net.pk (Naveed Ahmed Khan) Date: Wed Nov 17 07:08:05 2004 Subject: [Tutor] Dictionary command Message-ID: <200411170604.iAH64i5w009916@svmout.wol.net.pk> Dear friends, Thanks a lot for your help my problem is solved. Though I am afraid to tell you of my real blunder. I mean you must understand that it's my first time with programming. I was trying to achieve the following: >>> dict = {} >>> dict['boolean'] = "A value which is either true or false" >>> dict['integer'] = "A whole number" >>> print dict['boolean'] A value which is either true or false What I was doing was that I was writing dict = () instead of dict = {}, got it, I was using the wrong bracket. It's really embarrassing, but true. For the next time I will try to figure out how to copy the "Python command line screen" so that you can see exactly what I have done there. Thanks a lot again. Regards, NAK -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041117/47ca146b/attachment-0001.html From pan at uchicago.edu Wed Nov 17 09:00:15 2004 From: pan at uchicago.edu (pan@uchicago.edu) Date: Wed Nov 17 09:01:59 2004 Subject: [Tutor] Set/get doc strings of ALL attributes? In-Reply-To: <20041117060809.06A3E1E4012@bag.python.org> References: <20041117060809.06A3E1E4012@bag.python.org> Message-ID: <1100678415.419b050fb4b3e@webmail.uchicago.edu> Hi there, I've been wondering if there's a way to set/get doc string for ALL elements of a class (but not just the __doc__ of function/method). I ended writing a class BaseObject for this purpose. It stores doc strings of variables (that is, the that is assigned to a class using myclass.name). When asking for all docs, doc strings are collected from 3 different sources: 1) property __doc__; 2) the variables mentioned above; 3) function/method __doc__; It seems to work well. My questions: A) Will the above approach be able to cover all elements such that an automatic documentation mechinsm can be programmed? B) Is there any other better way to do this? C) I intend to use this class as the base class for all other subclass. Will this kind of design cause any problem in any class inherited from it? Thx in advance. pan Here's the code: class BaseObject(object): '''An extention of class object, have the capacity of storing/retrieving doc string for variables. Doc strings are retrievd from 3 different elements: variable (name), property, and method (or function). See the code in getDoc() for how to retrieve them. ''' def __init__(self): object.__init__(self) self.__docs__ ={'__docs__':'An internal dict storing doc' ' string of variables. Write: setattr(name, val, doc) or' ' setDoc(name, doc), read: getDoc(name) or getDocs().' ' Defined in class BaseObject.'} def setattr(self, name, val, doc=None): '''setattr(name, val, doc=None): set value and doc string of a variable . If doc=None, doc is not changed Defined in class BaseObject.''' if doc!=None: self.__docs__[name] = doc self.__setattr__(name,val) return self def setDoc(self, name, doc, checkName=1): '''setDoc(name, doc, checkName=1): Set doc string of variable. Defined in class BaseObject.''' if checkName and (name not in self.__dict__): pass else: self.__docs__[name] = doc def getDoc(self, name): '''getDoc(name): get the doc string of . Defined in BaseObject.''' fromProperty = lambda x: self.__class__.__dict__[x].__doc__ fromVariable = lambda x: self.__docs__[x] fromMethod = lambda x: getattr(self, x).__doc__.strip().replace('\n','') try: txt = fromProperty(name) except: try: txt = fromVariable(name) except: try: txt = fromMethod(name) except: txt = '' if txt==None or txt=='': return txt else: return re.sub('\s+', ' ', txt) def getDocs(self): '''getDocs(): return a dict representing the doc strings of all attributes(variables, properties, functions, methods...) of this class. Defined in BaseObject.''' dic = {} for x in dir(self): if not x.startswith('_'): dic[x] = self.getDoc(x) return dic class MyObj(BaseObject): def __init__(self): BaseObject.__init__(self) self.setattr('name', 'myobj', 'this is my obj') self._size=10 def setSize(self, size): self._size=size def getSize(self): return self._size size= property(getSize, setSize, None, 'Size of the object') def test(): mo = MyObj() x = mo.getDocs() print x text() From max_russell2000 at yahoo.co.uk Wed Nov 17 10:02:51 2004 From: max_russell2000 at yahoo.co.uk (Max Russell) Date: Wed Nov 17 10:02:54 2004 Subject: [Tutor] popularity Message-ID: <20041117090251.10717.qmail@web25401.mail.ukl.yahoo.com> If the increase in volume of mails to this list are any indication, Python must be really blossoming (as far as the programming public is concerned) about now. ___________________________________________________________ Moving house? Beach bar in Thailand? New Wardrobe? Win ?10k with Yahoo! Mail to make your dream a reality. Get Yahoo! Mail www.yahoo.co.uk/10k From philipasmith at blueyonder.co.uk Wed Nov 17 10:08:04 2004 From: philipasmith at blueyonder.co.uk (Phil Smith) Date: Wed Nov 17 10:08:06 2004 Subject: [Tutor] building c extensions Message-ID: <002001c4cc84$f2302f50$91c22252@Pandora> Hi I'm running activepython 2.3 under windows32 I'm using SWIG and Pyrex tp write extensions I'm trying to compile the c extensions with mingw/cygwin gcc but can't seem to get the python23 library to link - gcc just reports "undefined reference" to all the builtins Do I have to do something other than specifiy -L.....python23.lib????? Thanks Phil -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041117/bfbbc0ab/attachment.htm From revanna at mn.rr.com Wed Nov 17 10:41:06 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Wed Nov 17 10:41:27 2004 Subject: [Tutor] Critique of program In-Reply-To: <200411162231.45730.billburns@pennswoods.net> References: <200411162231.45730.billburns@pennswoods.net> Message-ID: <419B1CB2.7070307@mn.rr.com> Bill Burns wrote: Just a few observations: > def clearLineEdits(self): > """Clears the data in every lineEdit > """ > for name in self.__dict__: > w = getattr(self, name) > if hasattr(w, "displayText"): # if isinstance(w, QLineEdit): > w.clear() > self.lineEditTotal.setText("") You said: > I'm not really trying to check whether the object has a certain > attribute that I desire, I just want to know if it's the object that > I'm looking for. IOW, are you a lineEdit or are you a button, if > you're a button then go away I only like lineEdits ;-) Is it *likely* to be a lineEdit? Can you *DO* w.clear() on a button? If it's likely to be a lineEdit, and it's only possible to do w.clear() on a lineEdit, then you might want to use the "Better to ask forgiveness than permission" idiom of a try/except loop. Same with your other uses of hasattr. Something like (pseudocode): for name in self.__dict__: w = getattr(self, name) try w.clear() except TypeError: pass Or something like that... (It's morning and I haven't finished my second cup of tea yet...) > def volCalc(ID, length): > """ Calculates the water volume inside of the pipe > """ > gal = ((ID*.5)**2)*3.14159265*(12*length)/(230.9429931) > gal = "%0.2f" % gal > return gal You're going to be adding these things. It's already a float - so, leave it as such. Your presentation/reporting functions can deal with formatting stuff like the "0.2f"%gal. > def add(args): > """Sums all of the values on the stack > """ > sum = 0 > for i in args: > i = float(i) > sum = sum + i > sum = str(sum) > return sum There is a built-in sum as of Python 2.3 which is very fast. You may want to try using that instead. Also, same comment here as in volCalc: return a float. Your presentation/reporting functions can stringify it as necessary. HTH Anna From gew75 at hotmail.com Wed Nov 17 13:19:20 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Wed Nov 17 13:20:37 2004 Subject: [Tutor] popularity References: <20041117090251.10717.qmail@web25401.mail.ukl.yahoo.com> Message-ID: Try reading the newsgroup ;). Glen ----- Original Message ----- From: "Max Russell" To: Sent: Wednesday, November 17, 2004 8:02 PM Subject: [Tutor] popularity > If the increase in volume of mails to this list are > any indication, Python must be really blossoming (as > far as the programming public is concerned) about now. > > > > ___________________________________________________________ > Moving house? Beach bar in Thailand? New Wardrobe? Win ?10k with Yahoo! > Mail to make your dream a reality. > Get Yahoo! Mail www.yahoo.co.uk/10k > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From op73418 at mail.telepac.pt Wed Nov 17 13:31:04 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Nov 17 13:27:51 2004 Subject: [Tutor] Dictionary command In-Reply-To: <200411170604.iAH64i5w009916@svmout.wol.net.pk> References: <200411170604.iAH64i5w009916@svmout.wol.net.pk> Message-ID: <419B4488.6080400@mail.telepac.pt> Naveed Ahmed Khan wrote: [text snip] > > What I was doing was that I was writing dict = () instead of dict = {}, got > it, I was using the wrong bracket. > > It's really embarrassing, but true. > > For the next time I will try to figure out how to copy the "Python command > line screen" so that you can see exactly what I have done there. > Besides using {} brackets for dictionaries do *not* use dict for your own variables. dict is the name of the dictionary class object builtin as the following shows: >>> dict >>> With my best regards, G. Rodrigues From op73418 at mail.telepac.pt Wed Nov 17 13:52:36 2004 From: op73418 at mail.telepac.pt (=?UTF-8?B?R29uw6dhbG8gUm9kcmlndWVz?=) Date: Wed Nov 17 13:49:19 2004 Subject: [Tutor] Set/get doc strings of ALL attributes? In-Reply-To: <1100678415.419b050fb4b3e@webmail.uchicago.edu> References: <20041117060809.06A3E1E4012@bag.python.org> <1100678415.419b050fb4b3e@webmail.uchicago.edu> Message-ID: <419B4994.8000901@mail.telepac.pt> pan@uchicago.edu wrote: > Hi there, > > I've been wondering if there's a way to set/get doc string > for ALL elements of a class (but not just the __doc__ of > function/method). > No. Imagine the following: >>> class Test(object): ... clsAttrib = 1 ... >>> >>> Test >>> Test.clsAttrib 1 clsAttrib is simply an attribute with no attached __doc__. If you do want to attach docstring to simple attributes you have to "wrap" the attribute in what is called a descriptor. > I ended writing a class BaseObject for this purpose. It stores doc > strings of variables (that is, the that is assigned to a > class using myclass.name). When asking for all docs, doc strings > are collected from 3 different sources: > > 1) property __doc__; > 2) the variables mentioned above; > 3) function/method __doc__; > > It seems to work well. My questions: > > A) Will the above approach be able to cover all elements > such that an automatic documentation mechinsm can be > programmed? > Yes. > B) Is there any other better way to do this? > Yes -- see below. > C) I intend to use this class as the base class for all > other subclass. Will this kind of design cause any problem > in any class inherited from it? > Yes, because you do *not* want inheritance here -- see below. > Thx in advance. > pan > I have not tested your code, but I think it is not going to work, because there are (at least) two problems with it. Warning: we are dangerously entering metaclass programming, so I'm just going to go ahead without too many explanations. If you can't follow me just holler. > > Here's the code: > > class BaseObject(object): This is the first problem. Think about what you want to do: you want to control the setting of elements in *the class*. If you want to control the setting of attributes in an instance of some class you override __setattr__ of *the class*, in this case, the class of a class, so what you want is a *metaclass*. So it should be: class MetaCls(type): You have to alter some stuff below because of this, I'll leave that for now and jump to the second main problem. > '''An extention of class object, have the capacity of storing/retrieving > doc string for variables. Doc strings are retrievd from 3 different > elements: variable (name), property, and method (or function). See > the code in getDoc() for how to retrieve them. > ''' > def __init__(self): > object.__init__(self) > self.__docs__ ={'__docs__':'An internal dict storing doc' > ' string of variables. Write: setattr(name, val, doc) or' > ' setDoc(name, doc), read: getDoc(name) or getDocs().' > ' Defined in class BaseObject.'} > > def setattr(self, name, val, doc=None): > '''setattr(name, val, doc=None): set value and doc string > of a variable . If doc=None, doc is not changed > Defined in class BaseObject.''' > > if doc!=None: self.__docs__[name] = doc > self.__setattr__(name,val) > return self > This is the second problem: When you're doing an assignment as cls.attribute = value this ends up calling cls.__class__.__setattr__(name, val) Note the signature: the default value is never passed so the above will never work. What you want here is to *wrap* the attribute in a descriptor so that it can gain a docstring. Check the docs for a primer on descriptors. After it, if you have any doubts just holler. Note: This is already advanced stuff, so you may want to go at comp.lang.python for further help. With my best regards, G. Rodrigues From carroll at tjc.com Wed Nov 17 19:49:29 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed Nov 17 19:49:33 2004 Subject: [Tutor] Threads In-Reply-To: <1f7befae04111519063a3a3bcf@mail.gmail.com> Message-ID: Thanks to everyone for the ideas on using threads for my scraper app. I was unable to sleep last night (my wife snores), so having nothing better to do, I got up and played with Python. I was able to convert my serial download program to a threaded app pretty quickly. My first step was to discard the use of the list of lists, in which I was storing the URLs from which to download, in favor of a Queue object, and then continuing to process the entries the same way. Once that was done, I found it pretty straightforward to take the consumer part of the program and turn it into a thread. Great results. The serial approach took about 21 minutes to process 20 files; basically about a minute to generate the list of files, and then about a minute each for all the files. With my present threaded approach, using 4 threads, that's cut down to about 6 minutes: one minute to generate the list, and then five minutes for each thread to download five files each. Of course, increasing the number of threads made it even faster. I went up to six, but feel I'm being abusinve if I do more than about 4. I plan to go back and rework the part that generates the queue. As written, it first generates a list of URLs of pages to process, and then processes each of those pages; each page in turn has a URL pointing to the file I want to download. I'm going to rework this so that each page is processed as soon as identified, rather than identifying all 20, and the queue entry is immediately made. This would allow my consumer threads to begin work much earlier, rather than waiting the minute or so to build the queue in its entirety first. By the way, the shutdown method I chose was as we discussed yesterday: add an element to the queue with a shutdown flag on it. When a thread popped this element off the queue, it requeued it for the next thread to discover and shut down. Worked like a champ first time. I'm not a programmer any more, so having something work the first time is a pretty big deal for me these days! From STEVEN.M.FAULCONER at saic.com Wed Nov 17 20:51:04 2004 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Wed Nov 17 20:50:59 2004 Subject: [Tutor] Request for Project Message-ID: <207DA77D2384D411A48B0008C7095D810152B955@us-melbourne.mail.saic.com> Hello everyone, I've been doing Python programming for some time, and have succeeded in converting our developers to use it for all our scripting needs (Windows & Solaris). However, our need for converting/creating scripts as declined, mainly since we've done almost everything we can at the moment. So, I'm offering my time to a project, and I was hoping someone might have some suggestions for a good project to start working with. I'm moderately familiar with Python. I've only played with Tkinter for GUI creation, though, I've been wanting to do something with wxPython. I'd prefer a project that is intended to be multiplatform. Just something to keep my hand in it and continue my python education. I don't have an exact estimate for available time, but I'd guess it would be in the area of 10 hours a week or so. Feel free to send me a private message if you don't want your project discussed on the general list. Thanks! Steven Faulconer From x.ultimate at verizon.net Wed Nov 17 21:07:26 2004 From: x.ultimate at verizon.net (Joe Chiocchi) Date: Wed Nov 17 21:07:31 2004 Subject: [Tutor] Python Timer Message-ID: <20041117150726.49927c22.x.ultimate@verizon.net> Ok, so right now I am in the progress of writing it. I'm using ansi characters so that I can clear the line and stuff. Here is an example of just a counter..(counts up every second until u stop it) You have to make sure you run it python unbuffered mode. #!/usr/bin/python -u from time import sleep def ansi(str): return chr(27)+'['+str x = 0 while 1: x=x+1 print x, sleep(1) print ansi('0E')+ansi('K'), Ok so the plan is to integrate this into my timer. I just need to figure out how to compare it the time right now, and the time at which I want it to end. Thanks From tony at tcapp.com Wed Nov 17 21:56:53 2004 From: tony at tcapp.com (Tony Cappellini) Date: Wed Nov 17 21:46:45 2004 Subject: [Tutor] Using the structs module for the first time Message-ID: <20041117125345.Q93438@yamato.yamato.com> I've been able to get a string to unpack showing the correct values, I would like to display the unpacked values in hex. Is there a formatting code for the structs module to display the returned tuple from unpack() in hex, or do I have to manually post-process the data ? thanks From pythontut at pusspaws.net Wed Nov 17 21:58:51 2004 From: pythontut at pusspaws.net (Dave S) Date: Wed Nov 17 21:58:58 2004 Subject: [Tutor] .pth instead of PYTHONPATH Message-ID: <419BBB8B.8000902@pusspaws.net> Hi all, I have several scripts that are in separate directories, all under a 'gg1.3' directory I am pleased with the scripts but I now need some scripts to import others. I am working in '/home/dave/mygg/gg1.3/ftsd', but I need to import scripts from amongst others, /home/dave/mygg/gg1.3/logging where the script logger.py lives So I have created 'paths.pth' which contains the line '/home/dave/mygg/gg1.3/logging' & dropped it into '/home/dave/mygg/gg1.3/ftsd' When I execute ./ftsd, the line 'from logger import log' gives, bash-2.05b$ ./html_strip.py Traceback (most recent call last): File "./html_strip.py", line 12, in ? from logger import log ImportError: No module named logger bash-2.05b$ In the past I have used PYTHONPATH successfully, can anyone tell me where I am going wrong now ? Dave From pythonTutor at venix.com Wed Nov 17 23:03:59 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Wed Nov 17 23:04:05 2004 Subject: [Tutor] Using the structs module for the first time In-Reply-To: <20041117125345.Q93438@yamato.yamato.com> References: <20041117125345.Q93438@yamato.yamato.com> Message-ID: <1100729039.5476.51.camel@laptop.venix.com> Python's format string operater can do what you need. >>> '%x' % 128 '80' print ['%x' % x for x in unpacked_from_struct] provides a simple view. See the string formating section of the Library Reference for fancier options. On Wed, 2004-11-17 at 15:56, Tony Cappellini wrote: > I've been able to get a string to unpack showing the correct values, I > would like to display the unpacked values in hex. > > Is there a formatting code for the structs module to display the returned > tuple from unpack() in hex, or do I have to manually post-process the data > ? > > thanks > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From pythontut at pusspaws.net Wed Nov 17 23:38:49 2004 From: pythontut at pusspaws.net (Dave S) Date: Wed Nov 17 23:38:58 2004 Subject: [Tutor] .pth instead of PYTHONPATH In-Reply-To: <419BBB8B.8000902@pusspaws.net> References: <419BBB8B.8000902@pusspaws.net> Message-ID: <419BD2F9.2000501@pusspaws.net> Dave S wrote: > Hi all, > > I have several scripts that are in separate directories, all under a > 'gg1.3' directory > I am pleased with the scripts but I now need some scripts to import > others. > > I am working in '/home/dave/mygg/gg1.3/ftsd', but I need to import > scripts from amongst others, /home/dave/mygg/gg1.3/logging where the > script logger.py lives > > So I have created 'paths.pth' which contains the line > '/home/dave/mygg/gg1.3/logging' > & dropped it into '/home/dave/mygg/gg1.3/ftsd' > > When I execute ./ftsd, the line 'from logger import log' gives, > > bash-2.05b$ ./html_strip.py > Traceback (most recent call last): > File "./html_strip.py", line 12, in ? > from logger import log > ImportError: No module named logger > bash-2.05b$ > > In the past I have used PYTHONPATH successfully, can anyone tell me > where I am going wrong now ? > > Dave > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Dope :-[ , put it in /usr/lib/python2.3/site-packages & all is well Dave From marilyn at deliberate.com Wed Nov 17 23:50:03 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Nov 17 23:50:14 2004 Subject: [Tutor] Request for Project In-Reply-To: <207DA77D2384D411A48B0008C7095D810152B955@us-melbourne.mail.saic.com> Message-ID: Hi Steven, I've been thinking of a little C/Python project that the community might find useful, I know I would. Maybe it already exists, I don't know. How about a python daemon? The problem is that if you are calling python scripts from a very busy program, like a mail transfer agent, then you'll get lots of interpreters running at the same time and this doesn't scale at all well. The python daemon would read a socket for a command line and then some more input which would be input that would usually be found on stdin. It would import what it needs to run the python command and feed it the stdin it collected. A little C program to feed it, called py_it, would be called: py_it python_command arg1 arg2 < some_stdin The C program would talk to py_it via the socket and communicate the call and arguments and push in the some_stdin. If you don't know C, you could write both parts in python and then maybe someone (maybe me) would rewrite the py_it part in C. It's a nice little project, involving threads and sockets. ---- Another project would be to wrap the Clerk's library (which is a specialized data-base server for vote-keeping) and make a user interface for eVote. See http://www.sourceforge.net/projects/evote That's more pie-in-the-sky, but potentially important. Thanks for your offer Steven. I hope you find a juicy project. Marilyn Davis, Ph.D marilyn@deliberate.com -1 650 965-7121 Author of eVote(R)/Clerk http://www.deliberate.com On Wed, 17 Nov 2004, Faulconer, Steven M. wrote: > Hello everyone, > > I've been doing Python programming for some time, and have succeeded in > converting our developers to use it for all our scripting needs (Windows & > Solaris). However, our need for converting/creating scripts as declined, > mainly since we've done almost everything we can at the moment. > > So, I'm offering my time to a project, and I was hoping someone might have > some suggestions for a good project to start working with. I'm moderately > familiar with Python. I've only played with Tkinter for GUI creation, > though, I've been wanting to do something with wxPython. I'd prefer a > project that is intended to be multiplatform. Just something to keep my hand > in it and continue my python education. I don't have an exact estimate for > available time, but I'd guess it would be in the area of 10 hours a week or > so. > > Feel free to send me a private message if you don't want your project > discussed on the general list. Thanks! > > Steven Faulconer > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From tony at tcapp.com Thu Nov 18 00:01:01 2004 From: tony at tcapp.com (Tony Cappellini) Date: Wed Nov 17 23:50:53 2004 Subject: [Tutor] Using the structs module for the first time In-Reply-To: <1100729039.5476.51.camel@laptop.venix.com> References: <20041117125345.Q93438@yamato.yamato.com> <1100729039.5476.51.camel@laptop.venix.com> Message-ID: <20041117145834.D95280@yamato.yamato.com> Thanks Lloyd BAsed on your answer, I'll assume there's no way to have unpack() format the resulting tuple in hex, and that post-processing is the only way to get the results in hex. I had already looked in the library reference for formatting options for the struct module, but didn't see anything obvious. On Wed, 17 Nov 2004, Lloyd Kvam wrote: > Python's format string operater can do what you need. > >>> '%x' % 128 > '80' > > print ['%x' % x for x in unpacked_from_struct] > provides a simple view. > > See the string formating section of the Library Reference for fancier > options. > > On Wed, 2004-11-17 at 15:56, Tony Cappellini wrote: > > I've been able to get a string to unpack showing the correct values, I > > would like to display the unpacked values in hex. > > > > Is there a formatting code for the structs module to display the returned > > tuple from unpack() in hex, or do I have to manually post-process the data > > ? > > > > thanks > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp > > From rdm at rcblue.com Thu Nov 18 03:01:21 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Nov 18 03:01:37 2004 Subject: [Tutor] Python Timer In-Reply-To: <20041117150726.49927c22.x.ultimate@verizon.net> References: <20041117150726.49927c22.x.ultimate@verizon.net> Message-ID: <6.1.2.0.2.20041117175645.03d7dac0@rcblue.com> Joe, if you rely on time.sleep() in counting seconds, check out the inaccuracy that builds up: ======================= from time import sleep, time def ansi(str): return chr(27)+'['+str x = 0 startTime = time() while 1: x=x+1 print x, sleep(1) currentTime = time() print ansi('0E')+ansi('K'), print "%.3f" % (currentTime - startTime), ================================= Dick Joe Chiocchi wrote at 12:07 11/17/2004: >Ok, so right now I am in the progress of writing it. I'm using ansi >characters so that I can clear the line and stuff. Here is an example of >just a counter..(counts up every second until u stop it) >You have to make sure you run it python unbuffered mode. > >#!/usr/bin/python -u > >from time import sleep > >def ansi(str): > return chr(27)+'['+str >x = 0 >while 1: > x=x+1 > print x, > sleep(1) > print ansi('0E')+ansi('K'), > >Ok so the plan is to integrate this into my timer. I just need to figure >out how to compare it the time right now, and the time at which I want >it to end. > >Thanks >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From billburns at pennswoods.net Thu Nov 18 05:03:57 2004 From: billburns at pennswoods.net (Bill Burns) Date: Thu Nov 18 04:56:39 2004 Subject: [Tutor] Critique of program In-Reply-To: <419B1CB2.7070307@mn.rr.com> References: <200411162231.45730.billburns@pennswoods.net> <419B1CB2.7070307@mn.rr.com> Message-ID: <200411172303.57510.billburns@pennswoods.net> Anna, Thank you for your help! I appriecate it! I have made some of the changes that you suggested, please see below: You wrote: > Just a few observations: > > def clearLineEdits(self): > > """Clears the data in every lineEdit > > """ > > for name in self.__dict__: > > w = getattr(self, name) > > if hasattr(w, "displayText"): # if isinstance(w, QLineEdit): > > w.clear() > > self.lineEditTotal.setText("") > > You said: > > I'm not really trying to check whether the object has a certain > > attribute that I desire, I just want to know if it's the object that > > I'm looking for. IOW, are you a lineEdit or are you a button, if > > you're a button then go away I only like lineEdits ;-) > > Is it *likely* to be a lineEdit? Can you *DO* w.clear() on a button? If > it's likely to be a lineEdit, and it's only possible to do w.clear() on > a lineEdit, then you might want to use the "Better to ask forgiveness > than permission" idiom of a try/except loop. Same with your other uses > of hasattr. > > Something like (pseudocode): > > for name in self.__dict__: > w = getattr(self, name) > try w.clear() > except TypeError: > pass > > Or something like that... (It's morning and I haven't finished my second > cup of tea yet...) I took the pseudocode above and did this: for name in self.__dict__: w = getattr(self, name) try: w.clear() except TypeError: pass Upon executing the revised code, I received the following error: AttributeError: 'builtin_function_or_method' object has no attribute 'clear' I changed "except TypeError:" to except AttributeError:" and it worked, sort of....As it turns out, a QLabel also has a method clear() so not only did the revised code clear all of the lineEdits, it also cleared all of the labels on the form as well. It sure gives me a nice clean looking interface :-) As you had anticipated, as long as no other object had a clear() method, I would be O.K. So I'll work on this one. > > def volCalc(ID, length): > > """ Calculates the water volume inside of the pipe > > """ > > gal = ((ID*.5)**2)*3.14159265*(12*length)/(230.9429931) > > gal = "%0.2f" % gal > > return gal > > You're going to be adding these things. It's already a float - so, leave > it as such. Your presentation/reporting functions can deal with > formatting stuff like the "0.2f"%gal. I've removed the formatting as you suggested. Now I just take care of it right before it is displayed in lineEditTotal. > > def add(args): > > """Sums all of the values on the stack > > """ > > sum = 0 > > for i in args: > > i = float(i) > > sum = sum + i > > sum = str(sum) > > return sum > > There is a built-in sum as of Python 2.3 which is very fast. You may > want to try using that instead. Also, same comment here as in volCalc: > return a float. Your presentation/reporting functions can stringify it > as necessary. I had no idea that there was a built-in sum. I completely removed the add() function all together. Before I was using add() like this: total = add(stack) Now I'm using: total = sum(stack) which works like a charm, so I don't even need the add() function at all. Again, thank you for the help!! Bill From ET at cheminova.dk Thu Nov 18 07:56:33 2004 From: ET at cheminova.dk (Eivind Triel) Date: Thu Nov 18 11:05:30 2004 Subject: [Tutor] Recursive permutation Message-ID: <5B781258906020498D4E0EF8A79A38C70BB0C7@dk01a128.cheminova.com> Hi I am pusling withe a code that makes all the possible permutations of a string, not only the entire lenght of the string but also len(string) - 1 , -2 etc etc. Like this: Sting = 123 This give: ['1','2','3','12','13','21','23','31','32','123','132','213','231,'312', 321'] Well, I've found this code: #!/usr/bin/python import sys def tree(txt, result=''): if txt: for i in range(len(txt)): tree(txt[:i] + txt[i+1:], result + txt[i]) else: print result if __name__ == "__main__": tree(list(sys.argv[1])) #Bob Gailer #bgailer@[...].edu #303 442 2625 Thanx, Bob This code maks a permutation of the entire list (all the 3 digs), but how do I make the permutations of lower lists? Going one down i seems easy: Remove alle the element one at a time and make a permultation of the rest. But going two down - it's like: Remove [1,2] then [1,3] then [1, ..] then [2,3] then [2,..] then [3,4] then [3,..] etc etc. But what i going n'th down like? It seems to be som kind of combination but I just can't get i right. Well is there a nice code that will do the trick? -Eivind -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041118/d4970a52/attachment.htm From kent37 at tds.net Thu Nov 18 12:08:45 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Nov 18 12:08:48 2004 Subject: [Tutor] Critique of program In-Reply-To: <200411162231.45730.billburns@pennswoods.net> References: <200411162231.45730.billburns@pennswoods.net> Message-ID: <419C82BD.8030209@tds.net> Bill, To me, it seems a little strange to be using introspection every time you want a list of all the lineEdits. I think it would be more straightforward to keep a list of all the lineEdits with their attributes and iterate the list. This would avoid searching through self.__dict__ and trying to figure out what is in it. I'll try to sketch out this solution: Start with a list of everything you need to know about a lineEdit. This includes ID, OD and maybe the label you use on the form - pipes = [ ( '1/2"', .622), ('3/4"', .824), ('1"', 1.049), # etc ] You might divide this up into four pieces, one for each page. Now create the forms based on data in the list, and while you do it create a new list (or maybe a dict, if you ever need access to a data about a specific lineEdit) that keeps a reference to the lineEdit and the data about it: lineEdits = [] for od, id in pipes: lineEdit = ... # however you create this lineEdits.append( (lineEdit, od, id) ) # or maybe lineEdits[lineEdit] = (od, id) for a dict Now you calc loop looks like this: for w, od, id in lineEdits: length = w.displayText() if length: # Note: this is same as if not length == "" length = int(length) # No need for str or 10 x = volCalc(id, length) stack.append(x) and the clear loop is just for w, od, id in lineEdits: w.clear() Kent Bill Burns wrote: > You will see in the code below there are several places where I have > replaced the line "if isinstance():" with "if hasattr():". After reading some > posts on c.l.p, I got the feeling that it is better to use hasattr() instead > of isinstance(). Is this correct?? You can find the posts I'm talking about > by "googling" c.l.p for the phrase "isinstance considered harmful". > Either way, I'm not really trying to check whether the object has a certain > attribute that I desire, I just want to know if it's the object that I'm > looking for. IOW, are you a lineEdit or are you a button, if you're a button > then go away I only like lineEdits ;-) The code seems to work no matter which > function I use. > > #! /usr/bin/env python > > """ > Pipe Volume Calc - calculates the water volume (in U.S. gallons) contained > inside various types and sizes of pipe. > > The user selects a type of pipe, a size of pipe and then enters a length (in > feet). Water volume is automatically calculated and displayed as the data is > entered into the form. > > There's a GUI front-end which is separate from this module. I made the GUI > using Qt Designer, PyQt and pyuic. The GUI is a tabbed dialog containing > multiple lineEdits. Each lineEdit corresponds to a specific size of pipe, > i.e., 1/2", 3/4", etc. Each tabbed page corresponds to a different type of > pipe (steel, copper or PVC). The user selects the page containing the type > of pipe and then enters the total footage. > > The first dictionary below (pipeDict) holds all the inside diameters (in > inches) for the various pipes. The inside diameter (and length) are needed > to calculate water volume. > > The lineEdit "groups" are broken out as follows: > > lineEdit1 -> lineEdit25 (standard steel pipe) > lineEdit1_1 -> lineEdit25_1 (extra strong steel pipe) > lineEdit1_2 -> lineEdit15_2 (type L copper pipe) > lineEdit1_3 -> lineEdit13_3 (schedule 40 PVC pipe) > lineEdit1_4 -> lineEdit13_4 (schedule 80 PVC pipe) > """ > > pipeDict = \ > {'lineEdit1': .622, 'lineEdit2': .824, 'lineEdit3': 1.049, > 'lineEdit4': 1.38, 'lineEdit5': 1.61, 'lineEdit6': 2.067, > 'lineEdit7': 2.469, 'lineEdit8': 3.068, 'lineEdit9': 3.548, > 'lineEdit10': 4.026, 'lineEdit11': 5.047, 'lineEdit12': 6.065, > 'lineEdit13': 7.981, 'lineEdit14': 10.02, 'lineEdit15': 12.00, > 'lineEdit16': 13.25, 'lineEdit17': 15.25, 'lineEdit18': 17.25, > 'lineEdit19': 19.25, 'lineEdit20': 21.25, 'lineEdit21': 23.25, > 'lineEdit22': 29.25, 'lineEdit23': 35.25, 'lineEdit24': 41.25, > 'lineEdit25': 47.25, > > 'lineEdit1_1': .546, 'lineEdit2_1': .742, 'lineEdit3_1': .957, > 'lineEdit4_1': 1.278, 'lineEdit5_1': 1.50, 'lineEdit6_1': 1.939, > 'lineEdit7_1': 2.323, 'lineEdit8_1': 2.90, 'lineEdit9_1': 3.364, > 'lineEdit10_1': 3.826, 'lineEdit11_1': 4.813, 'lineEdit12_1': 5.761, > 'lineEdit13_1': 7.625, 'lineEdit14_1': 9.75, 'lineEdit15_1': 11.75, > 'lineEdit16_1': 13.00, 'lineEdit17_1': 15.00, 'lineEdit18_1': 17.00, > 'lineEdit19_1': 19.00, 'lineEdit20_1': 21.00, 'lineEdit21_1': 23.00, > 'lineEdit22_1': 29.00, 'lineEdit23_1': 35.00, 'lineEdit24_1': 41.00, > 'lineEdit25_1': 47.50, > > 'lineEdit1_2': .585, 'lineEdit2_2': .830, 'lineEdit3_2': 1.075, > 'lineEdit4_2': 1.32, 'lineEdit5_2': 1.565, 'lineEdit6_2': 2.055, > 'lineEdit7_2': 2.545, 'lineEdit8_2': 3.035, 'lineEdit9_2': 3.525, > 'lineEdit10_2': 4.015, 'lineEdit11_2': 5.00, 'lineEdit12_2': 5.985, > 'lineEdit13_2': 7.925, 'lineEdit14_2': 9.875, 'lineEdit15_2': 11.845, > > 'lineEdit1_3': .731, 'lineEdit2_3': .937, 'lineEdit3_3': 1.182, > 'lineEdit4_3': 1.52, 'lineEdit5_3': 1.755, 'lineEdit6_3': 2.221, > 'lineEdit7_3': 2.672, 'lineEdit8_3': 3.284, 'lineEdit9_3': 4.263, > 'lineEdit10_3': 6.345, 'lineEdit11_3': 8.303, 'lineEdit12_3': 10.385, > 'lineEdit13_3': 12.344, > > 'lineEdit1_4': .693, 'lineEdit2_4': .896, 'lineEdit3_4': 1.136, > 'lineEdit4_4': 1.469, 'lineEdit5_4': 1.70, 'lineEdit6_4': 2.157, > 'lineEdit7_4': 2.599, 'lineEdit8_4': 3.20, 'lineEdit9_4': 4.163, > 'lineEdit10_4': 6.193, 'lineEdit11_4': 8.125, 'lineEdit12_4': 10.157, > 'lineEdit13_4': 12.063} > > """ > This dictionary (sizeDict) holds all of the pipe sizes. Each size > corresponds to a matching lineEdit on the GUI. I'm thinking I may > use this dict to generate some kind of report. Something that the > user can print out or save. I don't know if this is the right > direction or not but I'll figure it out later! > """ > > sizeDict = \ > {'lineEdit1': '1/2"', 'lineEdit2': '3/4"', 'lineEdit3': '1"', > 'lineEdit4': '1-1/4"', 'lineEdit5': '1-1/2"', 'lineEdit6': '2"', > 'lineEdit7': '2-1/2"', 'lineEdit8': '3"', 'lineEdit9': '3-1/2"', > 'lineEdit10': '4"', 'lineEdit11': '5"', 'lineEdit12': '6"', > 'lineEdit13': '8"', 'lineEdit14': '10"', 'lineEdit15': '12"', > 'lineEdit16': '14"', 'lineEdit17': '16"', 'lineEdit18': '18"', > 'lineEdit19': '20"', 'lineEdit20': '22"', 'lineEdit21': '24"', > 'lineEdit22': '30"', 'lineEdit23': '36"', 'lineEdit24': '42"', > 'lineEdit25': '48"', > > 'lineEdit1_1': '1/2"', 'lineEdit2_1': '3/4"', 'lineEdit3_1': '1"', > 'lineEdit4_1': '1-1/4"', 'lineEdit5_1': '1-1/2"', 'lineEdit6_1': '2"', > 'lineEdit7_1': '2-1/2"', 'lineEdit8_1': '3"', 'lineEdit9_1': '3-1/2"', > 'lineEdit10_1': '4"', 'lineEdit11_1': '5"', 'lineEdit12_1': '6"', > 'lineEdit13_1': '8"', 'lineEdit14_1': '10"', 'lineEdit15_1': '12"', > 'lineEdit16_1': '14"', 'lineEdit17_1': '16"', 'lineEdit18_1': '18"', > 'lineEdit19_1': '20"', 'lineEdit20_1': '22"', 'lineEdit21_1': '24"', > 'lineEdit22_1': '30"', 'lineEdit23_1': '36"', 'lineEdit24_1': '42"', > 'lineEdit25_1': '48"', > > 'lineEdit1_2': '1/2"', 'lineEdit2_2': '3/4"', 'lineEdit3_2': '1"', > 'lineEdit4_2': '1-1/4"', 'lineEdit5_2': '1-1/2"', 'lineEdit6_2': '2"', > 'lineEdit7_2': '2-1/2"', 'lineEdit8_2': '3"', 'lineEdit9_2': '3-1/2"', > 'lineEdit10_2': '4"', 'lineEdit11_2': '5"', 'lineEdit12_2': '6"', > 'lineEdit13_2': '8"', 'lineEdit14_2': '10"', 'lineEdit15_2': '12"', > > 'lineEdit1_3': '1/2"', 'lineEdit2_3': '3/4"', 'lineEdit3_3': '1"', > 'lineEdit4_3': '1-1/4"', 'lineEdit5_3': '1-1/2"', 'lineEdit6_3': '2"', > 'lineEdit7_3': '2-1/2"', 'lineEdit8_3': '3"', 'lineEdit9_3': '4"', > 'lineEdit10_3': '6"', 'lineEdit11_3': '8"', 'lineEdit12_3': '10"', > 'lineEdit13_3': '12"', > > 'lineEdit1_4': '1/2"', 'lineEdit2_4': '3/4"', 'lineEdit3_4': '1"', > 'lineEdit4_4': '1-1/4"', 'lineEdit5_4': '1-1/2"', 'lineEdit6_4': '2"', > 'lineEdit7_4': '2-1/2"', 'lineEdit8_4': '3"', 'lineEdit9_4': '4"', > 'lineEdit10_4': '6"', 'lineEdit11_4': '8"', 'lineEdit12_4': '10"', > 'lineEdit13_4': '12"'} > > import sys > import types > from qt import * > > from pipeCalcGUI import PipeForm > > class PipeConnector(PipeForm): > def __init__(self, parent=None): > PipeForm.__init__(self, parent) > self.connect(self.buttonClear,SIGNAL("clicked()"), self.clearLineEdits) > self.connect(self.buttonExit,SIGNAL("clicked()"),self,SLOT("close()")) > self.connect(self.buttonPrint,SIGNAL("clicked()"), self.report) > self.lineEditTotal.setAlignment(QLineEdit.AlignRight) > > for name in self.__dict__: > w = getattr(self, name) > if name != "lineEditTotal": > if hasattr(w, "displayText"): # if isinstance(w, QLineEdit): > self.connect(w,SIGNAL("textChanged(const QString &)"), > self.calc) > w.setAlignment(QLineEdit.AlignRight) > validator=QIntValidator(0.00, 9999999.00, w) > w.setValidator(validator) > > def report(self): > pass > """Maybe I can use some variation of this to build a dictionary > that contains the values from sizeDict and the lengths that > the user has entered. At some point in time, I'm going to want > a nicely formatted report or print out. > """ > """ > reportDict = {} > for name in self.__dict__: > w = getattr(self, name) > if name != "lineEditTotal": > if hasattr(w, "displayText"): # if isinstance(w, QLineEdit): > length = w.displayText() > if not length == "": > length = int(str(length),10) > #size = sizeDict[name] > #reportDict[size] = length > reportDict[name] = length > print reportDict > """ > > def calc(self): > """First I create an empty list, then iterate through all the objects > in self.__dict__, then "weed out" all of the objects / instances > that are NOT lineEdits, grab the text from each lineEdit, skipping > any lineEdit with and empty string, pull an inside diameter for > each corresponding lineEdit from the dictionary, send that data > to volCalc() to calculate gallons in the pipe, pop each gallon > calculation on to the stack, send the data on the stack to add() > to be summed and finally, set lineEditTotal to display the total > gallons > """ > stack = [] > for name in self.__dict__: > w = getattr(self, name) > if name != "lineEditTotal": > if hasattr(w, "displayText"): #if isinstance(w, QLineEdit): > length = w.displayText() > if not length == "": > length = int(str(length),10) > ID = pipeDict[name] > x = volCalc(ID, length) > stack.append(x) > total = add(stack) > self.lineEditTotal.setText(total) > > def clearLineEdits(self): > """Clears the data in every lineEdit > """ > for name in self.__dict__: > w = getattr(self, name) > if hasattr(w, "displayText"): # if isinstance(w, QLineEdit): > w.clear() > self.lineEditTotal.setText("") > > def volCalc(ID, length): > """ Calculates the water volume inside of the pipe > """ > gal = ((ID*.5)**2)*3.14159265*(12*length)/(230.9429931) > gal = "%0.2f" % gal > return gal > > def add(args): > """Sums all of the values on the stack > """ > sum = 0 > for i in args: > i = float(i) > sum = sum + i > sum = str(sum) > return sum > > if __name__ == "__main__": > app = QApplication(sys.argv) > QObject.connect(app, SIGNAL("lastWindowClosed()"), > app, SLOT("quit()")) > win = PipeConnector() > app.setMainWidget(win) > win.show() > app.exec_loop() > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From billburns at pennswoods.net Thu Nov 18 13:13:03 2004 From: billburns at pennswoods.net (Bill Burns) Date: Thu Nov 18 13:05:44 2004 Subject: [Tutor] Critique of program In-Reply-To: <419C82BD.8030209@tds.net> References: <200411162231.45730.billburns@pennswoods.net> <419C82BD.8030209@tds.net> Message-ID: <200411180713.03479.billburns@pennswoods.net> On Thursday 18 November 2004 6:08 am, Kent Johnson wrote: > Bill, > > To me, it seems a little strange to be using introspection every time > you want a list of all the lineEdits. I think it would be more > straightforward to keep a list of all the lineEdits with their > attributes and iterate the list. This would avoid searching through > self.__dict__ and trying to figure out what is in it. > Introspection.........so that's what it's called. Yes, I also thought it was strange that I was doing self.__dict__ all over the place. I will take a look at making a list to store the lineEdit attributes/information. > I'll try to sketch out this solution: > > Start with a list of everything you need to know about a lineEdit. This > includes ID, OD and maybe the label you use on the form - > > pipes = [ > ( '1/2"', .622), > ('3/4"', .824), > ('1"', 1.049), > # etc > ] > > You might divide this up into four pieces, one for each page. Like you mention, I might need to split this into four pieces. I'm sure I will if I use a dict as many of the keys would be the same. Every type of pipe has a 1/2", 3/4", 1", etc. > > Now create the forms based on data in the list, and while you do it > create a new list (or maybe a dict, if you ever need access to a data > about a specific lineEdit) that keeps a reference to the lineEdit and > the data about it: > > lineEdits = [] > for od, id in pipes: > lineEdit = ... # however you create this > lineEdits.append( (lineEdit, od, id) ) > # or maybe lineEdits[lineEdit] = (od, id) for a dict > > Now you calc loop looks like this: > > for w, od, id in lineEdits: > length = w.displayText() > if length: # Note: this is same as if not length == "" > length = int(length) # No need for str or 10 > x = volCalc(id, length) > stack.append(x) > > and the clear loop is just > > for w, od, id in lineEdits: > w.clear() > > Kent > I'll try to make some of these changes tonight, after work. Thank you for your help! Bill From dimitri.dor at fssintl.com Thu Nov 18 13:55:39 2004 From: dimitri.dor at fssintl.com (Dimitri D'Or) Date: Thu Nov 18 13:56:01 2004 Subject: [Tutor] all elements equal in tuple or list Message-ID: <200411181355.39341.dimitri.dor@fssintl.com> Hello list, I'm quite new in the Python world and I'm coming from Matlab. I have a tuple (or a list) made itself of lists and I want to know if all lists in this tuple are equal. Is there a function to do that ? Clearly, I have : t=(a,b,c) wherein a,b and c are lists of equal size. (Note that the number of lists in the tuple is arbitrary). I want to know if all the lists in the tuple are equal. In Matlab, I simply use equal(A,B,C) or equal(D{:}) if D is a cell array containing A, B and C as cells. A suggestion for me ? Thank you, Dimitri From kent37 at tds.net Thu Nov 18 16:06:00 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Nov 18 16:06:07 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <200411181355.39341.dimitri.dor@fssintl.com> References: <200411181355.39341.dimitri.dor@fssintl.com> Message-ID: <419CBA58.6000209@tds.net> Here is one way to do it. It should work with any iterable (list, tuple...) whose elements can be compared with ==. It compares the first element of the iterable with each subsequent element. I thought of a couple other ways to do it but I like this one because it doesn't create any new data and it returns as soon as it finds a mismatch - it doesn't need to compare against the whole list. Kent def test(vals): if not vals: return True i = iter(vals) first = i.next() for item in i: if first != item: return False return True vals1 = [1, 1, 1, 1] vals2 = [1, 2, 1, 1] vals3 = [2, 1, 1, 1] print test(vals1) print test(vals2) print test(vals3) Dimitri D'Or wrote: > Hello list, > > I'm quite new in the Python world and I'm coming from Matlab. > > I have a tuple (or a list) made itself of lists and I want to know if all > lists in this tuple are equal. Is there a function to do that ? > > Clearly, I have : > t=(a,b,c) wherein a,b and c are lists of equal size. (Note that the number of > lists in the tuple is arbitrary). > I want to know if all the lists in the tuple are equal. > > In Matlab, I simply use equal(A,B,C) or equal(D{:}) if D is a cell array > containing A, B and C as cells. > > A suggestion for me ? > > Thank you, > > Dimitri > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bwinton at latte.ca Thu Nov 18 16:16:12 2004 From: bwinton at latte.ca (Blake Winton) Date: Thu Nov 18 16:16:17 2004 Subject: [Tutor] Recursive permutation In-Reply-To: <5B781258906020498D4E0EF8A79A38C70BB0C7@dk01a128.cheminova.com> References: <5B781258906020498D4E0EF8A79A38C70BB0C7@dk01a128.cheminova.com> Message-ID: <419CBCBC.4080205@latte.ca> Eivind Triel wrote: > Well is there a nice code that will do the trick? We've discussed this on the list before, so searching the archive for "list permutation recursive" should yield up some hits. (Sadly, it doesn't really give me anything. Maybe someone else on the Tutor list will post the thread title?) > This code maks a permutation of the entire list (all the 3 digs), but > how do I make the permutations of lower lists? > Going one down i seems easy: Remove alle the element one at a time and > make a permultation of the rest. But going two down... Perhaps it would be easier to start from the bottom, and build your way up? So, all the lists of length 0, then all the lists of length 1, etc, etc, until you get to all the lists of length len(input). > Like this: > Sting = 123 > This give: > ['1','2','3','12','13','21','23','31','32','123','132','213','231,'312',321'] I think you're missing the list of length 0 ('') in your output... Later, Blake. From bgailer at alum.rpi.edu Thu Nov 18 17:45:09 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Nov 18 17:43:13 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <419CBA58.6000209@tds.net> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> Message-ID: <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> At 08:06 AM 11/18/2004, Kent Johnson wrote: >Here is one way to do it. It should work with any iterable (list, >tuple...) whose elements can be compared with ==. It compares the first >element of the iterable with each subsequent element. I thought of a >couple other ways to do it but I like this one because it doesn't create >any new data and it returns as soon as it finds a mismatch - it doesn't >need to compare against the whole list. > >Kent > >def test(vals): > if not vals: return True > > i = iter(vals) > first = i.next() > for item in i: > if first != item: > return False > return True > >vals1 = [1, 1, 1, 1] >vals2 = [1, 2, 1, 1] >vals3 = [2, 1, 1, 1] > >print test(vals1) >print test(vals2) >print test(vals3) Would not the following be a bit simpler? def test(vals): if vals: for item in vals[1:]: if vals[0] != item: return False return True Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From kent37 at tds.net Thu Nov 18 18:15:43 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Nov 18 18:15:50 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> Message-ID: <419CD8BF.6060500@tds.net> Bob Gailer wrote: > At 08:06 AM 11/18/2004, Kent Johnson wrote: >> def test(vals): >> if not vals: return True >> >> i = iter(vals) >> first = i.next() >> for item in i: >> if first != item: >> return False >> return True >> >> vals1 = [1, 1, 1, 1] >> vals2 = [1, 2, 1, 1] >> vals3 = [2, 1, 1, 1] >> >> print test(vals1) >> print test(vals2) >> print test(vals3) > > > Would not the following be a bit simpler? > def test(vals): > if vals: > for item in vals[1:]: > if vals[0] != item: > return False > return True A little shorter, but it has to copy vals[1:] and it deferences vals[0] each time through the loop. You could write mine as def test(vals): if vals: i = iter(vals) first = i.next() for item in i: if first != item: return False return True and yours as def test(vals): if vals: first = vals[0] for item in vals[1:]: if first != item: return False return True which shows that they are very similar. For short lists, I doubt it makes much difference which one you use. For longer lists, I expect mine would have an edge but I haven't tested that assumption! Kent > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > From kyeser at gmail.com Thu Nov 18 18:48:41 2004 From: kyeser at gmail.com (Hee-Seng Kye) Date: Thu Nov 18 18:48:46 2004 Subject: [Tutor] Recursive permutation In-Reply-To: <5B781258906020498D4E0EF8A79A38C70BB0C7@dk01a128.cheminova.com> References: <5B781258906020498D4E0EF8A79A38C70BB0C7@dk01a128.cheminova.com> Message-ID: <122df2fa0411180948cb77b12@mail.gmail.com> You might find something useful at the following website: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 If this is not exactly what you are looking for, you can still use the search option there; I got quite a few by typing "permutation"! The subject of "permutation" was in fact discussed on this list before, but I'm not sure if it's exactly what you are looking for. The thread title was "Permutations?". Best, Kye From glingl at aon.at Thu Nov 18 19:01:00 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Nov 18 19:00:40 2004 Subject: [Tutor] Recursive permutation In-Reply-To: <5B781258906020498D4E0EF8A79A38C70BB0C7@dk01a128.cheminova.com> References: <5B781258906020498D4E0EF8A79A38C70BB0C7@dk01a128.cheminova.com> Message-ID: <419CE35C.8080004@aon.at> Eivind Triel schrieb: > Hi > > I am pusling withe a code that makes all the possible permutations of > a string, not only the entire lenght of the string but also > len(string) - 1 , -2 etc etc. > > Like this: > Sting = 123 > This give: > ['1','2','3','12','13','21','23','31','32','123','132','213','231,'312',321'] Hi Eivind! one way to accomplish this could be first to construct all "subset-strings" of the given string - in your example this would return ['','1','2','3','12','13','23','123'] Then you can apply your tree-function to each of these strings. Regards, Gregor > > Well, I've found this code: > > #!/usr/bin/python > import sys > > def tree(txt, result=''): > if txt: > for i in range(len(txt)): > tree(txt[:i] + txt[i+1:], result + txt[i]) > else: > print result > > if __name__ == "__main__": > tree(list(sys.argv[1])) > > #Bob Gailer > #bgailer@[...].edu > #303 442 2625 > > Thanx, Bob > > This code maks a permutation of the entire list (all the 3 digs), but > how do I make the permutations of lower lists? > Going one down i seems easy: Remove alle the element one at a time and > make a permultation of the rest. But going two down - it's like: > Remove [1,2] then [1,3] then [1, ..] then [2,3] then [2,..] then [3,4] > then [3,..] etc etc. > But what i going n'th down like? It seems to be som kind of > combination but I just can't get i right. > > Well is there a nice code that will do the trick? > > -Eivind > > > > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From jeff at ccvcorp.com Thu Nov 18 19:58:37 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Nov 18 19:54:56 2004 Subject: [Tutor] Critique of program In-Reply-To: <200411180713.03479.billburns@pennswoods.net> References: <200411162231.45730.billburns@pennswoods.net> <419C82BD.8030209@tds.net> <200411180713.03479.billburns@pennswoods.net> Message-ID: <419CF0DD.2020509@ccvcorp.com> Bill Burns wrote: >Like you mention, I might need to split this into four pieces. I'm sure I will >if I use a dict as many of the keys would be the same. Every type of pipe >has a 1/2", 3/4", 1", etc. > > Well, you could always key the dictionary with a tuple of (type, size). That should give you unique keys for each entry, right? And if you need to iterate through, instead of doing random lookups, they keys() list should sort (and filter) nicely... Jeff Shannon Technician/Programmer Credit International From pthorstenson at co.montezuma.co.us Thu Nov 18 23:24:24 2004 From: pthorstenson at co.montezuma.co.us (Patrick Thorstenson) Date: Thu Nov 18 23:24:04 2004 Subject: [Tutor] using a button to make a variable in Tk Message-ID: <000001c4cdbd$5bf125a0$8235a8c0@co.montezuma.co.us> I have a GUI in Tk with 2 buttons. I would like one button to make a variable called "abortcode" equal to 3 (text number) and have the other button make "abortcode" equal to 5. Then if abortcode equals "5" exit, or "3" continue with the script (it doesn't have to be 3 or 5). This last part I have - I just need to know how to make the variable equal to 3 or 5. OR is there an easier way to do this? Basically, this script in its entirety creates new parcels for our county. Before the final update process occurs, the program needs to allow the user to view the possible parcel updates and then decide to continue the process or abort the program. "Destroy" only kills the GUI but I need to exit the entire script. ##### from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="continue on and update parcels", fg="red", Abortcode = 3????) #this should = 3 self.button.pack(side=LEFT) self.stop = Button(frame, text="Stop the update process", fg="orange", Abortcode = 5????) #this should = 5 self.stop.pack(side=RIGHT) root = Tk() app = App(root) root.mainloop() #end test area abortcode = "5" if abortcodeb == "5": sys.exit else: gp.Rename_management(renametest_Copy_shp, Output_data_element__2_, "") #### Patrick Thorstenson GIS Specialist Montezuma County (970) 564-9298 pthorstenson@co.montezuma.co.us -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041118/f0949127/attachment.htm From billburns at pennswoods.net Fri Nov 19 00:32:00 2004 From: billburns at pennswoods.net (Bill Burns) Date: Fri Nov 19 00:24:40 2004 Subject: [Tutor] Critique of program In-Reply-To: <419CF0DD.2020509@ccvcorp.com> References: <200411162231.45730.billburns@pennswoods.net> <200411180713.03479.billburns@pennswoods.net> <419CF0DD.2020509@ccvcorp.com> Message-ID: <200411181832.00905.billburns@pennswoods.net> > Bill Burns wrote: > >Like you mention, I might need to split this into four pieces. I'm sure I > > will if I use a dict as many of the keys would be the same. Every type of > > pipe has a 1/2", 3/4", 1", etc. > > Well, you could always key the dictionary with a tuple of (type, size). > That should give you unique keys for each entry, right? And if you need > to iterate through, instead of doing random lookups, they keys() list > should sort (and filter) nicely... I hadn't even considered this. I was stuck in the mind set that I would need a dict that looked like this: pipeDict = {'1/2"': .622, '3/4"': .824, '1"': 1.049} But doing it as you mentioned, makes perfect sense.... pipeDict = \ {('steel','1/2"'): .622, ('steel','3/4"'): .824, ('steel','1"'):1.049} Now I can have one dict that contains all types & sizes of pipe. Thanks for the help. Bill From nage.ramy at mail.sy Fri Nov 19 10:17:09 2004 From: nage.ramy at mail.sy (Nagi Nablsi) Date: Fri Nov 19 01:12:28 2004 Subject: [Tutor] teaching Message-ID: <419DBA15.000003.01700@nagi-nablsi> Skipped content of type multipart/alternative-------------- next part -------------- This mail is probably spam. The original message has been attached along with this report, so you can recognize or block similar unwanted mail in future. See http://spamassassin.org/tag/ for more details. Content preview: Dear Sir I interested in python language , I want to learn it so would you please : tell me haw I can start if there any site teach me that , if there any books Best regards, Naji Nablsi Dear Sir I interested in python language , [...] Content analysis details: (5.20 points, 5 required) DEAR_SOMETHING (2.6 points) BODY: Contains 'Dear (something)' HTML_TAG_EXISTS_TBODY (0.5 points) BODY: HTML has "tbody" tag HTML_80_90 (0.5 points) BODY: Message is 80% to 90% HTML HTML_MESSAGE (0.1 points) BODY: HTML included in message DATE_IN_FUTURE_06_12 (1.5 points) Date: is 6 to 12 hours after Received: date From tmclaughlin at csu.edu.au Fri Nov 19 01:40:58 2004 From: tmclaughlin at csu.edu.au (McLaughlin, Toby) Date: Fri Nov 19 01:41:09 2004 Subject: [Tutor] Debugging in emacs Message-ID: <211F78EFD1D870409CC3E4158F4881DA08B32E26@xcww01.riv.csu.edu.au> Hi All, Could somebody suggest a way to debug python in emacs? I'd like to be able to single-step while seeing the code marked in some way and possiblly set breakpoints. I read about using pdb from the command line but would love to have debugging integrated in emacs. Perhaps I should make life easy for myself and use one of the fancy GUI editors, but I think it's character building for me to learn emacs. Thanks, Toby McLaughlin. From bvande at po-box.mcgill.ca Fri Nov 19 02:04:33 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Nov 19 02:06:14 2004 Subject: [Tutor] file in use oddness with Python 2.3.4 and IDLE 1.0.3 on WinMe Message-ID: <419D46A1.3050207@po-box.mcgill.ca> Hi all, I've got something I cannot work out. I am using Python 2.3.4 on WinME and IDLE 1.03. I've previously written (and made much successful use of) the following utility functions: def writer(full_file_path, contents): '''writes contents to file and closes it when done. Given a full file path (or a file name in which case the current working directory is assumed) and a list of file contents, writer() writelines the contents to the file and closes it. ''' result_file = open(full_file_path, 'w') result_file.writelines(contents) result_file.close() def reader(full_file_path): '''-> file_contents (as a list) Given a full file path (or a file name in the current working directory), reader() uses the readlines() method of file objects to read the lines into a list, closes the file, and then returns the list. ''' the_file_to_read = open(full_file_path, 'r') file_contents = the_file_to_read.readlines() the_file_to_read.close() return file_contents (Note the calls to file.close() in both functions ) The program I'm currently working on uses the writer() function to write a simple log file if a call to os.rename() raises an OSError Exception (which is expected and caused by the destination filepath of the os.rename call already existing). Before using writer(), it checks if the file exists, and, if it does, uses reader() so as to preserve its contents. The only other contact my program has with the file is that if it existed before the program was run, it will be part of a list returned by a call to os.listdir(). Several times when running my program, and after the program had ended, the file created by the call to writer() could not be deleted -- I got the standard Windows "This file is in use by another process" (or however the standard one is worded) message. This has happened only when running my program through IDLE, and only intermittently there. I have tried it in succession with the system unaltered and all of the data used by my program exactly the same. Sometimes I get that Windows error message, and sometimes not. Whenever I do, I need to shut IDLE down before I can delete the writer() created file. I know that my program exits cleanly, and IDLE sits there happily waiting for the next thing I want to do. From the Python command line and SciTE, I ran the program 10'ish times each, without the problem manifesting itself. With IDLE, it seems to pop up ever 3-4 program runs. I had noticed that some of the times where the Windows error occurred, the writer() written file was being viewed either by Firefox or by a text editor. Even though that has never been a problem before, I checked and was able to replicate when I made certain that there was no other application viewing the file. My writer() and reader() functions look good to me, and have never caused my troubles before. So, I'm stumped. Anyone have an idea what might be the trouble? It's not critical for my program, but questions like this nag at me. Best to all, Brian vdB From keridee at jayco.net Fri Nov 19 02:29:57 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Nov 19 02:30:56 2004 Subject: [Tutor] how do i use p2exe References: <1033bb7f041109191055f46aee@mail.gmail.com><00e701c4c6d9$ac052e00$db5428cf@JSLAPTOP><6.1.2.0.2.20041112042711.08269eb0@rcblue.com><002501c4ca69$62a69e40$065428cf@JSLAPTOP> <6.1.2.0.2.20041114234942.04cc5eb0@rcblue.com> Message-ID: <004f01c4cdd7$539a9980$8d5328cf@JSLAPTOP> Thanks for replying to my correction, Dick. Kent, Thanks for clearing us all up. To anyone else, feel free to use the same automation technique that I gave Dick! I would be honored! Jacob Schmidt From rdm at rcblue.com Fri Nov 19 02:57:25 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Nov 19 02:57:30 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <419CD8BF.6060500@tds.net> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> <419CD8BF.6060500@tds.net> Message-ID: <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> Kent, I'm having trouble getting my mind around this. Why do you use "if vals"? Thanks, Dick Kent Johnson wrote at 09:15 11/18/2004: >def test(vals): > if vals: > i = iter(vals) > first = i.next() > for item in i: > if first != item: > return False > return True From keridee at jayco.net Fri Nov 19 03:13:00 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Nov 19 03:14:16 2004 Subject: [Tutor] multidemisional arrays References: <000601c4c9c4$a53196c0$121c8645@oemcomputer> <1100381951.21480.73.camel@laptop.venix.com> Message-ID: <007901c4cddd$66eab1e0$8d5328cf@JSLAPTOP> I'm surprised that nobody has corrected the excessive code involved in the first loop. >i=0 >howMany=input('How many artists will you enter? ') >paintings=[]#painting >artists=[]#artist >values=[]#value >for i in range(0,howMany,1): > painting=raw_input('Painting Name ') > artist=raw_input('Artist Name ') > value=input('Painting Value ') > paintings+=[painting] > artists+=[artist] > values+=[value] > artists=zip(artists,paintings,values) > artists.sort() > i=i+1 You do not need to define i as 0, you do not need to increment i at the end of loop, that is what for i in range(0,howMany,1): means. Also, you can shorten that to: for i in range(howMany): >n=0 >for n in range(0,howMany,1): > print artists[n] If you want to figure this out as a learning experience, DO NOT READ ANY FURTHER!!! I would do this. def rfill(stri,length): if len(stri) < length: stri = stri+' '*(length-len(stri)) return stri howMany = input('How many artists will you enter? ') artists = {} for i in range(howMany): artist = raw_input('Who is the artist? ') painting = raw_input('What is the painting called? ') value = raw_input('What is the value of the painting? ') artists[artist] = (painting,value) artists.keys().sort() l = 15 a = rfill("Artist",l) p = rfill("Painting",l) v = rfill("Value",l) print "".join([a,p,v]) for x in artists.keys(): a = rfill(x,l) p = rfill(artists[x][0],l) v = rfill(artists[x][1],l) print "".join([a,p,v]) From keridee at jayco.net Fri Nov 19 03:24:32 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Nov 19 03:25:00 2004 Subject: [Tutor] all elements equal in tuple or list References: <200411181355.39341.dimitri.dor@fssintl.com><419CBA58.6000209@tds.net><6.1.2.0.0.20041118093916.04d94220@mail.mric.net><419CD8BF.6060500@tds.net> <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> Message-ID: <008201c4cdde$ebd5fd00$8d5328cf@JSLAPTOP> My name's not Kent, but... >def test(vals): > if vals: > i = iter(vals) > first = i.next() > for item in i: > if first != item: > return False > return True The if vals: is an interesting idea... If no comparison operators are entered after a variable, the interpreter automatically checks to see if the variable returns true. So if vals returns true, then the code block beneath it is executed. Otherwise, the function returns True. All that does is check to see that vals is not an empty list. (Therefore returning False) Empty tuples,lists,dictionaries,strings,etc. return False ex. (),[],{},"" If they have anything in them, they return True ex. (''),["hello"],{"Jacob",3},"A" Nonzero integers,floats,complex numbers,Long integers, etc. return True All others return True From kent37 at tds.net Fri Nov 19 03:28:33 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 19 03:28:37 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> <419CD8BF.6060500@tds.net> <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> Message-ID: <419D5A51.4050608@tds.net> The rest of the algorithm will fail if vals is None or an empty list or tuple. But an empty list, especially, should return True - all of the elements are the same. Both None and [] evaluate to False in a conditional so this skips the rest of the algoritm in those cases. It will also return true if vals is the number 0 so maybe it is a bit over broad, but anyway that is the idea. In general anything empty or 0 will evaluate to False in a conditional. Kent Dick Moores wrote: > Kent, I'm having trouble getting my mind around this. Why do you use "if > vals"? > > Thanks, > > Dick > > Kent Johnson wrote at 09:15 11/18/2004: > >> def test(vals): >> if vals: >> i = iter(vals) >> first = i.next() >> for item in i: >> if first != item: >> return False >> return True > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Fri Nov 19 03:53:27 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Nov 19 03:54:12 2004 Subject: [Tutor] teaching References: <419DBA15.000003.01700@nagi-nablsi> Message-ID: <010101c4cde2$fc69ed80$8d5328cf@JSLAPTOP> Search on Google search engine or some other search engine for "Python Tutorial" or something similar. You should get quite a bit of results. From kent37 at tds.net Fri Nov 19 03:58:43 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 19 03:58:48 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <419D5A51.4050608@tds.net> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> <419CD8BF.6060500@tds.net> <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> <419D5A51.4050608@tds.net> Message-ID: <419D6163.5010502@tds.net> Kent Johnson wrote: > It will also return true if vals is the number 0 so maybe it is a bit > over broad, but anyway that is the idea. I decided to write a version of this that behaves 'correctly' for all inputs. What 'correct' means to me is, if the input is not iterable, the function raises an exception; if the input is an empty iterable, the function returns True; otherwise it compares the first element to all the others and reports the result. To test for an iterable, I use the typical Python 'Easier to ask forgiveness than permission' idiom - rather than trying to figure out if vals is iterable, I just try to get an iterator from it. If it fails I let the exception propagate out of the function. To allow for empty iterables, I catch the StopIteration that i.next() will raise and just return True. For good measure I threw in some unit tests - everyone reading this list should be learning how to write unit tests, right? :-) OK maybe I got a little carried away on the unit tests... Kent ##############################3 import itertools, unittest def allTheSame(vals): ''' Test if vals is an iterable whose elements are all equal. ''' i = iter(vals) # Raises TypeError if vals is not a sequence try: first = i.next() except StopIteration: # vals is an empty sequence return True for item in i: if first != item: return False return True if __name__ == '__main__': class Test(unittest.TestCase): def testLists(self): self.assert_(allTheSame([])) self.assert_(allTheSame([1])) self.assert_(allTheSame([1, 1, 1, 1])) self.failIf(allTheSame([1, 1, 2, 1])) self.failIf(allTheSame([2, 1, 1])) def testTuples(self): self.assert_(allTheSame(())) self.assert_(allTheSame((1,))) self.assert_(allTheSame((1, 1, 1, 1))) self.failIf(allTheSame((1, 1, 2, 1))) self.failIf(allTheSame((2, 1, 1))) def testStrings(self): self.assert_(allTheSame("")) self.assert_(allTheSame("1")) self.assert_(allTheSame("1111")) self.failIf(allTheSame("1121")) self.failIf(allTheSame("211")) def testDicts(self): # dicts are iterable too self.assert_(allTheSame( {} )) self.assert_(allTheSame( { 1:1, 1:1 })) self.failIf(allTheSame( { 1:1, 2:2 } )) def testNonSequence(self): self.assertRaises(TypeError, allTheSame, None) self.assertRaises(TypeError, allTheSame, 0) self.assertRaises(TypeError, allTheSame, 0.0) unittest.main() From kent37 at tds.net Fri Nov 19 03:59:13 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 19 03:59:18 2004 Subject: [Tutor] teaching In-Reply-To: <419DBA15.000003.01700@nagi-nablsi> References: <419DBA15.000003.01700@nagi-nablsi> Message-ID: <419D6181.9030201@tds.net> The documentation page at http://www.python.org/doc/ has links to beginners material and book lists. Kent Nagi Nablsi wrote: > Dear Sir > > I interested in python language , > > I want to learn it so would you please : > > tell me haw I can start > > if there any site teach me that , > > if there any books > > Best regards, > > Naji Nablsi > > > ------------------------------------------------------------------------ > > This mail is probably spam. The original message has been attached > along with this report, so you can recognize or block similar unwanted > mail in future. See http://spamassassin.org/tag/ for more details. > > Content preview: Dear Sir I interested in python language , I want to > learn it so would you please : tell me haw I can start if there any > site teach me that , if there any books Best regards, Naji Nablsi Dear > Sir I interested in python language , [...] > > Content analysis details: (5.20 points, 5 required) > DEAR_SOMETHING (2.6 points) BODY: Contains 'Dear (something)' > HTML_TAG_EXISTS_TBODY (0.5 points) BODY: HTML has "tbody" tag > HTML_80_90 (0.5 points) BODY: Message is 80% to 90% HTML > HTML_MESSAGE (0.1 points) BODY: HTML included in message > DATE_IN_FUTURE_06_12 (1.5 points) Date: is 6 to 12 hours after Received: date > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From jeff at ccvcorp.com Fri Nov 19 04:15:24 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Nov 19 04:11:43 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <419D6163.5010502@tds.net> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> <419CD8BF.6060500@tds.net> <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> <419D5A51.4050608@tds.net> <419D6163.5010502@tds.net> Message-ID: <419D654C.3030202@ccvcorp.com> Kent Johnson wrote: > Kent Johnson wrote: > >> It will also return true if vals is the number 0 so maybe it is a bit >> over broad, but anyway that is the idea. > > > I decided to write a version of this that behaves 'correctly' for all > inputs. What 'correct' means to me is, if the input is not iterable, > the function raises an exception; if the input is an empty iterable, > the function returns True; otherwise it compares the first element to > all the others and reports the result. So what's the result if you pass in an iterable of length 1? I *think* (from eyeballing -- I'm too lazy to type it in and try it ;) ) that it will return True, and it seems to me that that is probably the correct behavior (especially if it's correct for a zero-length iterable), but it's a corner case that probably deserves some mention. Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Fri Nov 19 04:23:00 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Nov 19 04:19:21 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <419D654C.3030202@ccvcorp.com> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> <419CD8BF.6060500@tds.net> <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> <419D5A51.4050608@tds.net> <419D6163.5010502@tds.net> <419D654C.3030202@ccvcorp.com> Message-ID: <419D6714.6060908@ccvcorp.com> Jeff Shannon wrote: > Kent Johnson wrote: > >> I decided to write a version of this that behaves 'correctly' for all >> inputs. What 'correct' means to me is, if the input is not iterable, >> the function raises an exception; if the input is an empty iterable, >> the function returns True; otherwise it compares the first element to >> all the others and reports the result. > > > So what's the result if you pass in an iterable of length 1? > > I *think* (from eyeballing -- I'm too lazy to type it in and try it ;) > ) that it will return True, and it seems to me that that is probably > the correct behavior (especially if it's correct for a zero-length > iterable), but it's a corner case that probably deserves some mention. Nevermind, looking a little closer now I see that this is covered in your unit tests. (And that you are, indeed, expecting it to behave in the same way that I did.) Jeff Shannon Technician/Programmer Credit International From bgailer at alum.rpi.edu Fri Nov 19 07:45:48 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Nov 19 07:43:56 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <008201c4cdde$ebd5fd00$8d5328cf@JSLAPTOP> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> <419CD8BF.6060500@tds.net> <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> <008201c4cdde$ebd5fd00$8d5328cf@JSLAPTOP> Message-ID: <6.1.2.0.0.20041118234055.04927440@mail.mric.net> At 07:24 PM 11/18/2004, Jacob S. wrote: >My name's not Kent, but... > > >def test(vals): > > if vals: > > i = iter(vals) > > first = i.next() > > for item in i: > > if first != item: > > return False > > return True > >The if vals: is an interesting idea... If no comparison operators are >entered after a variable, the interpreter automatically checks to see if the >variable returns true. So if vals returns true, then the code block beneath >it is executed. To be more explicit (quoting from the manual) "when expressions are used by control flow statements, the following values are interpreted as false: None, numeric zero of all types, empty sequences (strings, tuples and lists), and empty mappings (dictionaries). All other values are interpreted as true." Whatever follows - if - is taken as an expression, evaluated, then interpreted as stated above. The reason for doing this is: if vals is an empty sequence, iter(vals) will raise the StopIteration exception. >Otherwise, the function returns True. >All that does is check to see that vals is not an empty list. (Therefore >returning False) > >Empty tuples,lists,dictionaries,strings,etc. return False ex. (),[],{},"" >If they have anything in them, they return True ex. >(''),["hello"],{"Jacob",3},"A" > >Nonzero integers,floats,complex numbers,Long integers, etc. return True >All others return True > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From mehmety at carramar.auslin.com.au Fri Nov 19 08:53:08 2004 From: mehmety at carramar.auslin.com.au (Mehmet Yousouf) Date: Fri Nov 19 08:53:20 2004 Subject: [Tutor] Python script to change a password in linux Message-ID: Hi, I've been trying to write some functions to administer users? on our "mailserver" at home (an interesting way to learn python and zope...) I have the functions for adding and deleting users, however, I can't get the function for changing a password to work the way I want (I can write to a file "userid:password" strings and run a cron job to update the passwords using chpasswd which would no doubt be safer, but.....) Can someone tell me why this line does not work? def userChangePass(userid, password) ??? import os ??? import sys ??? os.system('echo %s:%s | sudo /usr/sbin/chpasswd -p' % (userid, password) ) Regards, Mehmet -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041119/6c5f1373/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Nov 19 10:21:41 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 19 10:21:48 2004 Subject: [Tutor] teaching In-Reply-To: <419D6181.9030201@tds.net> Message-ID: > The documentation page at http://www.python.org/doc/ has links to > beginners material and book lists. Hi Nagi, Just wanted to add to Kent's web link. Python.org also hosts a page that collects resources for beginners: http://www.python.org/moin/BeginnersGuide The tutorials at: http://www.python.org/moin/BeginnersGuide_2fNonProgrammers may be useful to start learning the Python language. You are also welcome to ask questions on this mailing list; many of us are learning the language, and are happy to share advice. From rschroev_nospam_ml at fastmail.fm Fri Nov 19 11:23:20 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Nov 19 11:23:33 2004 Subject: [Tutor] Re: file in use oddness with Python 2.3.4 and IDLE 1.0.3 on WinMe In-Reply-To: <419D46A1.3050207@po-box.mcgill.ca> References: <419D46A1.3050207@po-box.mcgill.ca> Message-ID: Brian van den Broek wrote: > > def writer(full_file_path, contents): > '''writes contents to file and closes it when done. > > Given a full file path (or a file name in which case the current > working directory is assumed) and a list of file contents, writer() > writelines the contents to the file and closes it. > ''' > result_file = open(full_file_path, 'w') > result_file.writelines(contents) > result_file.close() > The program I'm currently working on uses the writer() function to write > a simple log file if a call to os.rename() raises an OSError Exception > (which is expected and caused by the destination filepath of the > os.rename call already existing). Before using writer(), it checks if > the file exists, and, if it does, uses reader() so as to preserve its > contents. I don't know what the problem is, but there's something else: if you use 'a' for the mode in the open() call, new output to the file will be appended to the end; the old content will not be overwritten or truncated: result_file = open(full_file_path, 'a') That way you don't have to read and rewrite the old contents in order to preserve them. -- "Codito ergo sum" Roel Schroeven From johan at accesstel.co.za Fri Nov 19 13:06:39 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri Nov 19 13:08:21 2004 Subject: [Tutor] Monitoring ports on a PC Message-ID: <1100865998.4540.57.camel@KMA.accesstel> Hi, Is there a special way or modules that I can use for looking at data that goes in and out of ports on a PC like the IRda or comm ports? I want to write a script to use for monitoring serial connections on my PC or Irda connections and data. Thanks -- Johan -- This E-Mail has been scanned. Enjoy Your Day. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041119/58f77615/attachment.htm From rdm at rcblue.com Fri Nov 19 14:59:55 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Nov 19 15:00:00 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <6.1.2.0.0.20041118234055.04927440@mail.mric.net> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> <419CD8BF.6060500@tds.net> <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> <008201c4cdde$ebd5fd00$8d5328cf@JSLAPTOP> <6.1.2.0.0.20041118234055.04927440@mail.mric.net> Message-ID: <6.1.2.0.2.20041119055823.05782a90@rcblue.com> I've been unable to find this. Could you give the URL for the page? I figure there must be more good stuff near there.. Thanks, Dick Bob Gailer wrote at 22:45 11/18/2004: >To be more explicit (quoting from the manual) "when expressions are used >by control flow statements, the following values are interpreted as >false: None, numeric zero of all types, empty sequences (strings, tuples >and lists), and empty mappings (dictionaries). All other values are >interpreted as true." From glamorgan24 at hotmail.com Fri Nov 19 15:31:16 2004 From: glamorgan24 at hotmail.com (Nabil Hassoun) Date: Fri Nov 19 15:32:37 2004 Subject: [Tutor] E-mail Spam Filter Message-ID: Would you please help me with an exersise required from me by my school to submit? It is a very simple "Spam Filter" in Python. Thank you Yours truly Nabil Hassoun _________________________________________________________________ It's fast, it's easy and it's free. Get MSN Messenger today! http://www.msn.co.uk/messenger From rdm at rcblue.com Fri Nov 19 16:04:09 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Nov 19 16:04:15 2004 Subject: [Tutor] Trouble with psyco Message-ID: <6.1.2.0.2.20041119064940.05b60b70@rcblue.com> psyco is acting a bit psycho for me. Please see my spinForWeb.py at When psyco is in use, entering an integer somewhere between 2000 and 2500 causes my computer to freeze. Not really freeze but the program doesn't finish, and I have to quit with a ^Q. psyco is really impressive, but I'm disappointed that I can't demonstrate (to friends) counting with it to numbers above 2 billion. If I remark out the "psyco.bind(spin)" line, there's no problem no matter what integer I enter. Can someone explain what the problem with psyco is? Windows XP, Python 2.3.4 Thanks, tutors. Dick From John.Gooch at echostar.com Fri Nov 19 16:19:51 2004 From: John.Gooch at echostar.com (Gooch, John) Date: Fri Nov 19 16:20:03 2004 Subject: [Tutor] Placing Multiline T-SQL Query In a String Variable Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC0137@riv-excha5.echostar.com> I have a rather involved query to run on an MS SQL Server 2000 system. I developed the query using the MS SQL Query Analyzer, and it returns 5 records when I run it from there. I attempted to simply copy/paste it into a multi-line Python string ( full query below ), but the query fails when calling the odbc.cursor.fetchall()|odbc.cursor.fetchone() function within Python. First thing I tried to do to solve this issue was to add a newline character after every statement, in case it was running all of the commands together. That did not help. Secondly, I added backslashes before potential special characters ( I only identified '%' as special ) within the script. Still doesn't work. Am I missing any other formatting options/ special characters that could be tripping up my query? Perhaps the single quotes also need to be escaped? I am at quite a loss. While I would love to store the query server side, that database is part of a proprietary software application, and I cannot safely make any modifications to its structure without the risk of trashing the system or violating licensing restrictions. Any help would be appreciated. ssql = """--Get the Server's Object ID" DECLARE @ServerID int SELECT @ServerID = ob.objid FROM dbo.object as ob WHERE ob.name = 'SUPERMAN' --Find Out How Many Drives it Has DECLARE @intCount int SELECT @intCount = COUNT(*) FROM dbo.ArchiveDataHeader As adh (NOLOCK) WHERE adh.MCMachineObjID=@ServerID AND adh.Legend LIKE 'Ldsk: \%AVAIL^^MB' DECLARE @exec varchar(256) SET ROWCOUNT @intCount --Get the latest Drive Space Records SELECT adh.Legend,ad.DetailShort FROM dbo.ArchiveDataHeader As adh (NOLOCK), dbo.ArchiveData As ad (NOLOCK) WHERE adh.MCMachineObjID=@ServerID AND ad.DataID=adh.DataID AND adh.Legend LIKE 'Ldsk: \%AVAIL^^MB' AND DATEDIFF( day, DATEADD( second, ad.BiasedTime, '19700101' ), getdate() ) < 2 ORDER BY DATEADD( second, ad.BiasedTime, '19700101' ) DESC """ John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 From bvande at po-box.mcgill.ca Fri Nov 19 16:36:16 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Nov 19 16:36:58 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <6.1.2.0.2.20041119055823.05782a90@rcblue.com> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> <419CD8BF.6060500@tds.net> <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> <008201c4cdde$ebd5fd00$8d5328cf@JSLAPTOP> <6.1.2.0.0.20041118234055.04927440@mail.mric.net> <6.1.2.0.2.20041119055823.05782a90@rcblue.com> Message-ID: <419E12F0.9010902@po-box.mcgill.ca> Dick Moores said unto the world upon 2004-11-19 08:59: > I've been unable to find this. Could you give the URL for the page? I > figure there must be more good stuff near there.. > > Thanks, > > Dick > > Bob Gailer wrote at 22:45 11/18/2004: > >> To be more explicit (quoting from the manual) "when expressions are >> used by control flow statements, the following values are interpreted >> as false: None, numeric zero of all types, empty sequences (strings, >> tuples and lists), and empty mappings (dictionaries). All other values >> are interpreted as true." > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Dick, Since that isn't too readable, that's the result of typing: site:www.python.org "when expressions are used by control flow statements" into google's search box. Best, Brian vdB From Gregory.H.Bartz at usa-spaceops.com Fri Nov 19 16:40:33 2004 From: Gregory.H.Bartz at usa-spaceops.com (Bartz, Gregory H.) Date: Fri Nov 19 16:41:13 2004 Subject: [Tutor] Sending email... Message-ID: My company uses an MS Exchange server and I'd like to write a script to send emails. I've googled around but have been unsuccessful in finding help. Could someone point me to some documentation that would help me accomplish this task? Thanks, -Greg Bartz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041119/e4f37fa4/attachment.html From maxnoel_fr at yahoo.fr Fri Nov 19 16:51:39 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Nov 19 16:51:44 2004 Subject: [Tutor] E-mail Spam Filter In-Reply-To: References: Message-ID: On Nov 19, 2004, at 14:31, Nabil Hassoun wrote: > Would you please help me with an exersise required from me by my > school to submit? > It is a very simple "Spam Filter" in Python. Help you by answering specific questions you may ask regarding your understanding of Python or to a certain extent of algorithms, yes. Do your homework for you, no. -- 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 Nov 19 16:58:20 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 19 16:58:25 2004 Subject: [Tutor] Sending email... In-Reply-To: References: Message-ID: <419E181C.6020705@tds.net> Take a look at smtplib in the standard library. Kent Bartz, Gregory H. wrote: > > > My company uses an MS Exchange server and I'd like to write a script to > send emails. I've googled around but have been unsuccessful in finding > help. Could someone point me to some documentation that would help me > accomplish this task? > > Thanks, > -Greg Bartz > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From bvande at po-box.mcgill.ca Fri Nov 19 17:08:15 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Nov 19 17:11:02 2004 Subject: [Tutor] Re: file in use oddness with Python 2.3.4 and IDLE 1.0.3 on WinMe In-Reply-To: References: <419D46A1.3050207@po-box.mcgill.ca> Message-ID: <419E1A6F.7050002@po-box.mcgill.ca> Roel Schroeven said unto the world upon 2004-11-19 05:23: > Brian van den Broek wrote: > >> >> def writer(full_file_path, contents): >> result_file = open(full_file_path, 'w') >> result_file.writelines(contents) >> result_file.close() > > >> The program I'm currently working on uses the writer() function to >> write a simple log file if a call to os.rename() raises an OSError >> Exception >> (which is expected and caused by the destination filepath of the >> os.rename call already existing). Before using writer(), it checks if >> the file exists, and, if it does, uses reader() so as to preserve its >> contents. > > > I don't know what the problem is, but there's something else: if you use > 'a' for the mode in the open() call, new output to the file will be > appended to the end; the old content will not be overwritten or truncated: > > result_file = open(full_file_path, 'a') > > That way you don't have to read and rewrite the old contents in order to > preserve them. > Hi Roel, thanks for the tip. I did know about that; I've been meaning to 'upgrade' my writer() function to use a keyword argument with a default value to incorporate it. But, the files I process are almost all well under 1MB, and the tutor list helped cure me of my case of the newbie's "I need the *most* efficient way! Right *now*!" disease ;-) So, I've just not bothered. Thanks again, Brian vdB From bgailer at alum.rpi.edu Fri Nov 19 18:37:34 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Nov 19 18:35:30 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <6.1.2.0.2.20041119055823.05782a90@rcblue.com> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> <419CD8BF.6060500@tds.net> <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> <008201c4cdde$ebd5fd00$8d5328cf@JSLAPTOP> <6.1.2.0.0.20041118234055.04927440@mail.mric.net> <6.1.2.0.2.20041119055823.05782a90@rcblue.com> Message-ID: <6.1.2.0.0.20041119103248.04a15010@mail.mric.net> At 06:59 AM 11/19/2004, Dick Moores wrote: >I've been unable to find this. Could you give the URL for the page? I >figure there must be more good stuff near there.. Documentation is part of the Python installation. But you can also go to http://www.python.org/doc/ The quote I gave is in the Language Reference. In the TOC under 7 Compound Statements click 7.1 The if Statement. Then click one of the expression links which takes you to 5.10 Boolean operations where you find the quote. >Bob Gailer wrote at 22:45 11/18/2004: >>To be more explicit (quoting from the manual) "when expressions are used >>by control flow statements, the following values are interpreted as >>false: None, numeric zero of all types, empty sequences (strings, tuples >>and lists), and empty mappings (dictionaries). All other values are >>interpreted as true." > >Bob Gailer >bgailer@alum.rpi.edu >303 442 2625 home >720 938 2625 cell From unigeek at hotmail.com Fri Nov 19 18:59:38 2004 From: unigeek at hotmail.com (x x) Date: Fri Nov 19 19:00:13 2004 Subject: [Tutor] Recursive permutation In-Reply-To: <419CBCBC.4080205@latte.ca> Message-ID: Here is my 2 bits worth. If I understand what you want you need only use the Result and make a new list that takes each item and creates all possible orders of that item. Result = [''] def Combination(S): if len(S)>0: if S not in Result: Result.append(S) for I in range(len(S)): str2= S[0:I] + S[I+1:len(S)] Combination(str2) return Result Combination("123456") Result.sort() print Result >From: Blake Winton >To: Eivind Triel , tutor@python.org >Subject: Re: [Tutor] Recursive permutation >Date: Thu, 18 Nov 2004 10:16:12 -0500 > >Eivind Triel wrote: > > Well is there a nice code that will do the trick? > >We've discussed this on the list before, so searching the archive for "list >permutation recursive" should yield up some hits. (Sadly, it doesn't >really give me anything. Maybe someone else on the Tutor list will post >the thread title?) > >>This code maks a permutation of the entire list (all the 3 digs), but how >>do I make the permutations of lower lists? >>Going one down i seems easy: Remove alle the element one at a time and >>make a permultation of the rest. But going two down... > >Perhaps it would be easier to start from the bottom, and build your way up? > So, all the lists of length 0, then all the lists of length 1, etc, etc, >until you get to all the lists of length len(input). > >>Like this: >>Sting = 123 >>This give: >>['1','2','3','12','13','21','23','31','32','123','132','213','231,'312',321'] > >I think you're missing the list of length 0 ('') in your output... > >Later, >Blake. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Don't just Search. Find! http://search.sympatico.msn.ca/default.aspx The new MSN Search! Check it out! From rdm at rcblue.com Fri Nov 19 19:03:08 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Nov 19 19:03:12 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <6.1.2.0.0.20041119103248.04a15010@mail.mric.net> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> <419CD8BF.6060500@tds.net> <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> <008201c4cdde$ebd5fd00$8d5328cf@JSLAPTOP> <6.1.2.0.0.20041118234055.04927440@mail.mric.net> <6.1.2.0.2.20041119055823.05782a90@rcblue.com> <6.1.2.0.0.20041119103248.04a15010@mail.mric.net> Message-ID: <6.1.2.0.2.20041119100157.04f36a00@rcblue.com> Got it. Thanks very much. Dick Bob Gailer wrote at 09:37 11/19/2004: >At 06:59 AM 11/19/2004, Dick Moores wrote: >>I've been unable to find this. Could you give the URL for the page? I >>figure there must be more good stuff near there.. > >Documentation is part of the Python installation. But you can also go to >http://www.python.org/doc/ > >The quote I gave is in the Language Reference. In the TOC under 7 >Compound Statements click 7.1 The if Statement. Then click one of the >expression links which takes you to 5.10 Boolean operations where you >find the quote. > >>Bob Gailer wrote at 22:45 11/18/2004: >>>To be more explicit (quoting from the manual) "when expressions are >>>used by control flow statements, the following values are interpreted >>>as false: None, numeric zero of all types, empty sequences (strings, >>>tuples and lists), and empty mappings (dictionaries). All other values >>>are interpreted as true." >> >>Bob Gailer >>bgailer@alum.rpi.edu >>303 442 2625 home >>720 938 2625 cell > From unigeek at hotmail.com Fri Nov 19 19:12:06 2004 From: unigeek at hotmail.com (x x) Date: Fri Nov 19 19:13:24 2004 Subject: [Tutor] Recursive permutation In-Reply-To: <419CBCBC.4080205@latte.ca> Message-ID: Here is my 2 cents worth. If I understand what you are trying to get you just need to take each string in Result and create all possible orders of it into a new list. Result = [''] def Combination(S): if len(S)>0: if S not in Result: Result.append(S) for I in range(len(S)): str2= S[0:I] + S[I+1:len(S)] Combination(str2) return Result Combination("123456") Result.sort() print Result >>This code maks a permutation of the entire list (all the 3 digs), but how >>do I make the permutations of lower lists? >>Going one down i seems easy: Remove alle the element one at a time and >>make a permultation of the rest. But going two down... >>Like this: >>Sting = 123 >>This give: >>['1','2','3','12','13','21','23','31','32','123','132','213','231,'312',321'] > >I think you're missing the list of length 0 ('') in your output... > >Later, >Blake. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Take charge with a pop-up guard built on patented Microsoft® SmartScreen Technology. http://join.msn.com/?pgmarket=en-ca&page=byoa/prem&xAPID=1994&DI=1034&SU=http://hotmail.com/enca&HL=Market_MSNIS_Taglines Start enjoying all the benefits of MSN® Premium right now and get the first two months FREE*. From rdm at rcblue.com Fri Nov 19 19:40:48 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Nov 19 19:40:53 2004 Subject: [Tutor] all elements equal in tuple or list In-Reply-To: <419E12F0.9010902@po-box.mcgill.ca> References: <200411181355.39341.dimitri.dor@fssintl.com> <419CBA58.6000209@tds.net> <6.1.2.0.0.20041118093916.04d94220@mail.mric.net> <419CD8BF.6060500@tds.net> <6.1.2.0.2.20041118175018.04a5b060@rcblue.com> <008201c4cdde$ebd5fd00$8d5328cf@JSLAPTOP> <6.1.2.0.0.20041118234055.04927440@mail.mric.net> <6.1.2.0.2.20041119055823.05782a90@rcblue.com> <419E12F0.9010902@po-box.mcgill.ca> Message-ID: <6.1.2.0.2.20041119103948.043985f0@rcblue.com> Brian van den Broek wrote at 07:36 11/19/2004: >Dick Moores said unto the world upon 2004-11-19 08:59: >>I've been unable to find this. Could you give the URL for the page? I >>figure there must be more good stuff near there.. >>Thanks, >>Dick >>Bob Gailer wrote at 22:45 11/18/2004: >> >>>To be more explicit (quoting from the manual) "when expressions are >>>used by control flow statements, the following values are interpreted >>>as false: None, numeric zero of all types, empty sequences (strings, >>>tuples and lists), and empty mappings (dictionaries). All other values >>>are interpreted as true." > >Hi Dick, > > > >Since that isn't too readable, that's the result of typing: > >site:www.python.org "when expressions are used by control flow statements" > >into google's search box. > >Best, > >Brian vdB Hey, good trick! I'll use it next time. Thanks, Dick From klappnase at freenet.de Fri Nov 19 23:00:07 2004 From: klappnase at freenet.de (Michael Lange) Date: Fri Nov 19 22:59:32 2004 Subject: [Tutor] using a button to make a variable in Tk In-Reply-To: <000001c4cdbd$5bf125a0$8235a8c0@co.montezuma.co.us> References: <000001c4cdbd$5bf125a0$8235a8c0@co.montezuma.co.us> Message-ID: <20041119230007.358f9105.klappnase@freenet.de> On Thu, 18 Nov 2004 15:24:24 -0700 "Patrick Thorstenson" wrote: > I have a GUI in Tk with 2 buttons. I would like one button to make a > variable called "abortcode" equal to 3 (text number) and have the other > button make "abortcode" equal to 5. > > Then if abortcode equals "5" exit, or "3" continue with the script (it > doesn't have to be 3 or 5). This last part I have - I just need to know > how to make the variable equal to 3 or 5. > > OR is there an easier way to do this? Basically, this script in its > entirety creates new parcels for our county. Before the final update > process occurs, the program needs to allow the user to view the possible > parcel updates and then decide to continue the process or abort the > program. "Destroy" only kills the GUI but I need to exit the entire > script. > Hi, Patrick, I'm not sure if I understood you correctly, but I think using Radiobuttons instead of Buttons might be what you need. You can assign a Tkinter variable to a set of Radiobuttons and define a certain value for each: self.abortcode = StringVar() self.abortcode.set("5") self.button = Radiobutton(frame, text="continue on and update parcels", fg='red', indicatoron=0,# makes the Radiobutton look like a "normal" button value="3", variable=self.abortcode, command=self.quit) self.button.pack(side=LEFT) self.stop = Radiobutton(frame, text="Stop the update process", fg='orange', indicatoron=0, value="5", variable=self.abortcode, command=self.quit) self.stop.pack(side=RIGHT) I hope this helps Michael > > ##### > > from Tkinter import * > > class App: > > def __init__(self, master): > > frame = Frame(master) > frame.pack() > > self.button = Button(frame, text="continue on and update parcels", > fg="red", Abortcode = 3????) #this should = 3 > self.button.pack(side=LEFT) > > self.stop = Button(frame, text="Stop the update process", > fg="orange", Abortcode = 5????) #this should = 5 > self.stop.pack(side=RIGHT) > > > > root = Tk() > app = App(root) > root.mainloop() > > #end test area > > abortcode = "5" > > if abortcodeb == "5": > sys.exit > > else: > gp.Rename_management(renametest_Copy_shp, Output_data_element__2_, "") > > #### > From meenakshi at mbi.ucla.edu Fri Nov 19 23:16:42 2004 From: meenakshi at mbi.ucla.edu (Meenakshi Roy) Date: Fri Nov 19 23:16:47 2004 Subject: [Tutor] adding text to openGL Message-ID: Hi, I am a novice to programming and this is my first mailing to the list. I am attempting to write a py OpenGL script that gets exon and splice information from a mysql database, and draws rectangles and lines to represent them. My question is: how do I add text, i.e. strings of characters and integers to the window, as a way of labeling the exons. When I search in OpenGL.org, I mostly get information about texture mapping, which is not what I am looking for, I think. I have been following the posts on this mailing list--thanks for the excellent resource! Meenakshi From marilyn at deliberate.com Fri Nov 19 23:27:57 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Nov 19 23:28:01 2004 Subject: [Tutor] Debugging in emacs In-Reply-To: <211F78EFD1D870409CC3E4158F4881DA08B32E26@xcww01.riv.csu.edu.au> Message-ID: On Fri, 19 Nov 2004, McLaughlin, Toby wrote: > Hi All, > > Could somebody suggest a way to debug python in emacs? I'd like to be > able to single-step while seeing the code marked in some way and > possiblly set breakpoints. I read about using pdb from the command line > but would love to have debugging integrated in emacs. Perhaps I should > make life easy for myself and use one of the fancy GUI editors, but I > think it's character building for me to learn emacs. Boy, you could hear a pin drop on this topic. I use emacs, even though I have spent some time with idle, because I like it much better. I'm real handy in emacs though, and I don't like mousing. Mice cause lots of repetitive stress injury. I spent some time and some email conversations trying to make use of the debugger in any environment. I don't remember what happened exactly but I gave up. The thing about an interpreted language is that you can say "print my_var" in the code instead of in the debugger. And with emacs, I go back and forth between my code and the emacs shell to run it. I'm pretty efficient that way. If anyone has any suggestions about debugging, in idle or anywhere, I too would love to hear them. Thank you. Marilyn Davis > > Thanks, > Toby McLaughlin. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From glingl at aon.at Sat Nov 20 00:33:25 2004 From: glingl at aon.at (Gregor Lingl) Date: Sat Nov 20 00:33:08 2004 Subject: [Tutor] Recursive permutation In-Reply-To: References: Message-ID: <419E82C5.4040404@aon.at> x x schrieb: > Here is my 2 bits worth. > If I understand what you want you need only use the Result and make a > new list that takes each item and creates all possible orders of that > item. > Hi x x! Yes, this is what I suggested in my previous post. > Result = [''] > > def Combination(S): > > if len(S)>0: > if S not in Result: > Result.append(S) > for I in range(len(S)): > str2= S[0:I] + S[I+1:len(S)] > Combination(str2) > > return Result > o.k., your code produces the correct Result. But it suffers from a serious drawback: it computes most of the elements of Result a lot of times - therefore you have to check for each of your candidates if its already in Result. This check is rather expensive, especially if Result is already a long list. Another way to get your Result, but much faster is: def subsets(txt): if txt: rest = subsets(txt[1:]) return rest + [txt[0] + x for x in rest] else: return [""] it relies on the idea, that you get all subsets of a given set, if you first compute all subsets, which do not contain the first element and then add all subsets which contain the first element. These have the form txt[0]+x where x is a subset without txt[0], that means it is in the first - already computed - set of subsets. For a string of 12 elements (resulting in a Result of 4096 elements) this algorithm is faster by a factor of 500 than your function Combination. On the other hand, these considerations are of minor importance if the function is used for solving Eivinds problem, because then there are necessarily only few elements in txt to be processed and most of the processing time is used to construct the permutations. Regards, Gregor > > Combination("123456") > Result.sort() > > print Result > > From John.Gooch at echostar.com Sat Nov 20 00:47:39 2004 From: John.Gooch at echostar.com (Gooch, John) Date: Sat Nov 20 00:47:50 2004 Subject: [Tutor] Multi-Line SQL Statement in Python Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC0143@riv-excha5.echostar.com> I have a rather involved query to run on an MS SQL Server 2000 system. I developed the query using the MS SQL Query Analyzer, and it returns 5 records when I run it from there. I attempted to simply copy/paste it into a multi-line Python string ( full query below ), but the query fails when calling the odbc.cursor.fetchall()|odbc.cursor.fetchone() function within Python. First thing I tried to do to solve this issue was to add a newline character after every statement, in case it was running all of the commands together. That did not help. Secondly, I added backslashes before potential special characters ( I only identified '%' as special ) within the script. Still doesn't work. Am I missing any other formatting options/ special characters that could be tripping up my query? Perhaps the single quotes also need to be escaped? I am at quite a loss. While I would love to store the query server side, that database is part of a proprietary software application, and I cannot safely make any modifications to its structure without the risk of trashing the system or violating licensing restrictions. Any help would be appreciated. ssql = """--Get the Server's Object ID" DECLARE @ServerID int SELECT @ServerID = ob.objid FROM dbo.object as ob WHERE ob.name = 'SUPERMAN' --Find Out How Many Drives it Has DECLARE @intCount int SELECT @intCount = COUNT(*) FROM dbo.ArchiveDataHeader As adh (NOLOCK) WHERE adh.MCMachineObjID=@ServerID AND adh.Legend LIKE 'Ldsk: \%AVAIL^^MB' DECLARE @exec varchar(256) SET ROWCOUNT @intCount --Get the latest Drive Space Records SELECT adh.Legend,ad.DetailShort FROM dbo.ArchiveDataHeader As adh (NOLOCK), dbo.ArchiveData As ad (NOLOCK) WHERE adh.MCMachineObjID=@ServerID AND ad.DataID=adh.DataID AND adh.Legend LIKE 'Ldsk: \%AVAIL^^MB' AND DATEDIFF( day, DATEADD( second, ad.BiasedTime, '19700101' ), getdate() ) < 2 ORDER BY DATEADD( second, ad.BiasedTime, '19700101' ) DESC """ John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 From billburns at pennswoods.net Sat Nov 20 02:08:46 2004 From: billburns at pennswoods.net (Bill Burns) Date: Sat Nov 20 02:01:22 2004 Subject: [Tutor] Critique of program In-Reply-To: References: Message-ID: <200411192008.46235.billburns@pennswoods.net> On Friday 19 November 2004 10:40 am, David wrote: > So after all of the help from the list, what does the final guts of the > program look like? > Hopefully the guts look good but since I'm a programming n00b who knows :-) I've tried incorporating (as best I can) the suggestions that I received. I hope I'm heading in the right direction, all feedback is welcome. You'll see below that I'm now using one list "lineEdits = []" instead of looking into self.__dict__ every time I want to access an object or attribute. I also removed my add() function in favor of the built-in sum() function and made other suggested changes. For the most part, I've added a new comment above a piece of code that has changed from the original. Some of the code for the report function (that I didn't have working any way), I've stripped out to make it easier to read. I'm still using the same "pipeDict" as before but I'm thinking about changing it to something like this: pipeDict = \ {('lineEdit1','stlStd','1/2"'): .622, ('lineEdit2','stlStd','3/4"'): .824, ('lineEdit3','stlStd','1"'): 1.049,('lineEdit4','stlStd','1-1/4"'): 1.38} and then possibly I can do: for name, typ, size in pipeDict: w = getattr(self, name) lineEdits.append((w,name,typ,size)) which would give me access to instances, lineEdit names, pipe types and pipe sizes. I need to figure out how to incorporate the keys for the pipeDict into this list as well. This new dict is probably the way to go since I want to add some kind of reporting/printing functionality to the program. Any suggestions are greatly appriecated. Thank you all for your help!! Bill #! /usr/bin/env python """ Pipe Volume Calc - calculates the water volume (in U.S. gallons) contained inside various types and sizes of pipe. The user selects a type of pipe, a size of pipe and then enters a length (in feet). Water volume is automatically calculated and displayed as the data is entered into the form. There's a GUI front-end which is separate from this module. I made the GUI using Qt Designer, PyQt and pyuic. The GUI is a tabbed dialog containing multiple lineEdits. Each lineEdit corresponds to a specific size of pipe, i.e., 1/2", 3/4", etc. Each tabbed page corresponds to a different type of pipe (steel, copper or PVC). The user selects the page containing the type of pipe and then enters the total footage. The first dictionary below (pipeDict) holds all the inside diameters (in inches) for the various pipes. The inside diameter (and length) are needed to calculate water volume. The lineEdit "groups" are broken out as follows: lineEdit1 -> lineEdit25 (standard steel pipe) lineEdit1_1 -> lineEdit25_1 (extra strong steel pipe) lineEdit1_2 -> lineEdit15_2 (type L copper pipe) lineEdit1_3 -> lineEdit13_3 (schedule 40 PVC pipe) lineEdit1_4 -> lineEdit13_4 (schedule 80 PVC pipe) """ pipeDict = \ {'lineEdit1': .622, 'lineEdit2': .824, 'lineEdit3': 1.049, 'lineEdit4': 1.38, 'lineEdit5': 1.61, 'lineEdit6': 2.067, 'lineEdit7': 2.469, 'lineEdit8': 3.068, 'lineEdit9': 3.548, 'lineEdit10': 4.026, 'lineEdit11': 5.047, 'lineEdit12': 6.065, 'lineEdit13': 7.981, 'lineEdit14': 10.02, 'lineEdit15': 12.00, 'lineEdit16': 13.25, 'lineEdit17': 15.25, 'lineEdit18': 17.25, 'lineEdit19': 19.25, 'lineEdit20': 21.25, 'lineEdit21': 23.25, 'lineEdit22': 29.25, 'lineEdit23': 35.25, 'lineEdit24': 41.25, 'lineEdit25': 47.25, 'lineEdit1_1': .546, 'lineEdit2_1': .742, 'lineEdit3_1': .957, 'lineEdit4_1': 1.278, 'lineEdit5_1': 1.50, 'lineEdit6_1': 1.939, 'lineEdit7_1': 2.323, 'lineEdit8_1': 2.90, 'lineEdit9_1': 3.364, 'lineEdit10_1': 3.826, 'lineEdit11_1': 4.813, 'lineEdit12_1': 5.761, 'lineEdit13_1': 7.625, 'lineEdit14_1': 9.75, 'lineEdit15_1': 11.75, 'lineEdit16_1': 13.00, 'lineEdit17_1': 15.00, 'lineEdit18_1': 17.00, 'lineEdit19_1': 19.00, 'lineEdit20_1': 21.00, 'lineEdit21_1': 23.00, 'lineEdit22_1': 29.00, 'lineEdit23_1': 35.00, 'lineEdit24_1': 41.00, 'lineEdit25_1': 47.50, 'lineEdit1_2': .585, 'lineEdit2_2': .830, 'lineEdit3_2': 1.075, 'lineEdit4_2': 1.32, 'lineEdit5_2': 1.565, 'lineEdit6_2': 2.055, 'lineEdit7_2': 2.545, 'lineEdit8_2': 3.035, 'lineEdit9_2': 3.525, 'lineEdit10_2': 4.015, 'lineEdit11_2': 5.00, 'lineEdit12_2': 5.985, 'lineEdit13_2': 7.925, 'lineEdit14_2': 9.875, 'lineEdit15_2': 11.845, 'lineEdit1_3': .731, 'lineEdit2_3': .937, 'lineEdit3_3': 1.182, 'lineEdit4_3': 1.52, 'lineEdit5_3': 1.755, 'lineEdit6_3': 2.221, 'lineEdit7_3': 2.672, 'lineEdit8_3': 3.284, 'lineEdit9_3': 4.263, 'lineEdit10_3': 6.345, 'lineEdit11_3': 8.303, 'lineEdit12_3': 10.385, 'lineEdit13_3': 12.344, 'lineEdit1_4': .693, 'lineEdit2_4': .896, 'lineEdit3_4': 1.136, 'lineEdit4_4': 1.469, 'lineEdit5_4': 1.70, 'lineEdit6_4': 2.157, 'lineEdit7_4': 2.599, 'lineEdit8_4': 3.20, 'lineEdit9_4': 4.163, 'lineEdit10_4': 6.193, 'lineEdit11_4': 8.125, 'lineEdit12_4': 10.157, 'lineEdit13_4': 12.063} import sys import types from qt import * from pipeCalcGUI import PipeForm """create an empty list that will hold the info/attributes of the lineEdits. if I put "lineEdits = []" directly under the class, then I need to call it like this > self.lineEdit. I don't know which spot is the preferred location? """ lineEdits = [] class PipeConnector(PipeForm): #lineEdits = [] def __init__(self, parent=None): PipeForm.__init__(self, parent) self.connect(self.buttonClear,SIGNAL("clicked()"), self.clearLineEdits) self.connect(self.buttonExit,SIGNAL("clicked()"),self,SLOT("close()")) self.lineEditTotal.setAlignment(QLineEdit.AlignRight) for name in pipeDict: w = getattr(self, name) """append tuple to list, index[0] of tuple holds all lineEdit instances, index[1] holds all lineEdit names. we need the instances to perform the built-in QLineEdit functions displayText() & clear() """ lineEdits.append((w,name)) self.connect(w,SIGNAL("textChanged(const QString &)"),self.calc) w.setAlignment(QLineEdit.AlignRight) validator=QIntValidator(0.00, 9999999.00, w) w.setValidator(validator) def calc(self): stack = [] """use the lineEdits list""" for w, name in lineEdits: """don't perform calc() operations on lineEditTotal, it's used to display the sum of our calculations, this is the same as before """ if name != "lineEditTotal": length = w.displayText() """changed from, if not length == """"" if length: """at this point, length is an instance and we need an int. first convert it to a string and then convert to an int. this is the only way I can seem to convert this, if I try to convert it directly to an int, I get errors... """ length = int(str(length),10) ID = pipeDict[name] x = volCalc(ID, length) stack.append(x) """use built-in sum() to add everthing on the stack, previously I was using my own add() function """ total = sum(stack) """format total before it is displayed, before I was formatting it in volCalc() """ total = "%0.2f" % total self.lineEditTotal.setText(total) def clearLineEdits(self): """use the lineEdits list""" for w, name in lineEdits: w.clear() self.lineEditTotal.setText("") def volCalc(ID, length): """calculates the water volume""" gal = ((ID*.5)**2)*3.14159265*(12*length)/(230.9429931) return gal if __name__ == "__main__": app = QApplication(sys.argv) QObject.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()")) win = PipeConnector() app.setMainWidget(win) win.show() app.exec_loop() From keridee at jayco.net Sat Nov 20 02:55:52 2004 From: keridee at jayco.net (Jacob S.) Date: Sat Nov 20 02:56:18 2004 Subject: [Tutor] Help with re module maybe? Message-ID: <000501c4cea4$14295cf0$7f5428cf@JSLAPTOP> Okay, say I have a string "x**2+sin(x**2+2*x)" and I want to split it at the addition sign. However, I don't want to split it at the addition signs inside the parenthesis. How do I go about doing this? Goes something along the lines a = a.split("+") # if and only if + not inside parenthesis That should be enough information to help... I think the re module might help. Any insights as to a good walkthrough of the re module would be helpful. If you have any suggestions, or would like to give me a more detailed way to do this (maybe a specific place in the re module?) Thanks in advance, Jacob Schmidt From keridee at jayco.net Sat Nov 20 04:09:28 2004 From: keridee at jayco.net (Jacob S.) Date: Sat Nov 20 04:11:10 2004 Subject: [Tutor] multidemisional arrays References: <000601c4c9c4$a53196c0$121c8645@oemcomputer> <1100381951.21480.73.camel@laptop.venix.com> <007901c4cddd$66eab1e0$8d5328cf@JSLAPTOP> <004401c4cdf6$02282210$121c8645@oemcomputer> Message-ID: <004201c4ceae$831a0b50$7f5428cf@JSLAPTOP> Okay. -------------------------------------------------------------------- def rfill(stri,length): # Step 1 if len(stri) < length: # 2 stri = stri+' '*(length-len(stri)) # 3 return stri # 4 howMany = input('How many artists will you enter? ') # 5 artists = {} # 6 for i in range(howMany): # 7 artist = raw_input('Who is the artist? ') # 8 painting = raw_input('What is the painting called? ') # 9 value = raw_input('What is the value of the painting? ') # 10 artists[artist] = (painting,value) # 11 artists.keys().sort() # 12 l = 15 # 13 a = rfill("Artist",l) # 14 p = rfill("Painting",l) # 15 v = rfill("Value",l) # 16 print "".join([a,p,v]) # 17 for x in artists.keys(): # 18 a = rfill(x,l) # 19 p = rfill(artists[x][0],l) # 20 v = rfill(artists[x][1],l) # 21 print "".join([a,p,v]) # 22 ---------------------------------------------- Steps: 1) We define a function named rfill. It needs the required variables stri and length 2) This says that if the stri (string) is less than the length specified, don't do anything but return the string 3) This tells appends spaces to the end of the string, stri. The ' '*(length-len(stri)) means to multiply the string " " (space) times (The specified length minus the length of the string that we are editing). Okay, if that doesn't make sense, all we are doing is right padding the given string with spaces until we have a string of the given length. 4) This returns the string whether we modified it or not. 5) Asks the user how many artists there are 6) Makes the variable "artists" refer to an empty dictionary so we can append to it. 7) for i in range(howMany): -- Alright... range([start,]end[,step]) (The brackets mean it is optional) for i in range(start,end,step): # The start is defaulted to zero, the step defaulted to one print "Hello" is equivalent to i = start while i < end: print "Hello" i = i + step 8 - 10) Ask the user for each different thing involved. 11) Now we come to the definition of key. In dictionaries, you have key : value pairs. Such as a telephone directory. a = {"Library":"726-7890","Jacob":"726-2998"} where "Library" and "Jacob" are 'keys' of the dictionary. "726-7890" and "726-2998" are there corresponding values, respectively. Now. L.keys() is a list of all the keys in the dictionary L L.values() is a list of all the values in the dictionary L L.items() is a list of all the items in dictionary L above ex. a = {"Library":"726-7890","Jacob":"726-2998"} print a.keys() print a.values() print a.items() yields ["Library","Jacob"] ["726-7890","726-2998"] ["Library","726-7890","Jacob","726-2998"] Okay, so now we know a little about dictionaries -- Oh! I almost forgot. print a["Library"] yields "726-7890" What I did in step 11 was to make a new key that is artist (What the user entered for artist) and have the corresponding value equal to a tuple of (painting, value) so that when I enter >>> a = {"Jacob":("Flowers",10),"Gary":("People",15)} >>> print a["Jacob"] ("Flowers":10) >>> print a["Gary"] ("People",15) >>> print a["Jacob"][0] Flowers >>> print a["Jacob"][1] 10 >>> 12) artists.keys().sort() means sort the dictionary by the keys in place. So, we take all of the information and sort alphabetically by artist. 13) This predefines the length as 15. It's just a constant that I put in there. If your artist names or paintings are longer that 15 characters, you might want to set that higher. 14 - 17) Okay, Our titles are automatically right padded with spaces to the preset length by our predefined function. Then with step 17, we print an odd thing. We take a list of our titles and we join them together with the seperator "" (an empty string). You can read more of this in the documentation under String Methods in the index. 18) This runs through every thing in the list of keys to the dictionary of artist : (painting,value) pairs. IOW, we take all of the artists in the dictionary, and in 19) we take each artist and right pad it with spaces and give it its own variable name for this loop through 20) we do the same with the corresponding painting 21) we do the same with the corresponding value 22) we join the three corresponding strings defined in steps 19-21 with an empty string as a seperator as before, and print the result. Each successive loop prints each corresponding values on its own line. If you count each word and the spaces to the right of it, you would get the value of length, since we did the right padding with the function rfill. Okay! Hope this is not too long winded an explanation. Feel free to ask more questions! Jacob Schmidt ----- Original Message ----- From: "Diana Furr" To: "Jacob S." Sent: Friday, November 19, 2004 12:09 AM Subject: Re: [Tutor] multidemisional arrays > Thank you for your response. As you can tell I'm new at this. I enjoy > learning but find it > difficult because even reading the tutorials seems like reading a foreign > language. I can > occasionally pick up something I understand. If you wouldn't mind could you > please explain > each thing you did to the program and maybe why it works, so that I will > have an understanding > of it. > Thank you, > Diana > P.S. One thing I see alot in the tutorials is 'key' what is the meaning of > key, what does it do. > > > ----- Original Message ----- > From: "Jacob S." > To: "Lloyd Kvam" ; "Diana Furr" > > Cc: "Tutor Python" > Sent: Thursday, November 18, 2004 9:13 PM > Subject: Re: [Tutor] multidemisional arrays > > > > I'm surprised that nobody has corrected the excessive code involved in the > > first loop. > > > >>i=0 > >>howMany=input('How many artists will you enter? ') > >>paintings=[]#painting > >>artists=[]#artist > >>values=[]#value > >>for i in range(0,howMany,1): > >> painting=raw_input('Painting Name ') > >> artist=raw_input('Artist Name ') > >> value=input('Painting Value ') > >> paintings+=[painting] > >> artists+=[artist] > >> values+=[value] > >> artists=zip(artists,paintings,values) > >> artists.sort() > >> i=i+1 > > > > You do not need to define i as 0, you do not need to increment i at the > > end > > of loop, that is what > > for i in range(0,howMany,1): means. > > Also, you can shorten that to: for i in range(howMany): > > > >>n=0 > >>for n in range(0,howMany,1): > >> print artists[n] > > > > If you want to figure this out as a learning experience, DO NOT READ ANY > > FURTHER!!! > > > > I would do this. > > > > def rfill(stri,length): > > if len(stri) < length: > > stri = stri+' '*(length-len(stri)) > > return stri > > > > howMany = input('How many artists will you enter? ') > > artists = {} > > for i in range(howMany): > > artist = raw_input('Who is the artist? ') > > painting = raw_input('What is the painting called? ') > > value = raw_input('What is the value of the painting? ') > > artists[artist] = (painting,value) > > artists.keys().sort() > > l = 15 > > a = rfill("Artist",l) > > p = rfill("Painting",l) > > v = rfill("Value",l) > > print "".join([a,p,v]) > > for x in artists.keys(): > > a = rfill(x,l) > > p = rfill(artists[x][0],l) > > v = rfill(artists[x][1],l) > > print "".join([a,p,v]) > > > > > > > From kent37 at tds.net Sat Nov 20 04:39:29 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Nov 20 04:39:32 2004 Subject: [Tutor] Help with re module maybe? In-Reply-To: <000501c4cea4$14295cf0$7f5428cf@JSLAPTOP> References: <000501c4cea4$14295cf0$7f5428cf@JSLAPTOP> Message-ID: <419EBC71.9030006@tds.net> In general it is hard to use regular expressions to parse when you have to keep some state to know what to do. In this case you have to keep track of the nesting of the parens in order to know how to handle a plus sign. This is a simple enough problem that a simple state machine that counts open and close parentheses does the job. For more complicated state a parsing library like pyparsing is very helpful. I encourage you to learn about the re module, though. It is often handy. This HOW-TO might help you get started: http://www.amk.ca/python/howto/regex/ Kent Some people, when confronted with a problem, think ?I know, I?ll use regular expressions.? Now they have two problems. --Jamie Zawinski, in comp.emacs.xemacs def splitter(s): ''' Split a string on each plus sign that is not inside parentheses ''' parenCount = 0 # Counts current nesting start = 0 # Start of current run for i, c in enumerate(s): if c == '+' and parenCount == 0: yield s[start:i] start = i+1 elif c == '(': parenCount += 1 elif c == ')': parenCount -= 1 # Yield any leftovers if start < len(s): yield s[start:] test = [ "x**2+sin(x**2+2*x)", 'abcd', '(a+b)+(c+d)', '((a+b)+(c+d))+e' ] for s in test: print s, list(splitter(s)) prints: x**2+sin(x**2+2*x) ['x**2', 'sin(x**2+2*x)'] abcd ['abcd'] (a+b)+(c+d) ['(a+b)', '(c+d)'] ((a+b)+(c+d))+e ['((a+b)+(c+d))', 'e'] Jacob S. wrote: > Okay, > > say I have a string "x**2+sin(x**2+2*x)" and I want to split it at the > addition sign. However, I don't want to split it at the addition signs > inside the parenthesis. How do I go about doing this? > > Goes something along the lines > > a = a.split("+") # if and only if + not inside parenthesis > > That should be enough information to help... > I think the re module might help. Any insights as to a good walkthrough of > the re module would be helpful. If you have any suggestions, or would like > to give me a more detailed way to do this (maybe a specific place in the re > module?) > > Thanks in advance, > Jacob Schmidt > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sat Nov 20 13:25:42 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Nov 20 13:25:50 2004 Subject: [Tutor] using a button to make a variable in Tk In-Reply-To: <000001c4cdbd$5bf125a0$8235a8c0@co.montezuma.co.us> References: <000001c4cdbd$5bf125a0$8235a8c0@co.montezuma.co.us> Message-ID: <419F37C6.5020200@tds.net> Patrick, It sounds like you need to add command handlers to the buttons. The handlers could set the variable, but a simpler approach is to have functions that just do what you want - the handler for the exit button exits the program; the handler for the update button starts the update. Here is an example. When the 'Stop' button is pressed the program will exit; when the 'Update' button is pressed, App.updateParcels() will be called: from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="continue on and update parcels", fg="red", command=self.updateParcels) self.button.pack(side=LEFT) self.stop = Button(frame, text="Stop the update process", fg="orange", command=frame.quit) self.stop.pack(side=RIGHT) def updateParcels(self): print 'Time to update the parcels' root = Tk() app = App(root) root.mainloop() Kent Patrick Thorstenson wrote: > I have a GUI in Tk with 2 buttons. I would like one button to make a > variable called ?abortcode? equal to 3 (text number) and have the other > button make ?abortcode? equal to 5. > > > > Then if abortcode equals ?5? exit, or ?3? continue with the script (it > doesn?t have to be 3 or 5). This last part I have - I just need to know > how to make the variable equal to 3 or 5. > > > > OR is there an easier way to do this? Basically, this script in its > entirety creates new parcels for our county. Before the final update > process occurs, the program needs to allow the user to view the possible > parcel updates and then decide to continue the process or abort the > program. ?Destroy? only kills the GUI but I need to exit the entire > script. > > > > > > ##### > > > > from Tkinter import * > > > > class App: > > > > def __init__(self, master): > > > > frame = Frame(master) > > frame.pack() > > > > self.button = Button(frame, text="continue on and update parcels", > fg="red", Abortcode = 3????) #this should = 3 > > self.button.pack(side=LEFT) > > > > self.stop = Button(frame, text="Stop the update process", > fg="orange", Abortcode = 5????) #this should = 5 > > self.stop.pack(side=RIGHT) > > > > > > > > root = Tk() > > app = App(root) > > root.mainloop() > > > > #end test area > > > > abortcode = "5" > > > > if abortcodeb == "5": > > sys.exit > > > > else: > > gp.Rename_management(renametest_Copy_shp, Output_data_element__2_, "") > > > > #### > > > > > > > > Patrick Thorstenson > > GIS Specialist > > Montezuma County > > (970) 564-9298 > > pthorstenson@co.montezuma.co.us > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From djennings3 at earthlink.net Sat Nov 20 14:26:15 2004 From: djennings3 at earthlink.net (Don Jennings) Date: Sat Nov 20 14:26:10 2004 Subject: [Tutor] Monitoring ports on a PC Message-ID: Try pySerial at http://pyserial.sourceforge.net/ Take care, Don From missive at hotmail.com Sat Nov 20 16:37:06 2004 From: missive at hotmail.com (Lee Harr) Date: Sat Nov 20 16:38:07 2004 Subject: [Tutor] Re: Multi-Line SQL Statement in Python Message-ID: >Secondly, I added backslashes before potential >special characters ( I only identified '%' as special ) within the script. I think the escape for % is %%, not \% >>>'\%' '\\%' >>>'\%s' % 'test' '\\test' >>>'%%s %s' % 'test' '%s test' _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From amonroe at columbus.rr.com Sat Nov 20 18:21:36 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Nov 20 18:21:55 2004 Subject: [Tutor] Help with re module maybe? In-Reply-To: <419EBC71.9030006@tds.net> References: <000501c4cea4$14295cf0$7f5428cf@JSLAPTOP> <419EBC71.9030006@tds.net> Message-ID: <71513655016.20041120122136@columbus.rr.com> > def splitter(s): > ''' Split a string on each plus sign that is not inside parentheses ''' Stupid question: how do you test generators in the interactive interpreter? Simply calling it didn't give me the result I expected... >>> splitter('x+(y+z)') Alan From kent37 at tds.net Sat Nov 20 18:37:59 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Nov 20 18:38:01 2004 Subject: [Tutor] Help with re module maybe? In-Reply-To: <71513655016.20041120122136@columbus.rr.com> References: <000501c4cea4$14295cf0$7f5428cf@JSLAPTOP> <419EBC71.9030006@tds.net> <71513655016.20041120122136@columbus.rr.com> Message-ID: <419F80F7.4070804@tds.net> Make it into a list: list(splitter('x+(y+z)') Kent R. Alan Monroe wrote: > Stupid question: how do you test generators in the interactive > interpreter? Simply calling it didn't give me the result I expected... > > >>>>splitter('x+(y+z)') > > From cyresse at gmail.com Sun Nov 21 02:26:43 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Nov 21 02:26:47 2004 Subject: [Tutor] CSV module? Message-ID: Hi all, Trying to work the CSV module, and I'm not quite sure how to input/output through it. I've worked out to output a CSV file that looks like - A B C 1 2 3 4 5 6 you have to use a list like this - spreadS=[['A','B','C'],[1,2,3],[4,5,6]], so each row is a separate list. and then dave=file('test.csv', 'w') henry=csv.writer(dave) and either for element in dave: henry.writerow(element) or just henry.writerows(dave). So writing is fine. But, if I were to reopen test.csv - x=file('test.csv','r') I can do this - >>> print x.readlines() ['A,B,C\r\n', '1,2,3\r\n', '4,5,6\r\n'] which is roughly what I expected. Howeever, if I were to do - >>>bob=csv.reader(x) And as per the Python docs - for element in bob: print element I get nothing. If I try bob.next(), I get 'StopIteration' which means that it's reached the end of the file. So help? I'm probably doing something quite simple & silly, but the documentation isn't much help (to me), and I've got not spreadsheet software installed on this comp to check that my csv's are valid. I figure if I can pipe some data out through the CSV module and then pipe it back in and nothing's changed then I'm doing OK. Regards, Liam Clarke -- '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 Sun Nov 21 02:40:13 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Nov 21 02:40:15 2004 Subject: [Tutor] CSV module? In-Reply-To: References: Message-ID: <419FF1FD.3090001@tds.net> Liam, I can't be sure without seeing your whole program, but my guess is you either - didn't close the output file before opening for read, or - didn't re-open the input file between trying readlines() and reading with the csv reader, so the csv reader was just getting the end-of-file. Anyway, here is a version of your snippets that works: import csv spreadS=[['A','B','C'],[1,2,3],[4,5,6]] dave=file('test.csv', 'w') henry=csv.writer(dave) henry.writerows(spreadS) dave.close() x=file('test.csv','r') bob=csv.reader(x) for element in bob: print element Kent Liam Clarke wrote: > Hi all, > > Trying to work the CSV module, and I'm not quite sure how to > input/output through it. > > I've worked out to output a CSV file that looks like - > > A B C > 1 2 3 > 4 5 6 > > you have to use a list like this - > spreadS=[['A','B','C'],[1,2,3],[4,5,6]], so each row is a separate > list. > > and then > > dave=file('test.csv', 'w') > henry=csv.writer(dave) > > and either > > for element in dave: > henry.writerow(element) > > or just > > henry.writerows(dave). > > So writing is fine. But, if I were to reopen test.csv - > > x=file('test.csv','r') > > I can do this - > > >>>>print x.readlines() > > ['A,B,C\r\n', '1,2,3\r\n', '4,5,6\r\n'] > > which is roughly what I expected. > > Howeever, if I were to do - > > >>>>bob=csv.reader(x) > > > And as per the Python docs - > > for element in bob: > print element > > I get nothing. > > If I try bob.next(), I get 'StopIteration' which means that it's > reached the end of the file. > > So help? I'm probably doing something quite simple & silly, but the > documentation isn't much help (to me), and I've got not spreadsheet > software installed on this comp to check that my csv's are valid. > > I figure if I can pipe some data out through the CSV module and then > pipe it back in and nothing's changed then I'm doing OK. > > Regards, > > Liam Clarke > From cyresse at gmail.com Sun Nov 21 03:17:21 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Nov 21 03:17:25 2004 Subject: [Tutor] CSV module? In-Reply-To: <419FF1FD.3090001@tds.net> References: <419FF1FD.3090001@tds.net> Message-ID: Kent, As always, you are a beam of light upon the darkness of my illogicity and/or ignorance. You're right, I wasn't reopening the inputfile after doing readlines(), which I was doing each time I opened the file! So, I guess there's a pointer for each file object, that readline increments. If I wanted to reset that pointer for fileObject=file('erm.scc', 'r'), could I just use fileObject.seek(0)? Thanks once again, Liam Clarke On Sat, 20 Nov 2004 20:40:13 -0500, Kent Johnson wrote: > Liam, > > I can't be sure without seeing your whole program, but my guess is you > either > - didn't close the output file before opening for read, or > - didn't re-open the input file between trying readlines() and reading > with the csv reader, so the csv reader was just getting the end-of-file. > > Anyway, here is a version of your snippets that works: > > import csv > > spreadS=[['A','B','C'],[1,2,3],[4,5,6]] > dave=file('test.csv', 'w') > henry=csv.writer(dave) > henry.writerows(spreadS) > dave.close() > > x=file('test.csv','r') > bob=csv.reader(x) > for element in bob: > print element > > > Kent > > > > > Liam Clarke wrote: > > Hi all, > > > > Trying to work the CSV module, and I'm not quite sure how to > > input/output through it. > > > > I've worked out to output a CSV file that looks like - > > > > A B C > > 1 2 3 > > 4 5 6 > > > > you have to use a list like this - > > spreadS=[['A','B','C'],[1,2,3],[4,5,6]], so each row is a separate > > list. > > > > and then > > > > dave=file('test.csv', 'w') > > henry=csv.writer(dave) > > > > and either > > > > for element in dave: > > henry.writerow(element) > > > > or just > > > > henry.writerows(dave). > > > > So writing is fine. But, if I were to reopen test.csv - > > > > x=file('test.csv','r') > > > > I can do this - > > > > > >>>>print x.readlines() > > > > ['A,B,C\r\n', '1,2,3\r\n', '4,5,6\r\n'] > > > > which is roughly what I expected. > > > > Howeever, if I were to do - > > > > > >>>>bob=csv.reader(x) > > > > > > And as per the Python docs - > > > > for element in bob: > > print element > > > > I get nothing. > > > > If I try bob.next(), I get 'StopIteration' which means that it's > > reached the end of the file. > > > > So help? I'm probably doing something quite simple & silly, but the > > documentation isn't much help (to me), and I've got not spreadsheet > > software installed on this comp to check that my csv's are valid. > > > > I figure if I can pipe some data out through the CSV module and then > > pipe it back in and nothing's changed then I'm doing OK. > > > > Regards, > > > > Liam Clarke > > > _______________________________________________ > 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 Sun Nov 21 03:45:13 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Nov 21 03:45:14 2004 Subject: [Tutor] CSV module? In-Reply-To: References: <419FF1FD.3090001@tds.net> Message-ID: <41A00139.4000106@tds.net> Liam Clarke wrote: > Kent, > > As always, you are a beam of light upon the darkness of my illogicity > and/or ignorance. Aw shucks... > > You're right, I wasn't reopening the inputfile after doing > readlines(), which I was doing each time I opened the file! So, I > guess there's a pointer for each file object, that readline > increments. Yes, an open file has a current position. f.readlines() reads until the end of file and leaves the file position at the end. f.tell() tells you the current position and f.seek() lets you set it. Unless you need the raw line data from the file as well as the lists from csv.reader, the simplest thing is just to get rid of the readlines(). Kent From jdecaro2 at comcast.net Sun Nov 21 05:36:23 2004 From: jdecaro2 at comcast.net (Jim DeCaro) Date: Sun Nov 21 05:19:24 2004 Subject: [Tutor] creating files Message-ID: I am very new, and am writing a sketchy program to do a simple encryption for a school project. I have created a loop that iterates through letters from a read file, and compares them to a list. When it finds a match, it converts the letter to a another letter from a corresponding list (hence the encryption) and prints it to the screen. The logic works fine, but I can't save the output to a file. I will not necessarily know what is in the file when it is read, so I can't tell the program to write specific known data as in the tutorials. The output comes from iterations. How do I make a variable that contains all of the letters combined in 1 string that can be saved to a file? I can sometimes get it to write 1 of the letters to the file. I have not gotten to functions yet, so I was hoping there would be a method to save each iterated letter to a variable. I have seen the append method, but I'm not sure about it. Thanks, Jim From cyresse at gmail.com Sun Nov 21 05:36:21 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Nov 21 05:36:23 2004 Subject: [Tutor] creating files In-Reply-To: References: Message-ID: Hi Jim, Are you able to post your code? So, you've got a loop (this is pseudo-code) for element in inputString: outputLetter = element if element in compareToList: outputLetter = otherListItem print outputLetter You could just do this - saveStringList=[] for element in inputString: outputLetter = element if element in compareToList: outputLetter = otherListItem print outputLetter saveStringList.append(outputLetter) saveString="".join(saveStringList) outputFile=file('encrypted.bit','w') outputFile.write(saveString) outputFile.close() So saveStringList starts as [] and each time through the loop, your output letter is printed to the screen, and then appended to saveStringList. So, if the word 'back' became 'head' when encrypted, the prog would flow like this - saveStringList would become ['h'] then ['h','e'] and so forth until your loop finished and it was ['h','e','a','d'] Then saveString="".join(saveStringList) just concentates the list elements into the string 'head'. Which you can then write happily to disk. Hope it helps. (I use a list to remove the hassle of globals.) Liam Clarke On Sat, 20 Nov 2004 23:36:23 -0500, Jim DeCaro wrote: > I am very new, and am writing a sketchy program to do a simple encryption > for a school project. I have created a loop that iterates through letters > from a read file, and compares them to a list. When it finds a match, it > converts the letter to a another letter from a corresponding list (hence the > encryption) and prints it to the screen. The logic works fine, but I can't > save the output to a file. I will not necessarily know what is in the file > when it is read, so I can't tell the program to write specific known data as > in the tutorials. The output comes from iterations. How do I make a > variable that contains all of the letters combined in 1 string that can be > saved to a file? I can sometimes get it to write 1 of the letters to the > file. > > I have not gotten to functions yet, so I was hoping there would be a method > to save each iterated letter to a variable. I have seen the append method, > but I'm not sure about it. > > Thanks, > > Jim > > _______________________________________________ > 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 cyresse at gmail.com Sun Nov 21 08:59:28 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Nov 21 08:59:30 2004 Subject: [Tutor] creating files In-Reply-To: References: Message-ID: Hi Jim, I'm glad it worked. I've forwarded this to the list because someone else usually posts a more elegant way to do something. Have fun, Liam Clarke On Sun, 21 Nov 2004 00:36:30 -0500, Jim DeCaro wrote: > THANK YOU IT WORKED!!!!!!!! > > > > Jim ---------- Forwarded message ---------- From: Jim DeCaro Date: Sun, 21 Nov 2004 00:24:21 -0500 Subject: RE: [Tutor] creating files To: Liam Clarke Thank you for responding so quickly. Here is what I have so far.... I will try your logic and see what happens. Thanks, I'll let you know how it works, and if you want to do anything with this code, feel free. Jim -----Original Message----- From: Liam Clarke [mailto:cyresse@gmail.com] Sent: Saturday, November 20, 2004 11:36 PM To: jdecaro2@comcast.net; Python Tutor Subject: Re: [Tutor] creating files Hi Jim, Are you able to post your code? So, you've got a loop (this is pseudo-code) for element in inputString: outputLetter = element if element in compareToList: outputLetter = otherListItem print outputLetter You could just do this - saveStringList=[] for element in inputString: outputLetter = element if element in compareToList: outputLetter = otherListItem print outputLetter saveStringList.append(outputLetter) saveString="".join(saveStringList) outputFile=file('encrypted.bit','w') outputFile.write(saveString) outputFile.close() So saveStringList starts as [] and each time through the loop, your output letter is printed to the screen, and then appended to saveStringList. So, if the word 'back' became 'head' when encrypted, the prog would flow like this - saveStringList would become ['h'] then ['h','e'] and so forth until your loop finished and it was ['h','e','a','d'] Then saveString="".join(saveStringList) just concentates the list elements into the string 'head'. Which you can then write happily to disk. Hope it helps. (I use a list to remove the hassle of globals.) Liam Clarke On Sat, 20 Nov 2004 23:36:23 -0500, Jim DeCaro wrote: > I am very new, and am writing a sketchy program to do a simple encryption > for a school project. I have created a loop that iterates through letters > from a read file, and compares them to a list. When it finds a match, it > converts the letter to a another letter from a corresponding list (hence the > encryption) and prints it to the screen. The logic works fine, but I can't > save the output to a file. I will not necessarily know what is in the file > when it is read, so I can't tell the program to write specific known data as > in the tutorials. The output comes from iterations. How do I make a > variable that contains all of the letters combined in 1 string that can be > saved to a file? I can sometimes get it to write 1 of the letters to the > file. > > I have not gotten to functions yet, so I was hoping there would be a method > to save each iterated letter to a variable. I have seen the append method, > but I'm not sure about it. > > Thanks, > > Jim > > _______________________________________________ > 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. -- '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. -------------- next part -------------- #Python 2.3 Decryption/Encryption Program #CSE 428 Progammin Language Concepts #Fall II, 2004 #James J. DeCaro #Front Row Plus 1 Group print "************" print "*Python 2.3*" print "************" print print "This program will input data from a file" print "encrypt it, and save the encrypted data" print "to a file. It will also decrypt data" print "and save the decrypted data to a seperate file." print encrypt = ['.',',','!',';','1','2','3','4','5','6','7','8','9','0',' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] decrypt = ['.',',','!',';','1','2','3','4','5','6','7','8','9','0',' ','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','A','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a'] f=open('a:\plain.txt','r') print f print print "Press ENTER to view the contents of the file." z=raw_input() y=f.read() print y print print "The encrypted form of the data is: " print i=0 while i <(len(y)): c=y[i] i=i+1 j=0 while j <(len(encrypt)): d=encrypt[j] if (c == d): e = decrypt[j] j=j+1 print(e), l=str(e) g=open('a:\encrypt.txt','w') h=g.write(l) print print print "The decrypted form of the data is: " print i=0 while i <(len(y)): c=y[i] i=i+1 j=0 while j <(len(decrypt)): d=encrypt[j] if (c == d): e = encrypt[j] j=j+1 print(e), f.close() g.close() a=raw_input() From alan.gauld at freenet.co.uk Sun Nov 21 09:55:42 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Nov 21 09:55:31 2004 Subject: [Tutor] creating files References: Message-ID: <002b01c4cfa7$e238ae30$1e8f8651@xp> > encryption) and prints it to the screen. The logic works fine, but I can't > save the output to a file. .... How do I make a > variable that contains all of the letters combined in 1 string that can be > saved to a file? The answer to your first question lies in the second. To create a string use the append method (or string addition). Once you have the string use the write() method to save it to a file. Here is a simplified (untested!) example: mystring = '' # read 20 characters for n in range(20): char = raw_input('Input a letter')[0] # collect 1st letter mystring += char # save mystring to myfile.txt f = open('myfile.txt','w') f.write(mystring) f.close() HTH. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From justinstraube at charter.net Mon Nov 22 00:20:42 2004 From: justinstraube at charter.net (justinstraube@charter.net) Date: Mon Nov 22 00:20:44 2004 Subject: [Tutor] py2exe - supress console window with GUI app? Message-ID: <3khdbt$d8im24@mxip05a.cluster1.charter.net> Hello, Im trying to use py2exe (a huge thanks to Jacob Schmidt for his previous post with the setup.py, .bat, and step by step instructions.). Py2exe created the .exe file but when I run it an empty console window appears with the program. I have looked around but havent seen anything on how to supress it. I searched through the Activestate message archives but didnt see anything. Can anyone give me a hint? Thanks in advance for your time. regards, Justin From tmclaughlin at csu.edu.au Mon Nov 22 00:38:44 2004 From: tmclaughlin at csu.edu.au (McLaughlin, Toby) Date: Mon Nov 22 00:39:16 2004 Subject: [Tutor] Debugging in emacs Message-ID: <211F78EFD1D870409CC3E4158F4881DA08B32E27@xcww01.riv.csu.edu.au> Thanks Marilyn, Debugging in emacs is obviously not the hottest topic around here. Luckily, I have something working now. For anyone who is interested, here is the trick: 1. Add the following to your program: import pdb pdb.set_trace() 2. Start an interactive Python buffer (C-c !) 3. Run your program (I use C-c C-c) Emacs picks up the line numbers from set_trace() and marks the appropriate line in the source buffer. You can now type 'n' to single step, as well as issue any of the pdb commands mentioned here: http://tinyurl.com/3na4u . The only trouble I have now is that the Python buffer and my source code keep switching places from top to bottom. A minor annoyance that hopefully I will rectify soon. Toby McLaughlin. > -----Original Message----- > From: Marilyn Davis [mailto:marilyn@deliberate.com] > Sent: Saturday, 20 November 2004 9:28 AM > To: McLaughlin, Toby > Cc: tutor@python.org > Subject: Re: [Tutor] Debugging in emacs > > > On Fri, 19 Nov 2004, McLaughlin, Toby wrote: > > > Hi All, > > > > Could somebody suggest a way to debug python in emacs? I'd > like to be > > able to single-step while seeing the code marked in some way and > > possiblly set breakpoints. I read about using pdb from the > command line > > but would love to have debugging integrated in emacs. > Perhaps I should > > make life easy for myself and use one of the fancy GUI > editors, but I > > think it's character building for me to learn emacs. > > Boy, you could hear a pin drop on this topic. > > I use emacs, even though I have spent some time with idle, because I > like it much better. I'm real handy in emacs though, and I don't like > mousing. Mice cause lots of repetitive stress injury. > > I spent some time and some email conversations trying to make use of > the debugger in any environment. I don't remember what happened > exactly but I gave up. > > The thing about an interpreted language is that you can say "print > my_var" in the code instead of in the debugger. And with emacs, I go > back and forth between my code and the emacs shell to run it. I'm > pretty efficient that way. > > If anyone has any suggestions about debugging, in idle or anywhere, I > too would love to hear them. > > Thank you. > > Marilyn Davis > > > > > > Thanks, > > Toby McLaughlin. > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > > From keridee at jayco.net Mon Nov 22 00:58:38 2004 From: keridee at jayco.net (Jacob S.) Date: Mon Nov 22 00:59:10 2004 Subject: [Tutor] py2exe - supress console window with GUI app? References: <3khdbt$d8im24@mxip05a.cluster1.charter.net> Message-ID: <003601c4d026$094ca890$f85328cf@JSLAPTOP> > Hello, > > Im trying to use py2exe (a huge thanks to Jacob Schmidt for his > previous post with the setup.py, .bat, and step by step instructions.). Thank you! > Py2exe created the .exe file but when I run it an empty console window > appears with the program. I have looked around but havent seen anything > on how to supress it. A little earlier in the mailing list, I believe someone wanted similar results, and they were directed toward the os.spawn*() functions. I didn't make very much heads or tails out of the documentation on it, but maybe this could help? Jacob Schmidt From keridee at jayco.net Mon Nov 22 01:00:27 2004 From: keridee at jayco.net (Jacob S.) Date: Mon Nov 22 01:00:53 2004 Subject: [Tutor] Help with re module maybe? References: <000501c4cea4$14295cf0$7f5428cf@JSLAPTOP> <419EBC71.9030006@tds.net> Message-ID: <003b01c4d026$4a1b1500$f85328cf@JSLAPTOP> Thank you Kent! Your function is nifty. I haven't fit it into my situation yet, but I like already! Jacob Schmidt Kent Johnson said one fine day... > In general it is hard to use regular expressions to parse when you have > to keep some state to know what to do. In this case you have to keep > track of the nesting of the parens in order to know how to handle a plus > sign. > > This is a simple enough problem that a simple state machine that counts > open and close parentheses does the job. For more complicated state a > parsing library like pyparsing is very helpful. > > I encourage you to learn about the re module, though. It is often handy. > This HOW-TO might help you get started: > http://www.amk.ca/python/howto/regex/ > > Kent > > Some people, when confronted with a problem, think ?I know, I?ll use > regular expressions.? Now they have two problems. > --Jamie Zawinski, in comp.emacs.xemacs > > > def splitter(s): > ''' Split a string on each plus sign that is not inside parentheses ''' > > parenCount = 0 # Counts current nesting > start = 0 # Start of current run > > for i, c in enumerate(s): > if c == '+' and parenCount == 0: > yield s[start:i] > start = i+1 > elif c == '(': > parenCount += 1 > elif c == ')': > parenCount -= 1 > > # Yield any leftovers > if start < len(s): > yield s[start:] > > test = [ > "x**2+sin(x**2+2*x)", > 'abcd', > '(a+b)+(c+d)', > '((a+b)+(c+d))+e' > ] > > for s in test: > print s, list(splitter(s)) > > > prints: > x**2+sin(x**2+2*x) ['x**2', 'sin(x**2+2*x)'] > abcd ['abcd'] > (a+b)+(c+d) ['(a+b)', '(c+d)'] > ((a+b)+(c+d))+e ['((a+b)+(c+d))', 'e'] > > > > Jacob S. wrote: > > Okay, > > > > say I have a string "x**2+sin(x**2+2*x)" and I want to split it at the > > addition sign. However, I don't want to split it at the addition signs > > inside the parenthesis. How do I go about doing this? > > > > Goes something along the lines > > > > a = a.split("+") # if and only if + not inside parenthesis > > > > That should be enough information to help... > > I think the re module might help. Any insights as to a good walkthrough of > > the re module would be helpful. If you have any suggestions, or would like > > to give me a more detailed way to do this (maybe a specific place in the re > > module?) > > > > Thanks in advance, > > Jacob Schmidt > > > > _______________________________________________ > > 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 pub at berlepsch.de Mon Nov 22 02:28:38 2004 From: pub at berlepsch.de (Fabian von Berlepsch) Date: Mon Nov 22 02:29:11 2004 Subject: [Tutor] trying to find the python equivalent for VB6 "left", "right" and "mid" Message-ID: <200411220129.iAM1Sxq9012974@smtp-prs03.proxy.aol.com> Hallo Guys, I am almost having a nerve crisis! Since 3 hours I am trying to find the python equivalent for VB6 "left", "right" and "mid". Example (what I am looking for): >>> mystring = "Hello world" >>> print left(mystring,7) Hello w - or - >>> mystring = "Hello world" >>> print mid(mystring,2,8) ello wor -------------------------- You see? Thank you so much for getting me out of that mess! Fabian From guillermo.fernandez.castellanos at gmail.com Mon Nov 22 02:39:58 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Mon Nov 22 02:40:01 2004 Subject: [Tutor] trying to find the python equivalent for VB6 "left", "right" and "mid" In-Reply-To: <200411220129.iAM1Sxq9012974@smtp-prs03.proxy.aol.com> References: <200411220129.iAM1Sxq9012974@smtp-prs03.proxy.aol.com> Message-ID: <7d7029e70411211739129156af@mail.gmail.com> hi, I can think of this: >>> mystring = "Hello world" >>> print mystring[:7] Hello w >>> print mystring[7:] orld >>> print mystring[1:9] ello wor Regards, Guille On Mon, 22 Nov 2004 02:28:38 +0100, Fabian von Berlepsch wrote: > Hallo Guys, > > I am almost having a nerve crisis! > Since 3 hours I am trying to find the python equivalent for VB6 "left", > "right" and "mid". > > Example (what I am looking for): > > >>> mystring = "Hello world" > > >>> print left(mystring,7) > > Hello w > > - or - > > >>> mystring = "Hello world" > > >>> print mid(mystring,2,8) > > ello wor > > -------------------------- > > You see? > Thank you so much for getting me out of that mess! > > Fabian > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From maxnoel_fr at yahoo.fr Mon Nov 22 02:41:46 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon Nov 22 02:45:37 2004 Subject: [Tutor] trying to find the python equivalent for VB6 "left", "right" and "mid" In-Reply-To: <200411220129.iAM1Sxq9012974@smtp-prs03.proxy.aol.com> References: <200411220129.iAM1Sxq9012974@smtp-prs03.proxy.aol.com> Message-ID: On Nov 22, 2004, at 01:28, Fabian von Berlepsch wrote: > Hallo Guys, > > I am almost having a nerve crisis! > Since 3 hours I am trying to find the python equivalent for VB6 "left", > "right" and "mid". What you're looking for is the slicing operator. Each character in a string is numbered from 0 to len - 1. >>> foo = "Hello World!" >>> len(foo) 12 You have to use foo[start:finish:step], where start is the first character you want, finish is the first character you don't want, and step is the step of the slice (step = 2 will take one character every two chars). You can omit finish and step if you don't want them. Also, you can use negative numbers to count from the end of the string, e.g. while foo[0] is the first character of the string, foo[-1] is the last one. Here are a few examples: >>> foo = "Hello World!" >>> foo[0:5] 'Hello' >>> foo[1:5] 'ello' >>> foo[5:] ' World!' >>> foo[:5] 'Hello' >>> foo[:-1] 'Hello World' >>> foo[:-2] 'Hello Worl' >>> foo[1] 'e' >>> foo[-1] '!' >>> foo[::2] 'HloWrd' This also works with lists and tuples. Hope that helped, -- 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 tmclaughlin at csu.edu.au Mon Nov 22 02:50:29 2004 From: tmclaughlin at csu.edu.au (McLaughlin, Toby) Date: Mon Nov 22 02:51:51 2004 Subject: [Tutor] trying to find the python equivalent for VB6 "left", "right" and "mid" Message-ID: <211F78EFD1D870409CC3E4158F4881DA09602B84@xcww01.riv.csu.edu.au> Hello Fabian, What you are looking for is Python "slicing". You can choose any subset of a sequence with slicing. Example: >>> mystring = "Hello world" >>> print mystring[0:7] Hello w >>> print mystring[1:9] ello wor >>> Note that the offsets are different to the ones you used in VB. I found this strange at first. The numbers specify where in the sequence to make a "cut". Here's a diagram: Elements: [H] [e] [l] [l] [o] [ ] [w] [o] [r] [l] [d] Indices: 0 1 2 3 4 5 6 7 8 9 10 Hope that helps, Toby McLaughlin. > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] On Behalf Of Fabian von Berlepsch > Sent: Monday, 22 November 2004 12:29 PM > To: tutor@python.org > Subject: [Tutor] trying to find the python equivalent for VB6 > "left","right" and "mid" > > > Hallo Guys, > > I am almost having a nerve crisis! > Since 3 hours I am trying to find the python equivalent for > VB6 "left", > "right" and "mid". > > Example (what I am looking for): > > >>> mystring = "Hello world" > > >>> print left(mystring,7) > > Hello w > > - or - > > >>> mystring = "Hello world" > > >>> print mid(mystring,2,8) > > ello wor > > -------------------------- > > You see? > Thank you so much for getting me out of that mess! > > Fabian > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Nov 22 03:17:45 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Nov 22 03:17:50 2004 Subject: [Tutor] py2exe - supress console window with GUI app? In-Reply-To: <3khdbt$d8im24@mxip05a.cluster1.charter.net> References: <3khdbt$d8im24@mxip05a.cluster1.charter.net> Message-ID: <41A14C49.50801@tds.net> I think you need to use windows = ["myprogram.py"] instead of console = ["myprogram.py"] Look at py2exe\samples\simple\setup.py for an example. I don't know if Jacob's script supports this, you might have to modify it or make your own setup.py... Kent justinstraube@charter.net wrote: > Hello, > > Im trying to use py2exe (a huge thanks to Jacob Schmidt for his > previous post with the setup.py, .bat, and step by step instructions.). > > Py2exe created the .exe file but when I run it an empty console window > appears with the program. I have looked around but havent seen anything > on how to supress it. I searched through the Activestate message > archives but didnt see anything. Can anyone give me a hint? > > Thanks in advance for your time. > > regards, > > Justin > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From justinstraube at charter.net Mon Nov 22 04:55:02 2004 From: justinstraube at charter.net (justinstraube@charter.net) Date: Mon Nov 22 04:55:04 2004 Subject: [Tutor] py2exe - supress console window with GUI app? Message-ID: <3khdfd$ddfkbi@mxip04a.cluster1.charter.net> On Sun, 21 Nov 2004 18:58:38 -0500, Jacob Schmidt wrote: >> Py2exe created the .exe file but when I run it an empty console window >> appears with the program. I have looked around but havent seen anything >> on how to supress it. > >A little earlier in the mailing list, I believe someone wanted similar >results, and they were directed toward the os.spawn*() functions. I didn't >make very much heads or tails out of the documentation on it, but maybe this >could help? > >Jacob Schmidt Thanks for the quick reply :) I had tried to read up about os.spawn but it was way too much for me also. Though somehow my problem has been solved. I think I know what it is. I had slightly altered setup.py, though Im not sure this had anything to do with it. setup(console = listed, windows = [{"script": "OneTime.pyw", "icon_resources": [(1, "d:/python23/me.ico")]}]) The .exe shows the icon as it should and no longer has the console box. However if I cancel out of opening a file a Nonetype is returned which raises an exception. A nice little log file is created for me with the traceback. If anyone is interested in seeing the script or the .exe its available at: http://www.angelfire.com/wi3/phosphorescent/scripts/onetime.html Its a simple attempt at a One Time pad with GUI. Compressed the .rar file is 1907kb, uncompressed its 5.76mb. regards, Justin From justinstraube at charter.net Mon Nov 22 05:09:16 2004 From: justinstraube at charter.net (justinstraube@charter.net) Date: Mon Nov 22 05:09:19 2004 Subject: [Tutor] py2exe - supress console window with GUI app? Message-ID: <3k7897$homn95@mxip12a.cluster1.charter.net> On Sun, 21 Nov 2004 21:17:45 -0500, you wrote: > >I think you need to use > windows = ["myprogram.py"] >instead of > console = ["myprogram.py"] > >Look at py2exe\samples\simple\setup.py for an example. > >I don't know if Jacob's script supports this, you might have to modify >it or make your own setup.py... > >Kent Thanks Kent, heh, I had just sent my last reply when I got this. It seems my change to Jacob's script did have the fix but I now need to remove the 'console = listed' line. So then setup.py now has: setup(windows = [{"script": "My_Script.pyw", "icon_resources": [(1, "My_Icon.ico")]}]) regards, Justin From ramster6 at gmail.com Mon Nov 22 05:48:44 2004 From: ramster6 at gmail.com (Ramkumar Parimal Alagan) Date: Mon Nov 22 05:48:48 2004 Subject: [Tutor] Help with re module maybe? In-Reply-To: <000501c4cea4$14295cf0$7f5428cf@JSLAPTOP> References: <000501c4cea4$14295cf0$7f5428cf@JSLAPTOP> Message-ID: <82c0f73b0411212048617170c4@mail.gmail.com> Python vulnerability permits remote attacks http://searchsecurity.techtarget.com/originalContent/0,289142,sid14_gci954658,00.html From cyresse at gmail.com Mon Nov 22 07:46:46 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Nov 22 07:46:49 2004 Subject: [Tutor] creating files In-Reply-To: References: Message-ID: > I'm sure there is a more elegant way of doing it since I am a non-programmer > beginner trying to learn Python for the first time. I've been at it six weeks, and I've nearly finished my first app, gui et al. If you're using Windows or DOS - You could simply do - dirPath = raw_input(" Please enter directory to save to: (in format c:\dave\ha\)") fileName = raw_input("Please enter filename : ") dirPath = dirPath.replace("\","/") if not dirPath.endswith("/") : filePath=dirPath+"/"+fileName else: filePath=dirPath+fileName saveFile = (filePath, "w") Raw input is the key. Please note that the above is very awkward, and Windows specific. ( Because os.path.join does funny stuff using 'current directories', which I don't understand ) For cross-platform compatibility, explore os.path.join, and then explain it to me when you get it : ) So, the user enters the directory to save to - 'C:\bob\marley\reggae\Man' and the filename '3lilbird.son' Now, dirPath.replace("\","/") does just that. It turns the directory into 'C:/bob/marley/reggae/Man' Python uses it like that, I guess it's a cross platform thing. It then checks whether or nor the user ended the directory with a '\' (which would now be a '/'), if not, it adds it before cocentating the filename The string methods are pretty logical, and very useful. > Thank you for your help. > > Oh, 1 other question though. It would enhance the program if the > interfacing user could type in the path and names of the files they want to > use rather than use already created files. Is there an easy way to do that? > Worth extra points. > > Thanks, > > > > Jim > > -----Original Message----- > From: Liam Clarke [mailto:cyresse@gmail.com] > Sent: Sunday, November 21, 2004 2:59 AM > To: Python Tutor; jdecaro2@comcast.net > Subject: Re: [Tutor] creating files > > Hi Jim, > > I'm glad it worked. > > I've forwarded this to the list because someone else usually posts a > more elegant way to do something. > > Have fun, > > Liam Clarke > > On Sun, 21 Nov 2004 00:36:30 -0500, Jim DeCaro wrote: > > THANK YOU IT WORKED!!!!!!!! > > > > > > > > Jim > > ---------- Forwarded message ---------- > From: Jim DeCaro > Date: Sun, 21 Nov 2004 00:24:21 -0500 > Subject: RE: [Tutor] creating files > To: Liam Clarke > > Thank you for responding so quickly. > > Here is what I have so far.... > > I will try your logic and see what happens. > > Thanks, I'll let you know how it works, and if you want to do anything with > this code, feel free. > > Jim > > -----Original Message----- > From: Liam Clarke [mailto:cyresse@gmail.com] > Sent: Saturday, November 20, 2004 11:36 PM > To: jdecaro2@comcast.net; Python Tutor > Subject: Re: [Tutor] creating files > > Hi Jim, > > Are you able to post your code? > > So, you've got a loop (this is pseudo-code) > > for element in inputString: > outputLetter = element > if element in compareToList: > outputLetter = otherListItem > print outputLetter > > You could just do this - > > saveStringList=[] > > for element in inputString: > outputLetter = element > if element in compareToList: > outputLetter = otherListItem > print outputLetter > saveStringList.append(outputLetter) > > saveString="".join(saveStringList) > > outputFile=file('encrypted.bit','w') > outputFile.write(saveString) > outputFile.close() > > So saveStringList starts as [] > > and each time through the loop, your output letter is printed to the > screen, and then appended to saveStringList. > > So, if the word 'back' became 'head' when encrypted, the prog would > flow like this - > > saveStringList would become ['h'] then ['h','e'] and so forth until > your loop finished and it was ['h','e','a','d'] > > Then saveString="".join(saveStringList) just concentates the list > elements into the string 'head'. > > Which you can then write happily to disk. > > Hope it helps. > > (I use a list to remove the hassle of globals.) > > Liam Clarke > > On Sat, 20 Nov 2004 23:36:23 -0500, Jim DeCaro wrote: > > I am very new, and am writing a sketchy program to do a simple encryption > > for a school project. I have created a loop that iterates through letters > > from a read file, and compares them to a list. When it finds a match, it > > converts the letter to a another letter from a corresponding list (hence > the > > encryption) and prints it to the screen. The logic works fine, but I > can't > > save the output to a file. I will not necessarily know what is in the > file > > when it is read, so I can't tell the program to write specific known data > as > > in the tutorials. The output comes from iterations. How do I make a > > variable that contains all of the letters combined in 1 string that can be > > saved to a file? I can sometimes get it to write 1 of the letters to the > > file. > > > > I have not gotten to functions yet, so I was hoping there would be a > method > > to save each iterated letter to a variable. I have seen the append method, > > but I'm not sure about it. > > > > Thanks, > > > > Jim > > > > _______________________________________________ > > 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. > > -- > '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. > > -- '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 cyresse at gmail.com Mon Nov 22 07:49:18 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Nov 22 07:49:21 2004 Subject: [Tutor] py2exe - supress console window with GUI app? In-Reply-To: <3k7897$homn95@mxip12a.cluster1.charter.net> References: <3k7897$homn95@mxip12a.cluster1.charter.net> Message-ID: If you're running on a Windows system, try using Pythonw.exe instead of Python. It's what IDLE runs through. : ) On Sun, 21 Nov 2004 22.07.51 -0800, justinstraube@charter.net wrote: > On Sun, 21 Nov 2004 21:17:45 -0500, you wrote: > > > > > >I think you need to use > > windows = ["myprogram.py"] > >instead of > > console = ["myprogram.py"] > > > >Look at py2exe\samples\simple\setup.py for an example. > > > >I don't know if Jacob's script supports this, you might have to modify > >it or make your own setup.py... > > > >Kent > > Thanks Kent, > > heh, I had just sent my last reply when I got this. It seems my change > to Jacob's script did have the fix but I now need to remove the > 'console = listed' line. > > So then setup.py now has: > > setup(windows = [{"script": "My_Script.pyw", > "icon_resources": [(1, "My_Icon.ico")]}]) > > > > > regards, > > Justin > > _______________________________________________ > 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 Mon Nov 22 08:39:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 22 08:39:42 2004 Subject: [Tutor] Help with re module maybe? [off-topic security bulletin?] In-Reply-To: <82c0f73b0411212048617170c4@mail.gmail.com> Message-ID: On Mon, 22 Nov 2004, Ramkumar Parimal Alagan wrote: > Python vulnerability permits remote attacks > > http://searchsecurity.techtarget.com/originalContent/0,289142,sid14_gci954658,00.html Hi Ramukumar, Thanks for the update. But... what does this have to do with regular expressions? This mailing list is dedicated to teaching folks how to program in Python; it's not quite useful to send security bulletins here. The main newsgroup at comp.lang.python might be more appropriate for security updates. Please try to stay topical; as we get more traffic on this Tutor list, we need to keep the signal-to-noise ratio as high as we can. As a side note, that security bulletin appears to cover Python 2.2. The bulletin was written in March, so it's pretty stale. It does not appear to apply to the current 2.3 release. Good luck to you. From cyresse at gmail.com Mon Nov 22 08:58:13 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Nov 22 08:58:16 2004 Subject: [Tutor] Dynamic-ish naming of variables? Message-ID: Hi all, As I've been following the tutor group, this has come up from time to time, and the usual response has been, why would you want to? Well, here's why. I'm building a GUI with PythonCard, and I want to allow the user to edit a list of people, which will then display or be removed from the window. Easy enough to do. But, what I want to do is to have a checkbox and choice box for each name. PythonCard uses a resource file to define widgets, and it would look like this - {'type':'Choice', 'name':'Choice1', 'position':(117, 112), 'items':[], }, {'type':'CheckBox', 'name':'CheckBox1', 'position':(104, 71), 'checked':True, 'label':'CheckBox1', }, So, I can use Python to write in widgets to that code or remove them, simple enough concept. My trouble is the name part. I haven't used dictionaries that often, or would a list be better? When the user clicks 'save' I want Python to move down the list, checking to see if each checkbox has been checked or not, and what the value of the choice box is. I figure simplest way to 'dynamically' create my widgets is to reference them by the name added - i.e. the name "Liam Clarke" added would create the following - {'type':'Choice', 'name':'LiamClarkeChoice', 'position':(117, 112), 'items':[], }, {'type':'CheckBox', 'name':'LiamClarkeCheck', 'position':(104, 71), 'checked':True, 'label':'CheckBox1', }, Python checks values assigned by the following - if self.components.LiamClarkeCheck.checked=True .... How do I do the name part randomly, short of having my module re-write itself? Ideally it would iterate over a list, something along these pseudo-lines - for name in nameList: if self.components.%sCheck.checked=True % name teamDict[name]=self.components.%sChoice.field % name That's impossible of course, but it's what I'd like to do. Any suggestions? Could I do something like the above and use eval / exec? I'm not too familiar with them. Thanks in advance, Liam Clarke -- '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 Mon Nov 22 09:08:31 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 22 09:08:34 2004 Subject: [Tutor] Multi-Line SQL Statement in Python In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC0143@riv-excha5.echostar.com> Message-ID: On Fri, 19 Nov 2004, Gooch, John wrote: > I have a rather involved query to run on an MS SQL Server 2000 system. I > developed the query using the MS SQL Query Analyzer, and it returns 5 > records when I run it from there. Hi John, Have you gotten a response for one of the Tutors here yet? It looks like most of us may be stumped! As far as I understand, the execute() method of a Python database connection can only execute a single command. I don't believe it has a provision for executing multiple commands at once. So you may need to split up your query into three pieces, or restructure the query so that it's a single SQL statement. I don't know if MS SQL supports subselect, but you may be able to restructure the query to something like: ### query = """ --Get the latest Drive Space Records SELECT adh.Legend,ad.DetailShort FROM dbo.ArchiveDataHeader As adh (NOLOCK), dbo.ArchiveData As ad (NOLOCK) WHERE adh.MCMachineObjID in ( SELECT ob.objid FROM dbo.object as ob WHERE ob.name = 'SUPERMAN' ) AND ad.DataID=adh.DataID AND adh.Legend LIKE 'Ldsk: \%AVAIL^^MB' AND DATEDIFF( day, DATEADD( second, ad.BiasedTime, '19700101' ), getdate() ) < 2 ORDER BY DATEADD( second, ad.BiasedTime, '19700101' ) DESC """ resultCount = cursor.execute(query) print resultCount ### But I could be totally wrong about this. *grin* Unfortunately, I can't test this, since I have no access to a MS SQL database. You may want to double check with the db-sig folks at: http://mail.python.org/mailman/listinfo/db-sig They'd have more competency about the database issues, so you should probably give them a try. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Mon Nov 22 09:35:15 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 22 09:35:23 2004 Subject: [Tutor] Dynamic-ish naming of variables? In-Reply-To: Message-ID: On Mon, 22 Nov 2004, Liam Clarke wrote: > Python checks values assigned by the following - > > if self.components.LiamClarkeCheck.checked=True .... Hi Liam, Hmmm! I haven't played with PythonCard that much yet. According to the documentation on: http://pythoncard.sourceforge.net/framework/general_concepts_and_limitations.html "components" is a dictionary-like object, with extra syntactic sugar so that we can use dot notation. That means that, hopefully, we're pretty much home free, because it's fairly easy to do dynamic inserts into a dictionary without much magic. I believe the 'components' attribute is an instance of the 'WidgetDict' class, from looking at the code of PythonCard's data model: http://cvs.sourceforge.net/viewcvs.py/pythoncard/PythonCard/model.py?rev=1.190&view=auto > Ideally it would iterate over a list, something along these pseudo-lines > for name in nameList: > if self.components.%sCheck.checked=True % name > teamDict[name]=self.components.%sChoice.field % name You should actually be able to say something like: ### for name in nameList: if self.components[name].checked = True: teamDict[name] = self.components[name].checked ### I have not tested this yet though. I'm going to regret saying that, aren't I? *grin* I just don't have access to wxPython at the moment. If you have more questions, please feel free to ask! From cyresse at gmail.com Mon Nov 22 10:59:11 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Nov 22 10:59:14 2004 Subject: [Tutor] Dynamic-ish naming of variables? In-Reply-To: References: Message-ID: Hi Danny, It has been said that Kiwis (the people, not bird or Americanised name of a fruit) are a fairly unemotional & laidback bunch of people. Well, not this misnamed fruit (which was originally called a chinese gooseberry). I just did an impression of an overexcitable Mediterranean soccer fan watching his 99th ranked in the world team come back to win in the penalty shoot out against Brazil. I tried the code as follows - def on_PastReportButton_mouseClick(self, event): nameList=['CheckBox1'] print "This won't be doing jack until you've run the first option." self.testWindow=model.childWindow(self, test.testDict) for name in nameList: if self.testWindow.components[name].checked: print "It vorked" and I got - This won't be doing jack until you've run the first option. It vorked So a thousand thanks Danny, my brain was going seriously curly trying to figure that one out. Regards, Liam Clarke On Mon, 22 Nov 2004 00:35:15 -0800 (PST), Danny Yoo wrote: > > > On Mon, 22 Nov 2004, Liam Clarke wrote: > > > Python checks values assigned by the following - > > > > if self.components.LiamClarkeCheck.checked=True .... > > Hi Liam, > > Hmmm! I haven't played with PythonCard that much yet. According to the > documentation on: > > http://pythoncard.sourceforge.net/framework/general_concepts_and_limitations.html > > "components" is a dictionary-like object, with extra syntactic sugar so > that we can use dot notation. That means that, hopefully, we're pretty > much home free, because it's fairly easy to do dynamic inserts into a > dictionary without much magic. > > I believe the 'components' attribute is an instance of the 'WidgetDict' > class, from looking at the code of PythonCard's data model: > > http://cvs.sourceforge.net/viewcvs.py/pythoncard/PythonCard/model.py?rev=1.190&view=auto > > > > Ideally it would iterate over a list, something along these pseudo-lines > > for name in nameList: > > if self.components.%sCheck.checked=True % name > > teamDict[name]=self.components.%sChoice.field % name > > > You should actually be able to say something like: > > ### > for name in nameList: > if self.components[name].checked = True: > teamDict[name] = self.components[name].checked > ### > > I have not tested this yet though. I'm going to regret saying that, > aren't I? *grin* I just don't have access to wxPython at the moment. > > If you have more questions, please feel free to ask! > > -- '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 alan.gauld at freenet.co.uk Mon Nov 22 11:55:23 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Nov 22 11:55:12 2004 Subject: [Tutor] Dynamic-ish naming of variables? References: Message-ID: <007401c4d081$c4b3e8e0$1e8f8651@xp> > Well, here's why. ... Nope, not yet. > {'type':'CheckBox', > 'name':'LiamClarkeCheck', > 'position':(104, 71), > 'checked':True, > 'label':'CheckBox1', > }, > > Python checks values assigned by the following - > > if self.components.LiamClarkeCheck.checked=True .... > > How do I do the name part randomly, short of having my module re-write itself? if self.components.checkboxes['LiamClarkCheck'].checked = True does the same thing using a dictionary. > Ideally it would iterate over a list, something along these pseudo-lines - > > for name in nameList: > > if self.components.%sCheck.checked=True % name > teamDict[name]=self.components.%sChoice.field % name > cb = self.comonents.checkBoxes # saves typing! for name in nameList: if cb[name].checked = True teamDict[name] = cb[name].field > Any suggestions? Could I do something like the above and use eval / > exec? I'm not too familiar with them. No magic just a dictionary for the checkbox components. Remember that Python uses dictionaries for all its variable name handling interally so whatever python does with names internally you can pretty much do explicitly by adding an explicit dictionary. HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Mon Nov 22 12:04:29 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Nov 22 12:04:42 2004 Subject: [Tutor] creating files In-Reply-To: References: Message-ID: <41A1C7BD.6060709@tds.net> Liam Clarke wrote: >>I'm sure there is a more elegant way of doing it since I am a non-programmer >>beginner trying to learn Python for the first time. > > If you're using Windows or DOS - > > You could simply do - > > dirPath = raw_input(" Please enter directory to save to: (in format > c:\dave\ha\)") > fileName = raw_input("Please enter filename : ") > > dirPath = dirPath.replace("\","/") You don't have to do this. Python works with both / and \ path separators on Windows. Side note: If you are putting a directory path in a string you have to be careful with \ because it is the string escape character so you have to use double \\ or raw strings: dirPath = "C:\\dave\\ha\\" or dirPath = r"C:\dave\ha\" > if not dirPath.endswith("/") : > filePath=dirPath+"/"+fileName > else: > filePath=dirPath+fileName These four lines can be replaced with filePath = os.path.join(dirPath, fileName) os.path.join() is smart enough to work with and without a trailing path separator on dirPath. > > saveFile = (filePath, "w") > > > > Raw input is the key. Please note that the above is very awkward, and > Windows specific. > ( Because os.path.join does funny stuff using 'current directories', > which I don't understand ) I didn't know what you meant by this, I had to look at the docs. It turns out that what I said about os.path.join() adding path separators is not quite the whole story. If the first argument is just a drive letter, then it will not put in a separator, giving a relative path. If the first component is more than just a drive letter, it will put in a separator. For example, >>> import os >>> os.path.join('c:', 'foo') 'c:foo' >>> os.path.join('c:/', 'foo') 'c:/foo' >>> os.path.join('c:/bar', 'foo') 'c:/bar\\foo' So in this case (where the user is typing in the directory) maybe Liam's code to concatenate the file path is the best solution. Kent From cyresse at gmail.com Mon Nov 22 15:11:24 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Nov 22 15:11:29 2004 Subject: [Tutor] Dynamic-ish naming of variables? In-Reply-To: <007401c4d081$c4b3e8e0$1e8f8651@xp> References: <007401c4d081$c4b3e8e0$1e8f8651@xp> Message-ID: Hi Alan, Feels pretty magical when I 'get' that concept, and I find myself wishing I could study this fulltime to 'get' it quicker. Oh well, one day at a time. Regards, Liam Clarke On Mon, 22 Nov 2004 10:55:23 -0000, Alan Gauld wrote: > > Well, here's why. ... > > Nope, not yet. > > > > > {'type':'CheckBox', > > 'name':'LiamClarkeCheck', > > 'position':(104, 71), > > 'checked':True, > > 'label':'CheckBox1', > > }, > > > > Python checks values assigned by the following - > > > > if self.components.LiamClarkeCheck.checked=True .... > > > > How do I do the name part randomly, short of having my module > re-write itself? > > if self.components.checkboxes['LiamClarkCheck'].checked = True > > does the same thing using a dictionary. > > > Ideally it would iterate over a list, something along these > pseudo-lines - > > > > for name in nameList: > > > > if self.components.%sCheck.checked=True % name > > teamDict[name]=self.components.%sChoice.field % name > > > > cb = self.comonents.checkBoxes # saves typing! > for name in nameList: > if cb[name].checked = True > teamDict[name] = cb[name].field > > > Any suggestions? Could I do something like the above and use eval / > > exec? I'm not too familiar with them. > > No magic just a dictionary for the checkbox components. > Remember that Python uses dictionaries for all its variable > name handling interally so whatever python does with names > internally you can pretty much do explicitly by adding an > explicit dictionary. > > HTH > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > -- '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 carroll at tjc.com Mon Nov 22 18:55:37 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon Nov 22 18:55:42 2004 Subject: [Tutor] Python security bug (was: Help with re module maybe? In-Reply-To: <82c0f73b0411212048617170c4@mail.gmail.com> Message-ID: On Mon, 22 Nov 2004, Ramkumar Parimal Alagan wrote: > Python vulnerability permits remote attacks > > http://searchsecurity.techtarget.com/originalContent/0,289142,sid14_gci954658,00.html Note this only bug (which seems to have been reported last March) applies to Python 2.2.1 or earlier. It's fixed in Python 2.2.2 and later releases. >From http://secunia.com/product/1361/ , it looks like Python 2.2 had a pretty good track record. Only two security advisories, one "moderate" one "less [critical]" That's not bad. Python 2.3, http://secunia.com/product/1362/ , has only one, the same "less". From pub at berlepsch.de Tue Nov 23 02:11:11 2004 From: pub at berlepsch.de (Fabian von Berlepsch) Date: Tue Nov 23 02:44:54 2004 Subject: [Tutor] problem with stirng.find Message-ID: <200411230112.iAN1BqU27429@mx3.evanzo-server.de> I am using pyserail for reading the serial port I get the following string (print s) : "\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n" When I do Import string Print string.find(s,"S!A") It prints: 11 What is happening here? Thank you very much for any advice! Yours Fabian From isrgish at fastem.com Tue Nov 23 03:35:40 2004 From: isrgish at fastem.com (Isr Gish) Date: Tue Nov 23 03:36:02 2004 Subject: [Tutor] problem with stirng.find Message-ID: <20041123023601.220861E4003@bag.python.org> Fabian von Berlepsch" wrote: >I am using pyserail for reading the serial port >I get the following string (print s) : >"\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n" > >When I do > >Import string You don't need to import string. You cAn do the following. >>> s = 'Hello world!' >>> s.find('w') IOW most of the functions in the string module, are now available as string methods. >Print string.find(s,"S!A") > >It prints: 11 The find method (function) returns the index where the substring was found. I'm not sure what you expected to happen. All the best, Isr > >What is happening here? > >Thank you very much for any advice! > >Yours Fabian > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From ramster6 at gmail.com Tue Nov 23 04:05:12 2004 From: ramster6 at gmail.com (Ramkumar Parimal Alagan) Date: Tue Nov 23 04:05:22 2004 Subject: [Tutor] how to zip data? Message-ID: <82c0f73b041122190571903dba@mail.gmail.com> I am on windows XP, new to Python. i'm learning to take back up, i want to know how to zip the data. ++++++++++++++++++++++++++++++++++++++++++ import os import time source = ['d:\\down'] target_dir = 'd:\\' target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED' ++++++++++++++++++++ is the zip command rite?? From orbitz at ezabel.com Tue Nov 23 04:19:38 2004 From: orbitz at ezabel.com (orbitz) Date: Tue Nov 23 04:19:52 2004 Subject: [Tutor] how to zip data? In-Reply-To: <82c0f73b041122190571903dba@mail.gmail.com> References: <82c0f73b041122190571903dba@mail.gmail.com> Message-ID: <41A2AC4A.6050909@ezabel.com> Doubtful, I don't think windows comes with any zip programs by default. python has a zipfile module, you should just use that. http://docs.python.org/lib/module-zipfile.html Ramkumar Parimal Alagan wrote: >I am on windows XP, new to Python. > >i'm learning to take back up, i want to know how to zip the data. > >++++++++++++++++++++++++++++++++++++++++++ > >import os >import time > >source = ['d:\\down'] > > >target_dir = 'd:\\' > > >target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' > > >zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > >if os.system(zip_command) == 0: > print 'Successful backup to', target >else: > print 'Backup FAILED' > > >++++++++++++++++++++ > >is the zip command rite?? >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From BranimirP at cpas.com Tue Nov 23 05:09:51 2004 From: BranimirP at cpas.com (Branimir Petrovic) Date: Tue Nov 23 05:09:59 2004 Subject: [Tutor] how to zip data? Message-ID: <33678E78A2DD4D418396703A750048D4010250D0@RIKER> > -----Original Message----- > From: Ramkumar Parimal Alagan [mailto:ramster6@gmail.com] > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > > if os.system(zip_command) == 0: > print 'Successful backup to', target > else: > print 'Backup FAILED' > """No such a thing as "zip" command/utility on Windows, but using Python's standard library you could build your own.... Example below shows how to gz-ip a file (if you wonder why .gz and not .zip: gzip library compresses as good and has no upper limit on how large file it can process). If below example looks too involving, you could purchase WinZip and get command line utility that will zip files for you via os.system call (but beware - WinZip can not zip/unzip files larger than 4 GB) Branimir """ ###################################################################### # FileName gzDemo.py ###################################################################### import exceptions, os, re, gzip def gzipIt(filetogzip, gzippedname=None): """Will GZIP file whose path is described by 'filetogzip' string. Parameters: filetogzip, gzippedname - STRING By default (if 'gzippedname' not supplied):, - will gunzip 'filetogzip' to same folder with the source file, - will add '.gz' suffix to file name - will remove source file after successful gzipping. If 'gzippedname' is supplied, the source ('filetogzip') is not removed. Works like a charm although is 20% slower than GNU's gunzip utility. """ chunksize=1048576 removesource = False if not gzippedname: gzippedname = filetogzip + r'.gz' removesource = True inputfile = file(filetogzip, r'rb', chunksize) try: chunkdata = inputfile.read(chunksize) gzoutfile = gzip.open(gzippedname, mode='wb', compresslevel=5) try: while chunkdata: gzoutfile.write(chunkdata) chunkdata = inputfile.read(chunksize) finally: gzoutfile.close() finally: inputfile.close() if removesource: os.remove(filetogzip) def gunzipIt(filetogunzip, gunzippedname=None): """Will GUNZIP file whose path is described by 'filetogzip' string. Parameters: filetogunzip, gunzippedname - STRING By default (if 'gunzippedname' not supplied):, - will gunzip 'filetogunzip' to same folder with the source file, - will strip '.gz' from file name suffix and - will remove source file after successful gunzipping. If 'gunzippedname' is supplied, the source ('filetogunzip') is not removed. Works like a charm although is 30% slower than GNU's gunzip utility. """ chunksize=8192 removesource = False if not gunzippedname: # strip '.gz' off the end of gzippedname gunzippedname = re.sub('(\.(g|G)(z|Z))', '', filetogunzip) removesource = True fgunzip = gzip.open(filetogunzip, mode='rb') try: chunkdata = fgunzip.read(chunksize) foutput = file(gunzippedname, r'wb', chunksize) try: while chunkdata: foutput.write(chunkdata) chunkdata = fgunzip.read(chunksize) finally: foutput.close() finally: fgunzip.close() if removesource: os.remove(filetogunzip) if __name__=="__main__": try: # 1st run will "do-it:" toZip = r'C:\_b\textStuff.txt' gzipIt(toZip) except exceptions.IOError: # 2nd run will "un-do-it": try: toUnZip = r'C:\_b\textStuff.txt.gz' gunzipIt(toUnZip) except exceptions.IOError: pass From glingl at aon.at Tue Nov 23 08:41:48 2004 From: glingl at aon.at (Gregor Lingl) Date: Tue Nov 23 08:41:30 2004 Subject: [Tutor] problem with stirng.find In-Reply-To: <20041123023601.220861E4003@bag.python.org> References: <20041123023601.220861E4003@bag.python.org> Message-ID: <41A2E9BC.2000301@aon.at> Isr Gish schrieb: >Fabian von Berlepsch" wrote: > >I am using pyserail for reading the serial port > >I get the following string (print s) : > >"\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n" > > > >When I do > > > >Import string > >... > > functions in the string module, are now available as string methods. > > >Print string.find(s,"S!A") > > > >It prints: 11 > >The find method (function) returns the index where the substring was found. I'm not sure what you expected to happen. > > First I was surprised to find >>> for c in "\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n": c,ord(c) ('\xff', 255) ('S', 83) ('!', 33) ('A', 65) ('A', 65) ('A', 65) ('A', 65) ('\xfe', 254) ('0', 48) ('.', 46) ('0', 48) ('0', 48) ('5', 53) ('\r', 13) ('\n', 10) ('\xff', 255) ('S', 83) ('!', 33) ('A', 65) ('A', 65) ('A', 65) ('A', 65) ('\xfe', 254) ('0', 48) ('.', 46) ('0', 48) ('0', 48) ('5', 53) ('\r', 13) ('\n', 10) >>> "\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n"[11:14] '05\r' So I checked if find indeed returned 11: >>> "\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n".find("S!A") 1 >>> "\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n".find("S!A",2) # next occurrence 16 >>> That's ok, isn't it? Gregor From erimendz at gmail.com Tue Nov 23 13:13:43 2004 From: erimendz at gmail.com (Eri Mendz) Date: Tue Nov 23 13:13:37 2004 Subject: [Tutor] RE: how to zip data? (Branimir Petrovic) In-Reply-To: <20041123110109.700051E4016@bag.python.org> References: <20041123110109.700051E4016@bag.python.org> Message-ID: <41A32977.1040103@gmail.com> Hello list, I'm trying to understanding this zip code. Can you kindly explain what's happening step by step? The try: finally clause is something new. And also what does the below code do? I see this always in the codes in this group. I seem not to encounter this (yet) in my tutorial reference. TIA > if __name__=="__main__": -- Regards, erimendz Gmail Google Mail >> -----Original Message----- >> From: Ramkumar Parimal Alagan [mailto:ramster6@gmail.com] [snip] >> zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) >> >> if os.system(zip_command) == 0: >> print 'Successful backup to', target >> else: >> print 'Backup FAILED' >> > """No such a thing as "zip" command/utility on Windows, but using > Python's standard library you could build your own.... > > Example below shows how to gz-ip a file (if you wonder why .gz and > not .zip: gzip library compresses as good and has no upper limit > on how large file it can process). > > If below example looks too involving, you could purchase WinZip > and get command line utility that will zip files for you via > os.system call (but beware - WinZip can not zip/unzip files larger > than 4 GB) > > Branimir > """ > > ###################################################################### > # FileName gzDemo.py > ###################################################################### > > import exceptions, os, re, gzip > > def gzipIt(filetogzip, gzippedname=None): > """Will GZIP file whose path is described by 'filetogzip' string. > > Parameters: > filetogzip, gzippedname - STRING > > By default (if 'gzippedname' not supplied):, > - will gunzip 'filetogzip' to same folder with the source file, > - will add '.gz' suffix to file name > - will remove source file after successful gzipping. > > If 'gzippedname' is supplied, the source ('filetogzip') is not removed. > > Works like a charm although is 20% slower than GNU's gunzip utility. > """ > > chunksize=1048576 > removesource = False > > if not gzippedname: > gzippedname = filetogzip + r'.gz' > removesource = True > > inputfile = file(filetogzip, r'rb', chunksize) > try: > chunkdata = inputfile.read(chunksize) > gzoutfile = gzip.open(gzippedname, mode='wb', compresslevel=5) > try: > while chunkdata: > gzoutfile.write(chunkdata) > chunkdata = inputfile.read(chunksize) > finally: > gzoutfile.close() > finally: > inputfile.close() > > if removesource: os.remove(filetogzip) > > > def gunzipIt(filetogunzip, gunzippedname=None): > """Will GUNZIP file whose path is described by 'filetogzip' string. > > Parameters: > filetogunzip, gunzippedname - STRING > > By default (if 'gunzippedname' not supplied):, > - will gunzip 'filetogunzip' to same folder with the source file, > - will strip '.gz' from file name suffix and > - will remove source file after successful gunzipping. > > If 'gunzippedname' is supplied, the source ('filetogunzip') is not > removed. > > Works like a charm although is 30% slower than GNU's gunzip utility. > """ > > chunksize=8192 > removesource = False > > if not gunzippedname: > # strip '.gz' off the end of gzippedname > gunzippedname = re.sub('(\.(g|G)(z|Z))', '', filetogunzip) > removesource = True > > fgunzip = gzip.open(filetogunzip, mode='rb') > try: > chunkdata = fgunzip.read(chunksize) > foutput = file(gunzippedname, r'wb', chunksize) > try: > while chunkdata: > foutput.write(chunkdata) > chunkdata = fgunzip.read(chunksize) > finally: > foutput.close() > finally: > fgunzip.close() > > if removesource: os.remove(filetogunzip) > > > > > if __name__=="__main__": > > try: > # 1st run will "do-it:" > toZip = r'C:\_b\textStuff.txt' > gzipIt(toZip) > except exceptions.IOError: > # 2nd run will "un-do-it": > try: > toUnZip = r'C:\_b\textStuff.txt.gz' > gunzipIt(toUnZip) > except exceptions.IOError: > pass > > From jmpurser at gmail.com Tue Nov 23 13:21:37 2004 From: jmpurser at gmail.com (John Purser) Date: Tue Nov 23 13:21:39 2004 Subject: [Tutor] RE: how to zip data? (Branimir Petrovic) In-Reply-To: <41A32977.1040103@gmail.com> References: <20041123110109.700051E4016@bag.python.org> <41A32977.1040103@gmail.com> Message-ID: <479803a704112304212658a198@mail.gmail.com> That limitation on Winzip may have been fixed. The other day I was having trouble zipping and reading a 10 gig file with the native XP zipping utility. It would zip fine but when I tried to extract from the archive XP complained that it was corrupted. I downloaded winzip and had no problems zipping and extracting. John Purser On Tue, 23 Nov 2004 15:13:43 +0300, Eri Mendz wrote: > Hello list, > > I'm trying to understanding this zip code. Can you kindly explain what's > happening step by step? The try: finally clause is something new. And also > what does the below code do? I see this always in the codes in this group. I > seem not to encounter this (yet) in my tutorial reference. TIA > > > if __name__=="__main__": > > -- > Regards, > erimendz > Gmail Google Mail > > >> -----Original Message----- > >> From: Ramkumar Parimal Alagan [mailto:ramster6@gmail.com] > > [snip] > >> zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > >> > >> if os.system(zip_command) == 0: > >> print 'Successful backup to', target > >> else: > >> print 'Backup FAILED' > >> > > > """No such a thing as "zip" command/utility on Windows, but using > > Python's standard library you could build your own.... > > > > Example below shows how to gz-ip a file (if you wonder why .gz and > > not .zip: gzip library compresses as good and has no upper limit > > on how large file it can process). > > > > If below example looks too involving, you could purchase WinZip > > and get command line utility that will zip files for you via > > os.system call (but beware - WinZip can not zip/unzip files larger > > than 4 GB) > > > > Branimir > > """ > > > > ###################################################################### > > # FileName gzDemo.py > > ###################################################################### > > > > import exceptions, os, re, gzip > > > > def gzipIt(filetogzip, gzippedname=None): > > """Will GZIP file whose path is described by 'filetogzip' string. > > > > Parameters: > > filetogzip, gzippedname - STRING > > > > By default (if 'gzippedname' not supplied):, > > - will gunzip 'filetogzip' to same folder with the source file, > > - will add '.gz' suffix to file name > > - will remove source file after successful gzipping. > > > > If 'gzippedname' is supplied, the source ('filetogzip') is not removed. > > > > Works like a charm although is 20% slower than GNU's gunzip utility. > > """ > > > > chunksize=1048576 > > removesource = False > > > > if not gzippedname: > > gzippedname = filetogzip + r'.gz' > > removesource = True > > > > inputfile = file(filetogzip, r'rb', chunksize) > > try: > > chunkdata = inputfile.read(chunksize) > > gzoutfile = gzip.open(gzippedname, mode='wb', compresslevel=5) > > try: > > while chunkdata: > > gzoutfile.write(chunkdata) > > chunkdata = inputfile.read(chunksize) > > finally: > > gzoutfile.close() > > finally: > > inputfile.close() > > > > if removesource: os.remove(filetogzip) > > > > > > def gunzipIt(filetogunzip, gunzippedname=None): > > """Will GUNZIP file whose path is described by 'filetogzip' string. > > > > Parameters: > > filetogunzip, gunzippedname - STRING > > > > By default (if 'gunzippedname' not supplied):, > > - will gunzip 'filetogunzip' to same folder with the source file, > > - will strip '.gz' from file name suffix and > > - will remove source file after successful gunzipping. > > > > If 'gunzippedname' is supplied, the source ('filetogunzip') is not > > removed. > > > > Works like a charm although is 30% slower than GNU's gunzip utility. > > """ > > > > chunksize=8192 > > removesource = False > > > > if not gunzippedname: > > # strip '.gz' off the end of gzippedname > > gunzippedname = re.sub('(\.(g|G)(z|Z))', '', filetogunzip) > > removesource = True > > > > fgunzip = gzip.open(filetogunzip, mode='rb') > > try: > > chunkdata = fgunzip.read(chunksize) > > foutput = file(gunzippedname, r'wb', chunksize) > > try: > > while chunkdata: > > foutput.write(chunkdata) > > chunkdata = fgunzip.read(chunksize) > > finally: > > foutput.close() > > finally: > > fgunzip.close() > > > > if removesource: os.remove(filetogunzip) > > > > > > > > > > if __name__=="__main__": > > > > try: > > # 1st run will "do-it:" > > toZip = r'C:\_b\textStuff.txt' > > gzipIt(toZip) > > except exceptions.IOError: > > # 2nd run will "un-do-it": > > try: > > toUnZip = r'C:\_b\textStuff.txt.gz' > > gunzipIt(toUnZip) > > except exceptions.IOError: > > pass > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ps_python at yahoo.com Tue Nov 23 14:37:58 2004 From: ps_python at yahoo.com (kumar s) Date: Tue Nov 23 14:38:03 2004 Subject: [Tutor] how to select a column from all files in one directory? Message-ID: <20041123133758.57295.qmail@web53703.mail.yahoo.com> Dear group, I have ~40 tab-delimitted text files in one directory. I have to select 4th column from all these files and write it into a single tab delimitted text file. How can I do this in python. I read a prev. post on tutor and tried the following: >>files = listdir('path') This returns the files(file names) in the directory as a list. However, I need the 4th column from all the files in the directory. Can you please help me. Thank you. -kumar __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jmpurser at gmail.com Tue Nov 23 15:28:13 2004 From: jmpurser at gmail.com (John Purser - Gmail) Date: Tue Nov 23 15:28:32 2004 Subject: [Tutor] how to select a column from all files in one directory? In-Reply-To: <20041123133758.57295.qmail@web53703.mail.yahoo.com> Message-ID: Morning Kumar, This worked for me: ###Code Start### import os path = 'C:\\Documents and Settings\\WHOEVER\\My Documents\\temp\\' files = os.listdir(path) out = file('output.txt', 'w') for inFile in files: f = file(path + inFile, 'r') b = f.readline().split(' ') #There's a tab in there, not spaces if len(b) >= 3: out.write(b[3] + '\n') f.close() out.close() ###Code End### I'd give the output file an output directory of it's own to be sure I didn't clobber anything and of course those are windows directory seperators. John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of kumar s Sent: Tuesday, November 23, 2004 05:38 To: tutor@python.org Subject: [Tutor] how to select a column from all files in one directory? Dear group, I have ~40 tab-delimitted text files in one directory. I have to select 4th column from all these files and write it into a single tab delimitted text file. How can I do this in python. I read a prev. post on tutor and tried the following: >>files = listdir('path') This returns the files(file names) in the directory as a list. However, I need the 4th column from all the files in the directory. Can you please help me. Thank you. -kumar __________________________________________________ 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 From BranimirP at cpas.com Tue Nov 23 15:44:16 2004 From: BranimirP at cpas.com (Branimir Petrovic) Date: Tue Nov 23 15:44:20 2004 Subject: [Tutor] RE: how to zip data? (Branimir Petrovic) Message-ID: <33678E78A2DD4D418396703A750048D4010250D1@RIKER> > -----Original Message----- > From: Eri Mendz [mailto:erimendz@gmail.com] > > I'm trying to understanding this zip code. Can you kindly > explain what's happening step by step? Except this piece of loop (that runs as long as inputfile.read(chunksize) has something to "pump out" from input file): > while chunkdata: > gzoutfile.write(chunkdata) > chunkdata = inputfile.read(chunksize) everything else is easy to single step through and see for yourself what happens. Skip over loop by setting break points just before and after the loop, step manually through the rest, and you will understand how all works. I got used to Active State's Komodo for occasional debugging purposes, but you may use whatever else (IDLE, ...) > The try: finally clause is something new. try/finally is the way to ensure clean-up, no matter what. In case of gzipIt/gunzipIt functions "finally" ensures that gzoutfile.close() is called even if there were errors. See "8.6 Defining Clean-up Actions": http://docs.python.org/tut/node10.html#SECTION0010300000000000000000 > And also > what does the below code do? I see this always in the codes > in this group. I > seem not to encounter this (yet) in my tutorial reference. TIA > > > if __name__=="__main__": The above trick works like this: Every python script or imported module has __name__ property and following rule holds: __name__ property of any script you may run is "__main__", but __name__ property of imported module is imported module's name! For instance, should I decide to import gzDemo as module from another script: # FileName: myOtherScript.py import gzDemo # gzDemo is compiled and executed, but since its # __name__ property at this point will be "gzDemo", # if __name__ == "__main__": will evaluate false # and the "demo case" (whatever was inside if) will # not be executed. toZip = r'C:\stuff.txt' gzDemo.gzipIt(toZip) To summarize the trick "if __name__=="__main__":" is typically used to add quick and dirty demo test case and/or to do actual work if and only if the script is run as stand alone script. Branimir From kent37 at tds.net Tue Nov 23 16:25:48 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Nov 23 16:25:52 2004 Subject: [Tutor] how to select a column from all files in one directory? In-Reply-To: References: Message-ID: <41A3567C.9060309@tds.net> This will only output the data from the first line of each file in the source directory. If the files have multiple lines, you need another loop. see below. Also you can make a string with a tab in it with '\t', maybe more readable than this: ' ' Kent John Purser - Gmail wrote: > Morning Kumar, > > This worked for me: > ###Code Start### > import os > path = 'C:\\Documents and Settings\\WHOEVER\\My Documents\\temp\\' > files = os.listdir(path) > out = file('output.txt', 'w') > > for inFile in files: > f = file(path + inFile, 'r') for line in f: b = line.split(' ') #There's a tab in there, not spaces if len(b) >= 3: out.write(b[3] + '\n') > f.close() > > out.close() > > ###Code End### > > > I'd give the output file an output directory of it's own to be sure I didn't > clobber anything and of course those are windows directory seperators. > > John Purser > > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On > Behalf Of kumar s > Sent: Tuesday, November 23, 2004 05:38 > To: tutor@python.org > Subject: [Tutor] how to select a column from all files in one directory? > > > Dear group, > I have ~40 tab-delimitted text files in one > directory. I have to select 4th column from all these > files and write it into a single tab delimitted text > file. How can I do this in python. > > I read a prev. post on tutor and tried the following: > > >>>files = listdir('path') > > > This returns the files(file names) in the directory as > a list. However, I need the 4th column from all the > files in the directory. > > Can you please help me. > > Thank you. > > -kumar > > __________________________________________________ > 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 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ps_python at yahoo.com Tue Nov 23 18:18:19 2004 From: ps_python at yahoo.com (kumar s) Date: Tue Nov 23 18:18:23 2004 Subject: [Tutor] how to select a column from all files in one directory? In-Reply-To: <41A3567C.9060309@tds.net> Message-ID: <20041123171819.42421.qmail@web53709.mail.yahoo.com> Dear Kent and John, thank you very much for your solutions. It is working, however, there is a problem in printing the output in a proper way: >>> path = "C:\\Documents and Settings\\data\\" >>> files = os.listdir(path) >>> out = file('output.txt','w') >>> for inFile in files: f = file(path + inFile,'r') for line in f: b = line.split('\t') if len(b)>=3: out1.write(b[3] + '\n' ) f.close() Here the output files has the 4th column from all the files in one single column. I wanted to have 40 columns (4th column of 40 files) rather instead of one column. I do not no how to ask the loop to print the contents of 4th column in second file after a tab. file1 file2 file3 file4 file5 1.4 34.5 34.2 567.3 344.2 34.3 21.3 76.2 24.4 34.4' ... ... .... ..... ..... could you please suggest. thanks kumar. --- Kent Johnson wrote: > This will only output the data from the first line > of each file in the > source directory. If the files have multiple lines, > you need another > loop. see below. > > Also you can make a string with a tab in it with > '\t', maybe more > readable than this: ' ' > > Kent > > John Purser - Gmail wrote: > > Morning Kumar, > > > > This worked for me: > > ###Code Start### > > import os > > path = 'C:\\Documents and Settings\\WHOEVER\\My > Documents\\temp\\' > > files = os.listdir(path) > > out = file('output.txt', 'w') > > > > for inFile in files: > > f = file(path + inFile, 'r') > for line in f: > b = line.split(' ') #There's a tab in there, not > spaces > if len(b) >= 3: > out.write(b[3] + '\n') > > f.close() > > > > out.close() > > > > ###Code End### > > > > > > I'd give the output file an output directory of > it's own to be sure I didn't > > clobber anything and of course those are windows > directory seperators. > > > > John Purser > > > > -----Original Message----- > > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org]On > > Behalf Of kumar s > > Sent: Tuesday, November 23, 2004 05:38 > > To: tutor@python.org > > Subject: [Tutor] how to select a column from all > files in one directory? > > > > > > Dear group, > > I have ~40 tab-delimitted text files in one > > directory. I have to select 4th column from all > these > > files and write it into a single tab delimitted > text > > file. How can I do this in python. > > > > I read a prev. post on tutor and tried the > following: > > > > > >>>files = listdir('path') > > > > > > This returns the files(file names) in the > directory as > > a list. However, I need the 4th column from all > the > > files in the directory. > > > > Can you please help me. > > > > Thank you. > > > > -kumar > > > > __________________________________________________ > > 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 > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? The all-new My Yahoo! - Get yours free! http://my.yahoo.com From kent37 at tds.net Tue Nov 23 19:13:34 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Nov 23 19:13:38 2004 Subject: [Tutor] how to select a column from all files in one directory? In-Reply-To: <20041123171819.42421.qmail@web53709.mail.yahoo.com> References: <20041123171819.42421.qmail@web53709.mail.yahoo.com> Message-ID: <41A37DCE.7060504@tds.net> To do this you have to remember the data from each file column in a list, then combine the lists. The built-in function map() will combine corresponding list elements. (So will zip, but it terminates when it hits the end of the first list. map will continue until all the lists have been exhausted.) Here is a fairly straightforward way to do it. This requires that the data from column 4 of all the files will fit in memory at once. ################################# path = "C:\\Documents and Settings\\data\\" files = os.listdir(path) listOfColumns = [] # This will contain one list for each file, with the contents of column 4 for inFile in files: columnData = [] f = file(path + inFile,'r') for line in f: b = line.split('\t') if len(b)>=3: columnData.append(b[3]) else: # Row data is too short columnData.append('Error') f.close() listOfColumns.append(columnData) # This creates a list of row lists from the list of column lists # If any of the column lists are too short they will be padded with None rows = map(None, *listOfColumns) out = file('output.txt','w') for row in rows: out.write('\t'.join(row)) out.write('\n') out.close() ########################### Here is a version that uses itertools.izip() to iterate over all the files at once. This only requires enough memory to hold one row from each file at the same time (plus 40 open file objects). This will stop when it hits the end of the file with the fewest lines. ###################################3 from itertools import izip def get3(line): ''' A function to extract the fourth column from a line of data ''' data = line.split('\t') try: return data[3] except IndexError: return 'Error' path = "C:\\Documents and Settings\\data\\" # This makes a list of all the open files files = map(open, [path+file for file in os.listdir(path)]) out = file('output.txt','w') # This iterates all the files in parallel for rows in izip(*files): # Rows is now a list with one line of data from each open file data = [get3(row) for row in rows] out.write('\t'.join(data)) out.write('\n') out.close() ############################## Warning: I haven't actually tested either of these! Kent kumar s wrote: > Dear Kent and John, > thank you very much for your solutions. It is > working, however, there is a problem in printing the > output in a proper way: > > > >>>>path = "C:\\Documents and Settings\\data\\" >>>>files = os.listdir(path) >>>>out = file('output.txt','w') >>>>for inFile in files: > > f = file(path + inFile,'r') > for line in f: > b = line.split('\t') > if len(b)>=3: > out1.write(b[3] + '\n' ) > f.close() > > > > Here the output files has the 4th column from all the > files in one single column. > > I wanted to have 40 columns (4th column of 40 files) > rather instead of one column. > > I do not no how to ask the loop to print the contents > of 4th column in second file after a tab. > > file1 file2 file3 file4 file5 > 1.4 34.5 34.2 567.3 344.2 > 34.3 21.3 76.2 24.4 34.4' > ... ... .... ..... ..... > > > could you please suggest. > > thanks > kumar. > > > > > --- Kent Johnson wrote: > > >>This will only output the data from the first line >>of each file in the >>source directory. If the files have multiple lines, >>you need another >>loop. see below. >> >>Also you can make a string with a tab in it with >>'\t', maybe more >>readable than this: ' ' >> >>Kent >> >>John Purser - Gmail wrote: >> >>>Morning Kumar, >>> >>>This worked for me: >>>###Code Start### >>>import os >>>path = 'C:\\Documents and Settings\\WHOEVER\\My >> >>Documents\\temp\\' >> >>>files = os.listdir(path) >>>out = file('output.txt', 'w') >>> >>>for inFile in files: >>> f = file(path + inFile, 'r') >> >> for line in f: >> b = line.split(' ') #There's a tab in there, not >>spaces >> if len(b) >= 3: >> out.write(b[3] + '\n') >> >>> f.close() >>> >>>out.close() >>> >>>###Code End### >>> >>> >>>I'd give the output file an output directory of >> >>it's own to be sure I didn't >> >>>clobber anything and of course those are windows >> >>directory seperators. >> >>>John Purser >>> >>>-----Original Message----- >>>From: tutor-bounces@python.org >> >>[mailto:tutor-bounces@python.org]On >> >>>Behalf Of kumar s >>>Sent: Tuesday, November 23, 2004 05:38 >>>To: tutor@python.org >>>Subject: [Tutor] how to select a column from all >> >>files in one directory? >> >>> >>>Dear group, >>> I have ~40 tab-delimitted text files in one >>>directory. I have to select 4th column from all >> >>these >> >>>files and write it into a single tab delimitted >> >>text >> >>>file. How can I do this in python. >>> >>>I read a prev. post on tutor and tried the >> >>following: >> >>> >>>>>files = listdir('path') >>> >>> >>>This returns the files(file names) in the >> >>directory as >> >>>a list. However, I need the 4th column from all >> >>the >> >>>files in the directory. >>> >>>Can you please help me. >>> >>>Thank you. >>> >>>-kumar >>> >>>__________________________________________________ >>>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 >>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > > > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - Get yours free! > http://my.yahoo.com > > > From jmutter at uakron.edu Wed Nov 24 01:56:12 2004 From: jmutter at uakron.edu (Jay Mutter) Date: Wed Nov 24 01:50:22 2004 Subject: [Tutor] Database questions Message-ID: Good evening; I am using OS X 10.3.6 on an ibook where I have python 2.3.3 and wxPython 2.5.3.1 installed with mxDateTime, Postgresql and psycopg. What i would like to know ( remember I have not really started using python or any of the others) is what would you suggest as a GUI designer to work with the above for someone who wants to develop a GUI client interface for a RDBMS system. I have looked at wxGlade, Pythoncard, wxDesigner, and Boa constructor and am currently clueless. If I wanted to hone my skills by creating a GUI checkbook register/balancing program would I be best off to simply use the DB modules built into Python. Remember I am definitely a newbie. Thanks Jay Mutter jmutter@uakron.edu From tktucker at gmail.com Wed Nov 24 04:55:20 2004 From: tktucker at gmail.com (Tom Tucker) Date: Wed Nov 24 04:55:23 2004 Subject: [Tutor] Multi-Line SQL Statement in Python In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC0143@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC0143@riv-excha5.echostar.com> Message-ID: <2a278ffe0411231955d2fdbfe@mail.gmail.com> John, Here is a quickie that includes the multi-lines and the "LIKE%" statement. #!/usr/bin/python import MySQLdb, sys sqlquery = """SELECT Host, User \ FROM user \ WHERE host LIKE \'localhost%\'""" try: db = MySQLdb.connect(host="localhost", user="root", db="mysql") cursor = db.cursor() cursor.execute(sqlquery) result = cursor.fetchall() for record in result: print record[0] , record[1] except MySQLdb.Error, e: print "Error %d: %s,\n" % (e.args[0], e.args[1]) cursor.close() db.close() Tom From ps_python at yahoo.com Wed Nov 24 05:48:41 2004 From: ps_python at yahoo.com (kumar s) Date: Wed Nov 24 05:48:45 2004 Subject: [Tutor] Writing SQL statments on multicolumn tab delimitted text file Message-ID: <20041124044842.6601.qmail@web53710.mail.yahoo.com> Dear group, I have a large tab-delimitted file with 82 columns (experiment name) and 13000 rows ( gene names). e1 e2 e3 e4 ..... e80 g1 23.5 34 34.5 45.3 23.5 g2 63.5 34.6 32.4 23.4 78.90 g3 12.2 23.4 56.3 14.6 98.20 g4 9.9 20.1 98.3 21.1 19.4 g5 23.5 23.3 34.3 19.5 18.5 .. g13K I wrote a script, that writes these numbers into SQL statement. for example: INSERT into experiment(exp_name,gene_name,exp_value) VALUES ('e1','g1',23.5); However, this program prints across samples (horizontally): INSERT into experiment(exp_name,gene_name,exp_value) VALUES ('e1','g1',23.5); INSERT into experiment(exp_name,gene_name,exp_value) VALUES ('e2','g1',34); INSERT into experiment(exp_name,gene_name,exp_value) VALUES ('e3','g1',34.5); INSTEAD Of this: I WANT To print the statements vertically (down the list of an experiment): INSERT into experiment(exp_name,gene_name,exp_value) VALUES ('e1','g1',23.5); INSERT into experiment(exp_name,gene_name,exp_value) VALUES ('e1','g2',63.5); INSERT into experiment(exp_name,gene_name,exp_value) VALUES ('e1','g3',12.2); How can I do this: Here is my code : import string from string import split file = open('sql_input.txt','r') read_lines = file.read() matrix = split(read_lines,'\n') first_row = matrix[0] samps = split(first_row,'\t') samples = samps[2:] filew = open('beer.sql','w') for i in range(len(matrix)-1): rows = split(matrix[i+1],'\t') for k in range(len(samples)): filew.write("INSERT INTO affy_proc_data(affy_proc_gene_name,affy_proc_probeset_id,affy_proc_sample,affy_proc_exprs)VALUES (" "'"+rows[0]+"'" "," "'"+rows[1]+"'"",""'"+samples[k]+"'" ","+rows[2+k]+");"'\n') filew.close() Can any one help me suggesting, how to make this loop running over a column and then jump to next , instead of running row by row. Thanks kumar. __________________________________ Do you Yahoo!? Take Yahoo! Mail with you! Get it on your mobile phone. http://mobile.yahoo.com/maildemo From cyresse at gmail.com Wed Nov 24 07:46:08 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Nov 24 07:46:10 2004 Subject: Fwd: [Tutor] problem with stirng.find In-Reply-To: References: <20041123023601.220861E4003@bag.python.org> <41A2E9BC.2000301@aon.at> Message-ID: ---------- Forwarded message ---------- From: Liam Clarke Date: Wed, 24 Nov 2004 19:45:58 +1300 Subject: Re: [Tutor] problem with stirng.find To: Gregor Lingl In the above >I get the following string (print s) : >"\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n" >When I do >Import string >Print string.find(s,"S!A") >It prints: 11 I have no idea what's happening, but if you remove the special characters - i.e. "<\xff>S!AAAA<\xfe>0.005<\r\n><\xff>S!AAAA<\xfe>0.005<\r\n>" x="S!AAAA0.005S!AAAA0.005" then x[:11]="S!AAAA0.005" and x[11:]="S!AAAA0.005" Go figure. On Tue, 23 Nov 2004 08:41:48 +0100, Gregor Lingl wrote: > > > Isr Gish schrieb: > > >Fabian von Berlepsch" wrote: > > >I am using pyserail for reading the serial port > > >I get the following string (print s) : > > >"\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n" > > > > > >When I do > > > > > >Import string > > > >... > > > > functions in the string module, are now available as string methods. > > > > >Print string.find(s,"S!A") > > > > > >It prints: 11 > > > >The find method (function) returns the index where the substring was found. I'm not sure what you expected to happen. > > > > > First I was surprised to find > > >>> for c in "\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n": > c,ord(c) > > ('\xff', 255) > ('S', 83) > ('!', 33) > ('A', 65) > ('A', 65) > ('A', 65) > ('A', 65) > ('\xfe', 254) > ('0', 48) > ('.', 46) > ('0', 48) > ('0', 48) > ('5', 53) > ('\r', 13) > ('\n', 10) > ('\xff', 255) > ('S', 83) > ('!', 33) > ('A', 65) > ('A', 65) > ('A', 65) > ('A', 65) > ('\xfe', 254) > ('0', 48) > ('.', 46) > ('0', 48) > ('0', 48) > ('5', 53) > ('\r', 13) > ('\n', 10) > >>> "\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n"[11:14] > '05\r' > > So I checked if find indeed returned 11: > > >>> "\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n".find("S!A") > 1 > >>> "\xffS!AAAA\xfe0.005\r\n\xffS!AAAA\xfe0.005\r\n".find("S!A",2) # > next occurrence > 16 > >>> > That's ok, isn't it? > > Gregor > > > > _______________________________________________ > 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 ba>>>sic human duty, to take the consequences. -- '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 nick at javacat.f2s.com Wed Nov 24 09:21:20 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Wed Nov 24 09:21:22 2004 Subject: [Tutor] Database questions In-Reply-To: References: Message-ID: <1101284480.41a44480409ba@webmail.freedom2surf.net> Quoting Jay Mutter : > what would you suggest as a GUI > designer to work with the above for someone who wants to develop a GUI > client interface for a RDBMS system. Hi Jay, a lot of folk will probably recommend Tk, and theres nothing wrong with that :) However, I use PythonCard http://www.pythoncard.org which I find absolutely stunning for easily and quickly creating GUI's . Hope that helps, Nick . ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From cyresse at gmail.com Wed Nov 24 09:51:14 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Nov 24 09:51:17 2004 Subject: [Tutor] Sort pointers - Message-ID: Kia ora, Just exploring the wonderful world of dictionaries, and I'm trying to comprehend the sort() method, because as I found, dictionaries are not sorted. So, I've got a dictionary, miscPeople= {'James Bond' : '007' , 'Enid Blyton' : '005' , 'Enid Blyton also' : '006' , 'Captain Planet' : '000' } (Okay, so that's a sample dictionary) So, if I wanted to sort by alphabetical key i.e. (first names here) for name, numerical in miscPeopledict.sorted() (pseudo code): print name, numerical Captain Planet 000 Enid Blyton 005 Enid Blyton also 006 James Bond 007 or conversely, to sort by value in some manner for name, numerical in miscPeopledict.sorted.reverse() James Bond 007 Enid Blyton also 006 Enid Blyton 005 Captain Planet 000 That's just an example of output. I'm not too hung up on the output at the moment, just sort(). It says to use a comparison function... And I have no idea how to work that. ??? Very confused. I've tried searching for info, there's some very complex ways out there to sort data, usually with proper first names (Schwartzian transformations...), but I can't seem to find the simple. Could anyone post some useful links for my education? Much appreciated. Liam Clarke -- '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 cyresse at gmail.com Wed Nov 24 10:02:45 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Nov 24 10:02:50 2004 Subject: [Tutor] Database questions In-Reply-To: <1101284480.41a44480409ba@webmail.freedom2surf.net> References: <1101284480.41a44480409ba@webmail.freedom2surf.net> Message-ID: PythonCard is my weapon of choice, but Spectix is worth looking at as well. It feels a little more... integrated, On Wed, 24 Nov 2004 08:21:20 +0000, nick@javacat.f2s.com wrote: > Quoting Jay Mutter : > > > what would you suggest as a GUI > > designer to work with the above for someone who wants to develop a GUI > > client interface for a RDBMS system. > > Hi Jay, > > a lot of folk will probably recommend Tk, and theres nothing wrong with that :) > However, I use PythonCard http://www.pythoncard.org which I find absolutely > stunning for easily and quickly creating GUI's . > > Hope that helps, > Nick . > > ------------------------------------------------- > Everyone should have http://www.freedom2surf.net/ > > > _______________________________________________ > 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 Wed Nov 24 11:53:21 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Nov 24 11:53:25 2004 Subject: [Tutor] Writing SQL statments on multicolumn tab delimitted text file In-Reply-To: <20041124044842.6601.qmail@web53710.mail.yahoo.com> References: <20041124044842.6601.qmail@web53710.mail.yahoo.com> Message-ID: <41A46821.50707@tds.net> kumar, If you are writing to a database, the order of the writes shouldn't matter. Most databases do not guarantee that insert order is preserved. Instead you should sort when you read from the database by including an 'order by' clause in your query SQL. If you still want to generate the SQL in column order, you have to read all the data into columns before you start generating SQL. This is similar to the last question you had. You can create lists of the row data, then use zip() to swap rows and columns. Kent kumar s wrote: > Dear group, > I have a large tab-delimitted file with 82 columns > (experiment name) and 13000 rows ( gene names). > > e1 e2 e3 e4 ..... e80 > g1 23.5 34 34.5 45.3 23.5 > g2 63.5 34.6 32.4 23.4 78.90 > g3 12.2 23.4 56.3 14.6 98.20 > g4 9.9 20.1 98.3 21.1 19.4 > g5 23.5 23.3 34.3 19.5 18.5 > .. > g13K > > I wrote a script, that writes these numbers into SQL > statement. > > for example: > INSERT into experiment(exp_name,gene_name,exp_value) > VALUES ('e1','g1',23.5); > > However, this program prints across samples > (horizontally): > INSERT into experiment(exp_name,gene_name,exp_value) > VALUES ('e1','g1',23.5); > INSERT into experiment(exp_name,gene_name,exp_value) > VALUES ('e2','g1',34); > INSERT into experiment(exp_name,gene_name,exp_value) > VALUES ('e3','g1',34.5); > > > INSTEAD Of this: > I WANT To print the statements vertically (down the > list of an experiment): > > INSERT into experiment(exp_name,gene_name,exp_value) > VALUES ('e1','g1',23.5); > INSERT into experiment(exp_name,gene_name,exp_value) > VALUES ('e1','g2',63.5); > INSERT into experiment(exp_name,gene_name,exp_value) > VALUES ('e1','g3',12.2); > > > How can I do this: > > Here is my code : > > > import string > from string import split > > file = open('sql_input.txt','r') > read_lines = file.read() > matrix = split(read_lines,'\n') > first_row = matrix[0] > samps = split(first_row,'\t') > samples = samps[2:] > filew = open('beer.sql','w') > for i in range(len(matrix)-1): > rows = split(matrix[i+1],'\t') > for k in range(len(samples)): > filew.write("INSERT INTO > affy_proc_data(affy_proc_gene_name,affy_proc_probeset_id,affy_proc_sample,affy_proc_exprs)VALUES > (" "'"+rows[0]+"'" "," > "'"+rows[1]+"'"",""'"+samples[k]+"'" > ","+rows[2+k]+");"'\n') > > filew.close() > > > Can any one help me suggesting, how to make this loop > running over a column and then jump to next , instead > of running row by row. > > Thanks > > kumar. > > > > > __________________________________ > Do you Yahoo!? > Take Yahoo! Mail with you! Get it on your mobile phone. > http://mobile.yahoo.com/maildemo > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Nov 24 12:05:47 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Nov 24 12:05:52 2004 Subject: [Tutor] Sort pointers - In-Reply-To: References: Message-ID: <41A46B0B.8070206@tds.net> As you have discovered, you can't directly sort a dict. You can only sort a mutable sequence such as a list. You can easily get a list from a dict in three ways: d.keys() is a list of the keys d.values() is a list of the values d.items() is a list of (key, value) tuples For example: >>> mp= {'James Bond' : '007' , 'Enid Blyton' : '005' , 'Enid Blyton also' : '006' , 'Captain Planet' : '000' } >>> mp.keys() ['Enid Blyton also', 'Captain Planet', 'James Bond', 'Enid Blyton'] >>> mp.values() ['006', '000', '007', '005'] >>> mp.items() [('Enid Blyton also', '006'), ('Captain Planet', '000'), ('James Bond', '007'), ('Enid Blyton', '005')] If you want to print the dict in order by key, it's easy - get the items list and sort that. Sorting a list of tuples will sort by the first item in the tuple. Important note: Lists are sorted in place, and sort() doesn't return any value. So you have to assign mp.items() to a name, sort it, and print it as three steps: >>> it = mp.items() >>> it.sort() >>> it [('Captain Planet', '000'), ('Enid Blyton', '005'), ('Enid Blyton also', '006'), ('James Bond', '007')] If you want to sort by something other than the first element, it gets more complicated and there are several options. I recommend using Python 2.4 which has an enhanced sort that greatly simplifies this common need. In P 2.4, sort() has an optional key argument that is a function to use to extract a key. The P 2.4 operator module defines an itemgetter function that makes functions to extract an indexed item from a list. So in P 2.4 you can sort your dict by the value like this: >>> import operator >>> it.sort(key=operator.itemgetter(1)) >>> it [('Captain Planet', '000'), ('Enid Blyton', '005'), ('Enid Blyton also', '006'), ('James Bond', '007')] In Python 2.3 you have two choices: - Use the decorate - sort - undecorate idiom (aka Schwartzian Transform) - Define your own comparison function I'm out of time for explaining right now, maybe someone else can pick up the thread or I'll come back to it later... Kent Liam Clarke wrote: > Kia ora, > > Just exploring the wonderful world of dictionaries, and I'm trying to > comprehend the sort() method, because as I found, dictionaries are not > sorted. > > So, I've got a dictionary, miscPeople= {'James Bond' : '007' , 'Enid > Blyton' : '005' , 'Enid Blyton also' : '006' , 'Captain Planet' : > '000' } > > (Okay, so that's a sample dictionary) > > So, if I wanted to sort by alphabetical key i.e. (first names here) > > for name, numerical in miscPeopledict.sorted() (pseudo code): > print name, numerical > > Captain Planet 000 > Enid Blyton 005 > Enid Blyton also 006 > James Bond 007 > > or conversely, to sort by value in some manner > > for name, numerical in miscPeopledict.sorted.reverse() > > James Bond 007 > Enid Blyton also 006 > Enid Blyton 005 > Captain Planet 000 > > That's just an example of output. I'm not too hung up on the output at > the moment, just sort(). > > It says to use a comparison function... > > And I have no idea how to work that. > > ??? Very confused. I've tried searching for info, there's some very > complex ways out there to sort data, usually with proper first names > (Schwartzian transformations...), but I can't seem to find the simple. > > Could anyone post some useful links for my education? > > Much appreciated. > > Liam Clarke > > From bvande at po-box.mcgill.ca Wed Nov 24 17:30:15 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Nov 24 17:32:43 2004 Subject: [Tutor] Sort pointers - In-Reply-To: <41A46B0B.8070206@tds.net> References: <41A46B0B.8070206@tds.net> Message-ID: <41A4B717.3020902@po-box.mcgill.ca> Kent Johnson said unto the world upon 2004-11-24 06:05: > > In Python 2.3 you have two choices: > - Use the decorate - sort - undecorate idiom (aka Schwartzian Transform) > - Define your own comparison function > > I'm out of time for explaining right now, maybe someone else can pick up > the thread or I'll come back to it later... > > Kent > > Liam Clarke wrote: > >> Kia ora, >> >> Just exploring the wonderful world of dictionaries, and I'm trying to >> comprehend the sort() method, because as I found, dictionaries are not >> sorted. >> >> That's just an example of output. I'm not too hung up on the output at >> the moment, just sort(). >> >> It says to use a comparison function... >> >> And I have no idea how to work that. >> >> ??? Very confused. I've tried searching for info, there's some very >> complex ways out there to sort data, usually with proper first names >> (Schwartzian transformations...), but I can't seem to find the simple. >> >> Could anyone post some useful links for my education? >> >> Much appreciated. >> >> Liam Clarke Hi Liam, maybe this will help: >>> def length_sort(first, second): '''A custom cmp function to pass to sort for sort on item length''' # We do a standard sort of the length of the items compared. return cmp(len(first), len(second)) >>> def alphabetical_sort(first, second): '''A custom cmp function to pass to sort for case insensitive sort''' first = first.lower() second = second.lower() # We do a standard sort on lower-cased versions of the items # compared. return cmp(first, second) a_list = ['BC', 'def', 'GHIJ', 'a', 'kH', 'AH'] >>> print a_list.sort() None >>> # sort modifies in place, so printing a_list.sort() gives None >>> # Probably not what was wanted! >>> >>> a_list.sort() >>> print a_list ['AH', 'BC', 'GHIJ', 'a', 'def', 'kH'] >>> # quite likely not what is wanted either, as all CAP letters come >>> # before lower-case when the standard cmp(x,y) function is used. >>> >>> a_list.sort(alphabetical_sort) >>> print a_list ['a', 'AH', 'BC', 'def', 'GHIJ', 'kH'] >>> # now, via alphabetical_sort(), it is sorted in true alpha-order >>> >>> a_list.sort(length_sort) >>> print a_list ['a', 'AH', 'BC', 'kH', 'def', 'GHIJ'] >>> # Since length_sort only cares about the len of an object, for >>> # any two string of equal length, it leaves their order unchanged >>> # from the way it was before the list was sorted. >>> >>> # Now let's try something a bit silly: >>> def goofy_H_sort(first, second): '''A custom cmp function to pass to sort for 'H'-based sorting''' if 'H' in first and 'H' not in second: return first, second if 'H' in second and 'H' not in first: return second, first return cmp(first, second) >>> a_list.sort(goofy_H_sort) Traceback (most recent call last): File "", line 1, in -toplevel- a_list.sort(goofy_H_sort) TypeError: comparison function must return int >>> >>> # Well, that didn't work! Checking section 2.1 of the Lib Ref >>> # for the cmp(x,y) built-in suggests we do: >>> def goofy_H_sort(first, second): '''A custom cmp function to pass to sort for 'H'-based sorting''' if 'H' in first and 'H' not in second: return -1 # cmp(x,y)'s way of saying x < y, so by returning -1, we # model that behaviour and have our custom sort function # say that first comes before second. if 'H' in second and 'H' not in first: return 1 # cmp(x,y)'s way of saying x > y, so by returning 1, we # model that behaviour and have our custom sort function # say that first comes after second. return cmp(first, second) >>> a_list.sort(goofy_H_sort) >>> print a_list ['AH', 'GHIJ', 'kH', 'BC', 'a', 'def'] >>> HTH, Brian vdB From flaxeater at yahoo.com Wed Nov 24 18:48:09 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Wed Nov 24 18:48:13 2004 Subject: [Tutor] Database questions Message-ID: <20041124174810.27659.qmail@web54310.mail.yahoo.com> Well I would suggest you use Tkinter for the GUI because for what you want to do. I do not feel that wxPython or any of the Designers are really that ready, not like VB or something. Tkinter can be learned in about 14 hours so that you can make interesting stuff, I do not feel that wxPython can be grokked in a like period of time. I too had ambitions of GUI stuff when just starting but have since found CGI to be a much easier UI than any other. However I would like to say that I use Pythoncard to good effect, but it is still immature and not really that newbie friendly, which I believe none of the GUI designers are mature enough to be really easy. HTH Jay Mutter wrote: > Good evening; > I am using OS X 10.3.6 on an ibook where I have python 2.3.3 and > wxPython 2.5.3.1 installed with mxDateTime, Postgresql and psycopg. > > What i would like to know ( remember I have not really started using > python or any of the others) is what would you suggest as a GUI > designer to work with the above for someone who wants to develop a GUI > client interface for a RDBMS system. I have looked at wxGlade, > Pythoncard, wxDesigner, and Boa constructor and am currently clueless. > If I wanted to hone my skills by creating a GUI checkbook > register/balancing program would I be best off to simply use the DB > modules built into Python. > Remember I am definitely a newbie. > > __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From cyresse at gmail.com Wed Nov 24 19:55:19 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Nov 24 19:55:23 2004 Subject: [Tutor] Sort pointers - In-Reply-To: <41A4B717.3020902@po-box.mcgill.ca> References: <41A46B0B.8070206@tds.net> <41A4B717.3020902@po-box.mcgill.ca> Message-ID: Hi all, Thanks Kent. Question - is Python 2.4 release 1 considered a stable release? Brian - Thanks very much for the illuminating functions, they help indeed. So when it returns cmp(x,y) it's returning a negative for x < y, 0 for x == y, and a positive for x > y... eep, a little confused, just trying to understand how Python sorts using that. I may go check out Python 2.4... Regards, Liam Clarke On Wed, 24 Nov 2004 11:30:15 -0500, Brian van den Broek wrote: > Kent Johnson said unto the world upon 2004-11-24 06:05: > > > > > > > > > In Python 2.3 you have two choices: > > - Use the decorate - sort - undecorate idiom (aka Schwartzian Transform) > > - Define your own comparison function > > > > I'm out of time for explaining right now, maybe someone else can pick up > > the thread or I'll come back to it later... > > > > Kent > > > > Liam Clarke wrote: > > > >> Kia ora, > >> > >> Just exploring the wonderful world of dictionaries, and I'm trying to > >> comprehend the sort() method, because as I found, dictionaries are not > >> sorted. > >> > > > > > > >> That's just an example of output. I'm not too hung up on the output at > >> the moment, just sort(). > >> > >> It says to use a comparison function... > >> > >> And I have no idea how to work that. > >> > >> ??? Very confused. I've tried searching for info, there's some very > >> complex ways out there to sort data, usually with proper first names > >> (Schwartzian transformations...), but I can't seem to find the simple. > >> > >> Could anyone post some useful links for my education? > >> > >> Much appreciated. > >> > >> Liam Clarke > > Hi Liam, > > maybe this will help: > > >>> def length_sort(first, second): > '''A custom cmp function to pass to sort for sort on item length''' > # We do a standard sort of the length of the items compared. > return cmp(len(first), len(second)) > > >>> def alphabetical_sort(first, second): > '''A custom cmp function to pass to sort for case insensitive sort''' > first = first.lower() > second = second.lower() > # We do a standard sort on lower-cased versions of the items > # compared. > return cmp(first, second) > > a_list = ['BC', 'def', 'GHIJ', 'a', 'kH', 'AH'] > >>> print a_list.sort() > None > >>> # sort modifies in place, so printing a_list.sort() gives None > >>> # Probably not what was wanted! > >>> > >>> a_list.sort() > >>> print a_list > ['AH', 'BC', 'GHIJ', 'a', 'def', 'kH'] > >>> # quite likely not what is wanted either, as all CAP letters come > >>> # before lower-case when the standard cmp(x,y) function is used. > >>> > >>> a_list.sort(alphabetical_sort) > >>> print a_list > ['a', 'AH', 'BC', 'def', 'GHIJ', 'kH'] > >>> # now, via alphabetical_sort(), it is sorted in true alpha-order > >>> > >>> a_list.sort(length_sort) > >>> print a_list > ['a', 'AH', 'BC', 'kH', 'def', 'GHIJ'] > >>> # Since length_sort only cares about the len of an object, for > >>> # any two string of equal length, it leaves their order unchanged > >>> # from the way it was before the list was sorted. > >>> > >>> # Now let's try something a bit silly: > >>> def goofy_H_sort(first, second): > '''A custom cmp function to pass to sort for 'H'-based sorting''' > if 'H' in first and 'H' not in second: > return first, second > if 'H' in second and 'H' not in first: > return second, first > return cmp(first, second) > > >>> a_list.sort(goofy_H_sort) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > a_list.sort(goofy_H_sort) > TypeError: comparison function must return int > >>> > >>> # Well, that didn't work! Checking section 2.1 of the Lib Ref > >>> # for the cmp(x,y) built-in suggests we do: > >>> def goofy_H_sort(first, second): > '''A custom cmp function to pass to sort for 'H'-based sorting''' > if 'H' in first and 'H' not in second: > return -1 > # cmp(x,y)'s way of saying x < y, so by returning -1, we > # model that behaviour and have our custom sort function > # say that first comes before second. > if 'H' in second and 'H' not in first: > return 1 > # cmp(x,y)'s way of saying x > y, so by returning 1, we > # model that behaviour and have our custom sort function > # say that first comes after second. > return cmp(first, second) > > >>> a_list.sort(goofy_H_sort) > >>> print a_list > ['AH', 'GHIJ', 'kH', 'BC', 'a', 'def'] > >>> > > HTH, > > Brian vdB > > -- '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 Wed Nov 24 21:11:28 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Nov 24 21:11:32 2004 Subject: [Tutor] Sort pointers - In-Reply-To: References: <41A46B0B.8070206@tds.net> <41A4B717.3020902@po-box.mcgill.ca> Message-ID: <41A4EAF0.9060009@tds.net> Liam Clarke wrote: > Hi all, > > Thanks Kent. Question - is Python 2.4 release 1 considered a stable release? Stable in the sense of feature-complete, yes. Stable in the sense of bug-free...not necessarily. It is a release candidate, not a final release. If you are just learning Python and writing simple scripts I would go for it. If you have a critical production application you are running, you probably want to wait for the final release. >>Kent Johnson said unto the world upon 2004-11-24 06:05: >>>In Python 2.3 you have two choices: >>>- Use the decorate - sort - undecorate idiom (aka Schwartzian Transform) OK, here is the explanation for decorate - sort - undecorate aka DSU aka Schwarzian transform. This idiom is generally considered better than writing a custom cmp function because it is faster in many cases. The idea is to transform the list to be sorted into a list of tuples, where the first element of the tuple is the sort key and the second element is the original list element. This is the 'decorate' step. It is usually done with a list comprehension: >>> mp= {'James Bond' : '007' , 'Enid Blyton' : '005' , 'Enid Blyton also' : '006' , 'Captain Planet' : '000' } >>> it = mp.items() >>> it [('Enid Blyton also', '006'), ('Captain Planet', '000'), ('James Bond', '007'), ('Enid Blyton', '005')] >>> dit = [ (item[1], item) for item in it ] >>> dit [('006', ('Enid Blyton also', '006')), ('000', ('Captain Planet', '000')), ('007', ('James Bond', '007')), ('005', ('Enid Blyton', '005'))] Sorting the decorated list produces the desired order, since the key is the first item in the tuple elements: >>> dit.sort() >>> dit [('000', ('Captain Planet', '000')), ('005', ('Enid Blyton', '005')), ('006', ('Enid Blyton also', '006')), ('007', ('James Bond', '007'))] >>> A second list comprehension retrieves the original list elements from the decorated list. This is the 'undecorate' step: >>> it = [ item[1] for item in dit ] >>> it [('Captain Planet', '000'), ('Enid Blyton', '005'), ('Enid Blyton also', '006'), ('James Bond', '007')] A link about DSU in the Python FAQ: http://www.python.org/doc/faq/programming.html#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python Kent From bvande at po-box.mcgill.ca Wed Nov 24 21:31:50 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Nov 24 21:34:10 2004 Subject: [Tutor] Sort pointers - In-Reply-To: References: <41A46B0B.8070206@tds.net> <41A4B717.3020902@po-box.mcgill.ca> Message-ID: <41A4EFB6.3070108@po-box.mcgill.ca> Liam Clarke said unto the world upon 2004-11-24 13:55: > Hi all, > > Thanks Kent. Question - is Python 2.4 release 1 considered a stable release? > > Brian - Thanks very much for the illuminating functions, they help indeed. > > So when it returns cmp(x,y) it's returning a negative for x < y, 0 for > x == y, and a positive for x > y... > > eep, a little confused, just trying to understand how Python sorts > using that. I may go check out Python 2.4... > > Regards, > > > Liam Clarke > > > On Wed, 24 Nov 2004 11:30:15 -0500, Brian van den Broek > wrote: > >>Kent Johnson said unto the world upon 2004-11-24 06:05: Hi Liam, I'm glad you found my post helpful :-) For Kent and the other list-members more knowledgeable than I, I'd be curious to know more about the "decorate - sort - undecorate idiom (aka Schwartzian Transform)" method. -- Oh, strike that, just got Kent's post. Thanks :-) (For what it worth, the names the idiom goes by make it sound a good deal more dark than it turns out to be!) Liam, in terms of actually using cmp() to make your own sort functions, it really isn't too hard. You've just got to remember which of 1 and -1 get returned in which circumstances. Or, if you are like me, you've got to look it up each time :-( You can really reduce the work, though. Each time I make a custom cmp() function for use with the sort method, I put it into a module -- I call mine sorters.py. Having done that, you can promptly forget about the details of cmp() again. Just import the desired custom cmp function from your sorters module and you are good to go. (Of course, this attitude goes a long way to explaining why I have to look up cmp() whenever I find the need to write a new comparison function ;-) You might also want to check out . Best, Brian vdB From cajuntechie at gmail.com Thu Nov 25 01:20:57 2004 From: cajuntechie at gmail.com (Anthony P.) Date: Thu Nov 25 01:21:08 2004 Subject: [Tutor] Python Advice Needed Message-ID: Good Evening Everyone, I've decided to embark on a rather ambitious new project and am seriously considering using Python for it. Basically, I'm creating a kiosk system that will need to be available 24/7, handle network and hard interfaces, and present a nice GUI to the customer. After reading a lot on both this group and a few other sites, I think that a combination of Linux, Python, and wxPython would be ideal for this task. But I wanted to ask those of you who actually use these technologies what you think. Do you believe that this combination is acceptable for a commercial, user facing product? Am I being a bit too "gung ho" about Python? I know I don't have the expertise to pull this project off all by myself so I will have to hire some programmers. Is hiring Python programmers any more cost effective than hiring say a C++ programmer or a Java programmer? From a financial standpoint (the open source thing not withstanding), does Python make sense? Thanks everyone, Anthony From amonroe at columbus.rr.com Thu Nov 25 01:29:35 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Nov 25 01:30:00 2004 Subject: [Tutor] Python Advice Needed In-Reply-To: References: Message-ID: <191884934468.20041124192935@columbus.rr.com> > After reading a lot on both this group and a few other sites, I think > that a combination of Linux, Python, and wxPython would be ideal for > this task. But I wanted to ask those of you who actually use these I'm not qualified to answer really, but I will say that the wxpython demo app has crashed back to the os on me more than once, under win32. Not sure if it's more stable on linux. Alan From cajuntechie at gmail.com Thu Nov 25 01:42:26 2004 From: cajuntechie at gmail.com (Anthony P.) Date: Thu Nov 25 01:42:39 2004 Subject: [Tutor] Python Advice Needed In-Reply-To: <191884934468.20041124192935@columbus.rr.com> References: <191884934468.20041124192935@columbus.rr.com> Message-ID: > I'm not qualified to answer really, but I will say that the wxpython > demo app has crashed back to the os on me more than once, under win32. > Not sure if it's more stable on linux. > > Alan I am hoping (and suspecting) that the instability of the demo app had more to do with the Win32 system than it did with wxPython as a whole. Nevertheless, if there is ANY chance that the problem might actually be with wxPython, I would opt for something else. Stability and reliability are essential here. Anthony From kent37 at tds.net Thu Nov 25 03:21:35 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Nov 25 03:21:42 2004 Subject: [Tutor] Python Advice Needed In-Reply-To: References: Message-ID: <41A541AF.5000702@tds.net> You might want to ask this question on the comp.lang.python newsgroup, you might find someone there who has done something like this. Kent Anthony P. wrote: > Good Evening Everyone, > > I've decided to embark on a rather ambitious new project and am > seriously considering using Python for it. Basically, I'm creating a > kiosk system that will need to be available 24/7, handle network and > hard interfaces, and present a nice GUI to the customer. > > After reading a lot on both this group and a few other sites, I think > that a combination of Linux, Python, and wxPython would be ideal for > this task. But I wanted to ask those of you who actually use these > technologies what you think. Do you believe that this combination is > acceptable for a commercial, user facing product? Am I being a bit too > "gung ho" about Python? > > I know I don't have the expertise to pull this project off all by > myself so I will have to hire some programmers. Is hiring Python > programmers any more cost effective than hiring say a C++ programmer > or a Java programmer? From a financial standpoint (the open source > thing not withstanding), does Python make sense? > > Thanks everyone, > Anthony > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Thu Nov 25 05:23:52 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Nov 25 05:24:27 2004 Subject: [Tutor] how to zip data? References: <33678E78A2DD4D418396703A750048D4010250D0@RIKER> Message-ID: <000d01c4d2a6$98865100$b25428cf@JSLAPTOP> If y'all want just a zip file you can look at this... ### Zip.py ### import zipfile, zlib, os thething = 0 file = raw_input('What are you doing to the zip file? (Writing, Reading, Unzipping) ') ##################################################### ## Default values for directories are listed here ## forschool = os.path.exists("F:\students\schmidja") if not forschool: dirlist = os.listdir("c:\\") if 'Jacob Laptop' in dirlist: default = 'C:\\documents and settings\\jacob\\desktop' elif 'Home Computer' in dirlist: default = 'C:\\documents and settings\\owner\\desktop' elif 'Sissy Computer' in dirlist: default = 'C:\\windows\\desktop' elif 'Michael Laptop' in dirlist: default = 'C:\\documents and settings\\michael\\desktop' elif 'Office Computer' in dirlist: default = 'C:\\windows\\desktop' elif 'School Auction Laptop' in dirlist: default = 'C:\\windows\\desktop' else: print 'Hey you need to put a folder in this computer!. ' print '''Folders include: Jacob Laptop Home Computer Sissy Computer Michael Laptop Office Computer School Auction Laptop ''' folder = raw_input('Which computer is this? ') folder = os.path.join('C:',folder) os.mkdir(folder) default = input('Give me a default folder for this session. Please update code for later use. ') else: default = 'F:\students\schmidja' ## Usually you want this as the desktop ## ##################################################### if file == "Writing": file = "a" usefile = "w" elif file == "Reading": file = "r" usefile = "r" elif file == "Unzipping": file = "r" usefile = "u" else: print "That didn't work... Close the program and start over." def printline(strng): t = 0 for x in strng: if t < 20: print x t = t + 1 else: raw_input() t = 0 def getsubs(dir): directorylist = [] filelist = [] for roots,directories,files in os.walk(dir): for x in files: directorylist.append(roots) filelist.append(x) return [directorylist,filelist] def selectdir(): ask2 = 'y' while ask2 == 'y': current = os.getcwd() c2 = current print "Current directory is: %s" % current ask = raw_input('Do you wish to see what\'s in current directory? ') if ask == 'y': printline(os.listdir(current)) ask2 = raw_input('Do you wish to change directory? ') if ask2 == 'y': current = raw_input('What directory do you want? ') if current == '': current = default elif current.count('chdir') == 1: current = os.path.join(c2,current.lstrip('chdir ')) os.chdir(current) def fileselection(): selectdir() name = raw_input('What is the file\'s name? ') while name == 'chdir': selectdir() name = raw_input('What is the file\'s name? ') return os.path.join(os.getcwd(),name) os.chdir(default) name = fileselection() maindir,check = os.path.split(name) new = os.listdir(maindir) if check not in new: if file == 'a': file = 'w' else: print "You should never see this. It means that you are trying to read a nonexistant zipfile. So there." print "Zip file %s was not there. I have hopefully created it for you. " % (check) zip = zipfile.ZipFile(name, file, zipfile.ZIP_DEFLATED) if usefile == "w": all = raw_input('Do you wish to zip those with a particular extension? ') if all == 'y': selectdir() new = os.listdir(os.getcwd()) while 1: ext = raw_input('Please type the extension. ') if ext == 'quit': break elif ext == 'all': include = raw_input("Should I include the subdirectories? ") m = os.getcwd() if include == 'y': directorylist,filelist = getsubs(m) elif include == 'n': filelist = [x for x in os.listdir(m) if os.path.isfile(os.path.join(m,x))] directorylist = [m for x in filelist] li = [] for n in range(len(filelist)): fpath = os.path.join(directorylist[n],filelist[n]) zip.write(fpath,filelist[n]) print "%s was copied to %s successfully. " % (filelist[n],check) li.append(fpath) d = raw_input('Would you like to delete these files? ') if d == 'y': for x in li: os.remove(x) print "%s was removed successfully. " % os.path.split(x)[1] elif ext == 'chdir': selectdir() else: delting = [] ext = "."+ext for x in new: extension = os.path.splitext(x)[1] if extension == ext or extension == ext.upper() or extension == ext.lower(): zip.write(x) print "%s was copied to %s successfully. " % (x,check) delting.append(x) delete = raw_input("Do you wish to delete these files? ") if delete == 'y': del x for x in delting: thing = os.path.join(os.getcwd(), x) os.remove(thing) print "%s was removed successfully. " % (x) if all == 'n': selectdir() listed = [] while 1: thing=raw_input('What is the name of the file you want to add? ') if thing == 'all': include = raw_input("Should I include the subdirectories? ") m = os.getcwd() directorylist,filelist = getsubs(m) li = [] for n in range(len(filelist)): fpath = os.path.join(directorylist[n],filelist[n]) zip.write(fpath,filelist[n]) print "%s was copied to %s successfully. " % (filelist[n],check) li.append(fpath) d = raw_input('Do you wish to delete these files? ') if d == 'y': for x in li: os.remove(x) tm = os.path.split(x) print "%s was removed from %s successfully. " % (tm[1],tm[0]) elif thing == "quit": break elif thing == 'chdir': selectdir() else: try: zip.write(thing) listed.append(thing) except: print "That file was not found. Please try another one." as = raw_input("Would you like to delete these files? ") if as == 'y': for x in listed: fpath2 = os.path.join(os.getcwd(),x) os.remove(fpath2) print "Removed %s successfully. " % (x) if usefile == "r": while 1: forlatuse = os.getcwd() try: os.chdir('C:\\Python23\\Temp') except: os.mkdir('C:\\Python23\\Temp') os.chdir('C:\\Python23\\Temp') ask = raw_input('Do you wish to see what\'s in the zip file? ') if ask == 'quit': break elif ask == 'y': l = zip.namelist() printline(l) view0 = raw_input('What is the name of the file you want to open? ') if view0 == 'quit': break print view0 filetoread = open(view0, 'wb') filetoread.write(zip.read(view0)) filetoread.close() os.startfile(view0) null = raw_input('Press enter when done looking at file. ') os.remove(view0) os.chdir(forlatuse) if usefile == "u": list = zip.namelist() hello = raw_input('Would you like to look at what is in the zip file? ') if hello == 'y': printline(list) dir = selectdir() dir = os.getcwd() ask = raw_input('Do you wish to unzip them all? ') if ask == 'y': thething = 1 for item in list: huh = zip.read(item) thing = open(item, "wb") thing.write(huh) thing.close() print item, "was unzipped successfully." if ask == 'n': thething = 0 while 1: item=raw_input('What is the name of the file you want to unzip? ') if item == "quit": break elif item == 'viewlist': printline(list) elif item in list: huh = zip.read(item) place = os.path.join(dir,item) thing = open(place, "wb") thing.write(huh) thing.close() else: print 'That file is not in the zip file. Type in "viewlist" for a list of files in zip file. ' zip.close() for x in locals().keys(): try: x.close() print "Have been able to close %s" % x except: pass if usefile == 'u': deleting = 'n' if thething == 1: deleting = raw_input('Would you like to delete the zip file %s that you just unzipped? ' % check) if deleting == 'y': ask = raw_input('Are you sure you want to do this -- this will delete the whole zip file!!! ') if ask == 'y': os.remove(name) print "Removed %s" % check ### End of Zip.py ### > > > -----Original Message----- > > From: Ramkumar Parimal Alagan [mailto:ramster6@gmail.com] > > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > > > > if os.system(zip_command) == 0: > > print 'Successful backup to', target > > else: > > print 'Backup FAILED' > > > > > """No such a thing as "zip" command/utility on Windows, but using > Python's standard library you could build your own.... > > Example below shows how to gz-ip a file (if you wonder why .gz and > not .zip: gzip library compresses as good and has no upper limit > on how large file it can process). > > If below example looks too involving, you could purchase WinZip > and get command line utility that will zip files for you via > os.system call (but beware - WinZip can not zip/unzip files larger > than 4 GB) > > Branimir > """ > > ###################################################################### > # FileName gzDemo.py > ###################################################################### > > import exceptions, os, re, gzip > > def gzipIt(filetogzip, gzippedname=None): > """Will GZIP file whose path is described by 'filetogzip' string. > > Parameters: > filetogzip, gzippedname - STRING > > By default (if 'gzippedname' not supplied):, > - will gunzip 'filetogzip' to same folder with the source file, > - will add '.gz' suffix to file name > - will remove source file after successful gzipping. > > If 'gzippedname' is supplied, the source ('filetogzip') is not removed. > > Works like a charm although is 20% slower than GNU's gunzip utility. > """ > > chunksize=1048576 > removesource = False > > if not gzippedname: > gzippedname = filetogzip + r'.gz' > removesource = True > > inputfile = file(filetogzip, r'rb', chunksize) > try: > chunkdata = inputfile.read(chunksize) > gzoutfile = gzip.open(gzippedname, mode='wb', compresslevel=5) > try: > while chunkdata: > gzoutfile.write(chunkdata) > chunkdata = inputfile.read(chunksize) > finally: > gzoutfile.close() > finally: > inputfile.close() > > if removesource: os.remove(filetogzip) > > > def gunzipIt(filetogunzip, gunzippedname=None): > """Will GUNZIP file whose path is described by 'filetogzip' string. > > Parameters: > filetogunzip, gunzippedname - STRING > > By default (if 'gunzippedname' not supplied):, > - will gunzip 'filetogunzip' to same folder with the source file, > - will strip '.gz' from file name suffix and > - will remove source file after successful gunzipping. > > If 'gunzippedname' is supplied, the source ('filetogunzip') is not > removed. > > Works like a charm although is 30% slower than GNU's gunzip utility. > """ > > chunksize=8192 > removesource = False > > if not gunzippedname: > # strip '.gz' off the end of gzippedname > gunzippedname = re.sub('(\.(g|G)(z|Z))', '', filetogunzip) > removesource = True > > fgunzip = gzip.open(filetogunzip, mode='rb') > try: > chunkdata = fgunzip.read(chunksize) > foutput = file(gunzippedname, r'wb', chunksize) > try: > while chunkdata: > foutput.write(chunkdata) > chunkdata = fgunzip.read(chunksize) > finally: > foutput.close() > finally: > fgunzip.close() > > if removesource: os.remove(filetogunzip) > > > > > if __name__=="__main__": > > try: > # 1st run will "do-it:" > toZip = r'C:\_b\textStuff.txt' > gzipIt(toZip) > except exceptions.IOError: > # 2nd run will "un-do-it": > try: > toUnZip = r'C:\_b\textStuff.txt.gz' > gunzipIt(toUnZip) > except exceptions.IOError: > pass > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Thu Nov 25 05:32:36 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Nov 25 05:32:39 2004 Subject: [Tutor] Python Advice Needed In-Reply-To: <41A541AF.5000702@tds.net> References: <41A541AF.5000702@tds.net> Message-ID: Might be because wxPython is a C++ library as opposed to Tkinter. On Wed, 24 Nov 2004 21:21:35 -0500, Kent Johnson wrote: > You might want to ask this question on the comp.lang.python newsgroup, > you might find someone there who has done something like this. > > Kent > > > > Anthony P. wrote: > > Good Evening Everyone, > > > > I've decided to embark on a rather ambitious new project and am > > seriously considering using Python for it. Basically, I'm creating a > > kiosk system that will need to be available 24/7, handle network and > > hard interfaces, and present a nice GUI to the customer. > > > > After reading a lot on both this group and a few other sites, I think > > that a combination of Linux, Python, and wxPython would be ideal for > > this task. But I wanted to ask those of you who actually use these > > technologies what you think. Do you believe that this combination is > > acceptable for a commercial, user facing product? Am I being a bit too > > "gung ho" about Python? > > > > I know I don't have the expertise to pull this project off all by > > myself so I will have to hire some programmers. Is hiring Python > > programmers any more cost effective than hiring say a C++ programmer > > or a Java programmer? From a financial standpoint (the open source > > thing not withstanding), does Python make sense? > > > > Thanks everyone, > > Anthony > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > 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 cyresse at gmail.com Thu Nov 25 05:48:31 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Nov 25 05:48:36 2004 Subject: [Tutor] Sort pointers - In-Reply-To: <41A4EFB6.3070108@po-box.mcgill.ca> References: <41A46B0B.8070206@tds.net> <41A4B717.3020902@po-box.mcgill.ca> <41A4EFB6.3070108@po-box.mcgill.ca> Message-ID: Thanks guys, I might hold off on Python 2.4 until it's out of the release candidate stage (I wonder how that differs from beta testing? Beta testing writ large?), but the Schwartzian Transform is a wonderfully simple way to do it, once you know how. Danke Kent. Like a cryptic crossword, it all makes sense when someone shows you the answer. And Brian, that link you provided explains the use of a function to sort, and also the use of lambda functions in one hit. Brilliant, I'd been avoiding lambda's for as long as possible. Oh. And when I say Schwartzian Transform, I think of Terminator and Decepticons so quite an evil robot sound to it. Regards, Liam Clarke On Wed, 24 Nov 2004 15:31:50 -0500, Brian van den Broek wrote: > Liam Clarke said unto the world upon 2004-11-24 13:55: > > > > Hi all, > > > > Thanks Kent. Question - is Python 2.4 release 1 considered a stable release? > > > > Brian - Thanks very much for the illuminating functions, they help indeed. > > > > So when it returns cmp(x,y) it's returning a negative for x < y, 0 for > > x == y, and a positive for x > y... > > > > eep, a little confused, just trying to understand how Python sorts > > using that. I may go check out Python 2.4... > > > > Regards, > > > > > > Liam Clarke > > > > > > On Wed, 24 Nov 2004 11:30:15 -0500, Brian van den Broek > > wrote: > > > >>Kent Johnson said unto the world upon 2004-11-24 06:05: > > > > Hi Liam, > > I'm glad you found my post helpful :-) > > For Kent and the other list-members more knowledgeable than I, I'd be > curious to know more about the "decorate - sort - undecorate idiom (aka > Schwartzian Transform)" method. -- Oh, strike that, just got Kent's > post. Thanks :-) (For what it worth, the names the idiom goes by make it > sound a good deal more dark than it turns out to be!) > > Liam, in terms of actually using cmp() to make your own sort functions, > it really isn't too hard. You've just got to remember which of 1 and -1 > get returned in which circumstances. Or, if you are like me, you've got > to look it up each time :-( > > You can really reduce the work, though. Each time I make a custom cmp() > function for use with the sort method, I put it into a module -- I call > mine sorters.py. Having done that, you can promptly forget about the > details of cmp() again. Just import the desired custom cmp function from > your sorters module and you are good to go. (Of course, this attitude > goes a long way to explaining why I have to look up cmp() whenever I > find the need to write a new comparison function ;-) > > You might also want to check out > . > > Best, > > Brian vdB > > -- '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 keridee at jayco.net Thu Nov 25 05:56:31 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Nov 25 05:56:57 2004 Subject: [Tutor] Sort pointers - References: Message-ID: <006901c4d2ab$231dc290$b25428cf@JSLAPTOP> If your curious and you want the output described, this would work. ---------------------------------------------------------------------------- -- miscPeople= {'James Bond' : '007' , 'Enid Blyton' : '005' , 'Enid Blyton also' : '006' , 'Captain Planet' : '000' } miscPeople.keys().sort() for x in miscPeople.keys(): print x,miscPeople[x] ---------------------------------------------------------------------------- -- Oh, and what does Kia ora mean, and what language is it in? Jacob Schmidt > Kia ora, > > Just exploring the wonderful world of dictionaries, and I'm trying to > comprehend the sort() method, because as I found, dictionaries are not > sorted. > > So, I've got a dictionary, miscPeople= {'James Bond' : '007' , 'Enid > Blyton' : '005' , 'Enid Blyton also' : '006' , 'Captain Planet' : > '000' } > > (Okay, so that's a sample dictionary) > > So, if I wanted to sort by alphabetical key i.e. (first names here) > > for name, numerical in miscPeopledict.sorted() (pseudo code): > print name, numerical > > Captain Planet 000 > Enid Blyton 005 > Enid Blyton also 006 > James Bond 007 > > or conversely, to sort by value in some manner > > for name, numerical in miscPeopledict.sorted.reverse() > > James Bond 007 > Enid Blyton also 006 > Enid Blyton 005 > Captain Planet 000 > > That's just an example of output. I'm not too hung up on the output at > the moment, just sort(). > > It says to use a comparison function... > > And I have no idea how to work that. > > ??? Very confused. I've tried searching for info, there's some very > complex ways out there to sort data, usually with proper first names > (Schwartzian transformations...), but I can't seem to find the simple. > > Could anyone post some useful links for my education? > > Much appreciated. > > Liam Clarke > > > -- > '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. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From cyresse at gmail.com Thu Nov 25 06:15:29 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Nov 25 06:15:33 2004 Subject: [Tutor] Sort pointers - In-Reply-To: <006901c4d2ab$231dc290$b25428cf@JSLAPTOP> References: <006901c4d2ab$231dc290$b25428cf@JSLAPTOP> Message-ID: Thanks Jacob, so many ways to do this... oh, and kia ora - literally means 'be healthy', from the Maori, used as a greeting these days. http://en.wikipedia.org/wiki/New_Zealand_English#M.26.23257.3Bori_influence On Wed, 24 Nov 2004 23:56:31 -0500, Jacob S. wrote: > If your curious and you want the output described, this would work. > > ---------------------------------------------------------------------------- > -- > miscPeople= {'James Bond' : '007' , 'Enid Blyton' : '005' , 'Enid Blyton > also' : '006' , 'Captain Planet' : '000' } > miscPeople.keys().sort() > for x in miscPeople.keys(): > print x,miscPeople[x] > ---------------------------------------------------------------------------- > -- > Oh, and what does Kia ora mean, and what language is it in? > > Jacob Schmidt > > > > > > Kia ora, > > > > Just exploring the wonderful world of dictionaries, and I'm trying to > > comprehend the sort() method, because as I found, dictionaries are not > > sorted. > > > > So, I've got a dictionary, miscPeople= {'James Bond' : '007' , 'Enid > > Blyton' : '005' , 'Enid Blyton also' : '006' , 'Captain Planet' : > > '000' } > > > > (Okay, so that's a sample dictionary) > > > > So, if I wanted to sort by alphabetical key i.e. (first names here) > > > > for name, numerical in miscPeopledict.sorted() (pseudo code): > > print name, numerical > > > > Captain Planet 000 > > Enid Blyton 005 > > Enid Blyton also 006 > > James Bond 007 > > > > or conversely, to sort by value in some manner > > > > for name, numerical in miscPeopledict.sorted.reverse() > > > > James Bond 007 > > Enid Blyton also 006 > > Enid Blyton 005 > > Captain Planet 000 > > > > That's just an example of output. I'm not too hung up on the output at > > the moment, just sort(). > > > > It says to use a comparison function... > > > > And I have no idea how to work that. > > > > ??? Very confused. I've tried searching for info, there's some very > > complex ways out there to sort data, usually with proper first names > > (Schwartzian transformations...), but I can't seem to find the simple. > > > > Could anyone post some useful links for my education? > > > > Much appreciated. > > > > Liam Clarke > > > > > > -- > > '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. > > _______________________________________________ > > 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 cyresse at gmail.com Thu Nov 25 06:16:23 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Nov 25 06:16:25 2004 Subject: [Tutor] Sort pointers - In-Reply-To: References: <006901c4d2ab$231dc290$b25428cf@JSLAPTOP> Message-ID: It's also the name of a small fruit beverage in Britain manufactured by Coca-Cola. Way to rape a language Coke. On Thu, 25 Nov 2004 18:15:29 +1300, Liam Clarke wrote: > Thanks Jacob, so many ways to do this... > > oh, and kia ora - literally means 'be healthy', from the Maori, used > as a greeting these days. > > http://en.wikipedia.org/wiki/New_Zealand_English#M.26.23257.3Bori_influence > > > > > On Wed, 24 Nov 2004 23:56:31 -0500, Jacob S. wrote: > > If your curious and you want the output described, this would work. > > > > ---------------------------------------------------------------------------- > > -- > > miscPeople= {'James Bond' : '007' , 'Enid Blyton' : '005' , 'Enid Blyton > > also' : '006' , 'Captain Planet' : '000' } > > miscPeople.keys().sort() > > for x in miscPeople.keys(): > > print x,miscPeople[x] > > ---------------------------------------------------------------------------- > > -- > > Oh, and what does Kia ora mean, and what language is it in? > > > > Jacob Schmidt > > > > > > > > > > > Kia ora, > > > > > > Just exploring the wonderful world of dictionaries, and I'm trying to > > > comprehend the sort() method, because as I found, dictionaries are not > > > sorted. > > > > > > So, I've got a dictionary, miscPeople= {'James Bond' : '007' , 'Enid > > > Blyton' : '005' , 'Enid Blyton also' : '006' , 'Captain Planet' : > > > '000' } > > > > > > (Okay, so that's a sample dictionary) > > > > > > So, if I wanted to sort by alphabetical key i.e. (first names here) > > > > > > for name, numerical in miscPeopledict.sorted() (pseudo code): > > > print name, numerical > > > > > > Captain Planet 000 > > > Enid Blyton 005 > > > Enid Blyton also 006 > > > James Bond 007 > > > > > > or conversely, to sort by value in some manner > > > > > > for name, numerical in miscPeopledict.sorted.reverse() > > > > > > James Bond 007 > > > Enid Blyton also 006 > > > Enid Blyton 005 > > > Captain Planet 000 > > > > > > That's just an example of output. I'm not too hung up on the output at > > > the moment, just sort(). > > > > > > It says to use a comparison function... > > > > > > And I have no idea how to work that. > > > > > > ??? Very confused. I've tried searching for info, there's some very > > > complex ways out there to sort data, usually with proper first names > > > (Schwartzian transformations...), but I can't seem to find the simple. > > > > > > Could anyone post some useful links for my education? > > > > > > Much appreciated. > > > > > > Liam Clarke > > > > > > > > > -- > > > '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. > > > _______________________________________________ > > > 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. > -- '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 godoy at ieee.org Thu Nov 25 11:52:12 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu Nov 25 11:55:23 2004 Subject: [Tutor] Re: Python Advice Needed References: Message-ID: "Anthony P." writes: > I've decided to embark on a rather ambitious new project and am > seriously considering using Python for it. Basically, I'm creating a > kiosk system that will need to be available 24/7, handle network and > hard interfaces, and present a nice GUI to the customer. > > After reading a lot on both this group and a few other sites, I think > that a combination of Linux, Python, and wxPython would be ideal for > this task. But I wanted to ask those of you who actually use these > technologies what you think. Do you believe that this combination is > acceptable for a commercial, user facing product? Am I being a bit too > "gung ho" about Python? > > I know I don't have the expertise to pull this project off all by > myself so I will have to hire some programmers. Is hiring Python > programmers any more cost effective than hiring say a C++ programmer > or a Java programmer? From a financial standpoint (the open source > thing not withstanding), does Python make sense? I would go for it if I were you. You can restart the application automatically if it crashes or is closed somehow (though I don't think it should happen). We use Python + wxPython on some cross platform software that are critical for offices and they only show some kind of problem when the machines are overloaded. If the machine is processing within its nominal load and with enough RAM, the application is rock solid. The thing is: design everything to work on a maximum load and minimum RAM environment. If this is unlikely to happen, you can relax on some points to not waste engineering effort on it, but not too much. On the other hand, I am not sure I'd write a life support system in Python. Be seeing you, -- Godoy. From mlists at orfu.net Thu Nov 25 13:01:30 2004 From: mlists at orfu.net (Matthijs) Date: Thu Nov 25 13:01:28 2004 Subject: [Tutor] Python Advice Needed In-Reply-To: References: Message-ID: <41A5C99A.4070208@orfu.net> (ahem, accidentally bcc'ed this message to the wrong address) Anthony P. wrote: > Good Evening Everyone, > > I've decided to embark on a rather ambitious new project and am > seriously considering using Python for it. Basically, I'm creating a > kiosk system that will need to be available 24/7, handle network and > hard interfaces, and present a nice GUI to the customer. > > After reading a lot on both this group and a few other sites, I think > that a combination of Linux, Python, and wxPython would be ideal for > this task. But I wanted to ask those of you who actually use these > technologies what you think. Do you believe that this combination is > acceptable for a commercial, user facing product? Am I being a bit too > "gung ho" about Python? > > I know I don't have the expertise to pull this project off all by > myself so I will have to hire some programmers. Is hiring Python > programmers any more cost effective than hiring say a C++ programmer > or a Java programmer? From a financial standpoint (the open source > thing not withstanding), does Python make sense? > > Thanks everyone, > Anthony You may seriously want to consider PyGTK for this project, since it seems you will only run the application on Linux. I don't have much experience with PyGTK. But for a Linux-only application it seems the obvious choice. The great strength of wxPython is its crossplatformness, which works great (in particular on Win32, I might add), but will still limit you in various areas. Whereas PyGTK is native to GTK, so it should be more straightforward on Linux. And yes, Python makes sense. I've done a lot of C, C++, Java and (even) dotNet. And Python is in my opinion the most friendly combination of language, libraries and runtime to work with. Oh, and in my experience, wxPython is very stable. Good luck, Matthijs de Smedt From kent37 at tds.net Thu Nov 25 14:07:03 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Nov 25 14:07:08 2004 Subject: [Tutor] Sort pointers - In-Reply-To: References: <41A46B0B.8070206@tds.net> <41A4B717.3020902@po-box.mcgill.ca> <41A4EFB6.3070108@po-box.mcgill.ca> Message-ID: <41A5D8F7.2090104@tds.net> Liam Clarke wrote: > Thanks guys, > > I might hold off on Python 2.4 until it's out of the release candidate > stage (I wonder how that differs from beta testing? Beta testing writ > large?) Release candidate is a later stage than beta. Python 2.4 has had three alpha releases and two beta releases already. The best description of the release stages I can find is in the Python FAQ: Alphas are early releases in which interfaces aren't yet finalized; it's not unexpected to see an interface change between two alpha releases. Betas are more stable, preserving existing interfaces but possibly adding new modules, and release candidates are frozen, making no changes except as needed to fix critical bugs. Python 2.4 final is scheduled for end of November so you shouldn't have long to wait. Kent From kent37 at tds.net Thu Nov 25 14:15:40 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Nov 25 14:15:45 2004 Subject: [Tutor] Sort pointers - In-Reply-To: <006901c4d2ab$231dc290$b25428cf@JSLAPTOP> References: <006901c4d2ab$231dc290$b25428cf@JSLAPTOP> Message-ID: <41A5DAFC.2040100@tds.net> No, this will not print miscPeople sorted by key except perhaps by accident. Jacob S. wrote: > If your curious and you want the output described, this would work. > > ---------------------------------------------------------------------------- > -- > miscPeople= {'James Bond' : '007' , 'Enid Blyton' : '005' , 'Enid Blyton > also' : '006' , 'Captain Planet' : '000' } > miscPeople.keys().sort() miscPeople.keys() makes a new list. It is not a reference to the live dict keys - IOW changes to the list are *not* reflected in the dict. You sort the list but you don't keep a reference to it. > for x in miscPeople.keys(): > print x,miscPeople[x] Now you get a fresh copy of the keys and iterate over it. This copy is in no particular order. You have to get the keys, sort them, and iterate the sorted copy: keys = miscPeople.keys() keys.sort() for x in keys: print x, miscPeople[x] In Python 2.4 (there it is again), there is a built-in sorted() function that *returns* a sorted copy of any iterable. So you can do this: for x in sorted(miscPeople.keys()): print x, miscPeople[x] I would actually do it this way: for name, code in sorted(miscPeople.items()): print name, code (Liam, are you ready to upgrade yet? :-) Kent From johan at accesstel.co.za Thu Nov 25 14:47:57 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu Nov 25 14:49:22 2004 Subject: [Tutor] wxGlade installing Message-ID: <1101390477.4343.25.camel@KMA.accesstel> Hi, I am trying to use wxGlade.py and get this error: widgets and GTK+ is already installed. Can anybody please help? Traceback (most recent call last): File "wxglade.py", line 148, in ? run_main() File "wxglade.py", line 135, in run_main import main File "/usr/lib/wxGlade/main.py", line 10, in ? from widget_properties import * File "/usr/lib/wxGlade/widget_properties.py", line 16, in ? from xml.sax.saxutils import escape ImportError: No module named xml.sax.saxutils -- Johan -- This E-Mail has been scanned. Enjoy Your Day. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041125/30a4f5b6/attachment.htm From kent37 at tds.net Thu Nov 25 15:22:17 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Nov 25 15:22:22 2004 Subject: [Tutor] Sort pointers - In-Reply-To: <41A4EAF0.9060009@tds.net> References: <41A46B0B.8070206@tds.net> <41A4B717.3020902@po-box.mcgill.ca> <41A4EAF0.9060009@tds.net> Message-ID: <41A5EA99.708@tds.net> I should mention that compiled extensions to Python will have to be upgraded for 2.4. So if you rely on wxPython, py2exe or other compiled extensions, you should wait to upgrade until the extensions have been re-released. Kent Kent Johnson wrote: > Liam Clarke wrote: > >> Hi all, >> >> Thanks Kent. Question - is Python 2.4 release 1 considered a stable >> release? > > > Stable in the sense of feature-complete, yes. Stable in the sense of > bug-free...not necessarily. It is a release candidate, not a final > release. If you are just learning Python and writing simple scripts I > would go for it. If you have a critical production application you are > running, you probably want to wait for the final release. From dyoo at hkn.eecs.berkeley.edu Thu Nov 25 21:43:32 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 25 21:43:48 2004 Subject: [Tutor] wxGlade installing In-Reply-To: <1101390477.4343.25.camel@KMA.accesstel> Message-ID: On Thu, 25 Nov 2004, Johan Geldenhuys wrote: > I am trying to use wxGlade.py and get this error: > widgets and GTK+ is already installed. > Can anybody please help? > > Traceback (most recent call last): > File "wxglade.py", line 148, in ? > run_main() > File "wxglade.py", line 135, in run_main > import main > File "/usr/lib/wxGlade/main.py", line 10, in ? > from widget_properties import * > File "/usr/lib/wxGlade/widget_properties.py", line 16, in ? > from xml.sax.saxutils import escape > ImportError: No module named xml.sax.saxutils Hi Johan, I'll assume for the moment that you're running some kind of Linux distribution. Some distributions of Linux do include Python as part of the main core, but they separate some of the standard library components, like XML parsing, out of the main core, since not everyone has to do XML parsing. It appears that your system's missing the 'xml.sax.saxutils' standard library module. If you are running a linux distribution like Debian, you'll probably need to grab the 'python-xml' package: http://packages.debian.org/cgi-bin/search_packages.pl?searchon=names&version=all&exact=1&keywords=python-xml This all assumes, of course, that you're running a standard Linux distribution like Debian. *grin* Can you tell us more details about your system's configuration? That'll help us to better pinpoint the issue. Good luck to you. From elrood_corrino_ii at yahoo.com Fri Nov 26 04:39:22 2004 From: elrood_corrino_ii at yahoo.com (Harov Satmandirvich) Date: Fri Nov 26 04:39:26 2004 Subject: [Tutor] Help with very basic question Message-ID: <20041126033923.1697.qmail@web54002.mail.yahoo.com> Hello. Before I continue with a tutorial I would like to know something very basic: Is there any other way to advance a line in Python than hitting "tabtabtabtab"..etc? When I hit"enter?" it enters the line as if it was a complete bit of program. __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From cyresse at gmail.com Fri Nov 26 06:15:39 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 26 06:15:43 2004 Subject: [Tutor] Database questions In-Reply-To: <20041124174810.27659.qmail@web54310.mail.yahoo.com> References: <20041124174810.27659.qmail@web54310.mail.yahoo.com> Message-ID: I would agree about user friendliness, although I strongly suggest you reserve judgement until you try Spectix. http://starship.python.net/crew/mike/src/Spectix/Spectix.html That said, Tkinter isn't overly user friendly either. Oh, and the PythonCard documentation is quite useless at times. On Wed, 24 Nov 2004 09:48:09 -0800 (PST), Chad Crabtree wrote: > Well I would suggest you use Tkinter for the GUI because for what you > want to do. I do not feel that wxPython or any of the Designers are > really that ready, not like VB or something. Tkinter can be learned > in > about 14 hours so that you can make interesting stuff, I do not feel > that wxPython can be grokked in a like period of time. I too had > ambitions of GUI stuff when just starting but have since found CGI to > be > a much easier UI than any other. However I would like to say that I > use > Pythoncard to good effect, but it is still immature and not really > that > newbie friendly, which I believe none of the GUI designers are mature > enough to be really easy. > > HTH > > Jay Mutter wrote: > > > Good evening; > > I am using OS X 10.3.6 on an ibook where I have python 2.3.3 and > > wxPython 2.5.3.1 installed with mxDateTime, Postgresql and psycopg. > > > > What i would like to know ( remember I have not really started > using > > python or any of the others) is what would you suggest as a GUI > > > > designer to work with the above for someone who wants to develop a > GUI > > client interface for a RDBMS system. I have looked at wxGlade, > > Pythoncard, wxDesigner, and Boa constructor and am currently > clueless. > > If I wanted to hone my skills by creating a GUI checkbook > > register/balancing program would I be best off to simply use the DB > > > modules built into Python. > > Remember I am definitely a newbie. > > > > > > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - What will yours do? > http://my.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 cyresse at gmail.com Fri Nov 26 06:17:06 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 26 06:17:08 2004 Subject: [Tutor] Database questions In-Reply-To: References: <20041124174810.27659.qmail@web54310.mail.yahoo.com> Message-ID: Oh and also check out EasyGUI, for the quick and dirty GUI stuff. (Very quick and dirty.) http://www.ferg.org/easygui/ On Fri, 26 Nov 2004 18:15:39 +1300, Liam Clarke wrote: > I would agree about user friendliness, although I strongly suggest you > reserve judgement until you try Spectix. > > http://starship.python.net/crew/mike/src/Spectix/Spectix.html > > That said, Tkinter isn't overly user friendly either. Oh, and the > PythonCard documentation is quite useless at times. > > > > > On Wed, 24 Nov 2004 09:48:09 -0800 (PST), Chad Crabtree > wrote: > > Well I would suggest you use Tkinter for the GUI because for what you > > want to do. I do not feel that wxPython or any of the Designers are > > really that ready, not like VB or something. Tkinter can be learned > > in > > about 14 hours so that you can make interesting stuff, I do not feel > > that wxPython can be grokked in a like period of time. I too had > > ambitions of GUI stuff when just starting but have since found CGI to > > be > > a much easier UI than any other. However I would like to say that I > > use > > Pythoncard to good effect, but it is still immature and not really > > that > > newbie friendly, which I believe none of the GUI designers are mature > > enough to be really easy. > > > > HTH > > > > Jay Mutter wrote: > > > > > Good evening; > > > I am using OS X 10.3.6 on an ibook where I have python 2.3.3 and > > > wxPython 2.5.3.1 installed with mxDateTime, Postgresql and psycopg. > > > > > > What i would like to know ( remember I have not really started > > using > > > python or any of the others) is what would you suggest as a GUI > > > > > > > designer to work with the above for someone who wants to develop a > > GUI > > > client interface for a RDBMS system. I have looked at wxGlade, > > > Pythoncard, wxDesigner, and Boa constructor and am currently > > clueless. > > > If I wanted to hone my skills by creating a GUI checkbook > > > register/balancing program would I be best off to simply use the DB > > > > > modules built into Python. > > > Remember I am definitely a newbie. > > > > > > > > > > > > __________________________________ > > Do you Yahoo!? > > The all-new My Yahoo! - What will yours do? > > http://my.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. > -- '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 cyresse at gmail.com Fri Nov 26 06:26:59 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 26 06:27:02 2004 Subject: [Tutor] Help with very basic question In-Reply-To: <20041126033923.1697.qmail@web54002.mail.yahoo.com> References: <20041126033923.1697.qmail@web54002.mail.yahoo.com> Message-ID: You're using the interpreter. It executes a line at at time. Download a Python friendly editor - http://www.python.org/moin/PythonEditors I use Pype on my WinXP box, but it's personal preference. Write a script (i.e.) import sys h = raw_input("What is your name? ") print h sys.exit() save it as somename.py, and run it as follows - python somename,py The interactive interpreter, which has a prompt like this - >>> Executes one block at at time. You can't type more than one line(unless you're writing a code block like - for a in item: or while x = 5: or try: or if not h: Notice how they all end with colons? Python will pick that up and change the promprt to ... to indicate a block. HTH Liam Clarke On Thu, 25 Nov 2004 19:39:22 -0800 (PST), Harov Satmandirvich wrote: > Hello. Before I continue with a tutorial I would like > to know something very basic: Is there any other way > to advance a line in Python than hitting > "tabtabtabtab"..etc? When I hit"enter?" it enters > the line as if it was a complete bit of program. > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - You care about security. So do we. > http://promotions.yahoo.com/new_mail > _______________________________________________ > 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 cyresse at gmail.com Fri Nov 26 06:29:20 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 26 06:29:23 2004 Subject: [Tutor] Sort pointers - In-Reply-To: <41A5EA99.708@tds.net> References: <41A46B0B.8070206@tds.net> <41A4B717.3020902@po-box.mcgill.ca> <41A4EAF0.9060009@tds.net> <41A5EA99.708@tds.net> Message-ID: I'm using Pythoncard which is wxPython but nicer... does this effect me? On Thu, 25 Nov 2004 09:22:17 -0500, Kent Johnson wrote: > I should mention that compiled extensions to Python will have to be > upgraded for 2.4. So if you rely on wxPython, py2exe or other compiled > extensions, you should wait to upgrade until the extensions have been > re-released. > > Kent > > > > Kent Johnson wrote: > > Liam Clarke wrote: > > > >> Hi all, > >> > >> Thanks Kent. Question - is Python 2.4 release 1 considered a stable > >> release? > > > > > > Stable in the sense of feature-complete, yes. Stable in the sense of > > bug-free...not necessarily. It is a release candidate, not a final > > release. If you are just learning Python and writing simple scripts I > > would go for it. If you have a critical production application you are > > running, you probably want to wait for the final release. > _______________________________________________ > 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 huw.davies at kerberos.davies.net.au Fri Nov 26 06:53:24 2004 From: huw.davies at kerberos.davies.net.au (Huw Davies) Date: Fri Nov 26 06:53:32 2004 Subject: [Tutor] Database questions In-Reply-To: References: <20041124174810.27659.qmail@web54310.mail.yahoo.com> Message-ID: <7C65951D-3F6F-11D9-BEED-000A957FD620@kerberos.davies.net.au> On 26/11/2004, at 4:15 PM, Liam Clarke wrote: > I would agree about user friendliness, although I strongly suggest you > reserve judgement until you try Spectix. > > http://starship.python.net/crew/mike/src/Spectix/Spectix.html > > That said, Tkinter isn't overly user friendly either. Oh, and the > PythonCard documentation is quite useless at times. Has Spectix been ported to Mac OS-X? The above link says that it's available for Windows and Linux but doesn't mention OS-X. Huw Davies | e-mail: Huw.Davies@kerberos.davies.net.au Melbourne | "If soccer was meant to be played in the Australia | air, the sky would be painted green" From cyresse at gmail.com Fri Nov 26 10:00:19 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 26 10:00:23 2004 Subject: [Tutor] Database questions In-Reply-To: <7C65951D-3F6F-11D9-BEED-000A957FD620@kerberos.davies.net.au> References: <20041124174810.27659.qmail@web54310.mail.yahoo.com> <7C65951D-3F6F-11D9-BEED-000A957FD620@kerberos.davies.net.au> Message-ID: ...My bad. Apologies. On Fri, 26 Nov 2004 16:53:24 +1100, Huw Davies wrote: > > On 26/11/2004, at 4:15 PM, Liam Clarke wrote: > > > I would agree about user friendliness, although I strongly suggest you > > reserve judgement until you try Spectix. > > > > http://starship.python.net/crew/mike/src/Spectix/Spectix.html > > > > That said, Tkinter isn't overly user friendly either. Oh, and the > > PythonCard documentation is quite useless at times. > > Has Spectix been ported to Mac OS-X? The above link says that it's > available for Windows and Linux but doesn't mention OS-X. > > Huw Davies | e-mail: Huw.Davies@kerberos.davies.net.au > Melbourne | "If soccer was meant to be played in the > Australia | air, the sky would be painted green" > > _______________________________________________ > > > 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 Fri Nov 26 10:45:53 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Nov 26 10:47:34 2004 Subject: [Tutor] time comparison question Message-ID: <41A6FB51.1080808@po-box.mcgill.ca> Hi all, I'm trying to build some Python 2.3.4 code which will determine if the actual time when it is run is after the date and time specified in some data. I want my data to be able to specify the target date/time in a various levels of detail. I.e., I want 2004-11-28 13:25, 2004-11-28, 11-28, 11-28 13:25 to all be accepted. My first thought was to get the current time via time.time() and then parse my target date into a struct_time tuple to pass to time.mktime(), run a comparison and be done. However, a struct_time tuple has data that I won't know, given one of my target dates. I can make sensible dummies for seconds (as well as year, hours and minutes when my target does not specify them), and I know that the time module will try to make a reasonable guess if given -1 for the DST element. But for a_struct_time_tuple[-3:-1], I'd just be guessing at the weekday and day of year. This leads to two questions: 1) As I write, time.asctime() gives 'Fri Nov 26 04:32:18 2004' for a time.localtime() of (2004, 11, 26, 4, 32, 18, 4, 331, 0). If I were filling out a target date of 2004-11-26 04:32, I might well end up passing something like (2004, 11, 26, 4, 32, 18, 6, 328, 0) to time.mktime() for the result 'Sun Nov 26 04:32:18 2004'. If I am not actually using the weekday information, I suspect that I can just ignore the incorrect 'Sun'. But I feel better checking -- is anything going to break by giving struct_time elements that don't make sense (provided of course I am not myself explicitly drawing upon them)? 2) Naturally, these worries lead me to think that there must be a better way. I took a brief look at the datetime module, thinking it was a natural place to find such tools. But it is all in terms of classes. Sadly, I am still not too comfortable with doing things via OOP, so I'd prefer a procedural (if that's the right term for a program with functions but no classes) way. Is there a cleaner, non-class employing, way of meeting my goal of finding out if a date of the form YYYY-MM-DD is in the future, present, or past? (If it matters, I am on Windows.) Thanks for any links, etc. Best to all, Brian vdB From cyresse at gmail.com Fri Nov 26 12:56:43 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 26 12:56:46 2004 Subject: [Tutor] time comparison question In-Reply-To: <41A6FB51.1080808@po-box.mcgill.ca> References: <41A6FB51.1080808@po-box.mcgill.ca> Message-ID: Hi Brian, I was in a similar position to you 3 weeks ago, and I was using time.time, and time.gmtime. Each of these returns a 9 value tuple, which is documented deep within the time module. The 9 value tuple has year to microsecond, and day of the week contained, so you can use it if you wish. I'm in the same boat as you, regarding OOP, although I use it when suitable, and all I've got to say is - what's the big deal? I can see it would be useful for certain applications, but it's nothing lifechanging, unlike Python :D I would recommend biting the bullet and using a date/time object. You don't need to grok OOP to use it, and it makes this easier. May I post some code to demonstrate? I wanted to write code which would find out what date last Friday was, whenever the code was run. Using time.gmtime, this is what I accomplished (kept for posteritie's sake only..) def getFriday(mail_offset): gm_data=time.gmtime() (year, month, day, weekday)=gm_data[0], gm_data[1], gm_data[2], gm_data[6] date_offset= -(mail_offset-weekday) last_friday=datetime.date(year, month, day) - datetime.timedelta(days=date_offset) retrieve_date_string=str(last_friday) split_date=retrieve_date_string.split('-') email_sent_date=time.strftime("%d-%b-%Y", (int(split_date[0]), int(split_date[1]), int(split_date[2]), 0, 0, 0, 0, 0, 0)) return email_sent_date Now, i posted this up to this list, Kent Johnson recommended this instead- def getFriday(day): lastFriday = datetime.date.today() oneday = datetime.timedelta(days=1) while lastFriday.weekday() != day: lastFriday -= oneday return lastFriday.strftime('%d-%b-%Y') Both returned a date in the format 15-Oct-2004 Guess which one I went with? My original code was brute forcish, unmaintainable & ugly, but it worked when I wrote it. Sounds like Perl really. But notice that I had to use an object anyway to invoke timedelta, so all my messing around was in vain. Highly recommend this - a) Use the datetime module b) Use datetime objects, so you don't have to mess around with functions that require 9 digit tuples c) Listen to Kent if he posts, he's good. Give datetime a try, and see how it goes. Good luck, Liam Clarke On Fri, 26 Nov 2004 04:45:53 -0500, Brian van den Broek wrote: > Hi all, > > I'm trying to build some Python 2.3.4 code which will determine if the > actual time when it is run is after the date and time specified in some > data. I want my data to be able to specify the target date/time in a > various levels of detail. I.e., I want 2004-11-28 13:25, 2004-11-28, > 11-28, 11-28 13:25 to all be accepted. > > My first thought was to get the current time via time.time() and then > parse my target date into a struct_time tuple to pass to time.mktime(), > run a comparison and be done. However, a struct_time tuple has data that > I won't know, given one of my target dates. I can make sensible dummies > for seconds (as well as year, hours and minutes when my target does not > specify them), and I know that the time module will try to make a > reasonable guess if given -1 for the DST element. But for > a_struct_time_tuple[-3:-1], I'd just be guessing at the weekday and day > of year. This leads to two questions: > > 1) As I write, time.asctime() gives 'Fri Nov 26 04:32:18 2004' for a > time.localtime() of (2004, 11, 26, 4, 32, 18, 4, 331, 0). If I were > filling out a target date of 2004-11-26 04:32, I might well end up > passing something like (2004, 11, 26, 4, 32, 18, 6, 328, 0) to > time.mktime() for the result 'Sun Nov 26 04:32:18 2004'. If I am not > actually using the weekday information, I suspect that I can just ignore > the incorrect 'Sun'. But I feel better checking -- is anything going to > break by giving struct_time elements that don't make sense (provided of > course I am not myself explicitly drawing upon them)? > > 2) Naturally, these worries lead me to think that there must be a better > way. I took a brief look at the datetime module, thinking it was a > natural place to find such tools. But it is all in terms of classes. > Sadly, I am still not too comfortable with doing things via OOP, so I'd > prefer a procedural (if that's the right term for a program with > functions but no classes) way. Is there a cleaner, non-class employing, > way of meeting my goal of finding out if a date of the form YYYY-MM-DD > is in the future, present, or past? (If it matters, I am on Windows.) > > Thanks for any links, etc. > > Best to all, > > Brian vdB > > _______________________________________________ > 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 ba sic human duty, to take the consequences. From cyresse at gmail.com Fri Nov 26 13:37:30 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 26 13:37:33 2004 Subject: [Tutor] time comparison question In-Reply-To: References: <41A6FB51.1080808@po-box.mcgill.ca> Message-ID: Hi Brian, class datetime( year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None) Ease of use demo - >>>import datetime >>>date1 = datetime.datetime(2001,11,11,12) >>>print str(date1) 2001-11-11 12:00:00 >>>date2 = datetime.datetime(2007,10,10,9,20,20,20) >>>print str(date2) 2007-10-10 09:20:20.000020 >>>print date1.strftime('"%d-%b-%Y"') 11-Nov-2001 >>>date2.strftime('"%A, %d %B %Y. Time is %X"') Wednesday, 10 October 2007. Time is 09:20:20 >>>print "difference between",date1,"&",date2 difference between 2001-11-11 12:00:00 & 2007-10-10 09:20:20.000020 >>> print date1-date2 -2159 days, 2:39:39.999980 >>> print "difference between",date2,"&",date1 difference between 2007-10-10 09:20:20.000020 & 2001-11-11 12:00:00 >>>print date2-date1 2158 days, 21:20:20.000020 >>>dateDif=date2-date1 >>>type(dateDif) So yeah, poke around, it'll do pretty much everything date related you need. Oh, and for your particular problem - so if 10/10/2007 minus 11/11/2001 is a positive value, then you know that all future dates will have a positive difference. Past dates will be negative difference, and it'd be very unlikely that you'd get a zero value, but it's possible. HTH Liam Clarke On Sat, 27 Nov 2004 00:56:43 +1300, Liam Clarke wrote: > Hi Brian, > > I was in a similar position to you 3 weeks ago, and I was using > time.time, and time.gmtime. > > Each of these returns a 9 value tuple, which is documented deep within > the time module. > > The 9 value tuple has year to microsecond, and day of the week > contained, so you can use it if you wish. > > I'm in the same boat as you, regarding OOP, although I use it when > suitable, and all I've got to say is - what's the big deal? I can see > it would be useful for certain applications, but it's nothing > lifechanging, unlike Python :D > > I would recommend biting the bullet and using a date/time object. You > don't need to grok OOP to use it, and it makes this easier. > > May I post some code to demonstrate? > > I wanted to write code which would find out what date last Friday was, > whenever the code was run. > > Using time.gmtime, this is what I accomplished (kept for posteritie's > sake only..) > def getFriday(mail_offset): > > gm_data=time.gmtime() > (year, month, day, weekday)=gm_data[0], gm_data[1], gm_data[2], > gm_data[6] > date_offset= -(mail_offset-weekday) > last_friday=datetime.date(year, month, day) - > datetime.timedelta(days=date_offset) > retrieve_date_string=str(last_friday) > split_date=retrieve_date_string.split('-') > email_sent_date=time.strftime("%d-%b-%Y", (int(split_date[0]), > int(split_date[1]), int(split_date[2]), 0, 0, 0, 0, 0, 0)) > > return email_sent_date > > Now, i posted this up to this list, Kent Johnson recommended this instead- > > def getFriday(day): > lastFriday = datetime.date.today() > oneday = datetime.timedelta(days=1) > > while lastFriday.weekday() != day: > lastFriday -= oneday > > return lastFriday.strftime('%d-%b-%Y') > > Both returned a date in the format 15-Oct-2004 > > Guess which one I went with? > My original code was brute forcish, unmaintainable & ugly, but it > worked when I wrote it. Sounds like Perl really. But notice that I had > to use an object anyway to invoke timedelta, so all my messing around > was in vain. > > Highly recommend this - > > a) Use the datetime module > b) Use datetime objects, so you don't have to mess around with > functions that require 9 digit tuples > c) Listen to Kent if he posts, he's good. > > Give datetime a try, and see how it goes. > > Good luck, > > Liam Clarke > > > > > On Fri, 26 Nov 2004 04:45:53 -0500, Brian van den Broek > wrote: > > Hi all, > > > > I'm trying to build some Python 2.3.4 code which will determine if the > > actual time when it is run is after the date and time specified in some > > data. I want my data to be able to specify the target date/time in a > > various levels of detail. I.e., I want 2004-11-28 13:25, 2004-11-28, > > 11-28, 11-28 13:25 to all be accepted. > > > > My first thought was to get the current time via time.time() and then > > parse my target date into a struct_time tuple to pass to time.mktime(), > > run a comparison and be done. However, a struct_time tuple has data that > > I won't know, given one of my target dates. I can make sensible dummies > > for seconds (as well as year, hours and minutes when my target does not > > specify them), and I know that the time module will try to make a > > reasonable guess if given -1 for the DST element. But for > > a_struct_time_tuple[-3:-1], I'd just be guessing at the weekday and day > > of year. This leads to two questions: > > > > 1) As I write, time.asctime() gives 'Fri Nov 26 04:32:18 2004' for a > > time.localtime() of (2004, 11, 26, 4, 32, 18, 4, 331, 0). If I were > > filling out a target date of 2004-11-26 04:32, I might well end up > > passing something like (2004, 11, 26, 4, 32, 18, 6, 328, 0) to > > time.mktime() for the result 'Sun Nov 26 04:32:18 2004'. If I am not > > actually using the weekday information, I suspect that I can just ignore > > the incorrect 'Sun'. But I feel better checking -- is anything going to > > break by giving struct_time elements that don't make sense (provided of > > course I am not myself explicitly drawing upon them)? > > > > 2) Naturally, these worries lead me to think that there must be a better > > way. I took a brief look at the datetime module, thinking it was a > > natural place to find such tools. But it is all in terms of classes. > > Sadly, I am still not too comfortable with doing things via OOP, so I'd > > prefer a procedural (if that's the right term for a program with > > functions but no classes) way. Is there a cleaner, non-class employing, > > way of meeting my goal of finding out if a date of the form YYYY-MM-DD > > is in the future, present, or past? (If it matters, I am on Windows.) > > > > Thanks for any links, etc. > > > > Best to all, > > > > Brian vdB > > > > _______________________________________________ > > 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 ba sic human duty, to take the consequences. > -- '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 op73418 at mail.telepac.pt Fri Nov 26 13:50:01 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Nov 26 13:46:46 2004 Subject: [Tutor] time comparison question In-Reply-To: <41A6FB51.1080808@po-box.mcgill.ca> References: <41A6FB51.1080808@po-box.mcgill.ca> Message-ID: <41A72679.5030306@mail.telepac.pt> Brian van den Broek wrote: > Hi all, [text snip] > 2) Naturally, these worries lead me to think that there must be a > better way. I took a brief look at the datetime module, thinking it > was a natural place to find such tools. But it is all in terms of > classes. Sadly, I am still not too comfortable with doing things via > OOP, so I'd prefer a procedural (if that's the right term for a > program with functions but no classes) way. Is there a cleaner, > non-class employing, way of meeting my goal of finding out if a date > of the form YYYY-MM-DD is in the future, present, or past? (If it > matters, I am on Windows.) > Spend a little time with the datetime module. Really, it will save you a lot of trouble. And you don't have to do OO by using it, or at least not more than you are *already* doing in Python - everything in Python is an object that has a class, etc. Think of the classes in datetime module as you think of the builtin classes like list, tuple, etc. You just use them, they do not force you to program in procedural or in OO or in the-whatever way. With my best regards, G. Rodrigues From cyresse at gmail.com Fri Nov 26 13:49:20 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Nov 26 13:49:22 2004 Subject: [Tutor] Sort pointers - In-Reply-To: References: <41A46B0B.8070206@tds.net> <41A4B717.3020902@po-box.mcgill.ca> <41A4EAF0.9060009@tds.net> <41A5EA99.708@tds.net> Message-ID: Erk, one more thing, Just playing with that Schwartzian thing, does Python automatically do secondary sorting? i.e. ('p', 11), ('bb', 11), ('uu', 11) Irrelevant bits snipped. So, this is my list sorted by first element. So after the second sort - (11, ('bb', 11)), (11, ('p', 11)), (11, ('uu', 11)) I notice it's already sorted them alphaetically. Is this normal, can I rely on it? Regards, Liam Clarke On Fri, 26 Nov 2004 18:29:20 +1300, Liam Clarke wrote: > I'm using Pythoncard which is wxPython but nicer... does this effect me? > > > > > On Thu, 25 Nov 2004 09:22:17 -0500, Kent Johnson wrote: > > I should mention that compiled extensions to Python will have to be > > upgraded for 2.4. So if you rely on wxPython, py2exe or other compiled > > extensions, you should wait to upgrade until the extensions have been > > re-released. > > > > Kent > > > > > > > > Kent Johnson wrote: > > > Liam Clarke wrote: > > > > > >> Hi all, > > >> > > >> Thanks Kent. Question - is Python 2.4 release 1 considered a stable > > >> release? > > > > > > > > > Stable in the sense of feature-complete, yes. Stable in the sense of > > > bug-free...not necessarily. It is a release candidate, not a final > > > release. If you are just learning Python and writing simple scripts I > > > would go for it. If you have a critical production application you are > > > running, you probably want to wait for the final release. > > _______________________________________________ > > 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. > -- '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 revanna at mn.rr.com Fri Nov 26 14:19:54 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Fri Nov 26 14:20:09 2004 Subject: [Tutor] time comparison question In-Reply-To: <41A6FB51.1080808@po-box.mcgill.ca> References: <41A6FB51.1080808@po-box.mcgill.ca> Message-ID: <41A72D7A.8080805@mn.rr.com> Brian van den Broek wrote: > Hi all, > > I'm trying to build some Python 2.3.4 code which will determine if the > actual time when it is run is after the date and time specified in some > data. I want my data to be able to specify the target date/time in a > various levels of detail. I.e., I want 2004-11-28 13:25, 2004-11-28, > 11-28, 11-28 13:25 to all be accepted. > > My first thought was to get the current time via time.time() and then > parse my target date into a struct_time tuple to pass to time.mktime(), > run a comparison and be done. However, a struct_time tuple has data that > I won't know, given one of my target dates. I can make sensible dummies > for seconds (as well as year, hours and minutes when my target does not > specify them), and I know that the time module will try to make a > reasonable guess if given -1 for the DST element. But for > a_struct_time_tuple[-3:-1], I'd just be guessing at the weekday and day > of year. This leads to two questions: > > 1) As I write, time.asctime() gives 'Fri Nov 26 04:32:18 2004' for a > time.localtime() of (2004, 11, 26, 4, 32, 18, 4, 331, 0). If I were > filling out a target date of 2004-11-26 04:32, I might well end up > passing something like (2004, 11, 26, 4, 32, 18, 6, 328, 0) to > time.mktime() for the result 'Sun Nov 26 04:32:18 2004'. If I am not > actually using the weekday information, I suspect that I can just ignore > the incorrect 'Sun'. But I feel better checking -- is anything going to > break by giving struct_time elements that don't make sense (provided of > course I am not myself explicitly drawing upon them)? > > 2) Naturally, these worries lead me to think that there must be a better > way. I took a brief look at the datetime module, thinking it was a > natural place to find such tools. But it is all in terms of classes. > Sadly, I am still not too comfortable with doing things via OOP, so I'd > prefer a procedural (if that's the right term for a program with > functions but no classes) way. Is there a cleaner, non-class employing, > way of meeting my goal of finding out if a date of the form YYYY-MM-DD > is in the future, present, or past? (If it matters, I am on Windows.) Actually, datetime is just about as painless OOP as you can get... It's no different from making a string, or an integer, and less complicated than time.mktime and its ilk. Let's try doing your task with it and see what you think: import datetime def comparedates(date1, date2): #define function try: date1 = date1.date() # coerce to date* except AttributeError: date1 # don't need to coerce try: date2= date2.date() except AttributeError: date2 print sorted([date1, date2]) # built-in list sort today = datetime.datetime.today() # right now comparedate1 = datetime.date(2004, 12, 25) # a date to compare comparedate2 = datetime.datetime(2004, 9, 1) # another date lcomp = [comparedate1, comparedate2] # a list of date for d in lcomp: # for each date in list comparedates(today,d) # compare with today If you prefer to just use less than or greater than, you can - you just have to remember to coerce any datetime objects to date objects. This isn't as complicated as it might sound. It's just like you use coercion between strings and integers and floats when you want to compare them. If you have list l = ['3', 2.4, 5] you would have to coerce the string to an integer or float in order to compare it with the other values in the list. Same here - you want to compare like with like, and it's pretty easy to coerce a datetime object into a date object. Don't think of it as doing OOP. Just think of it as using a nifty new Type that Python gives you - just as nifty as strings and integers are. Once you have two date objects, you can use < = > comparisons with them: >>> date1 = datetime.date(2004, 11, 25) >>> date2 = datetime.date(2004, 6, 25) >>> date1 < date2 False >>> date1 > date2 True >>> Note that, if you need to worry about the *TIME* it was run, not *JUST* the date, you'll need to the opposite coercion - I would coerce everything (datetimes and dates) into a timetuple using the datetime method: >>> date1 datetime.date(2004, 11, 25) >>> date1.timetuple() (2004, 11, 25, 0, 0, 0, 3, 330, -1) >>> time1 = date1.timetuple() >>> date3 = datetime.datetime.today() >>> date3 datetime.datetime(2004, 11, 26, 14, 8, 13, 252000) >>> time3=date3.timetuple() That way you've got all timetuples to compare. And again, you can compare those just fine. >>> time1 > time3 False >>> time1 < time3 True >>> Hope this helps. Anna From kent37 at tds.net Fri Nov 26 14:21:24 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 26 14:21:32 2004 Subject: [Tutor] Sort pointers - In-Reply-To: References: <41A46B0B.8070206@tds.net> <41A4B717.3020902@po-box.mcgill.ca> <41A4EAF0.9060009@tds.net> <41A5EA99.708@tds.net> Message-ID: <41A72DD4.5090401@tds.net> Yes it does. PythonCard is built on top of wxPython. So to use PythonCard with Python 2.4 you will have to wait for a new build of wxPython. Kent Liam Clarke wrote: > I'm using Pythoncard which is wxPython but nicer... does this effect me? > > On Thu, 25 Nov 2004 09:22:17 -0500, Kent Johnson wrote: > >>I should mention that compiled extensions to Python will have to be >>upgraded for 2.4. So if you rely on wxPython, py2exe or other compiled >>extensions, you should wait to upgrade until the extensions have been >>re-released. >> >>Kent From revanna at mn.rr.com Fri Nov 26 14:22:54 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Fri Nov 26 14:23:05 2004 Subject: [Tutor] time comparison question In-Reply-To: References: <41A6FB51.1080808@po-box.mcgill.ca> Message-ID: <41A72E2E.8000007@mn.rr.com> Liam Clarke wrote: > Hi Brian, > > I was in a similar position to you 3 weeks ago, and I was using > time.time, and time.gmtime. > Guess which one I went with? > My original code was brute forcish, unmaintainable & ugly, but it > worked when I wrote it. Sounds like Perl really. But notice that I had > to use an object anyway to invoke timedelta, so all my messing around > was in vain. Sounds like my first work with dates. (That was back before we had datetime.) > Highly recommend this - > > a) Use the datetime module > b) Use datetime objects, so you don't have to mess around with > functions that require 9 digit tuples > c) Listen to Kent if he posts, he's good. > > > Give datetime a try, and see how it goes. Great answer. I agree, especially with the "listen to Kent" part. ;-) Anna From kent37 at tds.net Fri Nov 26 14:26:26 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 26 14:26:31 2004 Subject: [Tutor] Sort pointers - In-Reply-To: References: <41A46B0B.8070206@tds.net> <41A4B717.3020902@po-box.mcgill.ca> <41A4EAF0.9060009@tds.net> <41A5EA99.708@tds.net> Message-ID: <41A72F02.6050302@tds.net> Liam Clarke wrote: > Erk, one more thing, > > Just playing with that Schwartzian thing, does Python automatically do > secondary sorting? Yes, this is normal and you can rely on it. Tuples and lists are sorted 'lexicographically' which means if the first elements are equal, they are sorted on the second, and so on. If all existing elements are equal but one sequence is longer, the shorter one is sorted first. Read all about it here: http://docs.python.org/ref/comparisons.html Kent > > i.e. > > ('p', 11), ('bb', 11), ('uu', 11) > > Irrelevant bits snipped. So, this is my list sorted by first element. > > So after the second sort - > > (11, ('bb', 11)), (11, ('p', 11)), (11, ('uu', 11)) > > I notice it's already sorted them alphaetically. > > Is this normal, can I rely on it? > > Regards, > > Liam Clarke > From revanna at mn.rr.com Fri Nov 26 14:28:31 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Fri Nov 26 14:28:41 2004 Subject: [Tutor] Help with very basic question In-Reply-To: <20041126033923.1697.qmail@web54002.mail.yahoo.com> References: <20041126033923.1697.qmail@web54002.mail.yahoo.com> Message-ID: <41A72F7F.6040000@mn.rr.com> Harov Satmandirvich wrote: > Hello. Before I continue with a tutorial I would like > to know something very basic: Is there any other way > to advance a line in Python than hitting > "tabtabtabtab"..etc? When I hit"enter?" it enters > the line as if it was a complete bit of program. When you're using the interactive interpreter, it'll keep doing that. BUT - it's easy to fix that. Presumably, you're using IDLE or something similar (if not - you probably should consider it. IDLE makes things a lot easier than the commandline interpreter - and IDLE comes packaged with Python.) In IDLE, just click on File > New Window and then type the statements in the new window. Use F5 to run it (it'll want you to "Save the File". Just give it a name like "temp1" or "testing" and enter. It'll try running the code in the main IDLE Shell and you'll see any errors that come up. It's a really handy way of working - I try out just about everything that way. Hope this helps! Anna From kent37 at tds.net Fri Nov 26 14:45:36 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 26 14:45:41 2004 Subject: [Tutor] Sort pointers - In-Reply-To: <41A5DAFC.2040100@tds.net> References: <006901c4d2ab$231dc290$b25428cf@JSLAPTOP> <41A5DAFC.2040100@tds.net> Message-ID: <41A73380.8030808@tds.net> Kent Johnson wrote: > In Python 2.4 (there it is again), there is a built-in sorted() function > that *returns* a sorted copy of any iterable. So you can do this: > for x in sorted(miscPeople.keys()): > print x, miscPeople[x] > > I would actually do it this way: > for name, code in sorted(miscPeople.items()): > print name, code The Python 2.4 sorted() function also takes an optional key parameter, so you can print a dictionary sorted by value very simply: >>> miscPeople= {'James Bond' : '007' , 'Enid Blyton' : '005' , 'Enid Blyton also' : '006' , 'Captain Planet' : '000' } >>> import operator >>> for name, code in sorted(miscPeople.items(), key=operator.itemgetter(1)): ... print name, code ... Captain Planet 000 Enid Blyton 005 Enid Blyton also 006 James Bond 007 operator.itemgetter(1) produces a *function* which, when given a sequence, returns item 1 of the sequence: >>> get1 = operator.itemgetter(1) >>> get1( ['a', 'b'] ) 'b' >>> get1(miscPeople.keys()) 'Captain Planet' Kent From python at bernardlebel.com Fri Nov 26 17:07:15 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Fri Nov 26 17:07:27 2004 Subject: [Tutor] String matching Message-ID: <41A754B3.5000201@bernardlebel.com> Hello, I'm a little bit confused about the match/search methods of the string module for regular expressions. I have looked the regular expression doc and I can't that one simple answer. So please excuse the basiqueness of my question, as I am used with the .match method of JScript and it kind of matches anything.... Let say I have this string: >>> import re >>> mystring = 'helloworldmynameisbernardlebel' Now I wish to attempt a match with 'bernard'. >>> if not re.compile( 'bernard' ).match( mystring ) == None: ... print 'success' Well, nothing gets printed. Could anyone tell me how to achieve that simple type of matching? Thanks in advance Bernard From keridee at jayco.net Thu Nov 25 21:12:27 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Nov 26 17:18:49 2004 Subject: [Tutor] Change to Python 2.4? Message-ID: <000001c4d3d3$93a7bba0$155328cf@JSLAPTOP> Hi everybody! How hard would it be to change to python 2.4? I have a lot of added things in my site-packages. I DO NOT want to keep two versions of python on my system due to the import problems, etc. Could I just copy my site-packages over to the new python 2.4 folder? Also, is there a list of new things in python 2.4? I have seen enough on this list to know that it would be advantageous for me to download it. Is it completely backwards compatible? IOW, if I change out the interpreters, will all of my current scripts written for 2.3 work for 2.4? It wouldn't be too much of a bother if it isn't. Um... Let's see... That's it. Thanks in advance, Jacob Schmidt From maxnoel_fr at yahoo.fr Fri Nov 26 17:59:38 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Nov 26 18:00:40 2004 Subject: [Tutor] String matching In-Reply-To: <41A754B3.5000201@bernardlebel.com> References: <41A754B3.5000201@bernardlebel.com> Message-ID: <8E82EC13-3FCC-11D9-94E1-000393CBC88E@yahoo.fr> On Nov 26, 2004, at 16:07, Bernard Lebel wrote: > >>> import re > >>> mystring = 'helloworldmynameisbernardlebel' > > Now I wish to attempt a match with 'bernard'. > > >>> if not re.compile( 'bernard' ).match( mystring ) == None: > ... print 'success' > > Well, nothing gets printed. Could anyone tell me how to achieve that > simple type of matching? You need to use search(), not match(). match() tries to match the pattern to the beginning of the string. IOW, in your case it tries to see if mystring begins with "bernard". -- 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 Nov 26 18:44:11 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Nov 26 18:44:15 2004 Subject: [Tutor] Change to Python 2.4? In-Reply-To: <000001c4d3d3$93a7bba0$155328cf@JSLAPTOP> References: <000001c4d3d3$93a7bba0$155328cf@JSLAPTOP> Message-ID: <41A76B6B.2020307@tds.net> Jacob S. wrote: > Hi everybody! > > How hard would it be to change to python 2.4? I have a lot of added > things in my site-packages. I DO NOT want to keep two versions of python on > my system due to the import problems, etc. I don't think you will have import problems, the new version installs into a separate directory and has its own lib folder. Could I just copy my > site-packages over to the new python 2.4 folder? Here is a thread on comp.lang.python that gives a pretty good answer to this: http://tinyurl.com/6eqzm Short answer: - any packages containing .pyd or .dll files, you need a new version - it's a good opportunity to look for more recent versions and install them. I just took a look at how many of my site-packages directories have .pyd files in them and decided *not* to copy my whole site-packages. Also, is there a list of > new things in python 2.4? New versions of Python come with a very handy "What's New" document. The current one can be found at http://www.python.org/dev/doc/devel/whatsnew/whatsnew24.html I have seen enough on this list to know that it > would be advantageous for me to download it. Is it completely backwards > compatible? IOW, if I change out the interpreters, will all of my current > scripts written for 2.3 work for 2.4? See the "Porting to Python 2.4" section of the "What's New" doc. The incompatibilities are pretty obscure. Python developers put a high value on backward compatibility. Kent It wouldn't be too much of a bother if > it isn't. Um... Let's see... That's it. > > Thanks in advance, > Jacob Schmidt > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bvande at po-box.mcgill.ca Fri Nov 26 20:16:40 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Nov 26 20:19:27 2004 Subject: [Tutor] time comparison question In-Reply-To: <41A72D7A.8080805@mn.rr.com> References: <41A6FB51.1080808@po-box.mcgill.ca> <41A72D7A.8080805@mn.rr.com> Message-ID: <41A78118.60100@po-box.mcgill.ca> Anna Ravenscroft said unto the world upon 2004-11-26 08:19: > Brian van den Broek wrote: > >> Hi all, >> >> I'm trying to build some Python 2.3.4 code which will determine if the >> actual time when it is run is after the date and time specified in >> some data. I want my data to be able to specify the target date/time >> in a various levels of detail. I.e., I want 2004-11-28 13:25, >> 2004-11-28, 11-28, 11-28 13:25 to all be accepted. Hi all, thanks to Anna, G. Rodrigues, and Liam for the replies. The code that was posted using datetime didn't seem so scary after all :-) As evidence accrues, I think I am going to just have to gather myself together and surmount the aversion to classes and other aspects of OOP. At least in this case, code has shown it isn't too tricky. One minor quibble with something Liam posted. Of struct_time objects he said: > The 9 value tuple has year to microsecond, and day of the week > contained, so you can use it if you wish. For future googlers, my understanding is that the first 6 elements of a struct_time tuple are the date and time from year down to the second (microseconds playing no role), and the last three are weekday, day of year, and DST flag. Anyway, having read the replies, it looks like my problem is solved. Thanks folks! Best to all, Brian vdB From missive at hotmail.com Fri Nov 26 20:45:20 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Nov 26 20:46:06 2004 Subject: [Tutor] Re: Python and statistics Message-ID: >If anyone has any specific ideas, particularly where the goal is to use >Python to assist in grasping the concepts of a typical introductory college >Statistics class - their input would be appreciated. > I have been playing with pyr -- python bindings to the R statistics package: http://www.r-project.org/ http://rpy.sourceforge.net/ Way more statistics power than I will (hopefully ;o) ever need. _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From dyoo at hkn.eecs.berkeley.edu Fri Nov 26 21:26:00 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 26 21:26:15 2004 Subject: [Tutor] String matching In-Reply-To: <8E82EC13-3FCC-11D9-94E1-000393CBC88E@yahoo.fr> Message-ID: > > >>> mystring = 'helloworldmynameisbernardlebel' > > > > Now I wish to attempt a match with 'bernard'. > > > > >>> if not re.compile( 'bernard' ).match( mystring ) == None: > > ... print 'success' > > > > Well, nothing gets printed. Could anyone tell me how to achieve that > > simple type of matching? > > You need to use search(), not match(). match() tries to match the > pattern to the beginning of the string. IOW, in your case it tries to > see if mystring begins with "bernard". Hi Bernard, If it helps, imagine that match() always puts a beginning anchor '^' at the beginning of the pattern, and you'll see the difference between match() and search(). (I'm lying in a small way: that's not exactly how match() works, but it's close... *grin*) There's also a brief discussion about it in the documentation: http://www.python.org/doc/lib/matching-searching.html which tries to show more formally why we have both match() and search(). Good luck to you! From python at bernardlebel.com Fri Nov 26 21:34:01 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Fri Nov 26 21:34:11 2004 Subject: [Tutor] String matching In-Reply-To: References: Message-ID: <41A79339.5070806@bernardlebel.com> Allrighty, thanks a lot everyone. Bernard Danny Yoo wrote: > >>>>>>mystring = 'helloworldmynameisbernardlebel' >>> >>>Now I wish to attempt a match with 'bernard'. >>> >>> >>>>>>if not re.compile( 'bernard' ).match( mystring ) == None: >>> >>>... print 'success' >>> >>>Well, nothing gets printed. Could anyone tell me how to achieve that >>>simple type of matching? >> >>You need to use search(), not match(). match() tries to match the >>pattern to the beginning of the string. IOW, in your case it tries to >>see if mystring begins with "bernard". > > > > Hi Bernard, > > If it helps, imagine that match() always puts a beginning anchor '^' at > the beginning of the pattern, and you'll see the difference between > match() and search(). > > (I'm lying in a small way: that's not exactly how match() works, but it's > close... *grin*) > > There's also a brief discussion about it in the documentation: > > http://www.python.org/doc/lib/matching-searching.html > > which tries to show more formally why we have both match() and search(). > > Good luck to you! From dyoo at hkn.eecs.berkeley.edu Fri Nov 26 21:35:05 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 26 21:35:15 2004 Subject: [Tutor] String matching In-Reply-To: <41A754B3.5000201@bernardlebel.com> Message-ID: On Fri, 26 Nov 2004, Bernard Lebel wrote: > >>> mystring = 'helloworldmynameisbernardlebel' > > >>> if not re.compile( 'bernard' ).match( mystring ) == None: > ... print 'success' > > Well, nothing gets printed. Could anyone tell me how to achieve that > simple type of matching? Hi Bernard, Oh, one more thing. If you're just trying to see if a string is a substring of another, then you might want to just say something like this: ### if 'bernard' in mystring: ... ### This is a simpler way to do a substring match. In general, we can see if one string is a substring of another by using the 'in' operator: if substring in anotherstring: ... If we need to know where a substring matches in the larger string, then there's a 'find()' string method that should do the trick. ### >>> "this is a test".find("is") 2 ### Note that this find() method is only checking for substring matching: it has no knowledge of words. If we needed it to match the whole word, then we'd probably need regular expressions: ### >>> import re >>> re.search(r'\bis\b', "this is a test").start() 5 ### But if we don't need the full power of regular expressions, then we may prefer the simpler exact string matching that find() gives us. Good luck! From keridee at jayco.net Fri Nov 26 18:56:55 2004 From: keridee at jayco.net (Jacob S.) Date: Sat Nov 27 01:09:47 2004 Subject: [Tutor] String matching References: <41A754B3.5000201@bernardlebel.com> Message-ID: <000201c4d415$5dd63e60$415328cf@JSLAPTOP> Hi Bernard! > Hello, > > I'm a little bit confused about the match/search methods of the string > module for regular expressions. I have looked the regular expression doc > and I can't that one simple answer. > > So please excuse the basiqueness of my question, as I am used with the > .match method of JScript and it kind of matches anything.... > > Let say I have this string: > > >>> import re > >>> mystring = 'helloworldmynameisbernardlebel' > > Now I wish to attempt a match with 'bernard'. > > >>> if not re.compile( 'bernard' ).match( mystring ) == None: > ... print 'success' First, you are printinting redundant code here. You are using double negatives. You first check to see if re.compile('bernard').match(mystring) registers false, if it is false the expression registers true. Then you check to see if that expression registers false. So really the equivalent expression is if re.compile('bernard').match(mystring): print 'success' However, I don't think that solves your problem. > Well, nothing gets printed. Could anyone tell me how to achieve that > simple type of matching? Re expressions are a little different from JScript. The match method only matches equivalent strings. (Or it only does in this case.) Instead, you want to use the search method. Oh, and by the way, if you're going to compile the expression without assigning it to a variable, you might use the re methods instead of the re pattern methods. IOW, use this code instead... import re mystring = 'helloworldmynameisbernardlebel' if re.search('bernard',mystring): print 'success' The documentation for the re methods are hidden, IMHO. You can find them by typing in 'search() (in module re)' in the index and that should take you right to it. That page contains explanations for all of the re methods. Good luck, Jacob Schmidt From John.Gooch at echostar.com Sat Nov 27 01:22:14 2004 From: John.Gooch at echostar.com (Gooch, John) Date: Sat Nov 27 01:22:20 2004 Subject: [Tutor] String matching Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC0166@riv-excha5.echostar.com> I am trying to extract data found in an MS Excel workbook using regular expressions. For some reason, it plain refuses to recognize the "-" unicode character. Here is what happens when I execute: print "Resolving name for "+tname+" type=",type(tname) rePName = re.compile( u"(-)", re.UNICODE ) m = rePName.match( tname ) print "Resolved to groups"+unicode(m.groups()) Resolving name for 1.0 Windows - AB - 11/23/04 type= Resolved to groups(u'1.0 Windows \u2013 HD - 11/23/04',) Notice I told it to match on the "-" character, which shows up in the print command. But when I tell it to match on the character, it doesn't match. U have tried the escape code "\u2013", but that does not match at all. Any ideas? John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 -----Original Message----- From: Jacob S. [mailto:keridee@jayco.net] Sent: Friday, November 26, 2004 10:57 AM To: Bernard Lebel Cc: tutor@python.org Subject: Re: [Tutor] String matching Hi Bernard! > Hello, > > I'm a little bit confused about the match/search methods of the string > module for regular expressions. I have looked the regular expression > doc and I can't that one simple answer. > > So please excuse the basiqueness of my question, as I am used with the > .match method of JScript and it kind of matches anything.... > > Let say I have this string: > > >>> import re > >>> mystring = 'helloworldmynameisbernardlebel' > > Now I wish to attempt a match with 'bernard'. > > >>> if not re.compile( 'bernard' ).match( mystring ) == None: ... > print 'success' First, you are printinting redundant code here. You are using double negatives. You first check to see if re.compile('bernard').match(mystring) registers false, if it is false the expression registers true. Then you check to see if that expression registers false. So really the equivalent expression is if re.compile('bernard').match(mystring): print 'success' However, I don't think that solves your problem. > Well, nothing gets printed. Could anyone tell me how to achieve that > simple type of matching? Re expressions are a little different from JScript. The match method only matches equivalent strings. (Or it only does in this case.) Instead, you want to use the search method. Oh, and by the way, if you're going to compile the expression without assigning it to a variable, you might use the re methods instead of the re pattern methods. IOW, use this code instead... import re mystring = 'helloworldmynameisbernardlebel' if re.search('bernard',mystring): print 'success' The documentation for the re methods are hidden, IMHO. You can find them by typing in 'search() (in module re)' in the index and that should take you right to it. That page contains explanations for all of the re methods. Good luck, Jacob Schmidt _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Sat Nov 27 01:58:37 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Nov 27 01:58:01 2004 Subject: [Tutor] Change to Python 2.4? References: <000001c4d3d3$93a7bba0$155328cf@JSLAPTOP> Message-ID: <009901c4d41c$3b531550$1abd8651@xp> > How hard would it be to change to python 2.4? Probably not very hard but, why would you want to? Do you have a need? At work I am still using Python 2.1, and at home I still use 2.2 on my Mac. I only moved to 2.3 on my PC so that I could update my tutor, I am not knowingly using any 2.3 specific features. So unless you need something specific in 2.4 there should be no reason to ruish to it, wait till a safe point in your project - like after you get a stable working release - and then upgrade at your leasure... > new things in python 2.4? THere is usually a list available on the web site. > I have seen enough on this list to know that it > would be advantageous for me to download it. If you have a specifc advantage that makes the advantage worth the risk then go ahead. Python release changes are usually pretty easy and backwardly compatible. > scripts written for 2.3 work for 2.4? Occasionally something might break but in most cases(99%?) I'd expect the 2.3 stuff to just work. Alan G. From alan.gauld at freenet.co.uk Sat Nov 27 02:17:53 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Nov 27 02:17:29 2004 Subject: [Tutor] Help with very basic question References: <20041126033923.1697.qmail@web54002.mail.yahoo.com> <41A72F7F.6040000@mn.rr.com> Message-ID: <00a201c4d41e$ec4a3490$1abd8651@xp> > Harov Satmandirvich wrote: > > Hello. Before I continue with a tutorial I would like > > to know something very basic: Is there any other way > > to advance a line in Python than hitting > > "tabtabtabtab"..etc? When I hit"enter?" it enters > > the line as if it was a complete bit of program. You can use a line continuatoion character (\) if you just want to break a line while in the interpreter. But if you want to type multi line programs without the interpreter executing it as you go follow Annas advice and use a text file to store the code. HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From billburns at pennswoods.net Sat Nov 27 03:41:06 2004 From: billburns at pennswoods.net (Bill Burns) Date: Sat Nov 27 03:33:19 2004 Subject: [Tutor] Database questions In-Reply-To: References: Message-ID: <200411262141.06192.billburns@pennswoods.net> On Tuesday 23 November 2004 7:56 pm, Jay Mutter wrote: > Good evening; > I am using OS X 10.3.6 on an ibook where I have python 2.3.3 and > wxPython 2.5.3.1 installed with mxDateTime, Postgresql and psycopg. > > What i would like to know ( remember I have not really started using > python or any of the others) is what would you suggest as a GUI > designer to work with the above for someone who wants to develop a GUI > client interface for a RDBMS system. I have looked at wxGlade, > Pythoncard, wxDesigner, and Boa constructor and am currently clueless. > If I wanted to hone my skills by creating a GUI checkbook > register/balancing program would I be best off to simply use the DB > modules built into Python. > Remember I am definitely a newbie. > Warning, the following doesn't meet all of your criteria, but if that doesn't bother you, keep reading :-) Have you looked at Qt Designer + PyQt? This solution is not "wx" based (which I think is the only criteria it doesn't meet) but it should provide everything else you want, i.e., OS X, works with databases and easy to use. I don't use OS X but I do use these programs (on Linux) and they are very newbie friendly. I'm also a fellow n00b :-) and believe me, with Qt, it's very simple and fast to make a nice GUI. Using Qt Designer, you can visually design a GUI without "hand coding" a thing. You literally just drop widgets, which are all accessible on the left-hand side of Designer, right on to your forms. After you've created the UI, you use a tool called pyuic (python user interface compiler) to compile it to python code. You can either make this code directly executable or import it into your own module. If you have access to a Linux box (with a modern distro) try typing "designer" (without the quotes) at a command prompt. Maybe you can at least look at the GUI builder and get a feel for it. You'll have to look at the licensing or distribution restrictions if you want to distribute this app on Windows. I really don't know all of the restrictions but I think if you're developing for just OS X or Linux you should have no concerns. There are definitely issues when it comes to using Qt and PyQt on the Windows platform. Look in to this, it's probably the single biggest reason why Designer & PyQt are not suggested more often. Even so, these are outstanding tools. The Qt docs are full of information and even- though they apply to C++, it's not hard to understand them and translate the info into Python. Here's some links you might want to check out: Info & download link for the gpl'ed version of QT for Mac: http://www.trolltech.com/download/qt/mac.html Subscribe to and/or search the PyKDE mailing list (this list is for both PyKDE & PyQt): http://mats.imk.fraunhofer.de/mailman/listinfo/pykde Main web site for PyQt: http://www.riverbankcomputing.co.uk/pyqt/index.php An excellent site for info about PyQt programming: http://www.opendocspublishing.com/pyqt/index.lxp eric3 - A Python IDE http://www.die-offenbachs.de/detlev/eric3.html Black Adder - a commercial IDE: http://www.thekompany.com/ HTH Bill From cyresse at gmail.com Sat Nov 27 04:53:47 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sat Nov 27 04:53:50 2004 Subject: [Tutor] time comparison question In-Reply-To: <41A78118.60100@po-box.mcgill.ca> References: <41A6FB51.1080808@po-box.mcgill.ca> <41A72D7A.8080805@mn.rr.com> <41A78118.60100@po-box.mcgill.ca> Message-ID: Eep, you're right Brian, mea culpa. On Fri, 26 Nov 2004 14:16:40 -0500, Brian van den Broek wrote: > Anna Ravenscroft said unto the world upon 2004-11-26 08:19: > > Brian van den Broek wrote: > > > >> Hi all, > >> > >> I'm trying to build some Python 2.3.4 code which will determine if the > >> actual time when it is run is after the date and time specified in > >> some data. I want my data to be able to specify the target date/time > >> in a various levels of detail. I.e., I want 2004-11-28 13:25, > >> 2004-11-28, 11-28, 11-28 13:25 to all be accepted. > > Hi all, > > thanks to Anna, G. Rodrigues, and Liam for the replies. The code that > was posted using datetime didn't seem so scary after all :-) > > As evidence accrues, I think I am going to just have to gather myself > together and surmount the aversion to classes and other aspects of OOP. > At least in this case, code has shown it isn't too tricky. > > One minor quibble with something Liam posted. Of struct_time objects he > said: > > > The 9 value tuple has year to microsecond, and day of the week > > contained, so you can use it if you wish. > > For future googlers, my understanding is that the first 6 elements of a > struct_time tuple are the date and time from year down to the second > (microseconds playing no role), and the last three are weekday, day of > year, and DST flag. > > Anyway, having read the replies, it looks like my problem is solved. > Thanks folks! > > > > Best to all, > > Brian vdB > > _______________________________________________ > 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 billburns at pennswoods.net Sat Nov 27 05:14:44 2004 From: billburns at pennswoods.net (Bill Burns) Date: Sat Nov 27 05:06:55 2004 Subject: [Tutor] Database questions In-Reply-To: <200411262141.06192.billburns@pennswoods.net> References: <200411262141.06192.billburns@pennswoods.net> Message-ID: <200411262314.44800.billburns@pennswoods.net> As a follow-up to my previous post: I just found this on the PyKDE mailing list. A web site that provides a binary installer for Qt / PyQt for OS X. Maybe this will make it easier for you to try out? Here's the link: http://www.wordtech-software.com/python.html Bill From sun at cae.wisc.edu Sat Nov 27 05:30:52 2004 From: sun at cae.wisc.edu (Hongyu Sun) Date: Sat Nov 27 05:30:59 2004 Subject: [Tutor] please recommend a book to learn Python for Abaqus scripting References: <000001c4d3d3$93a7bba0$155328cf@JSLAPTOP> Message-ID: <064101c4d439$e0e98040$0d779792@star> Dear tutor list: I am very new to Python. But I have to use Python to do Abaqus (a finite element software) scripting. I wonder if you could recommend a good start point(books etc.) that I can learn it fast? Many thanks! Hongyu From revanna at mn.rr.com Sat Nov 27 09:06:12 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Sat Nov 27 09:06:28 2004 Subject: [Tutor] Change to Python 2.4? In-Reply-To: <009901c4d41c$3b531550$1abd8651@xp> References: <000001c4d3d3$93a7bba0$155328cf@JSLAPTOP> <009901c4d41c$3b531550$1abd8651@xp> Message-ID: <41A83574.1070706@mn.rr.com> Alan Gauld wrote: >> How hard would it be to change to python 2.4? > > > Probably not very hard but, why would you want to? > Do you have a need? > > At work I am still using Python 2.1, and at home I > still use 2.2 on my Mac. I only moved to 2.3 on my > PC so that I could update my tutor, I am not knowingly > using any 2.3 specific features. Wow. I've heard so many kewl things on 2.3 (like datetime and sets and sum) that I can't imagine having to work in 2.2 or earlier anymore... > So unless you need something specific in 2.4 there > should be no reason to ruish to it, wait till a > safe point in your project - like after you get a > stable working release - and then upgrade at your > leasure... 2.4 has worked heavily on optimization. So lots of code runs faster on 2.4. There's also a new Decimal type, generator expressions, reverse iterators, built-in set objects, simpler string substitutions, and decorators for functions and methods. >new things in python 2.4? > > THere is usually a list available on the web site. http://www.python.org/dev/doc/devel/whatsnew/ >>I have seen enough on this list to know that it >>would be advantageous for me to download it. > > > If you have a specifc advantage that makes the > advantage worth the risk then go ahead. Python > release changes are usually pretty easy and > backwardly compatible. Generally yes. And there's no reason you can't install 2.4 in another directory and try both versions for a while to see which one you like better. Just make sure your !# line points to the right version. >scripts written for 2.3 work for 2.4? I can't see any reason why not. Backwards compatibility is a biggie with Python releases and I haven't heard of anything in the new release that "breaks" older ways of doing things. > Occasionally something might break but in most > cases(99%?) I'd expect the 2.3 stuff to just work. Yep. Anna From revanna at mn.rr.com Sat Nov 27 09:14:18 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Sat Nov 27 09:14:30 2004 Subject: [Tutor] Help with very basic question In-Reply-To: <00a201c4d41e$ec4a3490$1abd8651@xp> References: <20041126033923.1697.qmail@web54002.mail.yahoo.com> <41A72F7F.6040000@mn.rr.com> <00a201c4d41e$ec4a3490$1abd8651@xp> Message-ID: <41A8375A.7020608@mn.rr.com> Alan Gauld wrote: >>Harov Satmandirvich wrote: >> >>>Hello. Before I continue with a tutorial I would like >>>to know something very basic: Is there any other way >>>to advance a line in Python than hitting >>>"tabtabtabtab"..etc? When I hit"enter?" it enters >>>the line as if it was a complete bit of program. > > > You can use a line continuatoion character (\) if you just want > to break a line while in the interpreter. Oh yeah. I never thought of doing that in the interpreter, silly me. Kewl! (See, that's why I hang out here - I keep learning new things!) Anna From cyresse at gmail.com Sat Nov 27 11:00:37 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sat Nov 27 11:00:41 2004 Subject: [Tutor] Change to Python 2.4? In-Reply-To: <41A83574.1070706@mn.rr.com> References: <000001c4d3d3$93a7bba0$155328cf@JSLAPTOP> <009901c4d41c$3b531550$1abd8651@xp> <41A83574.1070706@mn.rr.com> Message-ID: Just reading the changes log for 2.4, biggies (to me) seem to be new iterator objects, email.Parser rewritten to handle malformed email, and a new collection type the deque (double ended queue). Oh, long integers & integers merged, and sorted(), and sort() using new keywords. if I did a lot of email parsing, I might upgrade. On Sat, 27 Nov 2004 09:06:12 +0100, Anna Ravenscroft wrote: > Alan Gauld wrote: > >> How hard would it be to change to python 2.4? > > > > > > Probably not very hard but, why would you want to? > > Do you have a need? > > > > At work I am still using Python 2.1, and at home I > > still use 2.2 on my Mac. I only moved to 2.3 on my > > PC so that I could update my tutor, I am not knowingly > > using any 2.3 specific features. > > Wow. I've heard so many kewl things on 2.3 (like datetime and sets and > sum) that I can't imagine having to work in 2.2 or earlier anymore... > > > So unless you need something specific in 2.4 there > > should be no reason to ruish to it, wait till a > > safe point in your project - like after you get a > > stable working release - and then upgrade at your > > leasure... > > 2.4 has worked heavily on optimization. So lots of code runs faster on > 2.4. There's also a new Decimal type, generator expressions, reverse > iterators, built-in set objects, simpler string substitutions, and > decorators for functions and methods. > > > > >new things in python 2.4? > > > > THere is usually a list available on the web site. > > http://www.python.org/dev/doc/devel/whatsnew/ > > >>I have seen enough on this list to know that it > >>would be advantageous for me to download it. > > > > > > If you have a specifc advantage that makes the > > advantage worth the risk then go ahead. Python > > release changes are usually pretty easy and > > backwardly compatible. > > Generally yes. And there's no reason you can't install 2.4 in another > directory and try both versions for a while to see which one you like > better. Just make sure your !# line points to the right version. > > >scripts written for 2.3 work for 2.4? > > I can't see any reason why not. Backwards compatibility is a biggie with > Python releases and I haven't heard of anything in the new release that > "breaks" older ways of doing things. > > > Occasionally something might break but in most > > cases(99%?) I'd expect the 2.3 stuff to just work. > > Yep. > > Anna > > > _______________________________________________ > 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 Sat Nov 27 11:39:46 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Nov 27 11:39:51 2004 Subject: [Tutor] please recommend a book to learn Python for Abaqus scripting In-Reply-To: <064101c4d439$e0e98040$0d779792@star> References: <000001c4d3d3$93a7bba0$155328cf@JSLAPTOP> <064101c4d439$e0e98040$0d779792@star> Message-ID: <41A85972.3090101@tds.net> Do you have other programming experience or is this your first exposure to programming? The Python tutorial is a good place to start. http://docs.python.org/tut/tut.html Browse the beginner's resources on these two pages and find one you like: http://www.python.org/moin/BeginnersGuide http://www.python.org/doc/Intros.html My personal favorites are listed here: http://personalpages.tds.net/~kent37/Python/PythonResources.html Kent Hongyu Sun wrote: > Dear tutor list: > > I am very new to Python. But I have to use Python to do Abaqus (a finite > element software) scripting. I wonder if you could recommend a good start > point(books etc.) that I can learn it fast? > > Many thanks! > > Hongyu > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ps_python at yahoo.com Sat Nov 27 18:19:33 2004 From: ps_python at yahoo.com (kumar s) Date: Sat Nov 27 18:19:37 2004 Subject: [Tutor] Error in loop. Please help. Message-ID: <20041127171933.85461.qmail@web53707.mail.yahoo.com> Dear group, I have the following files: sample_exp_name Apple Boy Cat Dog Elephant sample_name A B C D E A B C D E g1 12.6 23 67 87 87 g2 34 34 35 28 65 g3 34 397 55 224 45 g4 56 78 56 688 77 g5 8 35 42 2357 56 g6 34 56 56 34 59 Based on these I wanted to write an SQL file: INSERT INTO sample(sample_name)VALUES('A'); INSERT INTO samp_exp(sample_id,samp_exp_name)VALUES(currval('sample_sample_id_seq'),'Apple'); INSERT into vals(sample_id,samp_exp_id,val_name,val_val)VALUES(currval('sample_sample_id_seq'),currval('samp_exp_samp_exp_id_seq'),'A','',A); INSERT into vals(sample_id,samp_exp_id,val_name,val_val)VALUES(currval('sample_sample_id_seq'),currval('samp_exp_samp_exp_id_seq'),'A','g1',12.6); INSERT into vals(sample_id,samp_exp_id,val_name,val_val)VALUES(currval('sample_sample_id_seq'),currval('samp_exp_samp_exp_id_seq'),'A','g2',34); INSERT into vals(sample_id,samp_exp_id,val_name,val_val)VALUES(currval('sample_sample_id_seq'),currval('samp_exp_samp_exp_id_seq'),'A','g3',34); INSERT into vals(sample_id,samp_exp_id,val_name,val_val)VALUES(currval('sample_sample_id_seq'),currval('samp_exp_samp_exp_id_seq'),'A','g4',56); INSERT into vals(sample_id,samp_exp_id,val_name,val_val)VALUES(currval('sample_sample_id_seq'),currval('samp_exp_samp_exp_id_seq'),'A','g5',8); INSERT into vals(sample_id,samp_exp_id,val_name,val_val)VALUES(currval('sample_sample_id_seq'),currval('samp_exp_samp_exp_id_seq'),'A','g6',34); My Script: import string from string import split f= open('test.txt','r') #-- Reading the file that contains the matrix fr = f.read() f2 = open('sampledb.txt','r') #--(The above line reads sampledb file that contains sample_names f2r = f2.read() f2lines = f2r.split('\n') f2lines = f2lines[1:-1] # -- (The above line filters the first element which is sample_name) f3 = open('samp_exp.txt','r') #--(The above line reads sample_exp_.txt file that containts sample description such as a for apple). f3r = f3.read() f3lines = f3r.split('\n') f3lines = f3lines[1:-1] flines = fr.split('\n') samp = flines[0] samps = samp.split('\t') samples = samps[1:] #--(The above lines stores a list of sample ['a','b','c','d','e'] out = open('test.sql','w') for m in range(len(samples)): out.write("INSERT INTO sample(sample_name)VALUES(" "'"+samples[m]+"'" ");" "\n") #--Looping over a sample e.g. a for d in range(len(f3lines)): #--looping over sample name e.g. apple out.write("INSERT INTO samp_exp(sample_id,samp_exp_name)VALUES(currval('sample_sample_id_seq'),""'"+f3lines[d]+"'"");""\n") for i in range(len(flines[1:])): #-- looping over the values for g1,g2,g3,g4 in a column row-wise cols = split(flines[i],'\t') a = samples.index(samples[m]) out.write("INSERT into vals(sample_id,samp_exp_id,val_name,val_val)VALUES(currval('sample_sample_id_seq'),currval('samp_exp_samp_exp_id_seq'),""'"+samples[m]+"'"",""'"+cols[0]+"'"","+cols[a+1]+");""\n") My Problem: In my previous script versions, I could able to loop through all columns. I did something, I dont remember, unfortunately. Now I loop through only one column A. I am unable to make the script write the similar sql statements for column, B, C, D and E. I am particular about this sequence: Write sample_name write samp_exp_name write all the values for coulmn A write sample_name write sampl_exp_name write all the values for column B Can any one, PLEASE help me why I am unable to loop throug second, third columns. Somehow I made it loop night before yesterday. I did something when my mind was sleepy and from then i am baning my head and i am unable to get it again. thanks Kumar. __________________________________ Do you Yahoo!? Take Yahoo! Mail with you! Get it on your mobile phone. http://mobile.yahoo.com/maildemo From pythontut at pusspaws.net Sat Nov 27 21:57:57 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat Nov 27 21:58:04 2004 Subject: [Tutor] Closeing a file written to by cPickle dump Message-ID: <41A8EA55.707@pusspaws.net> So far when I have needed to write to a file I have: ...... import time,smtplib,os,sys ..... .... logfile=open(logdir+'log','w') logfile.write(blog) logfile.close() Now I need to use pickle to save dictionaries, I have started: ..... from cPickle import dump ...... dump(dict,open(data_dir+'/'+save_name,'w')) It appears to work OK & I can read from the pickle but in this dump format do I need to close the open file with an equiverlant of xxx.close(). Am I in danger of data not being flushed to the hard drive ? If I do need to close it, how do I do that because there is no class instance ? Cheers Dave From orbitz at ezabel.com Sat Nov 27 22:07:13 2004 From: orbitz at ezabel.com (orbitz) Date: Sat Nov 27 22:07:37 2004 Subject: [Tutor] Closeing a file written to by cPickle dump In-Reply-To: <41A8EA55.707@pusspaws.net> References: <41A8EA55.707@pusspaws.net> Message-ID: <41A8EC81.4040007@ezabel.com> In your example you do not have an object to close since you open it in the dump call. Also, you open it for writing only in your example so you will need to reopen it if you plan to read from it. If you want to read and write to it you'll need to open it for reading and writing and when you are done rewind the cursor so you are at the front. Dave S wrote: > So far when I have needed to write to a file I have: > > ...... > import time,smtplib,os,sys > ..... > .... > logfile=open(logdir+'log','w') > logfile.write(blog) > logfile.close() > > Now I need to use pickle to save dictionaries, I have started: > > ..... > from cPickle import dump > ...... > dump(dict,open(data_dir+'/'+save_name,'w')) > > It appears to work OK & I can read from the pickle but in this dump > format do I need to close the open file with an equiverlant of > xxx.close(). Am I in danger of data not being flushed to the hard drive ? > > If I do need to close it, how do I do that because there is no class > instance ? > > Cheers > Dave > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sat Nov 27 22:13:31 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Nov 27 22:13:36 2004 Subject: [Tutor] Closeing a file written to by cPickle dump In-Reply-To: <41A8EA55.707@pusspaws.net> References: <41A8EA55.707@pusspaws.net> Message-ID: <41A8EDFB.6050209@tds.net> Dave S wrote: > I need to use pickle to save dictionaries, I have started: > > ..... > from cPickle import dump > ...... > dump(dict,open(data_dir+'/'+save_name,'w')) > > It appears to work OK & I can read from the pickle but in this dump > format do I need to close the open file with an equiverlant of > xxx.close(). Am I in danger of data not being flushed to the hard drive ? Though it may not always be necessary, I think it is prudent to always close a file that was opened for writing. The call to open returns a file object, you just have to retain a reference to it so you can close it when you are done: f=open(data_dir+'/'+save_name,'w' dump(dict,f)) f.close() > > If I do need to close it, how do I do that because there is no class > instance ? > > Cheers > Dave > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Sun Nov 28 00:10:00 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Nov 28 00:10:04 2004 Subject: [Tutor] Closeing a file written to by cPickle dump In-Reply-To: <41A8EDFB.6050209@tds.net> References: <41A8EA55.707@pusspaws.net> <41A8EDFB.6050209@tds.net> Message-ID: Hi all, Pickle... just reading O'Reilly's Python In A Nutshell, and thought this would be an opportune time to clarify pickling. Pickle will write dictionaries/classes/functions to disk, and then read them back in a usable manner? I'm just trying to paraphrase this module's functionality, as O'Reilly states - "The pickle and cPickle modules supply factory functions, named Pickler and Unpickler, to generate objects that wrap file-like objects and supply serialization mechanisms." Which makes me say 'Wuzzah?' If so, how silly am I, creating functions to load/save dictionaries myself, when there already exists functions to do that, plus save other useful stuff. Regards, Liam Clarke On Sat, 27 Nov 2004 16:13:31 -0500, Kent Johnson wrote: > Dave S wrote: > > I need to use pickle to save dictionaries, I have started: > > > > ..... > > from cPickle import dump > > ...... > > dump(dict,open(data_dir+'/'+save_name,'w')) > > > > It appears to work OK & I can read from the pickle but in this dump > > format do I need to close the open file with an equiverlant of > > xxx.close(). Am I in danger of data not being flushed to the hard drive ? > > Though it may not always be necessary, I think it is prudent to always > close a file that was opened for writing. The call to open returns a > file object, you just have to retain a reference to it so you can close > it when you are done: > > f=open(data_dir+'/'+save_name,'w' > dump(dict,f)) > f.close() > > > > > > > If I do need to close it, how do I do that because there is no class > > instance ? > > > > Cheers > > Dave > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > 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 pythontut at pusspaws.net Sun Nov 28 01:17:21 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Nov 28 01:17:29 2004 Subject: [Tutor] Closeing a file written to by cPickle dump In-Reply-To: <41A8EDFB.6050209@tds.net> References: <41A8EA55.707@pusspaws.net> <41A8EDFB.6050209@tds.net> Message-ID: <41A91911.7040008@pusspaws.net> Kent Johnson wrote: > Dave S wrote: > >> I need to use pickle to save dictionaries, I have started: >> >> ..... >> from cPickle import dump >> ...... >> dump(dict,open(data_dir+'/'+save_name,'w')) >> >> It appears to work OK & I can read from the pickle but in this dump >> format do I need to close the open file with an equiverlant of >> xxx.close(). Am I in danger of data not being flushed to the hard >> drive ? > > > Though it may not always be necessary, I think it is prudent to > always close a file that was opened for writing. The call to open > returns a file object, you just have to retain a reference to it so > you can close it when you are done: > > f=open(data_dir+'/'+save_name,'w' > dump(dict,f)) > f.close() Thanks for the above, now in my code :) Dave From jmutter at uakron.edu Sun Nov 28 01:26:36 2004 From: jmutter at uakron.edu (Jay Mutter) Date: Sun Nov 28 01:20:37 2004 Subject: [Tutor] Re: Tutor Digest, Vol 9, Issue 82 In-Reply-To: <20041127040700.621A91E4009@bag.python.org> References: <20041127040700.621A91E4009@bag.python.org> Message-ID: <29E3A486-40D4-11D9-A636-000D93537766@uakron.edu> thanks On Nov 26, 2004, at 11:07 PM, tutor-request@python.org wrote: > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-owner@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: String matching (Bernard Lebel) > 2. Re: String matching (Danny Yoo) > 3. Re: String matching (Jacob S.) > 4. RE: String matching (Gooch, John) > 5. Re: Change to Python 2.4? (Alan Gauld) > 6. Re: Help with very basic question (Alan Gauld) > 7. Re: Database questions (Bill Burns) > 8. Re: time comparison question (Liam Clarke) > 9. Re: Database questions (Bill Burns) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 26 Nov 2004 15:34:01 -0500 > From: Bernard Lebel > Subject: Re: [Tutor] String matching > To: tutor@python.org > Message-ID: <41A79339.5070806@bernardlebel.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Allrighty, thanks a lot everyone. > > Bernard > > > Danny Yoo wrote: >> >>>>>>> mystring = 'helloworldmynameisbernardlebel' >>>> >>>> Now I wish to attempt a match with 'bernard'. >>>> >>>> >>>>>>> if not re.compile( 'bernard' ).match( mystring ) == None: >>>> >>>> ... print 'success' >>>> >>>> Well, nothing gets printed. Could anyone tell me how to achieve that >>>> simple type of matching? >>> >>> You need to use search(), not match(). match() tries to match the >>> pattern to the beginning of the string. IOW, in your case it tries to >>> see if mystring begins with "bernard". >> >> >> >> Hi Bernard, >> >> If it helps, imagine that match() always puts a beginning anchor '^' >> at >> the beginning of the pattern, and you'll see the difference between >> match() and search(). >> >> (I'm lying in a small way: that's not exactly how match() works, but >> it's >> close... *grin*) >> >> There's also a brief discussion about it in the documentation: >> >> http://www.python.org/doc/lib/matching-searching.html >> >> which tries to show more formally why we have both match() and >> search(). >> >> Good luck to you! > > > > ------------------------------ > > Message: 2 > Date: Fri, 26 Nov 2004 12:35:05 -0800 (PST) > From: Danny Yoo > Subject: Re: [Tutor] String matching > To: Bernard Lebel > Cc: tutor@python.org > Message-ID: > > Content-Type: TEXT/PLAIN; charset=US-ASCII > > > > On Fri, 26 Nov 2004, Bernard Lebel wrote: > >>>>> mystring = 'helloworldmynameisbernardlebel' >> >>>>> if not re.compile( 'bernard' ).match( mystring ) == None: >> ... print 'success' >> >> Well, nothing gets printed. Could anyone tell me how to achieve that >> simple type of matching? > > > Hi Bernard, > > Oh, one more thing. If you're just trying to see if a string is a > substring of another, then you might want to just say something like > this: > > ### > if 'bernard' in mystring: ... > ### > > > This is a simpler way to do a substring match. In general, we can see > if > one string is a substring of another by using the 'in' operator: > > if substring in anotherstring: ... > > > If we need to know where a substring matches in the larger string, then > there's a 'find()' string method that should do the trick. > > ### >>>> "this is a test".find("is") > 2 > ### > > Note that this find() method is only checking for substring matching: > it > has no knowledge of words. If we needed it to match the whole word, > then > we'd probably need regular expressions: > > ### >>>> import re >>>> re.search(r'\bis\b', "this is a test").start() > 5 > ### > > But if we don't need the full power of regular expressions, then we may > prefer the simpler exact string matching that find() gives us. > > > Good luck! > > > > ------------------------------ > > Message: 3 > Date: Fri, 26 Nov 2004 12:56:55 -0500 > From: "Jacob S." > Subject: Re: [Tutor] String matching > To: "Bernard Lebel" > Cc: tutor@python.org > Message-ID: <000201c4d415$5dd63e60$415328cf@JSLAPTOP> > Content-Type: text/plain; charset="iso-8859-1" > > Hi Bernard! > >> Hello, >> >> I'm a little bit confused about the match/search methods of the string >> module for regular expressions. I have looked the regular expression >> doc >> and I can't that one simple answer. >> >> So please excuse the basiqueness of my question, as I am used with the >> .match method of JScript and it kind of matches anything.... >> >> Let say I have this string: >> >>>>> import re >>>>> mystring = 'helloworldmynameisbernardlebel' >> >> Now I wish to attempt a match with 'bernard'. >> >>>>> if not re.compile( 'bernard' ).match( mystring ) == None: >> ... print 'success' > > First, you are printinting redundant code here. You are using double > negatives. > You first check to see if re.compile('bernard').match(mystring) > registers > false, if it is false the expression registers true. Then you check to > see > if that expression registers false. So really > the equivalent expression is > > if re.compile('bernard').match(mystring): > print 'success' > > However, I don't think that solves your problem. >> Well, nothing gets printed. Could anyone tell me how to achieve that >> simple type of matching? > > Re expressions are a little different from JScript. The match method > only > matches equivalent strings. (Or it only does in this case.) Instead, > you > want > to use the search method. Oh, and by the way, if you're going to > compile the > expression without assigning it to a variable, you might use the re > methods > instead > of the re pattern methods. IOW, use this code instead... > > import re > mystring = 'helloworldmynameisbernardlebel' > if re.search('bernard',mystring): > print 'success' > > The documentation for the re methods are hidden, IMHO. You can find > them > by typing in 'search() (in module re)' in the index and that should > take you > right to it. > That page contains explanations for all of the re methods. > > Good luck, > Jacob Schmidt > > > > ------------------------------ > > Message: 4 > Date: Fri, 26 Nov 2004 17:22:14 -0700 > From: "Gooch, John" > Subject: RE: [Tutor] String matching > To: "'tutor@python.org'" > Message-ID: > <15A1FDA26DAD524DA7A7AF77313EBA8F07BC0166@riv-excha5.echostar.com> > Content-Type: text/plain > > I am trying to extract data found in an MS Excel workbook using regular > expressions. For some reason, it plain refuses to recognize the "-" > unicode > character. Here is what happens when I execute: > print "Resolving name for "+tname+" type=",type(tname) > rePName = re.compile( u"(-)", re.UNICODE ) > m = rePName.match( tname ) > print "Resolved to groups"+unicode(m.groups()) > > > > > Resolving name for 1.0 Windows - AB - 11/23/04 type= > Resolved to groups(u'1.0 Windows \u2013 HD - 11/23/04',) > > Notice I told it to match on the "-" character, which shows up in the > print > command. But when I tell it to match on the character, it doesn't > match. U > have tried the escape code "\u2013", but that does not match at all. > > Any ideas? > > John A. Gooch > Systems Administrator > IT - Tools > EchoStar Satellite L.L.C. > 9601 S. Meridian Blvd. > Englewood, CO 80112 > Desk: 720-514-5708 > > > -----Original Message----- > From: Jacob S. [mailto:keridee@jayco.net] > Sent: Friday, November 26, 2004 10:57 AM > To: Bernard Lebel > Cc: tutor@python.org > Subject: Re: [Tutor] String matching > > > Hi Bernard! > >> Hello, >> >> I'm a little bit confused about the match/search methods of the string >> module for regular expressions. I have looked the regular expression >> doc and I can't that one simple answer. >> >> So please excuse the basiqueness of my question, as I am used with the >> .match method of JScript and it kind of matches anything.... >> >> Let say I have this string: >> >>>>> import re >>>>> mystring = 'helloworldmynameisbernardlebel' >> >> Now I wish to attempt a match with 'bernard'. >> >>>>> if not re.compile( 'bernard' ).match( mystring ) == None: ... >> print 'success' > > First, you are printinting redundant code here. You are using double > negatives. You first check to see if > re.compile('bernard').match(mystring) > registers false, if it is false the expression registers true. Then you > check to see if that expression registers false. So really the > equivalent > expression is > > if re.compile('bernard').match(mystring): > print 'success' > > However, I don't think that solves your problem. >> Well, nothing gets printed. Could anyone tell me how to achieve that >> simple type of matching? > > Re expressions are a little different from JScript. The match method > only > matches equivalent strings. (Or it only does in this case.) Instead, > you > want to use the search method. Oh, and by the way, if you're going to > compile the expression without assigning it to a variable, you might > use the > re methods instead of the re pattern methods. IOW, use this code > instead... > > import re > mystring = 'helloworldmynameisbernardlebel' > if re.search('bernard',mystring): > print 'success' > > The documentation for the re methods are hidden, IMHO. You can find > them by > typing in 'search() (in module re)' in the index and that should take > you > right to it. That page contains explanations for all of the re methods. > > Good luck, > Jacob Schmidt > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > Message: 5 > Date: Sat, 27 Nov 2004 00:58:37 -0000 > From: "Alan Gauld" > Subject: Re: [Tutor] Change to Python 2.4? > To: "Jacob S." , > Message-ID: <009901c4d41c$3b531550$1abd8651@xp> > Content-Type: text/plain; charset="iso-8859-1" > >> How hard would it be to change to python 2.4? > > Probably not very hard but, why would you want to? > Do you have a need? > > At work I am still using Python 2.1, and at home I > still use 2.2 on my Mac. I only moved to 2.3 on my > PC so that I could update my tutor, I am not knowingly > using any 2.3 specific features. > > So unless you need something specific in 2.4 there > should be no reason to ruish to it, wait till a > safe point in your project - like after you get a > stable working release - and then upgrade at your > leasure... > >> new things in python 2.4? > > THere is usually a list available on the web site. > >> I have seen enough on this list to know that it >> would be advantageous for me to download it. > > If you have a specifc advantage that makes the > advantage worth the risk then go ahead. Python > release changes are usually pretty easy and > backwardly compatible. > >> scripts written for 2.3 work for 2.4? > > Occasionally something might break but in most > cases(99%?) I'd expect the 2.3 stuff to just work. > > Alan G. > > > ------------------------------ > > Message: 6 > Date: Sat, 27 Nov 2004 01:17:53 -0000 > From: "Alan Gauld" > Subject: Re: [Tutor] Help with very basic question > To: , "Harov Satmandirvich" > > Cc: tutor@python.org > Message-ID: <00a201c4d41e$ec4a3490$1abd8651@xp> > Content-Type: text/plain; charset="iso-8859-1" > > >> Harov Satmandirvich wrote: >>> Hello. Before I continue with a tutorial I would like >>> to know something very basic: Is there any other way >>> to advance a line in Python than hitting >>> "tabtabtabtab"..etc? When I hit"enter?" it enters >>> the line as if it was a complete bit of program. > > You can use a line continuatoion character (\) if you just want > to break a line while in the interpreter. > > But if you want to type multi line programs without the > interpreter executing it as you go follow Annas advice > and use a text file to store the code. > > HTH > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > ------------------------------ > > Message: 7 > Date: Fri, 26 Nov 2004 21:41:06 -0500 > From: Bill Burns > Subject: Re: [Tutor] Database questions > To: tutor@python.org > Message-ID: <200411262141.06192.billburns@pennswoods.net> > Content-Type: text/plain; charset="iso-8859-1" > > On Tuesday 23 November 2004 7:56 pm, Jay Mutter wrote: >> Good evening; >> I am using OS X 10.3.6 on an ibook where I have python 2.3.3 and >> wxPython 2.5.3.1 installed with mxDateTime, Postgresql and psycopg. >> >> What i would like to know ( remember I have not really started using >> python or any of the others) is what would you suggest as a GUI >> designer to work with the above for someone who wants to develop a GUI >> client interface for a RDBMS system. I have looked at wxGlade, >> Pythoncard, wxDesigner, and Boa constructor and am currently clueless. >> If I wanted to hone my skills by creating a GUI checkbook >> register/balancing program would I be best off to simply use the DB >> modules built into Python. >> Remember I am definitely a newbie. >> > > Warning, the following doesn't meet all of your criteria, but if that > doesn't > bother you, keep reading :-) > > Have you looked at Qt Designer + PyQt? This solution is not "wx" based > (which I think is the only criteria it doesn't meet) but it should > provide > everything else you want, i.e., OS X, works with databases and easy to > use. > > I don't use OS X but I do use these programs (on Linux) and they are > very > newbie friendly. I'm also a fellow n00b :-) and believe me, with Qt, > it's very > simple and fast to make a nice GUI. > > Using Qt Designer, you can visually design a GUI without "hand coding" > a > thing. You literally just drop widgets, which are all accessible on > the > left-hand side of Designer, right on to your forms. After you've > created the > UI, you use a tool called pyuic (python user interface compiler) to > compile it > to python code. You can either make this code directly executable or > import > it into your own module. > > If you have access to a Linux box (with a modern distro) try typing > "designer" > (without the quotes) at a command prompt. Maybe you can at least look > at the > GUI builder and get a feel for it. > > You'll have to look at the licensing or distribution restrictions if > you want > to distribute this app on Windows. I really don't know all of the > restrictions > but I think if you're developing for just OS X or Linux you should > have no > concerns. There are definitely issues when it comes to using Qt and > PyQt > on the Windows platform. Look in to this, it's probably the single > biggest > reason why Designer & PyQt are not suggested more often. Even so, > these are outstanding tools. The Qt docs are full of information and > even- > though they apply to C++, it's not hard to understand them and > translate > the info into Python. > > Here's some links you might want to check out: > > Info & download link for the gpl'ed version of QT for Mac: > http://www.trolltech.com/download/qt/mac.html > > Subscribe to and/or search the PyKDE mailing list (this list is for > both PyKDE > & PyQt): > http://mats.imk.fraunhofer.de/mailman/listinfo/pykde > > Main web site for PyQt: > http://www.riverbankcomputing.co.uk/pyqt/index.php > > An excellent site for info about PyQt programming: > http://www.opendocspublishing.com/pyqt/index.lxp > > eric3 - A Python IDE > http://www.die-offenbachs.de/detlev/eric3.html > > Black Adder - a commercial IDE: > http://www.thekompany.com/ > > HTH > > Bill > > > > > > > > > > ------------------------------ > > Message: 8 > Date: Sat, 27 Nov 2004 16:53:47 +1300 > From: Liam Clarke > Subject: Re: [Tutor] time comparison question > To: Brian van den Broek > Cc: Python Tutor > Message-ID: > Content-Type: text/plain; charset=US-ASCII > > Eep, you're right Brian, mea culpa. > > > On Fri, 26 Nov 2004 14:16:40 -0500, Brian van den Broek > wrote: >> Anna Ravenscroft said unto the world upon 2004-11-26 08:19: >>> Brian van den Broek wrote: >>> >>>> Hi all, >>>> >>>> I'm trying to build some Python 2.3.4 code which will determine if >>>> the >>>> actual time when it is run is after the date and time specified in >>>> some data. I want my data to be able to specify the target date/time >>>> in a various levels of detail. I.e., I want 2004-11-28 13:25, >>>> 2004-11-28, 11-28, 11-28 13:25 to all be accepted. >> >> Hi all, >> >> thanks to Anna, G. Rodrigues, and Liam for the replies. The code that >> was posted using datetime didn't seem so scary after all :-) >> >> As evidence accrues, I think I am going to just have to gather myself >> together and surmount the aversion to classes and other aspects of >> OOP. >> At least in this case, code has shown it isn't too tricky. >> >> One minor quibble with something Liam posted. Of struct_time objects >> he >> said: >> >>> The 9 value tuple has year to microsecond, and day of the week >>> contained, so you can use it if you wish. >> >> For future googlers, my understanding is that the first 6 elements of >> a >> struct_time tuple are the date and time from year down to the second >> (microseconds playing no role), and the last three are weekday, day of >> year, and DST flag. >> >> Anyway, having read the replies, it looks like my problem is solved. >> Thanks folks! >> >> >> >> Best to all, >> >> Brian vdB >> >> _______________________________________________ >> 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. > > > ------------------------------ > > Message: 9 > Date: Fri, 26 Nov 2004 23:14:44 -0500 > From: Bill Burns > Subject: Re: [Tutor] Database questions > To: tutor@python.org > Message-ID: <200411262314.44800.billburns@pennswoods.net> > Content-Type: text/plain; charset="iso-8859-1" > > As a follow-up to my previous post: > > I just found this on the PyKDE mailing list. A web site that provides > a binary > installer for Qt / PyQt for OS X. Maybe this will make it easier for > you to > try out? > > Here's the link: > http://www.wordtech-software.com/python.html > > Bill > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 9, Issue 82 > ************************************ > From alan.gauld at freenet.co.uk Sun Nov 28 01:31:05 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Nov 28 01:31:00 2004 Subject: [Tutor] Error in loop. Please help. References: <20041127171933.85461.qmail@web53707.mail.yahoo.com> Message-ID: <010801c4d4e1$8cb3a4d0$1abd8651@xp> Its late so I haven't looked too closely but I did spot a couple of things... > f2r = f2.read() > f2lines = f2r.split('\n') Why not just use readlines() instead? > f2lines = f2lines[1:-1] > # -- (The above line filters the first element which > is sample_name) I think it will also filter the last line which you may not want! Try using [1:] instead... > ['a','b','c','d','e'] > out = open('test.sql','w') > for m in range(len(samples)): why not just use for m in samples; > out.write("INSERT INTO sample(sample_name)VALUES(" > "'"+samples[m]+"'" ");" "\n") + m + ... > for d in range(len(f3lines)): and similarly for d in f3lines: > a = samples.index(samples[m]) And won't this always return m?! Hmm maybe not if there are more than one instance of whatever is at m, but I'm not sure that finding the first instance is what you think you are doing... I don;t know if any of the above help solve the problem but they may make the code easier to read which is a start... Alan G From thisreallybeatsme at yahoo.com Sun Nov 28 14:10:56 2004 From: thisreallybeatsme at yahoo.com (Just Incase) Date: Sun Nov 28 14:10:59 2004 Subject: [Tutor] To post to list Message-ID: <20041128131056.97981.qmail@web54401.mail.yahoo.com> To post to this list, send your email to: tutor@python.org My e-mail is: thisreallybeatsme@yahoo.com Thank you. --------------------------------- Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041128/a0f4f2dc/attachment.html From klas.martelleur at telia.com Sun Nov 28 17:46:56 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Sun Nov 28 17:46:58 2004 Subject: [Tutor] os.popen Message-ID: <200411281746.56113.klas.martelleur@telia.com> Hi I have a little problem that is confusing me. If i write the following in a bash shell i get the desired output: [klas@h180n2fls32o849 klas]$ kwrite -v Qt: 3.2.3 KDE: 3.2 BRANCH >= 20040204 KWrite: 4.2 It also works in a python shell... >>> os.popen("kwrite -v").readlines() ['Qt: 3.2.3\n', 'KDE: 3.2 BRANCH >= 20040204\n', 'KWrite: 4.2\n'] If i try the following in a bash shell, it also workes: [klas@h180n2fls32o849 klas]$ tccat -v tccat (transcode v0.6.12) (C) 2001-2003 Thomas Oestreich But if i try the same in a python shell i get: >>> os.popen("tccat -v").readlines() [] Not even if i specify the path it works. >>> os.popen("/usr/bin/tccat -v").readlines() [] What am i missing? Kind Regards Klas From hugonz-lists at h-lab.net Sun Nov 28 19:26:05 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun Nov 28 19:26:52 2004 Subject: [Tutor] os.popen In-Reply-To: <200411281746.56113.klas.martelleur@telia.com> References: <200411281746.56113.klas.martelleur@telia.com> Message-ID: <41AA183D.4000805@h-lab.net> Hi Klas, Maybe the output you're trying to get is in STDERR and not STDOUT?? I've had to deal with this a number of times, so may I wrote a Tkinter script to let me know what output is to STDERR and what is to STDOUT. os.popen will open STDOUT if invoked with "r" (which is the default). Try looking of other popen* functions. They provide STDOUT + STDERR (popen4) or separate STDOUT + STDERR (popen3) BTW< if you'd like to have my script (the Streamshower, I call it =) ) just email me ... Hugo Klas Marteleur wrote: > Hi > I have a little problem that is confusing me. > > If i write the following in a bash shell i get the desired output: > [klas@h180n2fls32o849 klas]$ kwrite -v > Qt: 3.2.3 > KDE: 3.2 BRANCH >= 20040204 > KWrite: 4.2 > > It also works in a python shell... > >>>>os.popen("kwrite -v").readlines() > > ['Qt: 3.2.3\n', 'KDE: 3.2 BRANCH >= 20040204\n', 'KWrite: 4.2\n'] > > If i try the following in a bash shell, it also workes: > [klas@h180n2fls32o849 klas]$ tccat -v > tccat (transcode v0.6.12) (C) 2001-2003 Thomas Oestreich > > But if i try the same in a python shell i get: > >>>>os.popen("tccat -v").readlines() > > [] > > Not even if i specify the path it works. > >>>>os.popen("/usr/bin/tccat -v").readlines() > > [] > > > What am i missing? > > Kind Regards > Klas > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Sun Nov 28 23:19:32 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Nov 28 23:19:58 2004 Subject: [Tutor] Pythonw.exe doesn't work in the python2.4 distribution? Message-ID: <000701c4d598$5bb6d2f0$215328cf@JSLAPTOP> Hi everybody. I just installed Python2.4 by my Python2.3 folder in the C directory. I'm running WindowsXP. I tried to run any scripts of mine afterwards, but they didn't work. After messing with file associations, I finally can execute the scripts using python24. However, the "Edit with IDLE" command in the shorcut menu (right-click pull down menu) no longer worked. So I went to the registry (I know the risks involved) and checked out the commands and the like. I found a key named Python.File which had subsequent keys Shell,Edit with IDLE, and command. In the command key, there was a string value that told the shortcut menu to run the command "C:\python24\pythonw.exe" "C:\python24\lib\idlelib\idle.pyw -n -e %1" when Edit with IDLE was selected from the shortcut menu. I played with the above string doing things like "C:\python24\pythonw.exe" "C:\python24\lib\idlelib\idle.py -n-e %1", and I even tried using the idle.bat file in the directory. The only time it worked was when I change pythonw.exe to python.exe. Now this is fine and dandy, but I want IDLE to run without a console. So currently, the above string reads, "C:\python23\pythonw.exe" "C:\python24\lib\idlelib\idle.pyw -n -e %1" A few things... 1) Can anyone explain why pythonw.exe doesn't do what it is supposed to do in python24? 2) Can anyone directo me to a new pythonw.exe that works? Is all of the python included in the pythonXX.dll? IOW, could I copy the pythonw.exe file from the python23 distribution and still have all the functionality of python24? 3) Can anyone off-hand tell me what the arguments -n and -e mean in the above string? Does anybody know of a list of these? (Not urgent, if no one knows, I won't bother extensively searching for one.) Thanks in advance for anyone who can help with the above three things. Jacob Schmidt From klas.martelleur at telia.com Mon Nov 29 08:12:01 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Mon Nov 29 08:12:04 2004 Subject: [Tutor] os.popen In-Reply-To: <41AA183D.4000805@h-lab.net> References: <200411281746.56113.klas.martelleur@telia.com> <41AA183D.4000805@h-lab.net> Message-ID: <200411290812.01510.klas.martelleur@telia.com> Ok i used popen3 instead, reading the "child-stderr" instead and it worked. >>> tcextract = os.popen3("tcextract -v") >>> tcextract[2].readlines() ['tcextract (transcode v0.6.12) (C) 2001-2003 Thomas Oestreich\n'] Thanks Hugo Regards Klas s?ndagen den 28 november 2004 19.26 skrev du: > Hi Klas, > > Maybe the output you're trying to get is in STDERR and not STDOUT?? I've > had to deal with this a number of times, so may I wrote a Tkinter script > to let me know what output is to STDERR and what is to STDOUT. os.popen > will open STDOUT if invoked with "r" (which is the default). > > Try looking of other popen* functions. They provide STDOUT + STDERR > (popen4) or separate STDOUT + STDERR (popen3) > > BTW< if you'd like to have my script (the Streamshower, I call it =) ) > just email me ... > > Hugo > > Klas Marteleur wrote: > > Hi > > I have a little problem that is confusing me. > > > > If i write the following in a bash shell i get the desired output: > > [klas@h180n2fls32o849 klas]$ kwrite -v > > Qt: 3.2.3 > > KDE: 3.2 BRANCH >= 20040204 > > KWrite: 4.2 > > > > It also works in a python shell... > > > >>>>os.popen("kwrite -v").readlines() > > > > ['Qt: 3.2.3\n', 'KDE: 3.2 BRANCH >= 20040204\n', 'KWrite: 4.2\n'] > > > > If i try the following in a bash shell, it also workes: > > [klas@h180n2fls32o849 klas]$ tccat -v > > tccat (transcode v0.6.12) (C) 2001-2003 Thomas Oestreich > > > > But if i try the same in a python shell i get: > >>>>os.popen("tccat -v").readlines() > > > > [] > > > > Not even if i specify the path it works. > > > >>>>os.popen("/usr/bin/tccat -v").readlines() > > > > [] > > > > > > What am i missing? > > > > Kind Regards > > Klas > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Mon Nov 29 12:35:23 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Nov 29 12:35:27 2004 Subject: [Tutor] Pythonw.exe doesn't work in the python2.4 distribution? References: <000701c4d598$5bb6d2f0$215328cf@JSLAPTOP> Message-ID: <001501c4d607$85857e50$f1598651@xp> > execute the scripts using python24. However, the "Edit with IDLE" command in > the shorcut menu (right-click pull down menu) no longer worked. So I went to > the registry (I know the risks involved) BUt entirely unnecesary here! The way to check/fix the context(right-click) menu options is via Explorer. Its much easier and much safer. Go to Tools->Folder Optoions->File Types Select the file type you areinterested inn- .PYW in this case Hit the Change button, from the dialog you can select the associated executable. Using the Advanced button you can edit the existing entries, changing startup flags etc. You can also add new contrext actions there too - such as Edit with SCite or whatever. > "C:\python23\pythonw.exe" "C:\python24\lib\idlelib\idle.pyw -n -e %1" > > A few things... > > 1) Can anyone explain why pythonw.exe doesn't do what it is supposed to do > in python24? That I can't help with not having loaded 2.4 yet. > 3) Can anyone off-hand tell me what the arguments -n and -e mean in the > above string? Does anybody know of a list of these? (Not urgent, if no one > knows, I won't bother extensively searching for one.) According to the usage message in PyShell.py -n => start with no subprocess -e file => edit HTH Alan G. From ARobert at MFS.com Mon Nov 29 16:47:32 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Mon Nov 29 16:47:48 2004 Subject: [Tutor] How best to connect to Oracle databases under Linux Message-ID: <968452DD78695147AA4A369C3DF9E40A01F9394F@BOSMAILBOX3.corp.mfs.com> Hi Everyone, In an effort to learn Python better as well as tie it in to my everyday work, I would like to find a suitable Python module for Oracle v9 databases that works under both Linux and AIX. The cx_Oracle module has a Windows installer that works well but the RPM's available are only for RH9. I tried building a new rpm for Fedora Core 3 but ran into problems with the SPEC file and the setup.py included in the source. The SPEC file is hard-coded to reference Python v2.2 and the setup.py file does not have code in place to handle a sys.platform value of linux2. Does anyone know of a good alternate I might be able to use? Thank you, Andrew Robert Systems Architect Information Technology Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 "MFS Relay Service" made the following annotations on 11/29/2004 10:53:09 AM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From BranimirP at cpas.com Mon Nov 29 17:09:32 2004 From: BranimirP at cpas.com (Branimir Petrovic) Date: Mon Nov 29 17:09:28 2004 Subject: [Tutor] How best to connect to Oracle databases under Linux Message-ID: <33678E78A2DD4D418396703A750048D4010250ED@RIKER> > > I tried building a new rpm for Fedora Core 3 but ran into > problems with > the SPEC file and the setup.py included in the source. > > The SPEC file is hard-coded to reference Python v2.2 and the setup.py > file does not have code in place to handle a sys.platform value of > linux2. > > Does anyone know of a good alternate I might be able to use? Before writing off cx_Oracle, may be subscribe to cx_Oracle list and post your problem? http://lists.sourceforge.net/lists/listinfo/cx-oracle-users Branimir From klas.martelleur at telia.com Mon Nov 29 17:30:13 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Mon Nov 29 17:30:16 2004 Subject: [Tutor] os.popen In-Reply-To: <200411290812.01510.klas.martelleur@telia.com> References: <200411281746.56113.klas.martelleur@telia.com> <41AA183D.4000805@h-lab.net> <200411290812.01510.klas.martelleur@telia.com> Message-ID: <200411291730.13672.klas.martelleur@telia.com> hmm.. Is it nesessary to close the "file objects"? a = os.popen3("tcextract -v") tcexVerOut= a[2].readlines() a[0].close() #Nesessary? a[1].close() #Nesessary? a[2].close() #Nesessary? Regards Klas > Ok i used popen3 instead, reading the "child-stderr" instead and it worked. > > >>> tcextract = os.popen3("tcextract -v") > >>> tcextract[2].readlines() > > ['tcextract (transcode v0.6.12) (C) 2001-2003 Thomas Oestreich\n'] > > Thanks Hugo > > Regards Klas > > s?ndagen den 28 november 2004 19.26 skrev du: > > Hi Klas, > > > > Maybe the output you're trying to get is in STDERR and not STDOUT?? I've > > had to deal with this a number of times, so may I wrote a Tkinter script > > to let me know what output is to STDERR and what is to STDOUT. os.popen > > will open STDOUT if invoked with "r" (which is the default). > > > > Try looking of other popen* functions. They provide STDOUT + STDERR > > (popen4) or separate STDOUT + STDERR (popen3) > > > > BTW< if you'd like to have my script (the Streamshower, I call it =) ) > > just email me ... > > > > Hugo > > > > Klas Marteleur wrote: > > > Hi > > > I have a little problem that is confusing me. > > > > > > If i write the following in a bash shell i get the desired output: > > > [klas@h180n2fls32o849 klas]$ kwrite -v > > > Qt: 3.2.3 > > > KDE: 3.2 BRANCH >= 20040204 > > > KWrite: 4.2 > > > > > > It also works in a python shell... > > > > > >>>>os.popen("kwrite -v").readlines() > > > > > > ['Qt: 3.2.3\n', 'KDE: 3.2 BRANCH >= 20040204\n', 'KWrite: 4.2\n'] > > > > > > If i try the following in a bash shell, it also workes: > > > [klas@h180n2fls32o849 klas]$ tccat -v > > > tccat (transcode v0.6.12) (C) 2001-2003 Thomas Oestreich > > > > > > But if i try the same in a python shell i get: > > >>>>os.popen("tccat -v").readlines() > > > > > > [] > > > > > > Not even if i specify the path it works. > > > > > >>>>os.popen("/usr/bin/tccat -v").readlines() > > > > > > [] > > > > > > > > > What am i missing? > > > > > > Kind Regards > > > Klas > > > _______________________________________________ > > > 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 simon.brunning at gmail.com Tue Nov 2 10:21:35 2004 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon Nov 29 18:13:28 2004 Subject: [Tutor] Problem modify windows registry (desktop wallpaper) In-Reply-To: <5.0.2.1.2.20041101170023.022b8da8@qmail.dideas.com> References: <5.0.2.1.2.20041101170023.022b8da8@qmail.dideas.com> Message-ID: <8c7f10c604110201212e76738a@mail.gmail.com> On Mon, 01 Nov 2004 18:05:09 -0500, Chris Barnhart wrote: > Hi, > > I'm attempting to write a python (2.3.3) program that will update the > wallpaper under Windows 2000. I found an example delphi program : > (http://www.latiumsoftware.com/en/delphi/00020.php) which suggest that I > need to change a registry variable, and then execute a system parameters > changed statement. > > The following program attempts to change the desktop wallpaper by changing > a key in the HKEY_CURRENT_USER. This fails due to access denied? I'm > using methods from _winreg. > > What weird, is that by using OpenKey I've been able to create new registry > sub folders, and then using SetValue, change the value of the "default" key. > > I've also looked modifying the registry from WMI, and also looked at using > windll - but obsolete. > > Any ideas? I use ctypes[1] for this: def setWallpaper(wallpaperPath): wallpaperPath = ctypes.c_buffer(wallpaperPath) ctypes.windll.user32.SystemParametersInfoA(win32con.SPI_SETDESKWALLPAPER, 0, wallpaperPath, 0) -- Cheers, Simon B, simon.brunning@gmail.com, http://www.brunningonline.net/simon/blog/ [1] http://starship.python.net/crew/theller/ctypes/ From dustinp at pointclark.net Thu Nov 4 18:01:32 2004 From: dustinp at pointclark.net (dustinp@pointclark.net) Date: Mon Nov 29 18:13:34 2004 Subject: [Tutor] programming newbie question Message-ID: <16044.156.153.255.243.1099587688.squirrel@phome.pointclark.net> I am fairly new to programming and I have started to learn programming then stopped out of frustration several times in the past. I guess my frustration stems from not being able to understand when to use certain aspects of programming such as functions or classes. I have read enough books and tutorials to know the syntax of python and I understand most everything related to the concepts of programming, but I have never been able to put it all together and learn how and when to use specific features. Can anyone suggest a method or some reading to help out with this? I also struggle with finding projects to work on does anyone know of projects that a novice could contribute to? From timmoffatt at cogeco.ca Sun Nov 7 13:33:19 2004 From: timmoffatt at cogeco.ca (Tim Moffatt) Date: Mon Nov 29 18:13:39 2004 Subject: [Tutor] new function and a 3 line program not working Message-ID: <000a01c4c4c5$f55d9990$6500a8c0@cdca1h1bro1> This is my first post, so HI all! and thank you for you help! Below is a tutorial that I am trying to complete, but I can not duplicate this exercise in either the IDLE gui or command line. (ver 2.3.4) Tutorial says do this go to IDLE gui and define the new function def newLine(): print then i open another IDLE window and write the 3 line program like in the tutorial print "First Line." newLine() print "Second Line." save it as line.py Now I am to see this output result upon running it First line. Second line. But I dont get this, I get a First line." printed and a syntax error >>> First Line. Traceback (most recent call last): File "C:/Python23/newLine.py", line 2, in -toplevel- newLine() NameError: name 'newLine' is not defined >>> complete lesson below 3.6 Adding new functions So far, we have only been using the functions that come with Python, but it is also possible to add new functions. Creating new functions to solve your particular problems is one of the most useful things about a general-purpose programming language. In the context of programming, a function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition. The functions we have been using so far have been defined for us, and these definitions have been hidden. This is a good thing, because it allows us to use the functions without worrying about the details of their definitions. The syntax for a function definition is: def NAME( LIST OF PARAMETERS ): STATEMENTS You can make up any names you want for the functions you create, except that you can't use a name that is a Python keyword. The list of parameters specifies what information, if any, you have to provide in order to use the new function. There can be any number of statements inside the function, but they have to be indented from the left margin. In the examples in this book, we will use an indentation of two spaces. The first couple of functions we are going to write have no parameters, so the syntax looks like this: def newLine(): print This function is named newLine. The empty parentheses indicate that it has no parameters. It contains only a single statement, which outputs a newline character. (That's what happens when you use a printcommand without any arguments.) The syntax for calling the new function is the same as the syntax for built-in functions: print "First Line." newLine() print "Second Line." The output of this program is: First line. Second line. Notice the extra space between the two lines. What if we wanted more space between the lines? We could call the same function repeatedly: print "First Line." newLine() newLine() newLine() print "Second Line." Or we could write a new function named threeLines that prints three new lines: def threeLines(): newLine() newLine() newLine() print "First Line." threeLines() print "Second Line." This function contains three statements, all of which are indented by two spaces. Since the next statement is not indented, Python knows that it is not part of the function. You should notice a few things about this program: 1. You can call the same procedure repeatedly. In fact, it is quite common and useful to do so. 2. You can have one function call another function; in this case threeLines calls newLine. So far, it may not be clear why it is worth the trouble to create all of these new functions. Actually, there are a lot of reasons, but this example demonstrates two: * Creating a new function gives you an opportunity to name a group of statements. Functions can simplify a program by hiding a complex computation behind a single command and by using English words in place of arcane code. * Creating a new function can make a program smaller by eliminating repetitive code. For example, a short way to print nine consecutive new lines is to call threeLines three times. As an exercise, write a function called nineLines that uses threeLines to print nine blank lines. How would you print twenty-seven new lines? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041107/33d16176/attachment.html From kent_johnson at skillsoft.com Tue Nov 9 18:52:51 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Nov 29 18:13:43 2004 Subject: [Tutor] CGI problem. In-Reply-To: References: <20041106174835.95395.qmail@web54307.mail.yahoo.com> <6.1.0.6.0.20041107121235.02ae9300@mail4.skillsoft.com> <6.1.0.6.0.20041107151641.02af98b0@mail4.skillsoft.com> <6.1.0.6.0.20041108103300.02ab44a0@mail4.skillsoft.com> <6.1.0.6.0.20041108184758.0296cc38@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20041109120501.02aecbc0@mail4.skillsoft.com> At 07:06 PM 11/9/2004 +0200, Mark Kels wrote: >On Mon, 08 Nov 2004 18:49:28 -0500, Kent Johnson > wrote: > > At 09:40 PM 11/8/2004 +0200, Mark Kels wrote: > > >I'm sorry about the last post, I was cmparing 124 and 123. > > >here is what I get when I do it right (124 and 124): > > >\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E (filepass) > > >'\xc8\xff\xe9\xa5\x87\xb1&\xf1R\xed=\x89\xa1F\xb4E' (repr(userpass)) > > >Now its easy to just take off the ' chars from the string, and I hope > > >it will work... > > > > I just noticed the md5 function hexdigest(). If you use this instead of > > digest() you will get a nice clean hex string right at the start and > > dispense with all this \x and repr() stuff. > > > > > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > >It works!! >Here is the complete (and working) code: > >import cgi >import cgitb; cgitb.enable() >import md5 >import re >form = cgi.FieldStorage() >x=open("pass.txt","r") >form.getfirst("pass") >print "Content-type: text/html\n\n" >def printhtml(): > print """ > >
> """ >def checkpass(): > filepass=x.readline() # The password in the file is already digested. > userpass=md5.new(form.getfirst("pass")).digest() > userpass=repr(userpass) > userpass=re.sub("'","",userpass) > if userpass==filepass: > print "OK, come in." > else: > print "Wrong password, try again!" > > > >printhtml() >if form.has_key("pass"): > checkpass() >x.close() > >Thanks to all who helped me!! From timmoffatt at cogeco.ca Thu Nov 11 06:51:31 2004 From: timmoffatt at cogeco.ca (Tim Moffatt) Date: Mon Nov 29 18:13:47 2004 Subject: [Tutor] Re: New function and 3 line program not working? Message-ID: <005501c4c7b2$7dbe0dd0$6500a8c0@cdca1h1bro1> Thank you all for your help! Looking at 2 responses I recieved and combineing the info, I think I have solved the problem. When I first start up the IDLE gui, it is titled "Python Shell" and I was attempting to enter everything here and I kept getting >>> after each line I typed, and it would not work. IDLE 1.0.3 >>> def newLine(): print >>> print "First Line" First Line >>> newLine() >>> print "Second Line" Second Line But, I learned that if I open a new window from the "Python Shell" and then enter everything, then save, it would work just fine. Thank you again for your help Tim Moffatt -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041111/a438d9a7/attachment.htm From jjd278 at psu.edu Tue Nov 16 05:39:16 2004 From: jjd278 at psu.edu (Jim De Caro) Date: Mon Nov 29 18:13:51 2004 Subject: [Tutor] comapring lists Message-ID: <200411160439.XAA03967@webmail10.cac.psu.edu> I am getting user input and comparing it to an iterated list. I can get the input to print out verbatim. I want to then "swap" individual letters in the input with letters from a second list so it is like a simple encryption. I can't figure out the correct logic or syntax. Here is what I have so far: user = raw_input("Enter your selection: ") encrypt = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','0'] decrypt =['b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','A','0','1','2','3','4','5','6','7','8','9','0'] for i in range(len(encrypt)): print user[0:62] break for j in range(len(decrypt)): for j in zip(decrypt): print 'Encrypted-> %s' % (j,user) break This does not work. Any suggestions? Thanks Jim DeCaro Microsoft Certified Systems Engineer Windows 2000 - Windows NT 4.0 + Internet From fabian at berlepsch.de Mon Nov 22 02:44:54 2004 From: fabian at berlepsch.de (Fabian von Berlepsch) Date: Mon Nov 29 18:13:54 2004 Subject: [Tutor] trying to find the python equivalent for VB6 "left", "right" and "mid" In-Reply-To: <7d7029e70411211739129156af@mail.gmail.com> Message-ID: <200411220145.iAM1jFbX014680@smtp-prs03.proxy.aol.com> Thank you so much - you can not imagine how much you helped me with your response! Thank you again, Fabian -----Message d'origine----- De?: Guillermo Fernandez Castellanos [mailto:guillermo.fernandez.castellanos@gmail.com] Envoy??: lundi 22 novembre 2004 02:40 ??: Fabian von Berlepsch Cc?: tutor@python.org Objet?: Re: [Tutor] trying to find the python equivalent for VB6 "left", "right" and "mid" hi, I can think of this: >>> mystring = "Hello world" >>> print mystring[:7] Hello w >>> print mystring[7:] orld >>> print mystring[1:9] ello wor Regards, Guille On Mon, 22 Nov 2004 02:28:38 +0100, Fabian von Berlepsch wrote: > Hallo Guys, > > I am almost having a nerve crisis! > Since 3 hours I am trying to find the python equivalent for VB6 "left", > "right" and "mid". > > Example (what I am looking for): > > >>> mystring = "Hello world" > > >>> print left(mystring,7) > > Hello w > > - or - > > >>> mystring = "Hello world" > > >>> print mid(mystring,2,8) > > ello wor > > -------------------------- > > You see? > Thank you so much for getting me out of that mess! > > Fabian > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cm012b5105 at blueyonder.co.uk Fri Nov 26 22:18:27 2004 From: cm012b5105 at blueyonder.co.uk (cm012b5105) Date: Mon Nov 29 18:13:57 2004 Subject: [Tutor] Introduction/ box Message-ID: <200411262118.27140.cm012b5105@blueyonder.co.uk> Hello every body im new to python iv allways wanted to have go iv noticed there is loads of tutorials on the net for it any way i have a question which i hope some one will help me find the answer i want to know how to draw a box iv just installed pygame as i would like to have a go at making my own game i thought if i could get the source for something simple like drawing a box that would give me something to start with i hope this makes sense if not please tell me ill try to explain better thankyou nige From cm012b5105 at blueyonder.co.uk Sun Nov 28 11:24:58 2004 From: cm012b5105 at blueyonder.co.uk (cm012b5105) Date: Mon Nov 29 18:13:59 2004 Subject: [Tutor] graphics/box Message-ID: <200411281024.59032.cm012b5105@blueyonder.co.uk> Hello im not sure if your getting my email as i never see them on the list but here goes iv recently installed python and now iv been going through the tutorials fine they are great any way i want to do some graphics so i installed pygme i was hoping someone would be able to tell me how to do a simple box to give me something to work off i dont need colors just the outline of a box this would help me to get started thanks nige From farcepest at gmail.com Wed Nov 3 22:46:27 2004 From: farcepest at gmail.com (Andy Dustman) Date: Mon Nov 29 18:14:14 2004 Subject: [DB-SIG] Re: [Tutor] mysql formatting In-Reply-To: <1099514511.19711.45.camel@laptop.venix.com> References: <1099514511.19711.45.camel@laptop.venix.com> Message-ID: <9826f3800411031346314acbbf@mail.gmail.com> On Wed, 03 Nov 2004 15:41:52 -0500, Lloyd Kvam wrote: > I checked our programming. We add the % for like to the parameter! 1) Use %s for all parameter placeholders, regardless of type. 1a) You can use %(key)s for a placeholder if you pass a dictionary as the parameters. 2) Do not put additional quotes around the placeholder. 3) Do not use placeholders for things like table or column names; they only work for column values. 4) If you use % anywhere in your query (i.e. x LIKE 'foo%'), you must double it (%%, i.e. x LIKE 'foo%%'); it is not necessary to do this to your parameter values. https://sourceforge.net/forum/forum.php?thread_id=1075920&forum_id=70461 http://cvs.sourceforge.net/viewcvs.py/*checkout*/mysql-python/MySQLdb/doc/MySQLdb.txt?rev=HEAD -- Computer interfaces should never be made of meat. From NUG1978 at aol.com Wed Nov 3 11:02:26 2004 From: NUG1978 at aol.com (NUG1978@aol.com) Date: Mon Nov 29 18:15:39 2004 Subject: [Tutor] Python Message-ID: <12a.4f5eaa1e.2eba06aa@aol.com> Hi. Is there a way to get a user's URL with Python scripting? Example: A user logs onto your sight and want a script to automatically write their URL or domain to a file. I already know about the writing to file, I just don't know any python function or method that will get a user's URL or domain. Can you help me. Nug Johnson _nug1978@aol.com_ (mailto:nug1978@aol.com) P.S. I'm trying not to use cookies. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041103/ebd07f07/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Nov 29 18:21:22 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 29 18:21:27 2004 Subject: [Tutor] os.popen In-Reply-To: <200411291730.13672.klas.martelleur@telia.com> Message-ID: On Mon, 29 Nov 2004, Klas Marteleur wrote: > hmm.. > Is it nesessary to close the "file objects"? > > a = os.popen3("tcextract -v") > tcexVerOut= a[2].readlines() > a[0].close() #Nesessary? > a[1].close() #Nesessary? > a[2].close() #Nesessary? Hi Klas, Almost certainly yes at some point, due to "flow-control" issues. It's very possible that a command like tcextract will stall until its input stream is closed. For more information, see: http://www.python.org/doc/lib/popen2-flow-control.html Good luck to you! From maxnoel_fr at yahoo.fr Mon Nov 29 18:27:05 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon Nov 29 18:27:28 2004 Subject: [Tutor] comapring lists In-Reply-To: <200411160439.XAA03967@webmail10.cac.psu.edu> References: <200411160439.XAA03967@webmail10.cac.psu.edu> Message-ID: On Nov 16, 2004, at 04:39, Jim De Caro wrote: > I am getting user input and comparing it to an iterated list. I can > get the > input to print out verbatim. I want to then "swap" individual letters > in the > input with letters from a second list so it is like a simple > encryption. I > can't figure out the correct logic or syntax. Here is what I have so > far: > > [SNIP] > This does not work. Any suggestions? My first impression is that you should use a dictionary to do that, where for each element the key is the unencrypted character and the value is the encrypted one. For example, a ROT13 encryption dictionary would look like {'a': 'n', 'b': 'p', 'c': 'q', [...]}. Then, once you have your dictionary, all you have to do is: for i in user: print encryption[i] ...to get the encrypted version of your string. -- 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 ARobert at MFS.com Mon Nov 29 18:41:01 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Mon Nov 29 18:41:12 2004 Subject: [Tutor] RE: Comparing lists for encryption Message-ID: <968452DD78695147AA4A369C3DF9E40A01F93B18@BOSMAILBOX3.corp.mfs.com> You may want to consider a module that does encryption to do most of the leg work for you. This may be of some help. http://www.amk.ca/python/code/crypto.html Thank you, Andrew Robert Systems Architect Information Technology Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 "MFS Relay Service" made the following annotations on 11/29/2004 12:46:38 PM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From dyoo at hkn.eecs.berkeley.edu Mon Nov 29 18:41:54 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 29 18:41:58 2004 Subject: [Tutor] comapring lists In-Reply-To: <200411160439.XAA03967@webmail10.cac.psu.edu> Message-ID: On Mon, 15 Nov 2004, Jim De Caro wrote: > I am getting user input and comparing it to an iterated list. I can get > the input to print out verbatim. I want to then "swap" individual > letters in the input with letters from a second list so it is like a > simple encryption. I can't figure out the correct logic or syntax. > Here is what I have so far: > > user = raw_input("Enter your selection: ") [some code cut] > for i in range(len(encrypt)): > print user[0:62] > break Hi Jim, The 'break' statements here prematurely escape out of the loop. The code above, ### for i in range(len(encrypt)): print user[0:62] break ### ends up reducing down to: ### if len(encrypt) > 0: print user[0:62] ### which is probably not what you want. > for j in range(len(decrypt)): > for j in zip(decrypt): > print 'Encrypted-> %s' % (j,user) > break > > This does not work. Any suggestions? Try breaking the problem down a bit into a few subproblems. It looks like the code is trying to do too much at once --- whenever I see nested loops like this, I get nervous. *grin* In particular, can you define a function that takes a single character, and encrypts that character alone? Good luck to you! [Meta note: You need to be subscribed to tutor to be able to post messages directly to the list. Otherwise, your messages get put on a moderation queue. Please subscribe at: http://mail.python.org/mailman/listinfo/tutor.] From erimendz at gmail.com Mon Nov 29 18:51:56 2004 From: erimendz at gmail.com (Eri Mendz) Date: Mon Nov 29 18:47:09 2004 Subject: [Tutor] programming newbie question In-Reply-To: <16044.156.153.255.243.1099587688.squirrel@phome.pointclark.net> References: <16044.156.153.255.243.1099587688.squirrel@phome.pointclark.net> Message-ID: <200411292051.56665.erimendz@gmail.com> i like to join Dustin to help me enrich my knowledge with python. will appreciate if the group can point us to the right direction. -- regards, eri betamepis 2.4.26 On Thursday 04 November 2004 8:01, dustinp@pointclark.net wrote: > I am fairly new to programming and I have started to learn programming > then stopped out of frustration several times in the past. I guess my > frustration stems from not being able to understand when to use certain > aspects of programming such as functions or classes. I have read enough > books and tutorials to know the syntax of python and I understand most > everything related to the concepts of programming, but I have never been > able to put it all together and learn how and when to use specific > features. Can anyone suggest a method or some reading to help out with > this? I also struggle with finding projects to work on does anyone know > of projects that a novice could contribute to? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Mon Nov 29 18:53:23 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Nov 29 18:52:59 2004 Subject: [Tutor] programming newbie question References: <16044.156.153.255.243.1099587688.squirrel@phome.pointclark.net> Message-ID: <004201c4d63c$528b01c0$f1598651@xp> > frustration stems from not being able to understand when to use certain > aspects of programming such as functions or classes. Maybe it will help if you stop worrying about which is right. All design decisions are compromises, the best way to find out which work best is just to do it. There comes a point when theory must turn into practice... > features. Can anyone suggest a method or some reading to help out with > this? Read existing code - the samples that come with Python are a good starting point... Try changing them to add a feature (work on a copy for safety!) Try writing a new program, doesn't matter much what. Try rewriting it with a different set of design decisions - see how much code is similar/identical, what has changed? Why? > I also struggle with finding projects to work on does anyone know > of projects that a novice could contribute to? Try the Useless Python site for small scale challenges. Try sourceforge for some bigger scale challenges :-) HTH, 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 Nov 29 19:01:00 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Nov 29 19:03:35 2004 Subject: [Tutor] new function and a 3 line program not working References: <000a01c4c4c5$f55d9990$6500a8c0@cdca1h1bro1> Message-ID: <005001c4d63d$62d3bfd0$f1598651@xp> > go to IDLE gui and define the new function > > def newLine(): > print > > then i open another IDLE window and write the 3 line program like in the tutorial This is the second time this has come up recently. Which tutorial are you using? Does it tell you to go to a separate window to type the bit below? > print "First Line." > newLine() > print "Second Line." If so that is the problem. You cannot call newLine() in a separate file from the one where you defined it - python doesn't know about it. You need to *import* the file where you defined the function, like this: from newline.py import newline Ah, but reading further in your post and looking at the tutorial text you posted, the author does NOT say create a new file. Rather he (she?) says (or implies) to just keep on typing the program after the function definition in the same file. That way Python can read the file including the newline() definition. HTH, Alan G. ========================== The first couple of functions we are going to write have no parameters, so the syntax looks like this: def newLine(): print This function is named newLine. The empty parentheses indicate that it has no parameters. It contains only a single statement, which outputs a newline character. (That's what happens when you use a printcommand without any arguments.) The syntax for calling the new function is the same as the syntax for built-in functions: print "First Line." newLine() print "Second Line." From alan.gauld at freenet.co.uk Mon Nov 29 19:07:21 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Nov 29 19:07:00 2004 Subject: [Tutor] Python References: <12a.4f5eaa1e.2eba06aa@aol.com> Message-ID: <006c01c4d63e$466bc1c0$f1598651@xp> > Hi. Is there a way to get a user's URL with Python scripting? Example: A > user logs onto your sight and want a script to automatically write their URL > or domain to a file. I already know about the writing to file, I just don't > know any python function or method that will get a user's URL or domain. Can > you help me. I think you need to be a bit more precise about your terms. I think you mean: You want to run a script on your web server which, when a user visits the site, will extract the visitors and write it to a file. Now what's not clear is what exactly you mean by XXXX. - The user doesn't have a URL, they have an IP address. - The user may or may not have a domain (but their ISP will) - The user may be coming from another site which will have both URL and domain and those are available within the CGI environment variables. CAn you clarify what you mean? Writing clear and unambiguous requirements is one of the key skills of a software engineer! :-) Alan G. From flaxeater at yahoo.com Mon Nov 29 19:52:55 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Mon Nov 29 19:52:58 2004 Subject: [Tutor] programming newbie question Message-ID: <20041129185255.7737.qmail@web54303.mail.yahoo.com> How about some easy games, such as hangman, tic tac toe (called other things elsewhere), then move on to more challenging things, such as minesweeper. dustinp@pointclark.net wrote: >I am fairly new to programming and I have started to learn programming >then stopped out of frustration several times in the past. I guess my >frustration stems from not being able to understand when to use certain >aspects of programming such as functions or classes. I have read enough >books and tutorials to know the syntax of python and I understand most >everything related to the concepts of programming, but I have never been >able to put it all together and learn how and when to use specific >features. Can anyone suggest a method or some reading to help out with >this? I also struggle with finding projects to work on does anyone know >of projects that a novice could contribute to? > > __________________________________ Do you Yahoo!? Meet the all-new My Yahoo! - Try it today! http://my.yahoo.com From glingl at aon.at Mon Nov 29 20:11:31 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Nov 29 20:11:13 2004 Subject: [Tutor] Introduction/ box In-Reply-To: <200411262118.27140.cm012b5105@blueyonder.co.uk> References: <200411262118.27140.cm012b5105@blueyonder.co.uk> Message-ID: <41AB7463.6040501@aon.at> Hello nige ill try to give you an example which makes you a rectangle but only using tkinter which comes with python and is its standard graphics toolkit as i dont know pygame well enough here is it maybe it can be done similarly in pygame notice please that python is an artificial language so it has to be written more structured than natural languages like your english otherwise the programs wont run so please type the pragram exactly as it is written here provided your email client or mine dont destroy the correct structure which is not very probable coz the structure is very simple look: from Tkinter import * root = Tk() cv = Canvas(root, width=400, height=300, bg="blue") cv.pack() cv.create_rectangle(50,30,320,290,outline="yellow",fill="red",width=10) mainloop() --------- natural language following you can play around with the numbers in this program so you can find out what their meaning is eg replace 320 by 177 and so on and also with the names of the colors eg exchange them or replace "red" by "violet" and so on if you then want to go over to pygame contact the pygame mailing list you can find a link to it on the pygame website hope this helps gregor cm012b5105 schrieb: >Hello every body im new to python iv allways wanted to have go >iv noticed there is loads of tutorials on the net for it any way i have a >question which i hope some one will help me find the answer i want to know >how to draw a box iv just installed pygame as i would like to have a go at >making my own game i thought if i could get the source for something simple >like drawing a box that would give me something to start with i hope this >makes sense if not please tell me ill try to explain better thankyou > nige >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From bgailer at alum.rpi.edu Mon Nov 29 20:30:40 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Nov 29 20:30:40 2004 Subject: [Tutor] comapring lists In-Reply-To: <200411160439.XAA03967@webmail10.cac.psu.edu> References: <200411160439.XAA03967@webmail10.cac.psu.edu> Message-ID: <6.2.0.14.0.20041129121822.02e22d80@mail.mric.net> At 09:39 PM 11/15/2004, Jim De Caro wrote: >I am getting user input and comparing it to an iterated list. I can get the >input to print out verbatim. I want to then "swap" individual letters in the >input with letters from a second list so it is like a simple encryption. I >can't figure out the correct logic or syntax. Here is what I have so far: > >user = raw_input("Enter your selection: ") > > > >encrypt = >['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','0'] > >decrypt >=['b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','A','0','1','2','3','4','5','6','7','8','9','0'] > > >for i in range(len(encrypt)): > print user[0:62] > break > >for j in range(len(decrypt)): > for j in zip(decrypt): > print 'Encrypted-> %s' % (j,user) > break > >This does not work. "does not work" is not helpful. We'd rather hear what results you are getting (if any) and (if needed) how they differ from what you expect. The code above does nothing useful. It is hard to even begin to diagnose it. But get rid of the break statements. They cause the loops to end after 1 iteration. Is this a homework problem? Can you write a pseudocode version of what you think the program should look like? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From hugonz-lists at h-lab.net Mon Nov 29 20:39:06 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon Nov 29 20:39:22 2004 Subject: [Tutor] os.popen In-Reply-To: <200411291730.13672.klas.martelleur@telia.com> References: <200411281746.56113.klas.martelleur@telia.com> <41AA183D.4000805@h-lab.net> <200411290812.01510.klas.martelleur@telia.com> <200411291730.13672.klas.martelleur@telia.com> Message-ID: <41AB7ADA.8050006@h-lab.net> I would do it, even if the filehandles were automatically closed on exit. There's more to it though: the pipes are buffered and there may be more data in child_stdout. What I'd do is empty it before closing, though I'm not sure if this is necessary. Maybe someone can step in and clarify a bit, but to sum it up: by all means close the handles... Probably if this is the output of a command, then EOF has been encountered on child_stdout too, so you could do: tcextract[1].read() pretty safely, without blocking... then do: tcextract[1].close() tcextract[2].close() tcextract[0].close() #This one is STDIN... Hugo Klas Marteleur wrote: > hmm.. > Is it nesessary to close the "file objects"? > > a = os.popen3("tcextract -v") > tcexVerOut= a[2].readlines() > a[0].close() #Nesessary? > a[1].close() #Nesessary? > a[2].close() #Nesessary? > > Regards Klas > > > >>Ok i used popen3 instead, reading the "child-stderr" instead and it worked. >> >> >>>>>tcextract = os.popen3("tcextract -v") >>>>>tcextract[2].readlines() >> >>['tcextract (transcode v0.6.12) (C) 2001-2003 Thomas Oestreich\n'] >> >>Thanks Hugo >> >>Regards Klas >> >>s?ndagen den 28 november 2004 19.26 skrev du: >> >>>Hi Klas, >>> >>>Maybe the output you're trying to get is in STDERR and not STDOUT?? I've >>>had to deal with this a number of times, so may I wrote a Tkinter script >>>to let me know what output is to STDERR and what is to STDOUT. os.popen >>>will open STDOUT if invoked with "r" (which is the default). >>> >>>Try looking of other popen* functions. They provide STDOUT + STDERR >>>(popen4) or separate STDOUT + STDERR (popen3) >>> >>>BTW< if you'd like to have my script (the Streamshower, I call it =) ) >>>just email me ... >>> >>>Hugo >>> >>>Klas Marteleur wrote: >>> >>>>Hi >>>>I have a little problem that is confusing me. >>>> >>>>If i write the following in a bash shell i get the desired output: >>>>[klas@h180n2fls32o849 klas]$ kwrite -v >>>>Qt: 3.2.3 >>>>KDE: 3.2 BRANCH >= 20040204 >>>>KWrite: 4.2 >>>> >>>>It also works in a python shell... >>>> >>>> >>>>>>>os.popen("kwrite -v").readlines() >>>> >>>>['Qt: 3.2.3\n', 'KDE: 3.2 BRANCH >= 20040204\n', 'KWrite: 4.2\n'] >>>> >>>>If i try the following in a bash shell, it also workes: >>>>[klas@h180n2fls32o849 klas]$ tccat -v >>>>tccat (transcode v0.6.12) (C) 2001-2003 Thomas Oestreich >>>> >>>>But if i try the same in a python shell i get: >>>> >>>>>>>os.popen("tccat -v").readlines() >>>> >>>>[] >>>> >>>>Not even if i specify the path it works. >>>> >>>> >>>>>>>os.popen("/usr/bin/tccat -v").readlines() >>>> >>>>[] >>>> >>>> >>>>What am i missing? >>>> >>>>Kind Regards >>>>Klas >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >> >>_______________________________________________ >>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 mdcooper at uvic.ca Mon Nov 29 20:55:19 2004 From: mdcooper at uvic.ca (mdcooper) Date: Mon Nov 29 20:55:25 2004 Subject: [Tutor] Adding patches Message-ID: <41AD4DF4@wm2.uvic.ca> Hello all, I am attempting to run a large least squares fit program and I am getting the error: SystemError: com_backpatch: offset too large There is a possible solution here (the last entry): http://www.codecomments.com/Python/message312451.html What I need help with is how to add the patch he has offered. Thanks so much. Matthew From alan.gauld at freenet.co.uk Mon Nov 29 21:58:41 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Nov 29 21:58:17 2004 Subject: [Tutor] Python References: Message-ID: <008a01c4d656$359204f0$f1598651@xp> CC'd to the tutor list to ensure widest possible response. > Is there a way (with python) the store a users identity (URL, domain, IP, > etc.) in a variable when they visit your website? OK, I guess you need to define what you mean by identity. And that's not so easy. For example what do you think a users "URL" would look like? Can you give an example of what you think I should be able to record if you were to visit my web tutor say? IP address will locate the PC that the user is using, and possibly sharing. The domain will be from the service provider and is implicit in the IP address. > Yes, this can be done with cookies, ONly if the user tells you their ID by, say, logging on. You can then save their ID back to their browser in a cookie. But if the user doesn't tell you who they are in the first place then a cookie won't help you find out! Personal privacy is a big issue on the web and the standards do try to protect it. So while you might be able to identify a returning IP address(*), its very hard to be sure who the user is. That's why cookies were invented! (*)And if the PC is on a network with DHCP you can't even be sure the same IP address means it's the same PC... > which isn't hard at all to learn because programming > concepts are similar. Absolutely, thats why my tutor teaches 3 at a time :-) Alan G. From kent37 at tds.net Mon Nov 29 22:14:40 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Nov 29 22:14:46 2004 Subject: [Tutor] Adding patches In-Reply-To: <41AD4DF4@wm2.uvic.ca> References: <41AD4DF4@wm2.uvic.ca> Message-ID: <41AB9140.1070701@tds.net> The patch is a change to the Python source code. To apply it, you need to be able to build Python from source. This page has some brief instructions: http://www.python.org/download/download_source.html But looking at the thread you referenced, it sounds like the problem is caused by very large functions. Does your program have large functions (thousands of lines of code)? Can you refactor it to break it into smaller chunks? Kent mdcooper wrote: > Hello all, > > I am attempting to run a large least squares fit program and I am getting the > error: > > SystemError: com_backpatch: offset too large > > There is a possible solution here (the last entry): > http://www.codecomments.com/Python/message312451.html > > What I need help with is how to add the patch he has offered. > > Thanks so much. > > Matthew > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Mon Nov 29 23:14:37 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 29 23:14:45 2004 Subject: [Tutor] programming newbie question In-Reply-To: <20041129185255.7737.qmail@web54303.mail.yahoo.com> Message-ID: On Mon, 29 Nov 2004, Chad Crabtree wrote: > How about some easy games, such as hangman, tic tac toe (called other > > things elsewhere), then move on to more challenging things, such as > minesweeper. I just got in contact with Nick Parlante of the Nifty Assignments project; he's been collecting material on fun projects: http://nifty.stanford.edu/ The projects there look pretty nice. In fact, I'm thinking of adapting material on that page for us here on Python-Tutor. Is there a particular project that sounds interesting to folks? Personally, I'm interested in: http://nifty.stanford.edu/catandmouse/html/ But that's only because I helped tutor it back when I was at Berkeley's Self-Paced Center... *grin* But if people want, I'd be happy to convert Professor Clancy's support code from C++ to Python. From cyresse at gmail.com Mon Nov 29 23:28:00 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Nov 29 23:28:03 2004 Subject: [Tutor] programming newbie question In-Reply-To: <20041129185255.7737.qmail@web54303.mail.yahoo.com> References: <20041129185255.7737.qmail@web54303.mail.yahoo.com> Message-ID: As a beginner, I can understand the frustration. What's the right thing to use and how? Truth is, unless you're programming for some form of qualification there is no right way or style, only that which works for you. Use what works. If you just figured out how to use lists, then use two lists instead of a dictionary of tuples. I will say one thing though, OOP is overhyped. Don't be scared of objects, or the Python documentation. : ) As you get experience, you'll use new things to solve new problems, and your toolbox of tricks and objects/functions will grow, and you'll reach a point where you look back at that first code you wrote and shudder. Heck, I've reached that point, and I started learning Python 2 months ago. Good luck, Liam Clarke On Mon, 29 Nov 2004 10:52:55 -0800 (PST), Chad Crabtree wrote: > How about some easy games, such as hangman, tic tac toe (called other > > things elsewhere), then move on to more challenging things, such as > minesweeper. > > > > > dustinp@pointclark.net wrote: > > >I am fairly new to programming and I have started to learn > programming > >then stopped out of frustration several times in the past. I guess > my > >frustration stems from not being able to understand when to use > certain > >aspects of programming such as functions or classes. I have read > enough > >books and tutorials to know the syntax of python and I understand > most > >everything related to the concepts of programming, but I have never > been > >able to put it all together and learn how and when to use specific > >features. Can anyone suggest a method or some reading to help out > with > >this? I also struggle with finding projects to work on does anyone > know > >of projects that a novice could contribute to? > > > > > > > __________________________________ > Do you Yahoo!? > Meet the all-new My Yahoo! - Try it today! > http://my.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 jeffpeery at yahoo.com Mon Nov 29 23:29:43 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon Nov 29 23:29:47 2004 Subject: [Tutor] pickling? Message-ID: <20041129222943.82393.qmail@web60105.mail.yahoo.com> hello, I am not sure what pickling is, could someone give me a quick synopsis for a newbie? the reason I ask is that I think it might be useful for an application I am working on. Is pickling the process of storing data for later use? I have a system that measures liquid flow rate and we do regular measurements with flow meters, and I want to setup a statistical quality control system. the fiirst thing I am doing is sorting the measurement into categories and then I will do the stats. anyhow, I will have to store lots of information in a file and access it regularly to read and append new measurements. Is pickling a good way to store matricies and then pick then up later for use in python? thanks Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041129/e702a2a7/attachment.html From hugonz-lists at h-lab.net Mon Nov 29 23:50:43 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon Nov 29 23:50:55 2004 Subject: [Tutor] pickling? In-Reply-To: <20041129222943.82393.qmail@web60105.mail.yahoo.com> References: <20041129222943.82393.qmail@web60105.mail.yahoo.com> Message-ID: <41ABA7C3.3020901@h-lab.net> I guess pickling may be what you need. Basically you don't need to come up with a specific way to save your objects to a file (or send them over a network) but you can rely on pickle to do it for you. One of the issues is that the pickle format (a formatted stream of bytes) is python specific, so this may not be what you need if you intend to communicate with a non python app. It is indeed a good way to store matrices (either bidimensional lists or more efficient numeric matrices like those found in the numarray package) Hugo Jeff Peery wrote: > hello, I am not sure what pickling is, could someone give me a quick > synopsis for a newbie? > > the reason I ask is that I think it might be useful for an application I > am working on. Is pickling the process of storing data for later use? I > have a system that measures liquid flow rate and we do regular > measurements with flow meters, and I want to setup a statistical quality > control system. the fiirst thing I am doing is sorting the measurement > into categories and then I will do the stats. anyhow, I will have to > store lots of information in a file and access it regularly to read and > append new measurements. Is pickling a good way to store matricies and > then pick then up later for use in python? > > thanks > > Jeff > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From flaxeater at yahoo.com Mon Nov 29 23:57:46 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Mon Nov 29 23:57:48 2004 Subject: [Tutor] pickling? Message-ID: <20041129225746.13582.qmail@web54307.mail.yahoo.com> I would suggest that you use the csv module to make a file that is spreadsheet readable so that you can look at it. Maybe even make graphs from Excel if you care to. http://docs.python.org/lib/module-csv.html I really like this, and I find it pretty easy to understand by the examples in the above doc. Good Luck. Jeff Peery wrote: > hello, I am not sure what pickling is, could someone give me a quick > synopsis for a newbie? > > the reason I ask is that I think it might be useful for an application > I am working on. Is pickling the process of storing data for later > use? I have a system that measures liquid flow rate and we do regular > measurements with flow meters, and I want to setup a statistical > quality control system. the fiirst thing I am doing is sorting the > measurement into categories and then I will do the stats. anyhow, I > will have to store lots of information in a file and access it > regularly to read and append new measurements. Is pickling a good way > to store matricies and then pick then up later for use in python? > > thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jeff at ccvcorp.com Tue Nov 30 00:05:03 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Nov 30 00:01:46 2004 Subject: [Tutor] pickling? In-Reply-To: <20041129222943.82393.qmail@web60105.mail.yahoo.com> References: <20041129222943.82393.qmail@web60105.mail.yahoo.com> Message-ID: <41ABAB1F.1040408@ccvcorp.com> Jeff Peery wrote: > hello, I am not sure what pickling is, could someone give me a quick > synopsis for a newbie? > > the reason I ask is that I think it might be useful for an application I > am working on. Is pickling the process of storing data for later use? I > have a system that measures liquid flow rate and we do regular > measurements with flow meters, and I want to setup a statistical quality > control system. the fiirst thing I am doing is sorting the measurement > into categories and then I will do the stats. anyhow, I will have to > store lots of information in a file and access it regularly to read and > append new measurements. Is pickling a good way to store matricies and > then pick then up later for use in python? Pickling is indeed storing data for later use. However, from what you've said about your project, you may be better off using a simple database rather than plain pickles. A pickle is just a way of storing a Python object on disk (or sending it across a network). In order to use it, you would first unpickle any old data that you have, append any new data to it, and then pickle the whole bundle again. If you've really got lots of data, that unpickling and re-pickling could get pretty expensive, even if you only do it at startup and shutdown. (And if you repickle only at shutdown, you risk losing data when your program crashes...) A fairly lightweight database, however, will be much more efficient for storing large amounts of data. You won't have to do nearly as much unpickle-repickle style dancing; the database handles all that stuff for you transparently. I've never needed to use such a database myself, so I can't offer any specific advice. But I've heard people (here and on comp.lang.python) speak very well of mysql and sqlite, and their respective Python language bindings. Jeff Shannon Technician/Programmer Credit International From glingl at aon.at Tue Nov 30 00:44:29 2004 From: glingl at aon.at (Gregor Lingl) Date: Tue Nov 30 00:44:12 2004 Subject: [Tutor] Introduction/box In-Reply-To: <200411292143.02997.cm012b5105@blueyonder.co.uk> References: <200411292143.02997.cm012b5105@blueyonder.co.uk> Message-ID: <41ABB45D.8020605@aon.at> there is a very good tutorial which *uses pygame*: http://www.livewires.org.uk/python/ there you can download a lot of worksheets and examples they say: The LiveWires Python Course is intended to teach the Python programming language to people who have never programmed before. Gregor cm012b5105 schrieb: >Thankyou > > > > From jeffpeery at yahoo.com Tue Nov 30 00:58:29 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue Nov 30 00:58:32 2004 Subject: [Tutor] (no subject) Message-ID: <20041129235829.61985.qmail@web60110.mail.yahoo.com> Hello, was wondering how python handles multi-line code. for example if I have a really long equation and I don't want to have to scroll over to look at it, can I just continue the equation on the next line? is this good practice? similarly can I do this for things like dictionaries and lists? thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041129/6dc8c726/attachment.html From cyresse at gmail.com Tue Nov 30 01:23:42 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Nov 30 01:23:45 2004 Subject: [Tutor] (no subject) In-Reply-To: <20041129235829.61985.qmail@web60110.mail.yahoo.com> References: <20041129235829.61985.qmail@web60110.mail.yahoo.com> Message-ID: Hi Jeff, You can do that, just chuck it in brackets. i.e. a=(1+2+3+4+5+6+7+8+9+ 10+11+12+13+14+14+15 +19+20+212) or for a list - a=[1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17, 18,29,20] You can also do it for lists of lists, good for the array mindset. a=[ [1,2,3], [4,5,6], [7,8,9] ] Makes it easier to think of as a 2D array. or dictionaries a={ 'a':1, 'b':2, 'c':3, 'd':4, 'e':5 } Python knows to keep reading until the closing bracket. HTH Liam Clarke On Mon, 29 Nov 2004 15:58:29 -0800 (PST), Jeff Peery wrote: > > Hello, > > was wondering how python handles multi-line code. for example if I have a > really long equation and I don't want to have to scroll over to look at it, > can I just continue the equation on the next line? is this good practice? > similarly can I do this for things like dictionaries and lists? > > thanks. > _______________________________________________ > 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 bgailer at alum.rpi.edu Tue Nov 30 01:29:50 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Nov 30 01:31:03 2004 Subject: [Tutor] (no subject) In-Reply-To: <20041129235829.61985.qmail@web60110.mail.yahoo.com> References: <20041129235829.61985.qmail@web60110.mail.yahoo.com> Message-ID: <6.2.0.14.0.20041129172429.02ec8440@mail.mric.net> At 04:58 PM 11/29/2004, Jeff Peery wrote: >Hello, > >was wondering how python handles multi-line code. for example if I have a >really long equation and I don't want to have to scroll over to look at >it, can I just continue the equation on the next line? is this good >practice? similarly can I do this for things like dictionaries and lists? From the Python Language Reference: 2.1.5 Explicit line joining Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example: if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1 A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal. 2.1.6 Implicit line joining Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. For example: month_names = ['Januari', 'Februari', 'Maart', # These are the 'April', 'Mei', 'Juni', # Dutch names 'Juli', 'Augustus', 'September', # for the months 'Oktober', 'November', 'December'] # of the year Implicitly continued lines can carry comments. The indentation of the continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicitly continued lines can also occur within triple-quoted strings (see below); in that case they cannot carry comments. 2.4.1 String Literals ... In triple-quoted strings, unescaped newlines and quotes are allowed Thus: """this is a multiline string""" That should cover it Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041129/4f60fd56/attachment.htm From jeffpeery at yahoo.com Tue Nov 30 01:33:54 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue Nov 30 01:33:57 2004 Subject: [Tutor] data structures in python? Message-ID: <20041130003354.10925.qmail@web60109.mail.yahoo.com> hello, this makes three questions today... phew! is there something similar in python to a data structure in C? Would this be like creating a new module, or a new object? I have an object that is associated with several different variables and I want to arrange my data as if it were a structure so I can call object1.variable1 or object1.variable2 or object1000.variable1[5] etc. it would be much easier to keep track indexing and whatnot this way. thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041129/18b20f0b/attachment.html From orbitz at ezabel.com Tue Nov 30 01:56:21 2004 From: orbitz at ezabel.com (orbitz) Date: Tue Nov 30 01:56:30 2004 Subject: [Tutor] (no subject) In-Reply-To: <20041129235829.61985.qmail@web60110.mail.yahoo.com> References: <20041129235829.61985.qmail@web60110.mail.yahoo.com> Message-ID: <41ABC535.7070809@ezabel.com> Things inside unmatched (), [], and {} are evaluated as one whole unit until the corresponding 0, ], or }. If you have a really long equation though, it is probably a better idea to break it up into either variables or function calls. That way it is less prone to error. Jeff Peery wrote: > Hello, > > was wondering how python handles multi-line code. for example if I > have a really long equation and I don't want to have to scroll over to > look at it, can I just continue the equation on the next line? is this > good practice? similarly can I do this for things like dictionaries > and lists? > > thanks. > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From orbitz at ezabel.com Tue Nov 30 01:58:49 2004 From: orbitz at ezabel.com (orbitz) Date: Tue Nov 30 01:58:54 2004 Subject: [Tutor] data structures in python? In-Reply-To: <20041130003354.10925.qmail@web60109.mail.yahoo.com> References: <20041130003354.10925.qmail@web60109.mail.yahoo.com> Message-ID: <41ABC5C9.80908@ezabel.com> I think you are confused. Generally data structures are synonymous with abstract data types. But what you are really asking about, I think, are structs in C. Just use a class to hold your data, or a dict. The python tutorial easily available from the python website covers how to make and use both. Jeff Peery wrote: > hello, this makes three questions today... phew! > > is there something similar in python to a data structure in C? Would > this be like creating a new module, or a new object? I have an object > that is associated with several different variables and I want to > arrange my data as if it were a structure so I can call > object1.variable1 or object1.variable2 or object1000.variable1[5] etc. > it would be much easier to keep track indexing and whatnot this way. > thanks. > > Jeff > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From bvande at po-box.mcgill.ca Tue Nov 30 03:26:37 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Nov 30 03:28:48 2004 Subject: [Tutor] design question -- nested loops considered harmful? Message-ID: <41ABDA5D.40504@po-box.mcgill.ca> Hi all, in a recent post in the "comapring lists" thread, Danny Yoo wrote: > whenever I see nested loops > like this, I get nervous. *grin* This got me thinking about general design issues. In various programs I have made much use of nested loops in order to parse data files. I've done this in cases where I am interested in pulling out some data which is identified by a delimiter. Below is a minimal example of the sort of thing I have been doing: date_flag = '[Date]' email_flag = '[Email]' item_flags = [date_flag, email_flag] def parse_file(list_of_lines): data_dict = {} for line in list_of_lines: for item in item_flags: if line.startswith(item): data_dict[item] = line[len(item):] break return data_dict In this particular toy case, the "for i in item_flags" isn't too much help, as I've only listed two delimiters. But I often have a good many more, and thus thought the nested loop much better than a long list of if-tests. Since the logic in the "for item in item_flags:" loop is quite small, it never occurred to be to move it into its own function. I think I see that the nervous-making aspect of nested loops comes from concern about clarity of control flow. (Is there some other worry I'm missing?) But is my sort of case one which shows a rule of thumb isn't a rigid law? Is there a much better design for my task that I've missed? Do more experience folk doubt my wisdom in taking the embedded loop to be too short to bother factoring out? Thanks for any input. Best to all, Brian vdB From flaxeater at yahoo.com Tue Nov 30 03:46:59 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Nov 30 03:47:02 2004 Subject: [Tutor] design question -- nested loops considered harmful? Message-ID: <20041130024659.80860.qmail@web54310.mail.yahoo.com> Brian van den Broek wrote: > This got me thinking about general design issues. In various programs > I have made much use of nested loops in order to parse data files. > I've done this in cases where I am interested in pulling out some data > which is identified by a delimiter. Below is a minimal example of the > sort of thing I have been doing: > > date_flag = '[Date]' > email_flag = '[Email]' > item_flags = [date_flag, email_flag] > > def parse_file(list_of_lines): > data_dict = {} > for line in list_of_lines: > for item in item_flags: > if line.startswith(item): > data_dict[item] = line[len(item):] > break > return data_dict Well After pondering this for about five minutes I cannot really see anything particularly in elegant about this. Perhaps the only refinement that I have picked up recently is internal functions. Perhaps this would be more readable without cluttering your name space. def pars_file(list_of_lines): ####internal FunctionS########### def check_flags(line,flags=item_flags,adict=data_dict): for item in flags: if line.startswith(item): adict[item]=line[len(item)] return ####end internal functions#### ####start main function suite#### data_dict={} for line in list_of_lines: check_flags(line) return data_dict Granted this adds a layer of indirection, but for more complex examples I find this helpful when I need to look at this later, because it hides some of the nesting. Just My two cents. __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From bvande at po-box.mcgill.ca Tue Nov 30 05:49:23 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Nov 30 05:49:33 2004 Subject: [Tutor] design question -- nested loops considered harmful? In-Reply-To: References: <41ABDA5D.40504@po-box.mcgill.ca> Message-ID: <41ABFBD3.5050506@po-box.mcgill.ca> Hi all, thanks to Chad and Liam for the replies. Posts merged for reply: Chad Crabtree said unto the world upon 2004-11-29 21:46: > Perhaps the only refinement that I have picked up recently is internal > functions. Perhaps this would be more readable without cluttering your > name space. > > def pars_file(list_of_lines): > ####internal FunctionS########### > def check_flags(line,flags=item_flags,adict=data_dict): > for item in flags: > if line.startswith(item): > adict[item]=line[len(item)] > return > ####end internal functions#### > ####start main function suite#### > data_dict={} > for line in list_of_lines: > check_flags(line) > return data_dict > > Granted this adds a layer of indirection, but for more complex > examples I find this helpful when I need to look at this later, > because it hides some of the nesting. I could see how nested defs would help with namespace issues -- it does seem one way to avoid modifying globals or passing about a bunch of parameters and multi-itemed returns. In the case I posted, I'm not sure about the payoff, but I've been tempted to nest defs when dealing with more complicated logic. I've refrained, as I've heard tell that nested defs are widely thought to be "a bad thing". I don't know why, but I *do* know I've already lived to regret disregarding such bits of conventional wisdom in the past. So, I've decided to act as though I understood the point until either I do, or I come across a case where I *really* feel I need them. If anyone could either explain the conventional wisdom or set straight my belief that distaste for nested defs is indeed widespread and well founded, I'd be grateful. Liam Clarke said unto the world upon 2004-11-29 22:29: >>Assuming that there would only be one occurrence of each one in a file - >> >>x=file('Brian's source file') 'r') >>a=x.readlines() #How big is it? If it's a huge file, this may not be the best >>x.close() >>a="".join(a) #Turns a list into a string, the "" is the joiner, i.e. >> # a=["Hello","World"] would become "HelloWorld" >>whereas a="?M?".join(a) >> #would become "Hello?M?World" >> #Just had a thought - a=str(a) would do exactly the >>same as a="".join(a) >> #wouldn't it? >>item_flags=["[Date]","[Email]"] I perhaps should have made clear that the toy code I posted was more aimed to exhibit flow control than actual parsing functionality. It is, however, something rather like code I've actually used, though. But when I've use that structure, I've had enough info about the datafiles to make much of Liam's code unneeded. (Thanks for posting it though :-) When I've used that structure, I've had short datafiles that were either created by me or by a freeware app with a documented file format. So, I can disregard file size, and count on the delimiter being at the front of the line. Hence, joining the lines into a string would make it harder. But maybe the approach Liam posted might well work better for the general case, where it is not known that my constraints obtain. As for your embedded question, Liam: when in doubt, try it out ;-) >>> list_of_strings = ['a string\n', 'another one\n', 'yet one more\n'] >>> a = ''.join(list_of_strings) >>> b = str(list_of_strings) >>> a == b False >>> a 'a string\nanother one\nyet one more\n' >>> b "['a string\\n', 'another one\\n', 'yet one more\\n']" str(some_list) preserves the "listiness" of some_list in that it includes the '[', etc. Thanks again, fellows. Best to all, Brian vdB PS I forgot to mention in my earlier post today -- the list input on datetime was indeed very helpful. Got it all sorted and all I'm left with is a sense of puzzlement as to why I was leery of the datetime module :-) From dyoo at hkn.eecs.berkeley.edu Tue Nov 30 08:13:11 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 30 08:13:29 2004 Subject: [Tutor] design question -- nested loops considered harmful? In-Reply-To: <41ABFBD3.5050506@po-box.mcgill.ca> Message-ID: > > def pars_file(list_of_lines): > > ####internal FunctionS########### > > def check_flags(line,flags=item_flags,adict=data_dict): > > for item in flags: > > if line.startswith(item): > > adict[item]=line[len(item)] > > return > > ####end internal functions#### > > ####start main function suite#### > > data_dict={} > > for line in list_of_lines: > > check_flags(line) > > return data_dict > If anyone could either explain the conventional wisdom or set straight > my belief that distaste for nested defs is indeed widespread and well > founded, I'd be grateful. Hi Brian, It's a funny thing for me: whenever I write a nested definition, I often find that the embedded definition is often useful enough to be itself an outer definition. *grin* It does seem that internal definitions are mostly avoided. Part of this might be because Python didn't have real lexical scope until the Python 2 series, but I also suspect it's just because they're just harder to test, since they're only accessible from the scope of the surrounding function. I hardly write inner definitions without being tempted to make them generally useable. For the function above, for example, I can't help but see if a general definition might work: ### def parse_tagged_line(line): """A general parser for "tagged" lines of the form: [tag_name] rest_of_line Returns a 2-tuple (tag_name, rest_of_line). If the line doesn't appear to be tagged, returns (None, line). """ regex = re.compile(r""" \[ ([^\]]*) ## The tag \] (.*)$ ## followed by the end of the line """, re.VERBOSE) if regex.match(line): return regex.match(line).groups() else: return (None, line) ### This is a generalized version of the line-parsing inner loop code, but it tries to parse anything that looks like a tagged line. For example: ### >>> parse_tagged_line("[email] dyoo@hkn.eecs.berkeley.edu") ('email', ' dyoo@hkn.eecs.berkeley.edu') >>> parse_tagged_line("[Name] Brian van den Broek") ('Name', ' Brian van den Broek') >>> parse_tagged_line("This is just a regular line") (None, 'This is just a regular line') ### If we have 'parsed_tagged_line()', then the parse_file() function can be flattened down a bit, from: ### def parse_file(list_of_lines): data_dict = {} for line in list_of_lines: for item in item_flags: if line.startswith(item): data_dict[item] = line[len(item):] break return data_dict ### to something like this: ### def parse_file(list_of_lines): data_dict = {} for line in list_of_lines: tag, rest = parse_tagged_line(line) if tag in item_flags: data_dict[tag] = rest return data_dict ### Embedded inner loops can be a ripe target for refactoring. Sometimes, the refactoring makes absolutely no sense at all, and the inner loop is better left alone as it is. In the example above, though, I think the extraction can help. From cyresse at gmail.com Tue Nov 30 04:27:35 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Nov 30 08:27:38 2004 Subject: [Tutor] design question -- nested loops considered harmful? In-Reply-To: <41ABDA5D.40504@po-box.mcgill.ca> References: <41ABDA5D.40504@po-box.mcgill.ca> Message-ID: Hi Brian, Just curious - >date_flag = '[Date]' > email_flag = '[Email]' > item_flags = [date_flag, email_flag] >def parse_file(list_of_lines): > data_dict = {} > for line in list_of_lines: > for item in item_flags: > if line.startswith(item): > data_dict[item] = line[len(item):] > break > return data_dict So, you're thingmajig scans each line for either date_flag or email_flag, and then slices the rest of the line and saves it as a dict. And, I guess you're looking for one date_flag line or one email_flag... Assuming that there would only be one occurrence of each one in a file - x=file('Brian's source file') 'r') a=x.readlines() #How big is it? If it's a huge file, this may not be the best x.close() a="".join(a) #Turns a list into a string, the "" is the joiner, i.e. # a=["Hello","World"] would become "HelloWorld" whereas a="?M?".join(a) #would become "Hello?M?World" #Just had a thought - a=str(a) would do exactly the same as a="".join(a) #wouldn't it? item_flags=["[Date]","[Email]"] def parsefile(fileString): data_dict={} for item in item_flags: tagIndex=fileString.find(item) #Finds lowest occurrence of item. Index is would be #first letter of item_flag[item] newLineIndex=fileString.find('\n', tagIndex) #Finds next newline after item_flag[item] data_dict[item]=fileString[tagIndex+len(item):newLineIndex] The slice at the end should slice from the char after the ']' of item, to the char before the next '\n' which is the end of the line. If there are multiple occurrences, all you have to do is - for item in item_flags: foundIndice=[] findIndex=0 startIndex=0 while findIndex ! = -1: findIndex=string2FindIn.find(item, startIndex) foundIndice.append(findIndex) del foundIndice[len(foundIndice)-1] #Delete last item, as .find returns "-1" for string not #found, and this will always be appended at end. data_dict[item]=foundIndice Of course, this is entirely subjective on personal style. On Mon, 29 Nov 2004 21:26:37 -0500, Brian van den Broek wrote: > Hi all, > > in a recent post in the "comapring lists" thread, Danny Yoo wrote: > > > whenever I see nested loops > > like this, I get nervous. *grin* > > This got me thinking about general design issues. In various programs I > have made much use of nested loops in order to parse data files. I've > done this in cases where I am interested in pulling out some data which > is identified by a delimiter. Below is a minimal example of the sort of > thing I have been doing: > > date_flag = '[Date]' > email_flag = '[Email]' > item_flags = [date_flag, email_flag] > > def parse_file(list_of_lines): > data_dict = {} > for line in list_of_lines: > for item in item_flags: > if line.startswith(item): > data_dict[item] = line[len(item):] > break > return data_dict > > In this particular toy case, the "for i in item_flags" isn't too much > help, as I've only listed two delimiters. But I often have a good many > more, and thus thought the nested loop much better than a long list of > if-tests. Since the logic in the "for item in item_flags:" loop is quite > small, it never occurred to be to move it into its own function. > > I think I see that the nervous-making aspect of nested loops comes from > concern about clarity of control flow. (Is there some other worry I'm > missing?) But is my sort of case one which shows a rule of thumb isn't a > rigid law? Is there a much better design for my task that I've missed? > Do more experience folk doubt my wisdom in taking the embedded loop to > be too short to bother factoring out? > > Thanks for any input. Best to all, > > Brian vdB > > _______________________________________________ > 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 bsi c human duty, to take the consequences. From cyresse at gmail.com Tue Nov 30 04:29:54 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Nov 30 08:29:57 2004 Subject: [Tutor] design question -- nested loops considered harmful? In-Reply-To: References: <41ABDA5D.40504@po-box.mcgill.ca> Message-ID: Oh dear, Gmail is terrible to email code in. On Tue, 30 Nov 2004 16:27:35 +1300, Liam Clarke wrote: > Hi Brian, > > Just curious - > > > > >date_flag = '[Date]' > > email_flag = '[Email]' > > item_flags = [date_flag, email_flag] > > >def parse_file(list_of_lines): > > data_dict = {} > > for line in list_of_lines: > > for item in item_flags: > > if line.startswith(item): > > data_dict[item] = line[len(item):] > > break > > return data_dict > > So, you're thingmajig scans each line for either date_flag or > email_flag, and then slices the rest of the line and saves it as a > dict. And, I guess you're looking for one date_flag line or one > email_flag... > > Assuming that there would only be one occurrence of each one in a file - > > x=file('Brian's source file') 'r') > a=x.readlines() #How big is it? If it's a huge file, this may not be the best > x.close() > a="".join(a) #Turns a list into a string, the "" is the joiner, i.e. > # a=["Hello","World"] would become "HelloWorld" > whereas a="?M?".join(a) > #would become "Hello?M?World" > #Just had a thought - a=str(a) would do exactly the > same as a="".join(a) > #wouldn't it? > item_flags=["[Date]","[Email]"] > > def parsefile(fileString): > data_dict={} > for item in item_flags: > tagIndex=fileString.find(item) #Finds lowest occurrence of > item. Index is would be > #first letter of > item_flag[item] > newLineIndex=fileString.find('\n', tagIndex) #Finds next > newline after item_flag[item] > data_dict[item]=fileString[tagIndex+len(item):newLineIndex] > > The slice at the end should slice from the char after the ']' of item, > to the char before the next '\n' which is the end of the line. > > If there are multiple occurrences, all you have to do is - > > for item in item_flags: > > foundIndice=[] > findIndex=0 > startIndex=0 > > while findIndex ! = -1: > findIndex=string2FindIn.find(item, startIndex) > foundIndice.append(findIndex) > > del foundIndice[len(foundIndice)-1] #Delete last item, as .find > returns "-1" for string not > #found, and this > will always be appended at end. > data_dict[item]=foundIndice > > Of course, this is entirely subjective on personal style. > > > > > On Mon, 29 Nov 2004 21:26:37 -0500, Brian van den Broek > wrote: > > Hi all, > > > > in a recent post in the "comapring lists" thread, Danny Yoo wrote: > > > > > whenever I see nested loops > > > like this, I get nervous. *grin* > > > > This got me thinking about general design issues. In various programs I > > have made much use of nested loops in order to parse data files. I've > > done this in cases where I am interested in pulling out some data which > > is identified by a delimiter. Below is a minimal example of the sort of > > thing I have been doing: > > > > date_flag = '[Date]' > > email_flag = '[Email]' > > item_flags = [date_flag, email_flag] > > > > def parse_file(list_of_lines): > > data_dict = {} > > for line in list_of_lines: > > for item in item_flags: > > if line.startswith(item): > > data_dict[item] = line[len(item):] > > break > > return data_dict > > > > In this particular toy case, the "for i in item_flags" isn't too much > > help, as I've only listed two delimiters. But I often have a good many > > more, and thus thought the nested loop much better than a long list of > > if-tests. Since the logic in the "for item in item_flags:" loop is quite > > small, it never occurred to be to move it into its own function. > > > > I think I see that the nervous-making aspect of nested loops comes from > > concern about clarity of control flow. (Is there some other worry I'm > > missing?) But is my sort of case one which shows a rule of thumb isn't a > > rigid law? Is there a much better design for my task that I've missed? > > Do more experience folk doubt my wisdom in taking the embedded loop to > > be too short to bother factoring out? > > > > Thanks for any input. Best to all, > > > > Brian vdB > > > > _______________________________________________ > > 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 bsi c human duty, to take the consequences. > -- '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 Nov 30 08:43:39 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 30 08:43:42 2004 Subject: [Tutor] data structures in python? In-Reply-To: <20041130003354.10925.qmail@web60109.mail.yahoo.com> Message-ID: On Mon, 29 Nov 2004, Jeff Peery wrote: > is there something similar in python to a data structure in C? Would > this be like creating a new module, or a new object? [meta: includes C and Python code for comparison purposes] Hi Jeff, Sort of. Class definitions can play the role of structures. For example, let's say that we were doing some 2d graphs, and would like to represent things as (x, y) coordinate points. In C, we can write a point definition and a small program to add points together: /*** C code ***/ #include typedef struct { int x; int y; } point; point point_make(int x, int y) { point p; p.x = x; p.y = y; return p; } point point_add (point p1, point p2) { return point_make(p1.x + p2.x, p1.y + p2.y); } void point_print (point p) { printf("(%d, %d)\n", p.x, p.y); } int main() { point p1 = point_make(3, 4); point p2 = point_make(7, 17); point_println(p1); point_println(p2); point_println(point_add(p1, p2)); return 0; } /******/ Here, we've defined a structure 'point' and a few functions to play specifically with those points. If we want to do a strict "Abstract Data Type" (ADT) approach, we would only allow access to the structure through those functions alone, and forbid clients from touch the inner structure of a point at all. Now we can do a similar thing in Python, by using classes: ### import sys class Point: def __init__(self, x, y): self.x, self.y = x, y def add(self, other): return Point(self.x + other.x, self.y + other.y) def println(self): print "(%d, %d)" % (self.x, self.y) if __name__ == '__main__': p1 = Point(3, 4) p2 = Point(7, 17) p1.println() p2.println() p1.add(p2).println() sys.exit(0) ### Here, the code tries to make it more clear that the helper functions "add" and "println" really belong to Points, so that's why they're nested within the Point definition. It's not exactly a one-to-one mapping between the C point and Python Point code, but it's somewhat close. Note that there's no explicit definition of the real "structure" of a point in the Python translation. This might be unsettling: we really depend on our initializer to do proper initialization of a Point, so this is actually quite a bit less rigid than a real C structure. Just as C's make_point() guarantees that its return value is properly initialized, the Point's __init__ guarantees the same kind of initialization. So in practice, this turns out to work pretty well. I hope this makes the point clearer. *grin* Good luck! From cyresse at gmail.com Tue Nov 30 04:52:28 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Nov 30 08:52:35 2004 Subject: [Tutor] design question -- nested loops considered harmful? In-Reply-To: References: <41ABDA5D.40504@po-box.mcgill.ca> Message-ID: Oh terrible, terrible, the above multi-find is bad. It should be as below. index_dict={} for item in item_flags: foundIndice=[] findIndex=0 startIndex=0 while findIndex ! = -1: findIndex=string2FindIn.find(item, startIndex) findIndex += len(item) foundIndice.append(findIndex) startIndex=findIndex del foundIndice[len(foundIndice)-1] index_dict[item]=foundIndice So, it starts from zero in the string, searches for the next occurrence of your search string, records the index of that occurrence, and searches again, this time starting from the previous index + the length of the search string, records the next index and so on. String.find() returns -1 for string not found, so it searches until it finds no more occurrences. Due to the way I've written my loop, the last value of foundIndice is always going to be -1, so del[foundIndice[len(foundIndice)-1] just deletes the last item. And then, you can do a multiple search and slice in a similar method data_dict={} for item in item_flags: sliceList=[] for itemIndex in index_dict[item]: endOfSlice = string2FindIn.find('\n', itemIndex) slice=string2FindIn(itemIndex:endOfSlice) sliceList.append(slice) data_dict[item]=sliceList et voila. I hope this tangent helps in some small way. I don't see any harm in a couple of nested loops, particularly when you're a n00b, like me. One day list comprehensions will stop being so damn scary, but until then, I loop like buggery. On Tue, 30 Nov 2004 16:29:54 +1300, Liam Clarke wrote: > Oh dear, Gmail is terrible to email code in. > > > > > On Tue, 30 Nov 2004 16:27:35 +1300, Liam Clarke wrote: > > Hi Brian, > > > > Just curious - > > > > > > > > >date_flag = '[Date]' > > > email_flag = '[Email]' > > > item_flags = [date_flag, email_flag] > > > > >def parse_file(list_of_lines): > > > data_dict = {} > > > for line in list_of_lines: > > > for item in item_flags: > > > if line.startswith(item): > > > data_dict[item] = line[len(item):] > > > break > > > return data_dict > > > > So, you're thingmajig scans each line for either date_flag or > > email_flag, and then slices the rest of the line and saves it as a > > dict. And, I guess you're looking for one date_flag line or one > > email_flag... > > > > Assuming that there would only be one occurrence of each one in a file - > > > > x=file('Brian's source file') 'r') > > a=x.readlines() #How big is it? If it's a huge file, this may not be the best > > x.close() > > a="".join(a) #Turns a list into a string, the "" is the joiner, i.e. > > # a=["Hello","World"] would become "HelloWorld" > > whereas a="?M?".join(a) > > #would become "Hello?M?World" > > #Just had a thought - a=str(a) would do exactly the > > same as a="".join(a) > > #wouldn't it? > > item_flags=["[Date]","[Email]"] > > > > def parsefile(fileString): > > data_dict={} > > for item in item_flags: > > tagIndex=fileString.find(item) #Finds lowest occurrence of > > item. Index is would be > > #first letter of > > item_flag[item] > > newLineIndex=fileString.find('\n', tagIndex) #Finds next > > newline after item_flag[item] > > data_dict[item]=fileString[tagIndex+len(item):newLineIndex] > > > > The slice at the end should slice from the char after the ']' of item, > > to the char before the next '\n' which is the end of the line. > > > > If there are multiple occurrences, all you have to do is - > > > > for item in item_flags: > > > > foundIndice=[] > > findIndex=0 > > startIndex=0 > > > > while findIndex ! = -1: > > findIndex=string2FindIn.find(item, startIndex) > > foundIndice.append(findIndex) > > > > del foundIndice[len(foundIndice)-1] #Delete last item, as .find > > returns "-1" for string not > > #found, and this > > will always be appended at end. > > data_dict[item]=foundIndice > > > > Of course, this is entirely subjective on personal style. > > > > > > > > > > On Mon, 29 Nov 2004 21:26:37 -0500, Brian van den Broek > > wrote: > > > Hi all, > > > > > > in a recent post in the "comapring lists" thread, Danny Yoo wrote: > > > > > > > whenever I see nested loops > > > > like this, I get nervous. *grin* > > > > > > This got me thinking about general design issues. In various programs I > > > have made much use of nested loops in order to parse data files. I've > > > done this in cases where I am interested in pulling out some data which > > > is identified by a delimiter. Below is a minimal example of the sort of > > > thing I have been doing: > > > > > > date_flag = '[Date]' > > > email_flag = '[Email]' > > > item_flags = [date_flag, email_flag] > > > > > > def parse_file(list_of_lines): > > > data_dict = {} > > > for line in list_of_lines: > > > for item in item_flags: > > > if line.startswith(item): > > > data_dict[item] = line[len(item):] > > > break > > > return data_dict > > > > > > In this particular toy case, the "for i in item_flags" isn't too much > > > help, as I've only listed two delimiters. But I often have a good many > > > more, and thus thought the nested loop much better than a long list of > > > if-tests. Since the logic in the "for item in item_flags:" loop is quite > > > small, it never occurred to be to move it into its own function. > > > > > > I think I see that the nervous-making aspect of nested loops comes from > > > concern about clarity of control flow. (Is there some other worry I'm > > > missing?) But is my sort of case one which shows a rule of thumb isn't a > > > rigid law? Is there a much better design for my task that I've missed? > > > Do more experience folk doubt my wisdom in taking the embedded loop to > > > be too short to bother factoring out? > > > > > > Thanks for any input. Best to all, > > > > > > Brian vdB > > > > > > _______________________________________________ > > > 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 bsi c human duty, to take the consequences. > > > > -- > '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. > -- '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 Nov 30 09:09:38 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 30 09:09:42 2004 Subject: [Tutor] data structures in python? In-Reply-To: Message-ID: > void point_print (point p) { > printf("(%d, %d)\n", p.x, p.y); > } Hi Jeff, Gah! I forgot to rename that from point_print() to point_println(): /******/ void point_println(point p) { printf("(%d, %d)\n", p.x, p.y); } /******/ Sorry about that; I got sloppy when reworking the example to print out something readable. *grin* Ideally, I would have rather made a function to return a string representation of the point. But correct, dynamic string manipulation in standard C is a little ugly. I guess I can make a broken example: /******/ char* point_str(point p) { char *result; asprintf(&result, "(%d, %d)", p.x, p.y); /* I should be checking for NULL here... */ return result; } int main() { point p1 = point_make(3, 4); point p2 = point_make(7, 17); printf("%s\n", point_str(p1)); /* memory leak! */ printf("%s\n", point_str(p2)); /* memory leak! */ printf("%s\n", point_str(point_add(p1, p2))); /* memory leak! */ return 0; } /******/ (To correct the C example, I should capture the result of point_str(), and free() those memory blocks afterwards, but it clogs up the clarity of the main() function.) For the Python example, we write a similar "method" that emits a nice string representation of a Point: ## Within the Point class definition ### def __str__(self): return "(%d, %d)" % (self.x, self.y) ### The name we use here, __str__, is weird, but deliberately chosen. Traditionally, we name a function that turns something in a string as '__str__()', because Python has special hooks that automatically call it in common situations. For example, although we can call it directly: ### >>> p = Point(42, 17) >>> p.__str__() '(42, 17)' ### it's much nicer to use the str() builtin, which calls '__str__' for us: ### >>> str(p) '(42, 17)' ### str() is the same function we used to get string values of numbers and lists. Now it works on our own data structures too! (At least, as long as we use "__str__" as the name of our string-making method.) Best of all, the 'print' statement will automagically call str() on anything it prints out: ### >>> print p, "is my point" (42, 17) is my point ### Hope this helps! From alan.gauld at freenet.co.uk Tue Nov 30 10:21:22 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Nov 30 10:20:55 2004 Subject: [Tutor] design question -- nested loops considered harmful? References: <41ABDA5D.40504@po-box.mcgill.ca> Message-ID: <00de01c4d6bd$f6603640$f1598651@xp> > I think I see that the nervous-making aspect of nested loops comes from > concern about clarity of control flow. Thats one aspect. The likeliehood of introducing bugs increases with the depth of indentation level. THats one of the strongest arguments for functional programming since it tends to reduce the number of levels of indentation. Its to do with control of scopes... > (Is there some other worry I'm missing?) The other big problem with nested loops specifically is performance. They look innocuous and its easy to forget that the number of times the innermost level gets executed in the product of all the loop counters: for j in range(10): for k in range(20): for m in range (5): print "this gets done 1000 times..." > But is my sort of case one which shows a rule of thumb isn't a > rigid law? There are no rigid laws just principles. So long as you understand the consequences, and their impact then you can do what you want. > Is there a much better design for my task that I've missed? A list comprehension or other FP construct such as filter() might be appropriate. > Do more experience folk doubt my wisdom in taking the embedded loop to > be too short to bother factoring out? No, a loop over two items is not likely to be a major concern, but equally a simple if test might be more appropriate. And recall that you can often use boolean operators to eliminate multiple tests: item_flags = [date_flag, email_flag] ... for line in list_of_lines: if line.startswith(date_flag) or line.startswith(email_flag): doSomething() break But in your case, since you are using the object of the test you would need to split it up anyway. But an if/elif chain would be faster than the loop and avoid the break statement (which is also a "bad thing" in a purist sense because it breaks the rules of structured programming). But if you then tidied it up by putting the if/elif in a function you would lose the speed advantage! (But you would gain a clarity advantage and reduce the indentation level) Hopefully the above paragraph hints at the multitude of compromises you have to mentally deal with in writing "good" code. (Usually complex code is a sign of complex data and you are best off looking at reformatting your data to allow a simpler design!) As a beginner it's better to just focus on getting it to work. Afterwards you can clean it up as time allows. (As a professional you should get it peer reviewed and follow whatever coding standards exist in your office...) HTH, Alan G. From bvande at po-box.mcgill.ca Tue Nov 30 10:46:56 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Nov 30 10:47:19 2004 Subject: [Tutor] design question -- nested loops considered harmful? In-Reply-To: <00de01c4d6bd$f6603640$f1598651@xp> References: <41ABDA5D.40504@po-box.mcgill.ca> <00de01c4d6bd$f6603640$f1598651@xp> Message-ID: <41AC4190.3090700@po-box.mcgill.ca> Hi all, thanks Alan, and Danny, too, for the replies. Alan Gauld said unto the world upon 2004-11-30 04:21: > Hopefully the above paragraph hints at the multitude of compromises > you have to mentally deal with in writing "good" code. (Usually > complex code is a sign of complex data and you are best off > looking at reformatting your data to allow a simpler design!) > As a beginner it's better to just focus on getting it to work. > Afterwards you can clean it up as time allows. (As a professional > you should get it peer reviewed and follow whatever coding > standards exist in your office...) Office? ROTFLMAO! I'm just a duffer having some 'hard fun' :-) I've certainly tasted some of those compromises as I stumbled towards trying to have good code. And, even though it is very much a spare time endeavour for me, I've also started to see my "style" begin to calcify a bit. Hence the concern -- unlearning bad habits is hard, but no fun at all. Thanks again to both. Best, Brian vdB From cyresse at gmail.com Tue Nov 30 11:26:03 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Nov 30 11:26:06 2004 Subject: [Tutor] Logic error / poor understanding of classes? Message-ID: Hi all, Having an issue... creating a couple of methods in a class, and hitting a strange error. def genWin(self): self.Show(0) #Get dict vals of CM's and teams as (name, team) tuple tuplesToGen=self.sortAndTuple() print 'z point' print tuplesToGen def sortAndTuple(self): listOTuples=self.cmList.items() print listOTuples print 'List presort' print self.sortSetting if self.sortSetting == 0: print 'x point' listOTuples.sort() print 'y point' print listOTuples return listOTuples elif self.sortSetting == 1: schwartzList = [ (item[1],item) for item in listOTuples ] schwartzList.sort() listOTuples = [ item[1] for item in schwartzList ] print'No, wrong' return listOTuples So this is within a class, and genWin calls sortAndTuple() to sort the list by alphabetical order of either value. So, self.sortSetting is 0, so it should sort alphabetically... this is the console output I get - [('Carla', 'ECM'), ('Dave', 'ABC') ] List presort 0 z point None So my expected list of tuples is fine, and self.sortSetting is 0, as it should be... but, what happened to 'x' point and 'y' point? And also, why is my method returning None? self.sortSetting is not 0? If I replace elif self.sortSetting == 1: with else: it runs that clause fine, so what am I doing wrong? Oh, and if I place a print self.sortSetting command in the else clause, it prints zero... So, I know what the problem is, just not why it's happening. It is generating no error message for a missing var, and I'm sure it's a quirk of classes or (more likely) my limited knowledge. Can you not return values from one method to another in a class? Or, am I missing something like passing the calling function as a parameter i.e. tuplesToGen=self.sortAndTuple(self) or should I be passing self.sortSetting as an argument? I think I'm treating it as a global variable at the moment. Regards, (a Confused) Liam Clarke -- '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 Tue Nov 30 11:48:43 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Nov 30 11:48:53 2004 Subject: [Tutor] design question -- nested loops considered harmful? In-Reply-To: References: <41ABDA5D.40504@po-box.mcgill.ca> Message-ID: <41AC500B.2020806@tds.net> Liam Clarke wrote: > x=file('Brian's source file') 'r') > a=x.readlines() #How big is it? If it's a huge file, this may not be the best > x.close() > a="".join(a) #Turns a list into a string a = x.read() is simpler > If there are multiple occurrences, all you have to do is - > > for item in item_flags: > > foundIndice=[] > findIndex=0 > startIndex=0 > > while findIndex ! = -1: > findIndex=string2FindIn.find(item, startIndex) > foundIndice.append(findIndex) > > del foundIndice[len(foundIndice)-1] #Delete last item, as .find > returns "-1" for string not > #found, and this > will always be appended at end. > data_dict[item]=foundIndice I don't like this 'fix up the list after the loop' style. I would write it like this: index= -1 while True: index=string2FindIn.find(item, index+1) if index== -1: break foundIndice.append(index) Alternatively, foundIndice.pop() or del foundIndice[-1] is an easy way to remove the last element. Kent From cyresse at gmail.com Tue Nov 30 12:05:48 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Nov 30 12:05:52 2004 Subject: [Tutor] design question -- nested loops considered harmful? In-Reply-To: <41AC500B.2020806@tds.net> References: <41ABDA5D.40504@po-box.mcgill.ca> <41AC500B.2020806@tds.net> Message-ID: Oh, -1 is the index of the last element? On Tue, 30 Nov 2004 05:48:43 -0500, Kent Johnson wrote: > Liam Clarke wrote: > > x=file('Brian's source file') 'r') > > a=x.readlines() #How big is it? If it's a huge file, this may not be the best > > x.close() > > a="".join(a) #Turns a list into a string > > a = x.read() is simpler > > > > > If there are multiple occurrences, all you have to do is - > > > > for item in item_flags: > > > > foundIndice=[] > > findIndex=0 > > startIndex=0 > > > > while findIndex ! = -1: > > findIndex=string2FindIn.find(item, startIndex) > > foundIndice.append(findIndex) > > > > del foundIndice[len(foundIndice)-1] #Delete last item, as .find > > returns "-1" for string not > > #found, and this > > will always be appended at end. > > data_dict[item]=foundIndice > > I don't like this 'fix up the list after the loop' style. I would write > it like this: > > index= -1 > while True: > index=string2FindIn.find(item, index+1) > if index== -1: > break > foundIndice.append(index) > > Alternatively, foundIndice.pop() or del foundIndice[-1] is an easy way > to remove the last element. > > Kent > _______________________________________________ > > > 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 cyresse at gmail.com Tue Nov 30 12:09:31 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Nov 30 12:09:34 2004 Subject: [Tutor] Re: Logic error / poor understanding of classes? In-Reply-To: References: Message-ID: Erm... logic error. Please disregard this post, or use it to warn others of the danger of coding while caffeine deprived. when I loaded self.sortSetting, I forgot to add int() around it... *sigh* On Tue, 30 Nov 2004 23:26:03 +1300, Liam Clarke wrote: > Hi all, > > Having an issue... creating a couple of methods in a class, and > hitting a strange error. > > def genWin(self): > self.Show(0) > > #Get dict vals of CM's and teams as (name, team) tuple > tuplesToGen=self.sortAndTuple() > print 'z point' > print tuplesToGen > > def sortAndTuple(self): > listOTuples=self.cmList.items() > print listOTuples > print 'List presort' > print self.sortSetting > > if self.sortSetting == 0: > print 'x point' > listOTuples.sort() > print 'y point' > print listOTuples > return listOTuples > > elif self.sortSetting == 1: > schwartzList = [ (item[1],item) for item in listOTuples ] > schwartzList.sort() > listOTuples = [ item[1] for item in schwartzList ] > print'No, wrong' > return listOTuples > > So this is within a class, and genWin calls sortAndTuple() to sort the > list by alphabetical order of either value. > > So, self.sortSetting is 0, so it should sort alphabetically... this is > the console output I get - > > [('Carla', 'ECM'), ('Dave', 'ABC') ] > List presort > 0 > z point > None > > So my expected list of tuples is fine, and self.sortSetting is 0, as > it should be... > > but, what happened to 'x' point and 'y' point? And also, why is my > method returning None? > self.sortSetting is not 0? > > If I replace > > elif self.sortSetting == 1: > > with else: > > it runs that clause fine, so what am I doing wrong? Oh, and if I place a > print self.sortSetting command in the else clause, it prints zero... > > So, I know what the problem is, just not why it's happening. > It is generating no error message for a missing var, and I'm sure > it's a quirk of classes or (more likely) my limited knowledge. > > Can you not return values from one method to another in a class? Or, > am I missing something like passing the calling function as a > parameter i.e. > > tuplesToGen=self.sortAndTuple(self) > > or should I be passing self.sortSetting as an argument? I think I'm > treating it as a global variable at the moment. > > Regards, > > (a Confused) Liam Clarke > -- > '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. > -- '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 alan.gauld at freenet.co.uk Tue Nov 30 12:58:03 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Nov 30 12:57:25 2004 Subject: [Tutor] Logic error / poor understanding of classes? References: Message-ID: <010201c4d6d3$d918c820$f1598651@xp> > def sortAndTuple(self): > listOTuples=self.cmList.items() > print listOTuples > print 'List presort' > print self.sortSetting > > if self.sortSetting == 0: > elif self.sortSetting == 1: > > [('Carla', 'ECM'), ('Dave', 'ABC') ] > List presort > 0 > z point > None > > So my expected list of tuples is fine, and self.sortSetting is 0, as > it should be... Are you sure? It looks to me like sortSetting might be '0' - a string - and so neither of the two clauses in the function get called and it therefore returns the default value of None.... Just a guess though... Try running it in the debugger and steping through the code with a watch on sortSetting to check its value (and type!). This is the kind of problem debuggers are designed for :-) Alan G. From kent37 at tds.net Tue Nov 30 13:36:22 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Nov 30 13:37:02 2004 Subject: [Tutor] design question -- nested loops considered harmful? In-Reply-To: References: <41ABDA5D.40504@po-box.mcgill.ca> <41AC500B.2020806@tds.net> Message-ID: <41AC6946.20707@tds.net> Yes, any negative indices are counted from the end. One way to remember is to think of s[-x] as a shorthand for s[len(s)-x]. You can use negative indices in slices, too: >>> s='hello >>> s[-1] 'o' >>> s[-2] 'l' >>> s[1:-1] 'ell' >>> s[-3:-1] 'll' Kent Liam Clarke wrote: > Oh, -1 is the index of the last element? > > > > On Tue, 30 Nov 2004 05:48:43 -0500, Kent Johnson wrote: > >>Liam Clarke wrote: >> >>>x=file('Brian's source file') 'r') >>>a=x.readlines() #How big is it? If it's a huge file, this may not be the best >>>x.close() >>>a="".join(a) #Turns a list into a string >> >>a = x.read() is simpler >> >> >> >> >>>If there are multiple occurrences, all you have to do is - >>> >>>for item in item_flags: >>> >>> foundIndice=[] >>> findIndex=0 >>> startIndex=0 >>> >>> while findIndex ! = -1: >>> findIndex=string2FindIn.find(item, startIndex) >>> foundIndice.append(findIndex) >>> >>> del foundIndice[len(foundIndice)-1] #Delete last item, as .find >>>returns "-1" for string not >>> #found, and this >>>will always be appended at end. >>> data_dict[item]=foundIndice >> >>I don't like this 'fix up the list after the loop' style. I would write >>it like this: >> >> index= -1 >> while True: >> index=string2FindIn.find(item, index+1) >> if index== -1: >> break >> foundIndice.append(index) >> >>Alternatively, foundIndice.pop() or del foundIndice[-1] is an easy way >>to remove the last element. >> >>Kent >>_______________________________________________ >> >> >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > From bwinton at latte.ca Tue Nov 30 14:56:47 2004 From: bwinton at latte.ca (Blake Winton) Date: Tue Nov 30 14:56:58 2004 Subject: [Tutor] design question -- nested loops considered harmful? In-Reply-To: <00de01c4d6bd$f6603640$f1598651@xp> References: <41ABDA5D.40504@po-box.mcgill.ca> <00de01c4d6bd$f6603640$f1598651@xp> Message-ID: <41AC7C1F.2040105@latte.ca> Alan Gauld wrote: > No, a loop over two items is not likely to be a major concern, > but equally a simple if test might be more appropriate. And > recall that you can often use boolean operators to eliminate > multiple tests: > > item_flags = [date_flag, email_flag] > ... > for line in list_of_lines: > if line.startswith(date_flag) or line.startswith(email_flag): > doSomething() > break Of course, that only handles the case of testing for two flags. For a more general case (and because I wanted to play around with reduce a little), I give you the following: import operator prefixes = ["aaa", "bbb"] lines = ["abc","def","bbbdec", "ccc"] for line in lines: print line, reduce( operator.or_, [line.startswith(x) for x in prefixes] ) abc False def False bbbdec True ccc False or, more like your code: for line in list_of_lines: if reduce( operator.or_, [line.startswith(flag) for flag in flags] ) : doSomething() break (If anyone wants a description of what I'm doing there, please email me, and I'll be more than happy to describe it in more detail.) Later, Blake. From ARobert at MFS.com Tue Nov 30 17:05:57 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Tue Nov 30 17:06:17 2004 Subject: [Tutor] The case of the missing close Message-ID: <968452DD78695147AA4A369C3DF9E40A01F942DF@BOSMAILBOX3.corp.mfs.com> Hi everyone, I am trying to create a generic db_utils.py module that I will then generically import into programs as needed. The first function I am trying to implement iis to generically open an Oracle database connection based on passed database/authentication parameters. So far, I have been able to: - import the custom module db_utils - pass the parameters function dbopen in the custom module - open the connection to the requested database - pass back the cursor object to the calling program for later processing. The problem is in closing the connection. No matter what I try, I receive an error stating that the name is not defined. I receive an error such as: Traceback (most recent call last): File "M:\My Documents\python_code\oracle\maestrodev_oracle_connector.py", line 55, in ? db_utils.close() AttributeError: 'module' object has no attribute 'close' Does anyone have any ideas on how to properly close the connection? The db_utils module code is a rather short def dbopen(db,uname,passwd): # # Import required system modules needed specifically for function # import cx_Oracle # # Connect to remote database # connection = cx_Oracle.connect(dsn=db,user=uname,password=passwd) # # Return cursor object to calling program # return(connection.cursor()) The code that calls the db_utils module is #!c:\Python23\python # # File name: maestrodev_oracle_connector.py # Author: Andrew Robert # Date: 11/26/04 # # # Modification History # # Version Programmer Description # 1.0 AAR Creation # 1.1 AAR Shift database opens to called module # 1.2 AAR Fixed database link close - now works # # # Note on modules # # The imported db_utils module was designed by AAR to make standard database # routines available to all python programs as callable functions. # # Called functions are prefaced with the module name and then the function # within the module. # import sys,db_utils # # Make connection to Oracle development database and assign to object # print 'Establishing connection to remote database\n' cursobj = db_utils.dbopen('test_d','FOO','foo') # # Formulate sample querry # cursobj.execute('SELECT userid, name, role, desk_phone, pager FROM contacts') # # Extract querry results # results=cursobj.fetchall() for row in results: print row # # Break connection to Oracle development database # print '\n\n\nDisconnecting from remote database' db_utils.close() raw_input("\n\n\t\tPress Enter To Continue") Any help you can provide on this would be greatly appreciated. Thank you, Andrew Robert Systems Architect Information Technology Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 "MFS Relay Service" made the following annotations on 11/30/2004 11:11:35 AM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From rdm at rcblue.com Tue Nov 30 19:44:20 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Nov 30 19:44:25 2004 Subject: [Tutor] Python 2.4 final has been released! Message-ID: <6.1.2.0.2.20041130104327.04959300@rcblue.com> http://www.python.org/2.4/ Dick Moores From Richard_Moor at msn.com Tue Nov 30 20:50:40 2004 From: Richard_Moor at msn.com (Richard Moor) Date: Tue Nov 30 20:51:05 2004 Subject: [Tutor] Tutor Subscribers list. Message-ID: I entered my address(Rich624) my password(194224) and my e-mail address and get Tutor roster error. What am I doing wrong? Help RM. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041130/754d2c42/attachment.htm From jeffpeery at yahoo.com Tue Nov 30 20:51:46 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue Nov 30 20:51:49 2004 Subject: [Tutor] how to check if a file is being used by another person or application before writing to it? Message-ID: <20041130195146.8537.qmail@web60107.mail.yahoo.com> hello, I need to read/write from/to a file although I do not want to read/write a file that is being used by another person or application. is there a way to check if a file is already open by another person? this way I could use some sort of clock to periodically check if a specific file is open and when it isn't open then I could do what I need to it. similarly is there a way to check if a file has been written to? I suppose I would do something like periodically check the size of a particular file and if it increased then I would know it was written to. I didn't see anything in the python documentation for geting the size of a file. how is this normally performed? thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041130/00321dd9/attachment-0001.html From alan.gauld at freenet.co.uk Tue Nov 30 21:37:05 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Nov 30 21:36:25 2004 Subject: [Tutor] design question -- nested loops considered harmful? References: <41ABDA5D.40504@po-box.mcgill.ca><00de01c4d6bd$f6603640$f1598651@xp> <41AC7C1F.2040105@latte.ca> Message-ID: <012901c4d71c$5b795170$f1598651@xp> > or, more like your code: > for line in list_of_lines: > if reduce( operator.or_, [line.startswith(flag) for flag in flags] ) : > doSomething() > break While this does reduce the indentation levels and therefore the theoretical complexity, it introduces two implicit nested loops which will hit performance: both reduce and the list comprehension iterate over their respective lists. Which once again shows the careful thought and selection of which compromises are important - clarity and brevity and possibly reliability vv performance in this case. Alan G. From alan.gauld at freenet.co.uk Tue Nov 30 22:08:56 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Nov 30 22:08:18 2004 Subject: [Tutor] Tutor Subscribers list. References: Message-ID: <014b01c4d720$ce089210$f1598651@xp> > I entered my address(Rich624) my password(194224) > and my e-mail address and get Tutor roster error. > What am I doing wrong? Telling us your password?!! More seriously I don't know, I've never had a roster error and am not getting one just now. Have you tried again since? Alan G. From dyoo at hkn.eecs.berkeley.edu Tue Nov 30 22:15:46 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 30 22:15:53 2004 Subject: [Tutor] Tutor Subscribers list. In-Reply-To: Message-ID: On Tue, 30 Nov 2004, Richard Moor wrote: > I entered my address [personal information cut] > and get Tutor roster error. What am I doing wrong? Help RM. [meta: mailing list administration] Hi Richard, Ok, I think I see the problem; it's a user interface issue. I'm guessing that you are viewing: http://mail.python.org/mailman/listinfo/tutor and that you're looking at the last three text fields on that web page. To view the roster list, you just need to put in your email address in the "Address" field, and your password in the "Password" field. Afterwards, press the "Visit Subscriber List" button. So ignore the last text box: it is supposed to be a separate form that people use to unsubscribe from the list. It is not part of the roster viewing process, although it's physically on the same page. Our mailing list software does need a good human-interface design review, but we don't have the resources for that at the moment. By the way, you've just announced your mailing list password to the whole mailing list. This is not a good idea, as the list is actively archived. Please change it when you get the chance. Good luck to you. From dyoo at hkn.eecs.berkeley.edu Tue Nov 30 22:42:17 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 30 22:42:21 2004 Subject: [Tutor] how to check if a file is being used by another person or application before writing to it? In-Reply-To: <20041130195146.8537.qmail@web60107.mail.yahoo.com> Message-ID: On Tue, 30 Nov 2004, Jeff Peery wrote: > I need to read/write from/to a file although I do not want to read/write > a file that is being used by another person or application. Hi Jeff, The concept of a file "lock" should do the trick. See: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 The idea is to have one person "lock" the file when they open it. This prevents other people from opening the same file, as long as they check the lock first. The caveat is that this kind of locking has to be done intentionally: if one person forgets to check the lock, the whole scheme falls apart. > is there a way to check if a file is already open by another person? > this way I could use some sort of clock to periodically check if a > specific file is open and when it isn't open then I could do what I need > to it. > similarly is there a way to check if a file has been written to? One alternative is to make some kind of 'signature' of a file. This signature can be a function of the file's content. Take a signature at one time point, and another at a later time, and if the signatures don't match, the file was definitely munged. The 'md5' module might be useful for generating these file signatures: http://www.python.org/doc/lib/module-md5.html > I suppose I would do something like periodically check the size of a > particular file and if it increased then I would know it was written to. > I didn't see anything in the python documentation for geting the size of > a file. The 'os.stat()' function should do the trick: http://www.python.org/doc/lib/os-file-dir.html#l2h-1457 For example, on my Linux system, my /etc/passwd file is 1919 bytes: ### [dyoo@shoebox dyoo]$ ls -l /etc/passwd -rw-r--r-- 1 root root 1919 Oct 22 16:51 /etc/passwd ### and we get the same number from os.stat() in Python: ### >>> os.stat('/etc/passwd').st_size 1919L ### Hope this helps! From alan.gauld at freenet.co.uk Tue Nov 30 23:05:29 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Nov 30 23:04:44 2004 Subject: [Tutor] how to check if a file is being used by another person orapplication before writing to it? References: <20041130195146.8537.qmail@web60107.mail.yahoo.com> Message-ID: <015901c4d728$b4b48690$f1598651@xp> > I need to read/write from/to a file although I do not want > to read/write a file that is being used by another person This is very dependant on the operating system. For example CP/M used to tell you if a file was locked for read or for write(one of CP/Ms few good features!), whereas ISTR Unix only tells you its locked for writing - indeed it may not lock the file at all for reads. I suspect Microsoft will do the same but I've never tried... One approach is to read the access time (see below) and compare with now, but that's hardly an exact science! > similarly is there a way to check if a file has been written to? This is easier since both Unix and Windows provide access to the modification time. This is better than checking size since a modification could change two bytes say without changing the file size. Look in the os.stat() function docs and at the path.getmtime() function. The stat() function also returns the access time which tells you when the file was last read or executed. Unfortunately it doesn't tell you if the file is still being accessed! The usual approach in my experience is to open for write and check for IOErrors. If no error then go ahead and write and rely on the other program (if there is one) to either refuse to update the file after a change or to warn the user (this is what vi does). Its not very satisfactory and I look forward to anyone else providing a better answer on this one! HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jeffpeery at yahoo.com Tue Nov 30 23:04:45 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue Nov 30 23:04:48 2004 Subject: [Tutor] (no subject) Message-ID: <20041130220445.13168.qmail@web60108.mail.yahoo.com> hello again, I am thoroughly confused. I am using Timer from the threading module. I want to check a specific file every few minutes to see if it has been altered (I do this by checking the size of the file using stat) if it hasn't then I do nothing, if it has then I attempt to read the file, grab all the new numerical data and update a graph on my computer. this file I am reading holds liquid volumetric flow rate measurement data and the python code I am writing is to be used as a statistical process control. basically I watch the results from the measurements by watching a particular file for updates, when an update occurs I grab the data do some more stats, then update my graphs that show on my desktop. the timer I used is a class, so I defined a new object (I think thats the right word) as: myTimer = Timer(30.0, Update) where the timer runs every 30 seconds and Update is a function that checks if the file has been altered and if so then it updates my graphs. I then start the timer: myTimer.start() I am confused by two things: 1) I want my timer to restart every 30 seconds. as it shows above it will go just one time. If I put this in a while loop, will the while loop loop through the start command faster than 30 second intervals or will it wait for the timer to execute the Update function before calling timer.start() again? 2) I am also confused about how variables are handled when I have multiple and nested functions. for example, I would like to initiate the Update function every 30 seconds and I want the Update funtion to return any new data. how can I return something from a function when the function is called from a timer? I cannot do an assignment statement from within the definnition of myTimer? or do I even need to return the data? if I create a variable in the update function is it available in my main function? I am not sure how python handles variables that are defined in different functions. thank you very much for spending the time to help me, I appreciate it! Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041130/77cfdb8b/attachment.html From amonroe at columbus.rr.com Tue Nov 30 23:53:27 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Nov 30 23:53:48 2004 Subject: [Tutor] how to check if a file is being used by another person or application before writing to it? In-Reply-To: <20041130195146.8537.qmail@web60107.mail.yahoo.com> References: <20041130195146.8537.qmail@web60107.mail.yahoo.com> Message-ID: <69123920237.20041130175327@columbus.rr.com> > similarly is there a way to check if a file has been written to? I One way would be the last modified date. Check out os.path.getmtime() > suppose I would do something like periodically check the size of a > particular file and if it increased then I would know it was written This is probably less reliable than the date, but os.path.getsize() will tell you the file size. Alan From cyresse at gmail.com Tue Nov 30 23:58:47 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Nov 30 23:58:56 2004 Subject: [Tutor] (no subject) In-Reply-To: <20041130220445.13168.qmail@web60108.mail.yahoo.com> References: <20041130220445.13168.qmail@web60108.mail.yahoo.com> Message-ID: Hi, Do you need to use the threading module? Or are you using solely the timer? You could do a - import time while 1: time.sleep(30) dataBack=update() if dataBack: #process data That would be an infinite loop, and would rely on update returning None or similar if no update had occurred. I hope that helps in a small way. Regards, Liam Clarke On Tue, 30 Nov 2004 14:04:45 -0800 (PST), Jeff Peery wrote: > > hello again, > > I am thoroughly confused. I am using Timer from the threading module. I want > to check a specific file every few minutes to see if it has been altered (I > do this by checking the size of the file using stat) if it hasn't then I do > nothing, if it has then I attempt to read the file, grab all the new > numerical data and update a graph on my computer. > > this file I am reading holds liquid volumetric flow rate measurement data > and the python code I am writing is to be used as a statistical process > control. basically I watch the results from the measurements by watching a > particular file for updates, when an update occurs I grab the data do some > more stats, then update my graphs that show on my desktop. > > the timer I used is a class, so I defined a new object (I think thats the > right word) as: > > myTimer = Timer(30.0, Update) > > where the timer runs every 30 seconds and Update is a function that checks > if the file has been altered and if so then it updates my graphs. I then > start the timer: > > myTimer.start() > > I am confused by two things: > 1) I want my timer to restart every 30 seconds. as it shows above it will go > just one time. If I put this in a while loop, will the while loop loop > through the start command faster than 30 second intervals or will it wait > for the timer to execute the Update function before calling timer.start() > again? > 2) I am also confused about how variables are handled when I have multiple > and nested functions. for example, I would like to initiate the Update > function every 30 seconds and I want the Update funtion to return any new > data. how can I return something from a function when the function is called > from a timer? I cannot do an assignment statement from within the > definnition of myTimer? or do I even need to return the data? if I create a > variable in the update function is it available in my main function? I am > not sure how python handles variables that are defined in different > functions. > > thank you very much for spending the time to help me, I appreciate it! > > Jeff > _______________________________________________ > 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 hugonz-lists at h-lab.net Tue Nov 30 20:59:23 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed Dec 1 01:46:36 2004 Subject: [Tutor] The case of the missing close In-Reply-To: <968452DD78695147AA4A369C3DF9E40A01F942DF@BOSMAILBOX3.corp.mfs.com> References: <968452DD78695147AA4A369C3DF9E40A01F942DF@BOSMAILBOX3.corp.mfs.com> Message-ID: <41ACD11B.1060002@h-lab.net> Hi Andrew, The error you're getting has nothing to do aith a connection, it simply reports that the db_utils module does not have a close method. I'm thinking perhaps what you want to do is cursobj.close() As you instantiated a connection before, you should call that instance's "close" method. Please let me know if maybe I'm misunderstanding it... Hugo Robert, Andrew wrote: > Hi everyone, > > I am trying to create a generic db_utils.py module that I will then > generically import into programs as needed. > > The first function I am trying to implement iis to generically open an > Oracle database connection based on passed database/authentication > parameters. > > So far, I have been able to: > > - import the custom module db_utils > - pass the parameters function dbopen in the custom module > - open the connection to the requested database > - pass back the cursor object to the calling program for later > processing. > > The problem is in closing the connection. > > No matter what I try, I receive an error stating that the name is not > defined. > > I receive an error such as: > > Traceback (most recent call last): > File "M:\My > Documents\python_code\oracle\maestrodev_oracle_connector.py", line 55, > in ? > db_utils.close() > AttributeError: 'module' object has no attribute 'close' > > Does anyone have any ideas on how to properly close the connection? > > > > The db_utils module code is a rather short > > > def dbopen(db,uname,passwd): > # > # Import required system modules needed specifically for function > # > import cx_Oracle > > # > # Connect to remote database > # > connection = cx_Oracle.connect(dsn=db,user=uname,password=passwd) > > # > # Return cursor object to calling program > # > return(connection.cursor()) > > > The code that calls the db_utils module is > > #!c:\Python23\python > # > # File name: maestrodev_oracle_connector.py > # Author: Andrew Robert > # Date: 11/26/04 > # > # > # Modification History > # > # Version Programmer Description > # 1.0 AAR Creation > # 1.1 AAR Shift database opens to called > module > # 1.2 AAR Fixed database link close - now > works > # > # > # Note on modules > # > # The imported db_utils module was designed by AAR to make standard > database > # routines available to all python programs as callable functions. > # > # Called functions are prefaced with the module name and then the > function > # within the module. > # > > > import sys,db_utils > > # > # Make connection to Oracle development database and assign to object > # > > print 'Establishing connection to remote database\n' > cursobj = db_utils.dbopen('test_d','FOO','foo') > > # > # Formulate sample querry > # > cursobj.execute('SELECT userid, name, role, desk_phone, pager FROM > contacts') > > # > # Extract querry results > # > results=cursobj.fetchall() > > for row in results: > print row > > # > # Break connection to Oracle development database > # > print '\n\n\nDisconnecting from remote database' > > db_utils.close() > > raw_input("\n\n\t\tPress Enter To Continue") > > > Any help you can provide on this would be greatly appreciated. > > > > > Thank you, > Andrew Robert > Systems Architect > Information Technology > Massachusetts Financial Services > Phone: 617-954-5882 > Pager: 781-764-7321 > E-mail: arobert@mfs.com > Linux User Number: #201204 > > > "MFS Relay Service" made the following > annotations on 11/30/2004 11:11:35 AM > ------------------------------------------------------------------------------ > This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. > ============================================================================== > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor >