From phthenry@earthlink.net Sat Mar 1 03:00:02 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Sat Mar 1 03:00:02 2003 Subject: [Tutor] script still too slow In-Reply-To: <19614998877.20030228221412@rambler.ru> References: <20030227105905.D13858@localhost.localdomain> <3E5E6985.30700@ccvcorp.com> <19614998877.20030228221412@rambler.ru> Message-ID: <20030301025945.K13858@localhost.localdomain> On Fri, Feb 28, 2003 at 10:14:12PM +0300, antonmuhin at rambler.ru wrote: > 1. Psyco. > 2. mxTexttools > > Both of them are rumored to be real accelerators. And even Python2.3 > might be of help as they say that every version of Python is faster. As a matter of fact, I have mxTexttools installed. However, it is pretty difficult to figure out how to use. The author wrote a small demonstration script that actually converts RTF into tokens. However, I couldn't get this script to work on large files, probably because the tokens are stored in a dictionary, and I don't have enough memory (?). In the future, I may try to figure out mxTexttools, since it might shave from 5 to 10 percent off the time the script takes. On the other hand, I have already written a kind of hack that uses perl to form the tokens. Forming the tokens is a very small part of the code--perhaps has little as 30 lines, or less than one percent. I have written the script so that when the user installs and configures it, s/he has the option of using perl to tokenize. I am guessing that since 90 percent of users who have Python installed have perl installed, this doesn't seem like such a bad idea. I have read that even C++ programs that rely on regular expressions use perl. I don't know how true this is. Perl is probably as fast or faster than mxTexttools. I don't say this from personal experience, but from looking at comparison charts between languages. But certainly perl is much, much easier to figure out than mxTexttools! I don't know what Psyco is. I'll have to google it and see. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From phthenry@earthlink.net Sat Mar 1 04:12:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Sat Mar 1 04:12:01 2003 Subject: [Tutor] script too slow Message-ID: <20030301041137.L13858@localhost.localdomain> Thanks everyone for your help. I re-wrote the script using the suggestions of several people. I put a snippet of the code at the bottom. The old script took 1 minutes and 30 seconds to run. The new one takes 57 seconds. That is a dramatic improvement. Remember my fear was that the Python version would run 300 percent slower than the perl one. However, this is how things are shaping up: tokenze: perl => 7 seconds python => 22 seconds (Wow! perl really is fast here.) processing tokens: perl => 27 seconds Python => 36 (Pyton might be faster in other areas later on.) So Python is 40 percent slower in the second phase. I'm not saying this is in any way a benchmark. However, at this point I am getting the script to run 40 percent slower. I can live with that. That means a 2 minutes in perl *might* take less than 3 in Python. Before I was looking at 6 minutes ********************************************************* # rewritten script uses dictionaries as 'case' statements # This replaces the multiple if elif statements # The resulting code is amazing simple and clean def initiate_dict(self): self.dict_token = { '*' : ('*', self.default_func), ':' : (':', self.default_func), '{' : ('{', self.ob_func), '}' : ('}', self.cb_func), # ect hundreds of lines of dictionary entries } def process_cw(self, token): # some minor preliminary stuff for small exceptions token, action = self.dict_token.get(token, (None, None)) if action: to_print = action(token, num) return to_print def process_tokens(self): # open file and read one token at a time... ... if token[0:1] == "\\": line = self.process_cw(token) if line != None: write_obj.write(line) else: line = 'tx Would I gain a speed increase by using fixed fields rather than variable length ones? I am writing a script that converts Microsoft RTF to XML. The first stage breaks the file into tokens and puts one token on a line: obtruetruetrue" because all "<" and ">" have been converted to "<" and ">" I will make several passes through this file to convert the data. Each time I read a line, I will use the string method, and sometimes the split method: if line[12:23] == 'font-table': info = [12:23] list = info.split(">") if list[1] == 'true': # do something If I use fixed length fields, then I won't have to do any splitting. I also know that in perl, there is a way to use 'pack' and 'unpack' to quickly access fixed fields. I have never used this, and don't know if the pack in Python is similar. If fix fields did give me a speed increase, I would certainly suffer from readibility. For example, the above 4 lines of tokens might look like: opbr:null:null:null:0001 ctrw:null:null:true:rtfx ctrw:null:null:true:mact ctrw:null:null:true:fntb Instead of 'macintosh', I have 'mact'; instead of 'font-table', I have 'fntb'. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From antonmuhin at rambler.ru" References: <20030301041137.L13858@localhost.localdomain> Message-ID: <1354505678.20030301125615@rambler.ru> Hello Paul, Disclaimer: everywhere I write 'faster' or 'slower' I mean that it is faster in my environment (ActiveState Python2.2 on WinXP) and in my toy examples :) Saturday, March 1, 2003, 12:11:37 PM, you wrote: PT> ********************************************************* PT> # rewritten script uses dictionaries as 'case' statements PT> # This replaces the multiple if elif statements PT> # The resulting code is amazing simple and clean PT> def initiate_dict(self): PT> self.dict_token = PT> { PT> '*' : ('*', self.default_func), PT> ':' : (':', self.default_func), PT> '{' : ('{', self.ob_func), PT> '}' : ('}', self.cb_func), PT> # ect hundreds of lines of dictionary entries PT> } Sorry for repeating, but still: playing around with your previous snippet I tried to use dictionaries instead of if-elif-else (I do really like dictionaries for this kind of things). Surprisingly it was slower! Therefore, I'd sugegst you to clock both variants and to find out which one is fatser. PT> def process_cw(self, token): PT> # some minor preliminary stuff for small exceptions PT> token, action = self.dict_token.get(token, (None, None)) PT> if action: PT> to_print = action(token, num) PT> return to_print Two last lines can be written as return action(token, num) And it might be faster. Maybe this function can be boosted a little bit more: def process_cw(self, token): # some minor preliminary stuff for small exceptions action = self.dict_token.get(token) if action: return action[1](action[0], num) At least ActiveState Python 2.2 on WinXP favors idiom: el = d.get(key) if el: # do something with el[1] over _, x = d.get(key, (None, None)) if x: # do something with x It might be because of tuple pack/unpack And the last note: self.dict_token.get should take some valuable time. You might be better with passing self.dict_token.get in all the functions as a parameter PT> def process_tokens(self): PT> # open file and read one token at a time... PT> ... PT> if token[0:1] == "\\": PT> line = self.process_cw(token) PT> if line != None: PT> write_obj.write(line) token[0] seems to be a little bit faster. PT> else: PT> line = 'tx write_obj.write(line) 'tx # can I do: PT> # write_obj.write('tx # probably--will have to try You should be able and I suppose it to be faster too. -- Best regards, anton mailto:antonmuhin@rambler.ru From antonmuhin at rambler.ru" References: <20030301042742.M13858@localhost.localdomain> Message-ID: <195271900.20030301130901@rambler.ru> Hello Paul, Saturday, March 1, 2003, 12:27:42 PM, you wrote: PT> Would I gain a speed increase by using fixed fields rather than variable PT> length ones? PT> I am writing a script that converts Microsoft RTF to XML. The first PT> stage breaks the file into tokens and puts one token on a line: PT> ob cwtrue cwtrue cwtrue (Fields delimited with "<" and ">" because all "<" and ">" have PT> been converted to "<" and ">" PT> I will make several passes through this file to convert the data. PT> Each time I read a line, I will use the string method, and sometimes the PT> split method: PT> if line[12:23] == 'font-table': PT> info = [12:23] PT> list = info.split(">") PT> if list[1] == 'true': PT> # do something PT> If I use fixed length fields, then I won't have to do any splitting. I PT> also know that in perl, there is a way to use 'pack' and 'unpack' to PT> quickly access fixed fields. I have never used this, and don't know if PT> the pack in Python is similar. PT> If fix fields did give me a speed increase, I would certainly suffer PT> from readibility. For example, the above 4 lines of tokens might look PT> like: PT> opbr:null:null:null:0001 PT> ctrw:null:null:true:rtfx PT> ctrw:null:null:true:mact PT> ctrw:null:null:true:fntb PT> Instead of 'macintosh', I have 'mact'; instead of 'font-table', I have PT> 'fntb'. PT> Thanks PT> Paul There might be another source of your Python script poor performance, although I'm not sure and gurus might correct me. Slicing operations on string in Python seems to be rather expensive for strings are immutable: line[12:23], if I understand it right, should create new temporal string on heap, comapre it to the constant and lately gc it. You may use array module if you use a lot of slicing. struct module might be of interest for you too. Another source of improvment might be to use generatots instead of lists. -- Best regards, anton mailto:antonmuhin@rambler.ru From Janssen@rz.uni-frankfurt.de Sat Mar 1 07:58:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Mar 1 07:58:01 2003 Subject: [Tutor] fixed or variable length fields? In-Reply-To: <20030301042742.M13858@localhost.localdomain> Message-ID: On Sat, 1 Mar 2003, Paul Tremblay wrote: > ob cwtrue cwtrue cwtrue > (Fields delimited with "<" and ">" because all "<" and ">" have > been converted to "<" and ">" > > I will make several passes through this file to convert the data. > > Each time I read a line, I will use the string method, and sometimes the > split method: > > if line[12:23] == 'font-table': > info = [12:23] > list = info.split(">") > if list[1] == 'true': > # do something > > If I use fixed length fields, then I won't have to do any splitting. I > also know that in perl, there is a way to use 'pack' and 'unpack' to > quickly access fixed fields. I have never used this, and don't know if > the pack in Python is similar. > > If fix fields did give me a speed increase, I would certainly suffer > from readibility. For example, the above 4 lines of tokens might look > like: > > opbr:null:null:null:0001 > ctrw:null:null:true:rtfx > ctrw:null:null:true:mact > ctrw:null:null:true:fntb > > Instead of 'macintosh', I have 'mact'; instead of 'font-table', I have > 'fntb'. > > Thanks > > Paul > > -- > > ************************ > *Paul Tremblay * > *phthenry@earthlink.net* > ************************ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From borelan@wanadoo.fr Sat Mar 1 09:40:01 2003 From: borelan@wanadoo.fr (D2) Date: Sat Mar 1 09:40:01 2003 Subject: [Tutor] A tutorial on how to use regexp in python Message-ID: <3E60C5F1.8060301@wanadoo.fr> Hi, I'm searching a tutorial (as exhaustive as possible :), on regexp in Pyth= on. TIA Andr=E9 From phthenry@earthlink.net Sat Mar 1 11:09:02 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Sat Mar 1 11:09:02 2003 Subject: [Tutor] script too slow In-Reply-To: <1354505678.20030301125615@rambler.ru> References: <20030301041137.L13858@localhost.localdomain> <1354505678.20030301125615@rambler.ru> Message-ID: <20030301110821.N13858@localhost.localdomain> On Sat, Mar 01, 2003 at 12:56:15PM +0300, antonmuhin at rambler.ru wrote: > > Disclaimer: everywhere I write 'faster' or 'slower' I mean that it is > faster in my environment (ActiveState Python2.2 on WinXP) and in my > toy examples :) > Yes, absolutely! > Saturday, March 1, 2003, 12:11:37 PM, you wrote: > > PT> ********************************************************* > > > PT> # rewritten script uses dictionaries as 'case' statements > PT> # This replaces the multiple if elif statements > PT> # The resulting code is amazing simple and clean > > PT> def initiate_dict(self): > PT> self.dict_token = > PT> { > > PT> '*' : ('*', self.default_func), > PT> ':' : (':', self.default_func), > PT> '{' : ('{', self.ob_func), > PT> '}' : ('}', self.cb_func), > PT> # ect hundreds of lines of dictionary entries > PT> } > Sorry for repeating, but still: playing around with your previous > snippet I tried to use dictionaries instead of if-elif-else (I do > really like dictionaries for this kind of things). Surprisingly it was > slower! Therefore, I'd sugegst you to clock both variants and to > find out which one is fatser. > Hmm. Overall, my the second part of my module ran about 3 times faster when I used dictionaries rather than elif. However, I changed several things at once, so I guess I would have to change just one part of my code and test it. > PT> def process_cw(self, token): > PT> # some minor preliminary stuff for small exceptions > > PT> token, action = self.dict_token.get(token, (None, None)) > > > PT> if action: > PT> to_print = action(token, num) > PT> return to_print > Two last lines can be written as > > return action(token, num) > > And it might be faster. > > Maybe this function can be boosted a little bit more: > > def process_cw(self, token): > # some minor preliminary stuff for small exceptions > > action = self.dict_token.get(token) > if action: > return action[1](action[0], num) > > At least ActiveState Python 2.2 on WinXP favors idiom: > el = d.get(key) > if el: > # do something with el[1] > > over > > _, x = d.get(key, (None, None)) > if x: > # do something with x > > It might be because of tuple pack/unpack > > And the last note: self.dict_token.get should take some valuable time. > You might be better with passing self.dict_token.get in all the > functions as a parameter This suggestion confuses me. So far as I can tell, I'm using the lookup only in one function, when I have to. Each token gets only one lookup if it starts with a "\\". Can you give me an example? > > PT> def process_tokens(self): > PT> # open file and read one token at a time... > PT> ... > PT> if token[0:1] == "\\": > PT> line = self.process_cw(token) > PT> if line != None: > PT> write_obj.write(line) > token[0] seems to be a little bit faster. > > PT> else: > PT> line = 'tx PT> write_obj.write(line) > 'tx you may factor out appending '\n' to all the lines in caller that > might save some more time too, especially if you'll use something like > join or print. > > PT> # can I do: > PT> # write_obj.write('tx PT> # probably--will have to try > You should be able and I suppose it to be faster too. I'll try these suggestions. Thanks! Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From glingl@aon.at Sat Mar 1 11:34:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Sat Mar 1 11:34:01 2003 Subject: [Tutor] A tutorial on how to use regexp in python References: <3E60C5F1.8060301@wanadoo.fr> Message-ID: <3E60E102.4030709@aon.at> D2 schrieb: > Hi, > > I'm searching a tutorial (as exhaustive as possible :), on regexp in > Python. http://www.amk.ca/python/howto/regex/ also as pdf-document available: http://www.amk.ca/files/howto/regex.pdf HTH, Gregor From antonmuhin at rambler.ru" References: <20030301041137.L13858@localhost.localdomain> <1354505678.20030301125615@rambler.ru> <20030301110821.N13858@localhost.localdomain> Message-ID: <14524632850.20030301202115@rambler.ru> Hello Paul, Saturday, March 1, 2003, 7:08:21 PM, you wrote: PT> Hmm. Overall, my the second part of my module ran about 3 times faster PT> when I used dictionaries rather than elif. However, I changed several PT> things at once, so I guess I would have to change just one part of my PT> code and test it. It might depend on amount of if-elif-else parts. >> And the last note: self.dict_token.get should take some valuable time. >> You might be better with passing self.dict_token.get in all the >> functions as a parameter PT> This suggestion confuses me. So far as I can tell, I'm using the lookup PT> only in one function, when I have to. Each token gets only one lookup if PT> it starts with a "\\". Can you give me an example? If I understand it correctly, self.dict_token.get is resolved each time you call the function. It takes two lookups and might be expensive. Alternative approach might be to store self.dict_token.get as a bound method and call it than needed. Here comes a simple example of the technic: d = { "aaa": 1, "bbb": 2, "ccc": 3, } keys = ["ccc", "aaa", "bbb", "ddd", "eee", "fff", "ggg"] getter = d.get # Here we got a bound method def f1(d): for k in keys: x = d.get(k) # Takes one lookup more def f2(getter): for k in keys: x = getter(k) # Calling bound method import time def clock_func(f, params): t = time.clock() for i in range(1000): f(*params) print "%s:\t%06f" % (f.__name__, time.clock() - t) def main(): clock_func(f1, (d,)) clock_func(f2, (getter,)) main() <\code> In average it prints something like: f1: 0.013130 f2: 0.010207 Your gain might be even more as you need two lookups. Somewhere in the Web ;) there is really nice article by Guido about optimization, try to Google for it. -- Best regards, anton mailto:antonmuhin@rambler.ru From phthenry@earthlink.net Sat Mar 1 13:17:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Sat Mar 1 13:17:01 2003 Subject: [Tutor] fixed or variable length fields? In-Reply-To: References: <20030301042742.M13858@localhost.localdomain> Message-ID: <20030301131644.R13858@localhost.localdomain> On Sat, Mar 01, 2003 at 01:57:36PM +0100, Michael Janssen wrote: > > On Sat, 1 Mar 2003, Paul Tremblay wrote: > > > ob > cwtrue > cwtrue > cwtrue > I had taken a glimpse into an rtf-document and it looks different. > font-table is for example in such a line: > {\rtf1\ansi\ansicpg1252\deff0{\fonttbl [continues spaceless] > {\f0\fswiss\fprq2\fcharset0 Arial;}{\f1\fnil\fcharset2 Symbol;}} > > are your "lines of tokens" data from an intermediate step (or is rtf that > anti standardized)? Represent it an atomic rewrite of the information in > hairy lines like above? Right. The tokens are the result of two steps of processing. The first token is "{". I tranlate this to 'ob255<\blue255;' When I process the data, I can somewhat easily find a color item: if token[3:5] == 'cl': # do something > > now my question is (not affiliated with the subject of this thread, by > the way :-): > > In case it is intermediate data, why is it of type string? In case you > have processed the information earlier (possibly rewrite it into an > "normalized" format), you might want to save this results to disk - but > you needn't to restart from disk splitting each line into > computer-understandable datastructures. Just process with the > datastructures from your former step. > > Or is it neccessary to save memory? Or did i miss anything else? So for example I could save each token as part of a list? I rejected this idea right off, for better or worse, though many tokenizers use this method. For example, you often need to know the tokens that came *before* in order to process the current token. With a tokenizer, you can do this. However, RTF files can be over 20 M, and this just seemed very ineffecient. I believe that things run better if you read only one line into memory, especially if you have big files. Overall, writing to a file, closing the file, and then opening it up again to process takes some time. But to me is seemed that the small waste of time was worth it because (1) I could process any file, whether 1k or 100 Gibabytes (2) it kept the process very simple and manageable by breaking it down into steps that I could look at. Paul > > Michael > > > > > (Fields delimited with "<" and ">" because all "<" and ">" have > > been converted to "<" and ">" > > > > I will make several passes through this file to convert the data. > > > > Each time I read a line, I will use the string method, and sometimes the > > split method: > > > > if line[12:23] == 'font-table': > > info = [12:23] > > list = info.split(">") > > if list[1] == 'true': > > # do something > > > > If I use fixed length fields, then I won't have to do any splitting. I > > also know that in perl, there is a way to use 'pack' and 'unpack' to > > quickly access fixed fields. I have never used this, and don't know if > > the pack in Python is similar. > > > > If fix fields did give me a speed increase, I would certainly suffer > > from readibility. For example, the above 4 lines of tokens might look > > like: > > > > opbr:null:null:null:0001 > > ctrw:null:null:true:rtfx > > ctrw:null:null:true:mact > > ctrw:null:null:true:fntb > > > > Instead of 'macintosh', I have 'mact'; instead of 'font-table', I have > > 'fntb'. > > > > Thanks > > > > Paul > > > > -- > > > > ************************ > > *Paul Tremblay * > > *phthenry@earthlink.net* > > ************************ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From gp@pooryorick.com Sun Mar 2 11:43:02 2003 From: gp@pooryorick.com (gp@pooryorick.com) Date: Sun Mar 2 11:43:02 2003 Subject: [Tutor] depth first with a twist Message-ID: <269620-22003302164144825@M2W054.mail2web.com> Hi, I majored in a social science, so I'm hoping this group can help me fill in the gaps;) I have a dictionary where each key contains a list of values=2E Values 1 and 2 are parent, and older_sibling, respectively=2E = I would like to append an order number onto each list, using parent and older_sibling to determine the order, and am looking for an iterative solution=2E I have written a function which works, but boy, is it ugly!=20= Anyone care to comment? ---begin code--- d =3D {'monty': [None, None, "Monty Python's Flying Circus"], 'actors': ['monty', None, 'Actor Data'], 'sketches': ['monty', 'actors', 'Sketch Data'], 'basic': ['actors', None, 'Basic Bio'], 'filmography': ['actors', 'basic', 'Filmography']} PARENT =3D 0 OLDER_SIBLING =3D 1 NAME =3D 2 ORDER =3D 3 def OrderDepth(self): keys =3D d=2Ekeys() order =3D 1 parent =3D None sibling =3D None search =3D [] for i in keys: if d[i][PARENT] =3D=3D parent: if d[i][OLDER_SIBLING] =3D=3D sibling: search=2Eappend(keys=2Epop(keys=2Eindex(i))) d[i]=2Eappend(order) order +=3D 1 parent =3D i sibling =3D d[i][PARENT] break foundChild =3D 0 foundSibling =3D 0 while len(keys) > 0: print 'searching for parent %s and sibling %s', (parent, sibling) for i in keys: if d[i][PARENT] =3D=3D parent: if d[i][OLDER_SIBLING] =3D=3D sibling: print 'found a match: ', i search=2Eappend(keys=2Epop(keys=2Eindex(i))) d[i]=2Eappend(order) order +=3D1 if sibling =3D=3D None: foundChild =3D 1 else: foundSibling =3D 1 break if foundChild =3D=3D 1: print 'option 1' foundChild =3D 0 parent =3D i sibling =3D None elif foundSibling =3D=3D 1: print 'option 2' foundSibling =3D 0 parent =3D i sibling =3D None else: print 'option 3' sibling =3D parent parent =3D d[search[-1]][PARENT] if parent =3D=3D sibling: search=2Epop() result =3D {} for i in d: result[d[i][ORDER]] =3D i i =3D result=2Ekeys() i=2Esort() for j in i: print j, '\t\t', result[j] -- End Code -- Thanks, Poor Yorick -------------------------------------------------------------------- mail2web - Check your email from the web at http://mail2web=2Ecom/ =2E From erikprice@mac.com Sun Mar 2 13:06:01 2003 From: erikprice@mac.com (Erik Price) Date: Sun Mar 2 13:06:01 2003 Subject: [Tutor] a DateTime object Message-ID: Hi, What is a good way to take a user-supplied input string and convert it to a Unix timestamp (seconds since epoch)? I know that the time module in stdlib offers both time() and mktime() but these both operate on "now", rather than some user-supplied datetime. I am not really looking to implement this myself but rather if there is another module that does this kind of thing. If not, I can probably come up with my own implementation without too much trouble, just don't feel like doing extra work. (Use case: the user supplies the check-in and check-out times to a prompt. These are then passed as arguments to a function that generates the timestamp, which is then stored internally in my object. It is easier for me to perform calculations on the timestamps, such as determining the duration of time between check-in and check-out, etc.) Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From shalehperry@attbi.com Sun Mar 2 17:55:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Mar 2 17:55:01 2003 Subject: [Tutor] a DateTime object In-Reply-To: References: Message-ID: <200303021453.31968.shalehperry@attbi.com> On Sunday 02 March 2003 10:20, Erik Price wrote: > Hi, > > What is a good way to take a user-supplied input string and convert it > to a Unix timestamp (seconds since epoch)? I know that the time module > in stdlib offers both time() and mktime() but these both operate on > "now", rather than some user-supplied datetime. > > I am not really looking to implement this myself but rather if there is > another module that does this kind of thing. If not, I can probably > come up with my own implementation without too much trouble, just don't > feel like doing extra work. > hunt down mxDateTime. From phthenry@earthlink.net Sun Mar 2 18:58:02 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Sun Mar 2 18:58:02 2003 Subject: [Tutor] fixed or variable length fields? In-Reply-To: <20030301042742.M13858@localhost.localdomain> References: <20030301042742.M13858@localhost.localdomain> Message-ID: <20030302184418.A28322@localhost.localdomain> Answering my own question. It doesn't save any time to use pack and unpack (as opposed to perl, which runs faster with these commands). Using split runs a bit faster according to my tests, and it is of course much easier to use. On the other hand, it does make sense to use fixed fields. If I always know that my token is ten characters long, then I can use something like token_info = token[5:15] num = token[15:] # the length of the number can vary That will save me from having to use split very much, resulting in code that is a bit cleaner and faster. (Now I wonder if I make my fields smaller--say 4 characters rather than 10--if that would speed things up?) Paul On Sat, Mar 01, 2003 at 04:27:42AM -0500, Paul Tremblay wrote: > From: Paul Tremblay > To: tutor@python.org > User-Agent: Mutt/1.3.21i > Subject: [Tutor] fixed or variable length fields? > Date: Sat, 1 Mar 2003 04:27:42 -0500 > > Would I gain a speed increase by using fixed fields rather than variable > length ones? > > I am writing a script that converts Microsoft RTF to XML. The first > stage breaks the file into tokens and puts one token on a line: > > > ob cwtrue cwtrue cwtrue > (Fields delimited with "<" and ">" because all "<" and ">" have > been converted to "<" and ">" > > I will make several passes through this file to convert the data. > > Each time I read a line, I will use the string method, and sometimes the > split method: > > if line[12:23] == 'font-table': > info = [12:23] > list = info.split(">") > if list[1] == 'true': > # do something > > If I use fixed length fields, then I won't have to do any splitting. I > also know that in perl, there is a way to use 'pack' and 'unpack' to > quickly access fixed fields. I have never used this, and don't know if > the pack in Python is similar. > > If fix fields did give me a speed increase, I would certainly suffer > from readibility. For example, the above 4 lines of tokens might look > like: > > opbr:null:null:null:0001 > ctrw:null:null:true:rtfx > ctrw:null:null:true:mact > ctrw:null:null:true:fntb > > Instead of 'macintosh', I have 'mact'; instead of 'font-table', I have > 'fntb'. > > Thanks > > Paul > > -- > > ************************ > *Paul Tremblay * > *phthenry@earthlink.net* > ************************ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From magnus@thinkware.se Sun Mar 2 20:29:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Mar 2 20:29:02 2003 Subject: [Tutor] depth first with a twist In-Reply-To: <20030302170006.7636.28164.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030303015320.03700bc8@www.thinkware.se> At Sun, 2 Mar 2003 11:41:44 -0500, Poor Yorick wrote: >Hi, I majored in a social science, so I'm hoping this group can help me >fill in the gaps;) Sure. >I have a dictionary where each key contains a list of >values. Values 1 and 2 are parent, and older_sibling, respectively. I >would like to append an order number onto each list, using parent and >older_sibling to determine the order, and am looking for an iterative >solution. I have written a function which works, but boy, is it ugly! Ok. Maybe this indicates that you need a different abstraction. > def OrderDepth(self): I see that this is a method (due to indentation, and "self"), but the fact that you don't use "self" a single time in the code suggests that the code is in fact in the wrong class! Methods should work with the attributes of the instance of the class! May I suggest having a look at Arthur Riel's book "Object-Oriented Design Heuristics". In this case I think the logic should be in a Tree Item class. Below, I instanciate it from your dict, but it might be unwarranted to use both represetations in practice. As I see it, each parent object should be able to sort out his children, and then it's fairly trivial. I don't know if this is fewer lines of code than your version, but it makes more sense to me. Each method is fairly trivial. I didn't include the number before the printed item, but that's a trivial addition. E.g. instead of a print statement in "printTree" there could be an append to a list (either known by name or passed as argument), and then it's trivial to iterate the list and print with a number before each line. It's also possible to pass an object that returns an incremented number on each access, to printTree. # A registry of items in the tree, might not be global in "real" code. reg = {} class TreeItem: def __init__(self, name, parent, older_sibling, note): self.name = name self.parent = parent self.older_sibling = older_sibling self.note = note self.children = [] # Register myself by name, so my children will find me. reg[name] = self def tellParent(self): # Hi daddy, I'm your kid if self.parent: try: reg[self.parent].addChild(self) except KeyError: print self.name, "is missing his parent", self.parent raise def addChild(self, child): # Oops, this one claims to be my kid. ;) self.children.append(child) def printTree(self): # First me, then my kids (and their kids) in order print self self.sortChildren() for child in self.children: child.printTree() def sortChildren(self): lastChild = None sorted = [] while self.children: for child in self.children: if child.older_sibling == lastChild: self.children.remove(child) sorted.append(child) lastChild = child.name break else: # Error handling, we don't expect to get here print "Bad child list" print "Sorted", map(str, sorted) print "Leftovers", map(str, self.children) raise SystemExit self.children = sorted def __str__(self): return self.name d = {'monty': [None, None, "Monty Python's Flying Circus"], 'actors': ['monty', None, 'Actor Data'], 'sketches': ['monty', 'actors', 'Sketch Data'], 'basic': ['actors', None, 'Basic Bio'], 'filmography': ['actors', 'basic', 'Filmography']} for name, (parent, older, note) in d.items(): TreeItem(name, parent, older, note) # Self-registering... # Once all items are registered we can inform parents of their # chldren. for item in reg.values(): item.tellParent() # Find root item(s) and print tree(s) for item in reg.values(): if item.parent is None: # Root item! item.printTree() This should print: monty actors basic filmography sketches If you want the number before, write an incrementor class like this: class Incr: def __init__(self): self.x = 0 def get(self): self.x += 1 return self.x and modify one method: def printTree(self, incr = Incr()): print incr.get(), self self.sortChildren() for child in self.children: child.printTree(incr) Then it should come out like: 1 monty 2 actors 3 basic 4 filmography 5 sketches -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From tony@tcapp.com Mon Mar 3 02:05:01 2003 From: tony@tcapp.com (Tony Cappellini) Date: Mon Mar 3 02:05:01 2003 Subject: [Tutor] Why doesn't getopts() handle this character '^' ? Message-ID: <5.1.0.14.0.20030302224129.01a893e0@smtp.sbcglobal.net> --=====================_36804131==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed If I pass these arguments on the command line, to my python module, 2 ^ 2 (as in python mymodule.py 2 ^ 2) Why doesn't getopt() handle the ^ character ? Args= ['2', '2'] This is the code in my module import sys, operator opts, args = getopt( sys.argv[1:], "") print"\nArgs= " print args It works fine for other operators Args= ['2', '*', '2'] Tony Tony --=====================_36804131==_.ALT Content-Type: text/html; charset="us-ascii"

If I pass these arguments on the command line, to my python module,

  2 ^ 2  (as in python mymodule.py 2 ^  2)

Why doesn't getopt() handle the ^ character ?

Args=
['2', '2']


This is the code in my module

import sys, operator
opts, args = getopt( sys.argv[1:], "")
print"\nArgs= "
print args


It works fine for other operators

Args=
['2', '*', '2']



Tony

Tony
--=====================_36804131==_.ALT-- From tony@tcapp.com Mon Mar 3 02:09:02 2003 From: tony@tcapp.com (Tony Cappellini) Date: Mon Mar 3 02:09:02 2003 Subject: [Tutor] Why doesn't getopt() handle this character '^' ? Message-ID: <5.1.0.14.0.20030302231450.01aa3948@smtp.sbcglobal.net> --=====================_37089862==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed When I pass these arguments to my module 2 ^ 2 as in (python mymodule.py 2 ^ 2) This is what is displayed Args= ['2', '2'] This is the code in my module import sys, operator opts, args = getopt( sys.argv[1:], "") print"\nArgs= " print args getopts() works for other operators as in 2 * 2 Args= ['2', '*', '2'] Tony --=====================_37089862==_.ALT Content-Type: text/html; charset="us-ascii"

When I pass these arguments to my module

2 ^ 2  as in (python mymodule.py 2 ^ 2)

This is what is displayed

Args=
['2', '2']

This is the code in my module

import sys, operator
opts, args = getopt( sys.argv[1:], "")
print"\nArgs= "
print args

getopts() works for other operators
as in 2 * 2

Args=
['2', '*', '2']


Tony
--=====================_37089862==_.ALT-- From antonmuhin at rambler.ru" References: <269620-22003302164144825@M2W054.mail2web.com> Message-ID: <163115539.20030303141951@rambler.ru> Hello gp, Sunday, March 2, 2003, 7:41:44 PM, you wrote: gpc> Hi, I majored in a social science, so I'm hoping this group can help me gpc> fill in the gaps;) I have a dictionary where each key contains a list of gpc> values. Values 1 and 2 are parent, and older_sibling, respectively. I gpc> would like to append an order number onto each list, using parent and gpc> older_sibling to determine the order, and am looking for an iterative gpc> solution. I have written a function which works, but boy, is it ugly! gpc> Anyone care to comment? Do you want to implemant a tree? -- Best regards, anton mailto:antonmuhin@rambler.ru From abli@freemail.hu Mon Mar 3 10:19:01 2003 From: abli@freemail.hu (Abel Daniel) Date: Mon Mar 3 10:19:01 2003 Subject: [Tutor] Why doesn't getopt() handle this character '^' ? In-Reply-To: <5.1.0.14.0.20030302231450.01aa3948@smtp.sbcglobal.net> References: <5.1.0.14.0.20030302231450.01aa3948@smtp.sbcglobal.net> Message-ID: <20030303151826.GA2582@hooloovoo> Tony Cappellini (tony@tcapp.com) wrote: > When I pass these arguments to my module > > 2 ^ 2 as in (python mymodule.py 2 ^ 2) > > This is what is displayed > > Args= > ['2', '2'] > > This is the code in my module > > import sys, operator > opts, args = getopt( sys.argv[1:], "") > print"\nArgs= " > print args > > getopts() works for other operators > as in 2 * 2 > > Args= > ['2', '*', '2'] I could exactly reproduce the effect you describe. My guess is that the shell you type 'python mymodule.py 2 ^ 2' into mangles the ^ character. Using the bash shell, 'python mymodule.py 2 ^ 2' works as expected (the ^ character gets passed), but 'python mymodule.py 2 * 2' does something wierd: the shell replaces the * character with the list of files in the current directory. This means that the program never sees the * character. This subsitution makes things like 'ls *.txt' work. You should try quoting the parameters, like this: python mymodule.py "2 ^ 2" This tells the shell to pass those unchanged to you program. (So for me python mymodule.py "2 * 2" prints ['2', '*', '2'] and not the filelist.) Hope this helps abli From ramrom@earthling.net Mon Mar 3 11:11:11 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Mar 3 11:11:11 2003 Subject: [Tutor] Why doesn't getopt() handle this character '^' ? Message-ID: <5.2.0.9.0.20030303090954.02d9a890@66.28.54.253> --=======64865D1F======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-408946F3; boundary="=====================_8822365==.ALT" --=====================_8822365==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-408946F3; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:18 PM 3/2/2003 -0800, you wrote: >When I pass these arguments to my module >2 ^ 2 as in (python mymodule.py 2 ^ 2) >This is what is displayed >Args= >['2', '2'] >This is the code in my module >import sys, operator >opts, args = getopt( sys.argv[1:], "") >print"\nArgs= " >print args > >getopts() works for other operators >as in 2 * 2 > >Args= >['2', '*', '2'] What op sys? I'm running Win2K; when I try python mymodule.py 2 ^ 2 the ^ doesn't even appear in sys.argv. So, for me, it is not a getopt issue, it is an issue of passing data to sys.argv from the command line. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=====================_8822365==.ALT Content-Type: text/html; x-avg-checked=avg-ok-408946F3; charset=us-ascii Content-Transfer-Encoding: 8bit At 11:18 PM 3/2/2003 -0800, you wrote:
When I pass these arguments to my module
2 ^ 2  as in (python mymodule.py 2 ^ 2)
This is what is displayed
Args=
['2', '2']
This is the code in my module
import sys, operator
opts, args = getopt( sys.argv[1:], "")
print"\nArgs= "
print args

getopts() works for other operators
as in 2 * 2

Args=
['2', '*', '2']

What op sys? I'm running Win2K; when I try python mymodule.py 2 ^ 2 the ^ doesn't even appear in sys.argv. So, for me, it is not a getopt issue, it is an issue of passing data to sys.argv from the command line.

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=====================_8822365==.ALT-- --=======64865D1F======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-408946F3 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======64865D1F=======-- From gerrit@nl.linux.org Mon Mar 3 11:22:01 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Mon Mar 3 11:22:01 2003 Subject: [OT] Shell expanding (was: Re: [Tutor] Why doesn't getopt() handle this character '^' ?) In-Reply-To: <20030303151826.GA2582@hooloovoo> References: <5.1.0.14.0.20030302231450.01aa3948@smtp.sbcglobal.net> <20030303151826.GA2582@hooloovoo> Message-ID: <20030303162316.GA2724@nl.linux.org> Abel Daniel schreef op maandag 3 maart om 16:19:15 +0000: You should try quoting the parameters, like this: > python mymodule.py "2 ^ 2" > This tells the shell to pass those unchanged to you program. (So for me > python mymodule.py "2 * 2" > prints ['2', '*', '2'] and not the filelist.) It doesn't, really. '2 * 2' passes it as one single argument containing 5 characters. "2 * 2" expands * and passes a long single argument. 2 '*' 2 probably does what you want. yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From vicki@stanfield.net Mon Mar 3 12:11:15 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Mon Mar 3 12:11:15 2003 Subject: [Tutor] convert decimal to hex Message-ID: <20030303090935.13608.h018.c000.wm@mail.stanfield.net.criticalpath.net> I am working on a small Python script which sends data out on a serial port to a device and reads what that device sends back. What I send is in hex format as should be what I receive back. I should receive a "0x15) but I get what resembles a section break character in editing notation (=A7=A7). I am relatively sure of the port settings that I am using (and experimentation hasn't given me anything resembling what I expected anyway). Can anyone give me a clue as to how to proceed to fix this problem? I am using the serial module write and read commands. I tried readline as well. I can verify what is sent and received in another application that I have.=20 Thanks, --vicki From pversteegen@gcnetmail.net Mon Mar 3 16:33:06 2003 From: pversteegen@gcnetmail.net (Pete Versteegen) Date: Mon Mar 3 16:33:06 2003 Subject: [Tutor] Explain Message-ID: Could someone explain what I'm doing wrong? Thanks! -------------------------- #!/usr/bin/python class Single: def ___init___(self, maxmonths): self.size = [] self.n = maxmonths for i in range(0, self.n): self.size.append = 0.0 if __name__ == '__main__': unitsize = Single(20) unitsize.size[10] = 500. print unitsize.size ----------------------------- Traceback (most recent call last): File "./Single.py", line 11, in ? unitsize = Single(20) TypeError: this constructor takes no arguments Pete Versteegen pversteegen@gcnetmail.net __________________________ From ramrom@earthling.net Mon Mar 3 17:03:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Mar 3 17:03:01 2003 Subject: [Tutor] Explain In-Reply-To: Message-ID: <5.2.0.9.0.20030303150045.02f82560@66.28.54.253> --=======1DAC5065======= Content-Type: text/plain; x-avg-checked=avg-ok-408946F3; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 04:32 PM 3/3/2003 -0500, Pete Versteegen wrote: >-------------------------- >#!/usr/bin/python >class Single: > > def ___init___(self, maxmonths): > self.size = [] > self.n = maxmonths > for i in range(0, self.n): > self.size.append = 0.0 > >if __name__ == '__main__': > unitsize = Single(20) > unitsize.size[10] = 500. > print unitsize.size > >----------------------------- >Traceback (most recent call last): > File "./Single.py", line 11, in ? > unitsize = Single(20) >TypeError: this constructor takes no arguments Count the underscores around init. There should be 2 before and 2 after. After you fix that you will get another exception: self.size.append = 0.0 AttributeError: 'list' object attribute 'append' is read-only Correct syntax is: self.size.append(0.0) Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======1DAC5065======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-408946F3 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======1DAC5065=======-- From emil@lysator.liu.se Mon Mar 3 17:28:06 2003 From: emil@lysator.liu.se (Emil Styrke) Date: Mon Mar 3 17:28:06 2003 Subject: [Tutor] convert decimal to hex In-Reply-To: <20030303090935.13608.h018.c000.wm@mail.stanfield.net.criticalpath.net> (vicki@stanfield.net's message of "Mon, 03 Mar 2003 09:09:34 -0800 (PST)") References: <20030303090935.13608.h018.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <87k7fgf2u2.fsf@i110.ryd.student.liu.se> --=-=-= Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable vicki@stanfield.net writes: > I am working on a small Python script which sends data > out on a serial port to a device and reads what that > device sends back. What I send is in hex format as > should be what I receive back. I should receive a > "0x15) but I get what resembles a section break > character in editing notation (=A7=A7). I am relatively > sure of the port settings that I am using (and > experimentation hasn't given me anything resembling > what I expected anyway). Can anyone give me a clue as > to how to proceed to fix this problem? I am using the > serial module write and read commands. I tried readline > as well. I can verify what is sent and received in > another application that I have.=20 > What you have received is probably a character with the ordinal value 0x15. To convert character data to integers, you can use the ord() function, and to convert a number to hex notation you can use the hex() function. Example: >>> data =3D "hello" >>> for char in data: >>> print hex(ord(char)) Note that hex() returns a string, not a number. Note also that the same applies for writing to the device, so calling something like write("0x15") won't work, as it will send the four characters 0, x, 1 and 5 to the device. HTH /Emil =20=20=20=20=20 > Thanks, > --vicki --=-=-= Content-Type: application/pgp-signature -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQA+Y+TpEsW2TDYTdDYRAjjfAJ0REfMyyhHuL52QtZ7pfJmxVtIjnQCdF4AN xfWGXifeJ7pbdNAvFk+h/qA= =kwnW -----END PGP SIGNATURE----- --=-=-=-- From tony@tcapp.com Tue Mar 4 02:02:12 2003 From: tony@tcapp.com (Tony Cappellini) Date: Tue Mar 4 02:02:12 2003 Subject: [Tutor] Why doesn't getopt() handle this character '^' ? In-Reply-To: <20030303151826.GA2582@hooloovoo> References: <5.1.0.14.0.20030302231450.01aa3948@smtp.sbcglobal.net> <5.1.0.14.0.20030302231450.01aa3948@smtp.sbcglobal.net> Message-ID: <5.1.0.14.0.20030303225330.04923c30@tcapp.com> --=====================_2772386==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed wrote >I could exactly reproduce the effect you describe. My guess is that the >shell you type 'python mymodule.py 2 ^ 2' into mangles the ^ character. >Using the bash shell, 'python mymodule.py 2 ^ 2' works as expected (the >^ character gets passed), but 'python mymodule.py 2 * 2' does something >wierd: the shell replaces the * character with the list of files in the >current directory. This means that the program never sees the * >character. This subsitution makes things like 'ls *.txt' work. > >You should try quoting the parameters, like this: >python mymodule.py "2 ^ 2" >This tells the shell to pass those unchanged to you program. (So for me >python mymodule.py "2 * 2" >prints ['2', '*', '2'] and not the filelist.) I forgot to mention I'm running Windows 2000 This code, import sys, getopt, os opts, args = getopt.getopt( sys.argv[1:], "") print"\n\n\n\nsys.argv[1:]=", print sys.argv[1:] print"\nArgs=", print args print "\n\n\n" produces the out below, using the arguments as specified in each of the examples below. python mymodule.py 2 ^ 2 sys.argv[1:]= ['2', '2'] Args= ['2', '2'] python mymodule.py "2 ^ 2" sys.argv[1:]= ['2 ^ 2'] Args= ['2 ^ 2'] python mymodule.py 2 '"^" 2 sys.argv[1:]= ['2', '^', '2'] Args= ['2', '^', '2'] --=====================_2772386==_.ALT Content-Type: text/html; charset="us-ascii" <abli@freemail.hu> wrote

I could exactly reproduce the effect you describe. My guess is that the
shell you type 'python mymodule.py 2 ^ 2' into mangles the ^ character.
Using the bash shell, 'python mymodule.py 2 ^ 2' works as expected (the
^ character gets passed), but 'python mymodule.py 2 * 2' does something
wierd: the shell replaces the * character with the list of files in the
current directory. This means that the program never sees the *
character. This subsitution makes things like 'ls *.txt' work.

You should try quoting the parameters, like this:
python mymodule.py "2 ^ 2"
This tells the shell to pass those unchanged to you program. (So for me
python mymodule.py "2 * 2"
prints ['2', '*', '2'] and not the filelist.)


I forgot to mention I'm running Windows 2000
This code,

import sys, getopt, os
opts, args = getopt.getopt( sys.argv[1:], "")
print"\n\n\n\nsys.argv[1:]=",
print sys.argv[1:]
print"\nArgs=",
print args
print "\n\n\n"

produces the out below, using the arguments as specified in each of the examples below.


python mymodule.py 2 ^ 2

sys.argv[1:]= ['2', '2']
Args= ['2', '2']



python mymodule.py "2 ^ 2"

sys.argv[1:]= ['2 ^ 2']
Args= ['2 ^ 2']



python mymodule.py 2 '"^" 2

sys.argv[1:]= ['2', '^', '2']
Args= ['2', '^', '2']



--=====================_2772386==_.ALT-- From gp@pooryorick.com Tue Mar 4 02:09:00 2003 From: gp@pooryorick.com (Poor Yorick) Date: Tue Mar 4 02:09:00 2003 Subject: [Tutor] depth first with a twist References: <269620-22003302164144825@M2W054.mail2web.com> <163115539.20030303141951@rambler.ru> Message-ID: <3E64516C.1020701@pooryorick.com> antonmuhin at rambler.ru wrote: >Hello gp, > > >Do you want to implemant a tree? > Yes, that's what I'm trying to do. Poor Yorick gp@pooryorick.com From johnca@ourpla.net Tue Mar 4 03:08:02 2003 From: johnca@ourpla.net (John Abbe) Date: Tue Mar 4 03:08:02 2003 Subject: [Tutor] Global/Local confusions Message-ID: In my continuing effort to understand global / local interactions -- ======================================== #!/usr/local/bin/python """ Running this file generates this error: Traceback (most recent call last): File "./gltest", line 10, in ? f(9) File "./gltest", line 6, in f if x in b: UnboundLocalError: local variable 'b' referenced before assignment """ b = [9, 10] def f(x): if x in b: print "spam" b = [11, 12] # if this line is commented out, there's no error! f(9) ======================================== Any explanations? Life, John -- All you /\/\ John Abbe "If you don't like the news, need \ / CatHerder go out and make some of your own." is... \/ http://ourpla.net/john/ --Wes Nisker From Darren Munsell" This is a multi-part message in MIME format. ------=_NextPart_000_0016_01C2E1FE.DBA80680 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Its for my work. I work in a school where we punch in and out on a time = card, however we are also required to write out a time sheet to go = along with this. Since I'm no wizz at math, I want to make this time = consuming adding hours and minutes from my time card into a simple = program that's there when we need it. The only bad news is that my school probably will not allow the Python = program to sit on any of the computers (security reasons), so I was = hoping that maybe I could embed it into a Html or have it as an = excutable, all our mechines are Windows98, so there is no = cross-operating system to worry about. I'm very new to python and I understand the basics. But what would you = suggest for me to get started ? Yours truely, Darren Thanks !! ------=_NextPart_000_0016_01C2E1FE.DBA80680 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Its for my work.  I work in a school where we punch in and out = on a=20 time card, however we are also required to  write out a time sheet = to go=20 along with this. Since I'm no wizz at math, I want to make this time = consuming=20 adding hours and minutes from my time card into a simple program that's = there=20 when we need it.
The only bad news is that my school probably will not allow the = Python=20 program to sit on any of the computers (security reasons), so I was = hoping that=20 maybe I could embed it into a Html or have it as an excutable, all our = mechines=20 are Windows98, so there is no cross-operating system to worry = about.
I'm very new to python and I understand the basics. But what would = you=20 suggest for me to get started ?
 
 
Yours truely, Darren
Thanks !!
------=_NextPart_000_0016_01C2E1FE.DBA80680-- From shalehperry@attbi.com Tue Mar 4 03:37:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue Mar 4 03:37:02 2003 Subject: [Tutor] Global/Local confusions In-Reply-To: References: Message-ID: <200303040036.02871.shalehperry@attbi.com> On Monday 03 March 2003 23:36, John Abbe wrote: > In my continuing effort to understand global / local interactions -- > > =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D > #!/usr/local/bin/python > """ > Running this file generates this error: > > Traceback (most recent call last): > File "./gltest", line 10, in ? > f(9) > File "./gltest", line 6, in f > if x in b: > UnboundLocalError: local variable 'b' referenced before assignment > """ > > b =3D [9, 10] > > def f(x): > if x in b: > print "spam" > b =3D [11, 12] # if this line is commented out, there's no er= ror! > > f(9) > =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D > > Any explanations? Life, > John This was actually discussed here recently. What happens is Python sees t= he 'b =3D [11,12]' line and says "ah, this must be a local variable". So wh= en the=20 function is called Python is confused by the reference to be before the=20 assignment. To make this function work like you want you need 'global b' to be the fi= rst=20 line of the function. If the assignment does not occur in the function then Python decides to l= ook=20 for a global variable instead. This is why commenting out the last line=20 works. The basic rule is if you plan to change a global variable in a function y= ou=20 must declare the use of it at the top of the function. Reading a variabl= e=20 will always work. From erikprice@mac.com Tue Mar 4 08:01:16 2003 From: erikprice@mac.com (Erik Price) Date: Tue Mar 4 08:01:16 2003 Subject: [Tutor] I have a small project I want to work on.. In-Reply-To: Message-ID: <4D81E3DA-4E43-11D7-92F6-00039351FE6A@mac.com> On Tuesday, March 4, 2003, at 03:33 AM, Darren Munsell wrote: > Its for my work.=A0 I work in a school where we punch in and out on a=20= > time card, however we are also required to=A0 write out a time sheet = to=20 > go along with this. Since I'm no wizz at math, I want to make this=20 > time consuming adding hours and minutes from my time card into a=20 > simple program that's there when we need it. > The only bad news is that my school probably will not allow the Python=20= > program to sit on any of the computers (security reasons), so I was=20 > hoping that maybe I could embed it into a Html or have it as an=20 > excutable, all our mechines are Windows98, so there is no=20 > cross-operating system to worry about. > I'm very new to python and I understand the basics. But what would you=20= > suggest for me to get started ? Well, I've been working on a somewhat similar utility for my own use. =20= One night out of the week I wait tables at a restaurant and up till=20 lately I've been keeping all my income records in a spreadsheet, but=20 since I don't have any spreadsheet software on my main computer it=20 requires that I go to another computer just to enter in this data. =20 Plus, I honestly never really bothered to learn how to do any=20 calculations with spreadsheet software, so although I can see all the=20 income on the sheet, I'd far prefer to just whip up some code to=20 generate a report (such as avg tips per hour, avg income per month,=20 etc) in python. It's really simple. I have created a Shift class which tracks the=20 start and end time, the pay rate, the amount of tips earned and the=20 amount of tips paid out to the bartenders. The time is stored as a=20 Unix timestamp (seconds since 1970-01-01) for ease of calculation. =20 This class sits in its own file, shift.py, and is imported by the main=20= script, TipTracker.py. I've copied the very basic parts of what I have=20= into this email so you can see how I went about it for ideas (I removed=20= the tip parts since it doesn't sound like you need this, and it is=20 actually pretty long with all the tip calculations). My favorite parts=20= are the functions that get user input -- they are recursive, so if the=20= user enters invalid data, an exception is raised and then immediately=20 caught, calling the function again so that the entire script doesn't=20 have to be re-executed. It's not done yet -- specifically, I haven't yet written the=20 persistence part, where I write the user input (my input) to a file=20 that is read on successive uses of the program to build up a list of=20 Shift instances which can then be reported against. And I haven't=20 written the report-generating (output-generating) part either. (I just=20= started this the other day.) But hopefully this will get you started. #!/usr/bin/python # shift.py -- a file containing just the Shift class: # Class to represent a Shift worked by an Employee class Shift: "Represents a Shift worked by an Employee" # static class vars pay_rates =3D {} # cents per hour pay_rates['bar'] =3D 235 pay_rates['server'] =3D 235 pay_rates['host'] =3D 800 pay_rates['bus'] =3D 0 def __init__(self, shift_type, shift_start, shift_stop): if not Shift.pay_rates.has_key(shift_type): raise KeyError if shift_start > shift_stop: raise ValueError self.shift_type =3D shift_type self.shift_start =3D shift_start self.shift_stop =3D shift_stop def hours_worked(self): 'Returns the duration of the shift in hours.' totalseconds =3D self.shift_stop - self.shift_start return totalseconds / 3600 def wages(self): 'Returns the wages earned in the shift before taxes.' return float(self.hours_worked() * Shift.pay_rates[self.shift_type]) / 100 #!/usr/bin/python # TipTracker.py - a file containing the actual executed script # Driver script for TipTracker import sys import time from shift import Shift def fetch_shift_types(): 'create a list of the different shift types' output =3D '' keys =3D Shift.pay_rates.keys() num_key =3D 0 for key in keys: num_key +=3D 1 output +=3D key if num_key < len(keys): output +=3D ', ' else: output +=3D '' return output def timestr_to_timestamp(timestr): 'parse a time string entered by the user to a timestamp number' format =3D '%Y-%m-%d %H:%M' return time.strptime(timestr, format) def shift_type_input(): 'get user input for type of shift' shift_type =3D raw_input('Shift type (%s): ' % fetch_shift_types()) if not Shift.pay_rates.has_key(shift_type): print 'Invalid shift type "' + shift_type + '"' shift_type =3D shift_type_input() return shift_type def shift_start_input(): 'get user input for start of shift' tstart =3D raw_input('Start time (YYYY-MM-DD HH:MM): ') try: start =3D timestr_to_timestamp(tstart) except ValueError: print 'Invalid start time "' + tstart + '"' start =3D shift_start_input() return time.mktime(start) def shift_stop_input(): 'get user input for end of shift' tstop =3D raw_input('Stop time (YYYY-MM-DD HH:MM): ') try: stop =3D timestr_to_timestamp(tstop) except ValueError: print 'Invalid end time "' + tstop + '"' stop =3D shift_stop_input() return time.mktime(stop) def main(): 'Get user input, process, echo, and write to file' # user input shift_type =3D shift_type_input() shift_start =3D shift_start_input() shift_stop =3D shift_stop_input() # catch invalid data early while (shift_start > shift_stop): print 'Shift start time must precede shift end time' shift_start =3D shift_start_input() shift_stop =3D shift_stop_input() try: usershift =3D Shift(shift_type, shift_start, shift_stop) except KeyError: print 'Invalid shift type "' + shift_type + '"' sys.exit(0) except ValueError: print 'Shift start time must precede shift end time' sys.exit(0) # echo print "Hours worked: " + str(usershift.hours_worked()) print "Wages: " + str(usershift.wages()) # write to file # not done yet if __name__ =3D=3D '__main__': try: main() except EOFError: # exit script if user hits Ctrl-D print '\n' sys.exit(0) --=20 Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Tue Mar 4 08:03:02 2003 From: erikprice@mac.com (Erik Price) Date: Tue Mar 4 08:03:02 2003 Subject: [Tutor] a DateTime object In-Reply-To: <200303021453.31968.shalehperry@attbi.com> Message-ID: On Sunday, March 2, 2003, at 05:53 PM, Sean 'Shaleh' Perry wrote: > hunt down mxDateTime. Thanks Sean -- actually I found out I wasn't using the regular time module correctly. the time module offers "strptime()" which parsed my user input into a time tuple and I could pass the time tuple to mktime() to get the effect I wanted. But I will keep mxDateTime in mind for more advanced time needs (such as times outside the scope of the Unix timestamp). Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From nixonron@yahoo.com Tue Mar 4 10:55:02 2003 From: nixonron@yahoo.com (Ron Nixon) Date: Tue Mar 4 10:55:02 2003 Subject: [Tutor] newbie question--saving changes to a file Message-ID: <20030304155423.22322.qmail@web20308.mail.yahoo.com> --0-808239346-1046793263=:21820 Content-Type: text/plain; charset=us-ascii How do I save the changes I make to a file say for example if I change old to new in a file and then want to save the new changes to another file? import string file = open('c:/file.txt') s = file.read() s.replace('old', 'new') Please excuse the questions if it sounds to basic, but I have not be able to find an example of how to do this in the documentation--or perhaps I simply didn't see it. --------------------------------- Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, and more --0-808239346-1046793263=:21820 Content-Type: text/html; charset=us-ascii

How do I save the changes I make to a file say for example if I change old to new in a file and then want to save the new changes to another file?

import string

file = open('c:/file.txt')

s = file.read()

s.replace('old', 'new')

 

Please excuse the questions if it sounds to basic, but I have not be able to find an example of how to do this in the documentation--or perhaps I simply didn't see it.



Do you Yahoo!?
Yahoo! Tax Center - forms, calculators, tips, and more --0-808239346-1046793263=:21820-- From dyoo@hkn.eecs.berkeley.edu Tue Mar 4 11:35:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 4 11:35:03 2003 Subject: [Tutor] Why doesn't getopt() handle this character '^' ? In-Reply-To: <5.1.0.14.0.20030303225330.04923c30@tcapp.com> Message-ID: On Mon, 3 Mar 2003, Tony Cappellini wrote: > wrote > > >I could exactly reproduce the effect you describe. My guess is that the > >shell you type 'python mymodule.py 2 ^ 2' into mangles the ^ character. Hi everyone, The Windows 'cmd' shell does use '^' as an escape character. I hunted around and found this: http://www.robvanderwoude.com/index.html So in Win2k, the caret symbol '^' acts like Python's '\' escape character on its command line prompt. That's why we needed to quote it, to keep it from being used as an escape character by the Windows shell. (If anyone knows another good reference that talks about Win2k shell escape characters, that would be great; I had a heck of a time googling for this one... *grin*) Unix shells don't use '^', but they do conventionally use '*' as a "globbing" operation to get a list of similar-named files into our command line. It's the same sort of principle: the command prompt shell futzes with our command line arguments before Python has a chance to look at them. When we "quote" an argument, we try to keep the underlying system from fiddling with it, but rather, we'd like for it to treat it literally. Humans do quotation when they want to show that they don't want the following words to be interpreted as their own. And programmers do quotation when they don't want their words to be evaluated by the system. Talk to you later! From dyoo@hkn.eecs.berkeley.edu Tue Mar 4 12:00:13 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 4 12:00:13 2003 Subject: [Tutor] newbie question--saving changes to a file In-Reply-To: <20030304155423.22322.qmail@web20308.mail.yahoo.com> Message-ID: On Tue, 4 Mar 2003, Ron Nixon wrote: > How do I save the changes I make to a file say for example if I change > old to new in a file and then want to save the new changes to another > file? > > import string > > file = open('c:/file.txt') > > s = file.read() > > s.replace('old', 'new') > > Please excuse the questions if it sounds to basic, but I have not be > able to find an example of how to do this in the documentation--or > perhaps I simply didn't see it. Hi Ron, No problem; your question is perfectly reasonable! By the end of your program: ### import string file = open('c:/file.txt') s = file.read() s.replace('old', 'new') ### we have, in our computer's memory, the contents of that file, with some modifications that we'd like to save back to disk. What we can do is open up the same file in "write" mode: ### out_file = open("c:/file.txt", "w") ### This clears out the file so that it's ready for us to start writing into it. Once we have an open file, we can write() to it: ### out_file.write(s) ### Finally, we should close() the file. Python can put some finishing touches (like flushing buffers) when we close a file, so that we're sure that every last drop of data has gone into our out_file: ### out_file.close() ### Altogether, the program might look like this: ### import string file = open('c:/file.txt') s = file.read() s.replace('old', 'new') out_file = open("c:/file.txt", "w") out_file.write(s) out_file.close() ### And this should work, if I haven't put in any typos. *grin* But some people might feel slightly uncomfortable about how open() will clear out a file when it's in write mode. What happens if the power goes out before we have a chance to write() the modified contents? Think Ellen Feiss. A word processor, like Microsoft Word or Emacs, should be careful to avoid this danger. What these programs do (or should do) is make a copy of the old file --- a backup --- into a separate file. Once we have a backup, then we can go ahead and write into our file with some security: even if power goes out, we have a good chance of just retrieving our backup. Hope this helps! From antonmuhin at rambler.ru" References: <20030304155423.22322.qmail@web20308.mail.yahoo.com> Message-ID: <889768296.20030304203935@rambler.ru> Hello Ron, Tuesday, March 4, 2003, 6:54:23 PM, you wrote: RN> How do I save the changes I make to a file say for example if I RN> change old to new in a file and then want to save the new changes RN> to another file? RN> import string RN> file = open('c:/file.txt') RN> s = file.read() RN> s.replace('old', 'new') For your example: inText = file(r"c:\file.txt").read() inText.replace("old", "new") outFile = file(r"output.txt", 'w') outFile.write(inText) outFile.close() Several notes: 1. You'd better avoid names like 'file' for variables---it's actually a built-in function. 2. You mustn't import string module (at least for your example) 3. Don't forget to close files (althoug I think Python might close it for you, but still). 4. You may use r" to avoid \\ ugliness 5. If you're working with huse files, the following code would be better: outputFile = file(r"c:\output.txt", 'w') for line in file(r"c:\file.txt"): # Pick a line line.replace("old", "new") # Process it outputFile.write(line) outputFile.close() -- Best regards, anton mailto:antonmuhin@rambler.ru From drewp@bigasterisk.com Tue Mar 4 13:33:01 2003 From: drewp@bigasterisk.com (Drew Perttula) Date: Tue Mar 4 13:33:01 2003 Subject: [Tutor] newbie question--saving changes to a file In-Reply-To: Your message of "Tue, 04 Mar 2003 08:59:42 PST." Message-ID: <200303041831.h24IVxs06844@bang.houseoflove> Danny Yoo wrote: > > By the end of your > program: > > ### > import string > file = open('c:/file.txt') > s = file.read() > s.replace('old', 'new') > ### > > we have, in our computer's memory, the contents of that file, with some > modifications that we'd like to save back to disk. Almost-- Python strings are immutable, meaning that once the read() method created the string it returned, that string object will never change. So, even though the string object does indeed have a replace() method, that method can't alter the string in place: instead, it returns a new string with the changes. So here's the fix: infile = open('c:/file.txt') s = infile.read() s=s.replace('old', 'new') I changed 'file' so it's not the name of a builtin type, like someone else suggested. And, I replaced s with the new string returned by the replace() method. The rest of the program that writes s to a file doesn't have to change. -Drew From magnus@thinkware.se Tue Mar 4 16:08:25 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Mar 4 16:08:25 2003 Subject: [Tutor] newbie question--saving changes to a file In-Reply-To: <20030304155502.20267.81251.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030304220340.02c40420@www.thinkware.se> At Tue, 4 Mar 2003 07:54:23 -0800 (PST), Ron Nixon wrote: >How do I save the changes I make to a file say for example if I change old >to new in a file and then want to save the new changes to another file? # You don't need to import string...unless you plan to use it... >import string > >file = open('c:/file.txt') >s = file.read() >s.replace('old', 'new') file.close() file = open('c:/file.txt', 'w') file.write(s) file.close() -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Tue Mar 4 16:14:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Mar 4 16:14:02 2003 Subject: [Tutor] a DateTime object In-Reply-To: <20030304155502.20267.81251.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030304220741.02c3c640@www.thinkware.se> At Tue, 4 Mar 2003 08:17:40 -0500, Erik Price wrote: >Thanks Sean -- actually I found out I wasn't using the regular time >module correctly. the time module offers "strptime()" which parsed my >user input into a time tuple and I could pass the time tuple to >mktime() to get the effect I wanted. But it's only from Python 2.3 that strptime works cross platform. >But I will keep mxDateTime in mind for more advanced time needs (such >as times outside the scope of the Unix timestamp). Since 2.3 will also include a DateTime module, the need for mxDateTime is decreasing, but it's still very useful, as are the other mx extensions. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Tue Mar 4 17:17:05 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Mar 4 17:17:05 2003 Subject: [Tutor] Global/Local confusions In-Reply-To: <20030304155502.20267.81251.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030304221324.02ce49d0@www.thinkware.se> John Abbe wrote: >In my continuing effort to understand global / local interactions -- Ok. I assume then that you understand about local and global scopes, about the usefulness of using mainly the local scope, and that the variables in the local scope hides the global scope. For instance, the following will print 5 and then 3: x = 3 def f(): x = 5 print x f() print x Ok? I assume you have no problem with this. Since x is defined in the local scope, a lookup of the name x will find the local variable x, not the global variable x, right? Back in the global scope, we will find the global variable x, which is not the same. Scopes always have clear boundries. The local scope of a function contains the "def...:" line and all the following indented lines. A local scope won't start at any arbitrary line in the file. So, if you swap the lines in the function body above, like this: x = 3 def f(): print x x = 5 f() You will still have a local variable x in the local scope of the function f. This variable will hide the global variable x just as in the first example. In other words, you can't see the global x while you are inside the definition of function f. Since you do 'print x' before you do 'x = 5', you are trying to print something that you don't (yet) know the value of. Thus the error message. The name (x here, b in your example) is defined in the local scope, but at this point, it hasn't been bound to any object yet. Ok? In the following two lines, you have *one* variable, which is used twice. First it's bound to 5, and then to 3. When it's been bound to 3, there is no way of figuring out what it has been bound to before. x = 5 x = 3 On the other hand, in the code below, we have two completely separate variables in different scopes that happen to be called the same. They both exist at the same time, and are bound to two different objects. x = 5 def f(): x = 3 If you intend to use the global variable x inside a function where you make assignments to it, you must say so explicitly: x = 3 def f(): global x print x x = 5 f() This might seem silly in a tiny program, but when you are at line 2376 of a large file, and the global variable was defined at line 72, you will be very happy that Python behaves just the way it does... Imagine this case: x = 3 def f(i): if i == 'x': ... x = None ... elif i is None ... x = 6 ... print x ... f() In this case, if i is neither 'x' or None, you will get an UnboundLocalError again. For me it would certainly be strange if the same "print x" would either print a local or a global variable depending on how the if- statements evaluated. The current implementation does a lot to help programmers stay sane in the long run.. If your intention was actually to first print a *global* variable called x in the function, and then work with a *local* variable that just happens to have the same name, you *can* do that, but instead of using the trick below, I suggest that you choose better names and severely restrict your use of global variables. In other words, don't try this at home, kids: ;) x = 3 def f(): print globals()['x'] x = 5 f() >""" >Running this file generates this error: > >Traceback (most recent call last): > File "./gltest", line 10, in ? > f(9) > File "./gltest", line 6, in f > if x in b: >UnboundLocalError: local variable 'b' referenced before assignment >""" > >b = [9, 10] > >def f(x): > if x in b: > print "spam" > b = [11, 12] # if this line is commented out, there's no error! > >f(9) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From micforster@yahoo.com Tue Mar 4 22:17:02 2003 From: micforster@yahoo.com (Mic Forster) Date: Tue Mar 4 22:17:02 2003 Subject: [Tutor] problems with the bisect method Message-ID: <20030305031600.44894.qmail@web13403.mail.yahoo.com> Hi guys, I am using the bisect method to find the value of x. I am sure I am missing something simple here so I put it to you. Thanks for any help. >>> from math import log >>> def f(x, s): return ((1 - x) / x) * (-(log(1 - x))) >>> j = 1. / 7861 >>> s = 33 >>> def bisect(min, max, delta, function): fMax = function(max) fMin = function(min) assert fMax * fMin < 0 while max - min > delta: newX = 0.5 * (min + max) fNew = function(newX) if fNew * fMax > 0: max, fMax = newX, fNew else: min, fMin = newX, fNew return newX, fNew >>> def fun(k, s): return f(k, s) - j >>> delta = 1e-9 >>> bisect(delta, 1-delta, delta, fun) Traceback (most recent call last): File "", line 1, in ? bisect(delta, 1-delta, delta, fun) File "", line 2, in bisect fMax = function(max) TypeError: fun() takes exactly 2 arguments (1 given) >>> __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, more http://taxes.yahoo.com/ From GREENDAY31087@aol.com Tue Mar 4 23:17:01 2003 From: GREENDAY31087@aol.com (GREENDAY31087@aol.com) Date: Tue Mar 4 23:17:01 2003 Subject: [Tutor] .py to .exe Message-ID: <160.1cd01680.2b96d426@aol.com> --part1_160.1cd01680.2b96d426_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Sometimes I like to show my friends at school my little python programs that I've made. When I go to friend's houses I like to run the scripts with python instead of having them just look blankly at the code, their eyes glazing over. Anyway, my problem is that every time I want to show them to someone, They have to download the compiler and for some reason it annoys them. My question is this: Can I convert a python program to .Exe (so the compiler wont be needed)? I think I heard how to do this on tutor before, but I forgot. --part1_160.1cd01680.2b96d426_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable    Sometimes I like to show my friends at sc= hool my little python programs that I've made.  When I go to friend's h= ouses I like to run the scripts with python instead of having them just look= blankly at the code, their eyes glazing over.

       Anyway, my problem is that every time I= want to show them to someone, They have to download the compiler and for so= me reason it annoys them.

       My question is this: Can I convert a py= thon program to .Exe (so the compiler wont be needed)?
      
       I think I heard how to do this on tutor= before, but I forgot.
--part1_160.1cd01680.2b96d426_boundary-- From missive@hotmail.com Tue Mar 4 23:49:02 2003 From: missive@hotmail.com (Lee Harr) Date: Tue Mar 4 23:49:02 2003 Subject: [Tutor] Re: problems with the bisect method Message-ID: >>>from math import log >>>def f(x, s): return ((1 - x) / x) * (-(log(1 - x))) >>>j = 1. / 7861 >>>s = 33 >>>def bisect(min, max, delta, function): ^^^^^^^^ this name gets bound to fun fMax = function(max) ^^^^^^^^^^^^ and you try to call it with 1 argument fMin = function(min) assert fMax * fMin < 0 while max - min > delta: newX = 0.5 * (min + max) fNew = function(newX) if fNew * fMax > 0: max, fMax = newX, fNew else: min, fMin = newX, fNew return newX, fNew >>>def fun(k, s): ^^^^^^ here is your function with 2 arguments return f(k, s) - j >>>delta = 1e-9 >>>bisect(delta, 1-delta, delta, fun) Traceback (most recent call last): File "", line 1, in ? bisect(delta, 1-delta, delta, fun) File "", line 2, in bisect fMax = function(max) TypeError: fun() takes exactly 2 arguments (1 given) >>> _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From GREENDAY31087@aol.com Wed Mar 5 00:35:01 2003 From: GREENDAY31087@aol.com (GREENDAY31087@aol.com) Date: Wed Mar 5 00:35:01 2003 Subject: [Tutor] .py to .exe Message-ID: <1d2.4542256.2b96e652@aol.com> --part1_1d2.4542256.2b96e652_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit >I think py2exe might be what you are looking for. It is at >http://sourceforge.net/projects/py2exe/ Hey, that is what I was looking for! Looks great but.. I don't really know what to do with it. Could you or someone else show me an example of how to use 'py2exe' ? I would appreciate any help. -Wayne --part1_1d2.4542256.2b96e652_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable >I think py2exe might be what you are looking for.=20= It is at
>http://sourceforge.net/projects/py2exe/

Hey, that is what I was looking for! Looks great but.. I don't really= know what to do with it. Could you or someone else show me an example of ho= w to use 'py2exe' ? I would appreciate any help.

-Wayne


--part1_1d2.4542256.2b96e652_boundary-- From tony@tcapp.com Wed Mar 5 01:24:01 2003 From: tony@tcapp.com (Tony Cappellini) Date: Wed Mar 5 01:24:01 2003 Subject: [Tutor] Why doesn't getopt() handle this character '^' ? In-Reply-To: References: <5.1.0.14.0.20030303225330.04923c30@tcapp.com> Message-ID: <5.1.0.14.0.20030304223221.01aa23a0@tcapp.com> At 08:34 AM 3/4/2003 -0800, Danny Yoo wrote: >On Mon, 3 Mar 2003, Tony Cappellini wrote: > > > wrote > > > > >I could exactly reproduce the effect you describe. My guess is that the > > >shell you type 'python mymodule.py 2 ^ 2' into mangles the ^ character. > >Hi everyone, > >The Windows 'cmd' shell does use '^' as an escape character. I hunted >around and found this: > > http://www.robvanderwoude.com/index.html thanks again, Danny ! From Sean Abrahams Wed Mar 5 13:33:03 2003 From: Sean Abrahams (Sean Abrahams) Date: Wed Mar 5 13:33:03 2003 Subject: [Tutor] CVS Version Number in __version__ Message-ID: <1551201350515.20030305103243@sfsu.edu> How do I get CVS to automatically input the version of the file and the date into __version__ and __date__, respectively? Thanks, --Sean From abli@freemail.hu Wed Mar 5 14:05:05 2003 From: abli@freemail.hu (Abel Daniel) Date: Wed Mar 5 14:05:05 2003 Subject: [Tutor] CVS Version Number in __version__ In-Reply-To: <1551201350515.20030305103243@sfsu.edu> References: <1551201350515.20030305103243@sfsu.edu> Message-ID: <20030305190417.GA649@hooloovoo> Sean Abrahams (sa@sfsu.edu) wrote: > > How do I get CVS to automatically input the version of the file and > the date into __version__ and __date__, respectively? > What you need is called keyword substitution, see http://www.cvshome.org/docs/manual/cvs_12.html so you want something like __version__='$Revision$' __date__='$Date$' in the file When you do a cvs checkin, the $..$ will be substituted with the appropiate data. Of course for this, keyword expansion should be turned on. For normal textfiles it is turned on by default, but you can turn it off when you add the file to the repository (for data files, such expansion would cause mayor breakage). Also note the python style guide's recomendation: (from http://python.org/peps/pep-0008.html) """ Version Bookkeeping If you have to have RCS or CVS crud in your source file, do it as follows. __version__ = "$Revision: 1.18 $" # $Source: # /cvsroot/python/python/nondist/peps/pep-0008.txt,v # $ These lines should be included after the module's docstring, before any other code, separated by a blank line above and below. """ Abel Daniel From nixonron@yahoo.com Wed Mar 5 14:21:02 2003 From: nixonron@yahoo.com (Ron Nixon) Date: Wed Mar 5 14:21:02 2003 Subject: [Tutor] newbie question-saving changes to file thanks and another question Message-ID: <20030305192017.27135.qmail@web20310.mail.yahoo.com> --0-1403441201-1046892017=:26924 Content-Type: text/plain; charset=us-ascii Thanks to all who helped with the saving changes to a file. One additional question, if I want to go through and say change five or six things would I use search and then IF, ELSE ? and what would it look like. something like the code below? is this correct? infile = open('c:/address.txt') s = infile.read() IF s.search(s, 'ROAD') s=s.replace('ROAD', 'RD') IF s.search(s,'STREET') s =s.replace('STREET', 'ST') out_file = open("c:/address.txt", "w") out_file.write(s) out_file.close() --------------------------------- Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, and more --0-1403441201-1046892017=:26924 Content-Type: text/html; charset=us-ascii

Thanks to all who helped with the saving changes to a file. One additional question, if I want to go through and say change five or six things would I use search and then  IF, ELSE ? and what would it look like. something like the code below? is this correct?

infile = open('c:/address.txt')
s = infile.read()
IF s.search(s, 'ROAD')
s=s.replace('ROAD', 'RD')
IF s.search(s,'STREET')
s =s.replace('STREET', 'ST')
out_file = open("c:/address.txt", "w")
out_file.write(s)
out_file.close()

 



Do you Yahoo!?
Yahoo! Tax Center - forms, calculators, tips, and more --0-1403441201-1046892017=:26924-- From elh@outreachnetworks.com Wed Mar 5 14:56:15 2003 From: elh@outreachnetworks.com (Eric L Howard) Date: Wed Mar 5 14:56:15 2003 Subject: [Tutor] .py to .exe In-Reply-To: <1d2.4542256.2b96e652@aol.com> References: <1d2.4542256.2b96e652@aol.com> Message-ID: <20030305195523.GC2163@outreachnetworks.com> At a certain time, now past [Wed, Mar 05, 2003 at 12:34:10AM -0500], GREENDAY31087@aol.com spake thusly: > > >I think py2exe might be what you are looking for. It is at > >http://sourceforge.net/projects/py2exe/ > Hey, that is what I was looking for! Looks great but.. I don't really > know what to do with it. Could you or someone else show me an example > of how to use 'py2exe' ? I would appreciate any help. > -Wayne The 'Home Page' link under the Project Summary banner has some examples, references, samples files, etc. ~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 dyoo@hkn.eecs.berkeley.edu Wed Mar 5 15:28:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 5 15:28:01 2003 Subject: [Tutor] newbie question-saving changes to file thanks and another question In-Reply-To: <20030305192017.27135.qmail@web20310.mail.yahoo.com> Message-ID: On Wed, 5 Mar 2003, Ron Nixon wrote: > Thanks to all who helped with the saving changes to a file. One > additional question, if I want to go through and say change five or six > things would I use search and then IF, ELSE ? and what would it look > like. something like the code below? is this correct? > > infile = open('c:/address.txt') > s = infile.read() > IF s.search(s, 'ROAD') > s=s.replace('ROAD', 'RD') > IF s.search(s,'STREET') > s =s.replace('STREET', 'ST') > out_file = open("c:/address.txt", "w") > out_file.write(s) > out_file.close() Yes, it would look similar, but it needs a few changes to run in Python. You may want to look at: http://www.honors.montana.edu/~jjc/easytut/easytut/node7.html#SECTION00710000000000000000 The page above shows some examples of the 'if' statement in action; you should be able to fix up your code above so that it works out ok. You may also need to fix the check with "s.search()", since strings don't have a search() method. You probably mean to use the find() method instead: ### >>> 'foobar'.find('o') 1 >>> 'foobar'.find('z') -1 ### Notice that find() will tell us where it finds the smaller string within the larger string. If it can't find the "substring", then find() will give us back '-1'. (By the way, it looks like, in the future 2.3 release of Python, we'll be able to say: "test" in "this is a test": and have that work as a substring check. http://www.python.org/2.3/highlights.html Change is relentless... *grin*) However, the code above is a little redundant: if we try to first search for the word "ROAD", and then replace all instances of "ROAD" with "RD", it's more directly to just skip the check, and just replace all instances of "ROAD" with "RD". Good luck! From magnus@thinkware.se Wed Mar 5 17:13:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Mar 5 17:13:01 2003 Subject: [Tutor] Re: Tutor digest, Vol 1 #2302 - 11 msgs In-Reply-To: <20030305170007.31088.7937.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030305225011.02d3c028@www.thinkware.se> Anton Muhin wrote: >inText = file(r"c:\file.txt").read() >inText.replace("old", "new") > >outFile = file(r"output.txt", 'w') >outFile.write(inText) >outFile.close() > >Several notes: >1. You'd better avoid names like 'file' for variables---it's actually >a built-in function. Not function, type. In Python 2.2 and up, types are like classes, and can be used to instanciate objects just like any class: >>> int("23") 23 >>> float(6) 6.0 >>> str('Hello') 'Hello' >>> file('c:/autoexec.bat') >2. You mustn't import string module (at least for your example) I think Anton meant "you don't have to import the string module". Anton: English is a bit strange on negating must. Mustn't means "you are not allowed to". I.e. from a binding point of view, it's "must (not do)". You'd expect it to be "(must not) do", right. It seems russian is like Swedish here... >3. Don't forget to close files (althoug I think Python might close it >for you, but still). Which Anton didn't do above after reading the file. :) In C-Python, this will not matter in the current implementation, since the file will be closed directly due to the reference counting garbage collection. In Jython, Java might well decide not to garbage collect yet, and then you try to open a file for writing which is already open for reading. Can you do that? >4. You may use r" to avoid \\ ugliness Better to use / for path separators as God intended, unless you run a Mac. For platform indenpence, use os.path.join(). Drew Perttula wrote: >Almost-- Python strings are immutable, meaning that once the read() >method created the string it returned, that string object will never >change. So, even though the string object does indeed have a replace() >method, that method can't alter the string in place: instead, it returns >a new string with the changes. > >So here's the fix: > >infile = open('c:/file.txt') >s = infile.read() >s=s.replace('old', 'new') Oops, we all forgot that, didn't we? It's easy to determine where a problem lies, and copy someone elses code without really checking it... >I changed 'file' so it's not the name of a builtin type, like someone >else suggested. And, I replaced s with the new string returned by the >replace() method. The rest of the program that writes s to a file doesn't >have to change. If we use python 2.2 or newer, where file is a builtin type, we might as well use that. infile = file('c:/file.txt') On the other hand, using open() it will run with older pythons as well... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From pan" This is a multi-part message in MIME format. --_b1fbfa0c5db46d25b9b8e12f64e4c4cde Content-Type: text/plain; charset="Big5" Content-Transfer-Encoding: base64 SSBhbSB0cnlpbmcgdG8gY29kZSBhIG51bWVyaWMgY2xhc3MgaW4gd2hpY2ggc29tZSBmbG9hdCBu dW1iZXJzLCANCmxpa2UgNC4yNTc5MDMyMSwgd2lsbCBiZSBzdG9yZWQgd2l0aCB2YXJ5aW5nIGRl Y2ltYWwgc2l6ZXMgYXM6IA0KDQo0LjI1NzkwICAoZGVjaW1hbCBzaXplID0gNSkNCjQuMjU3ICAg ICAgKGRlY2ltYWwgc2l6ZSA9IDMpDQo0LjEgICAgICAgICAgKGRlY2ltYWwgc2l6ZSA9MSkNCg0K ZGVwZW5kaW5nIG9uIGFuIGF0dHJpYnV0ZSBzZWxmLmRlY2ltYWxTaXplIHNldCBieSB0aGUgdXNl cnMuDQoNCkkgbGVhcm5lZCB0aGF0IHRoZSBkZWNpbWFsIHNpemUgY2FuIGJlIHNldCBhcyBmb2xs b3dzOg0KDQpmbG9hdCgnJS4zZicgJW4pICA= --_b1fbfa0c5db46d25b9b8e12f64e4c4cde Content-Type: text/html; charset="Big5" Content-Transfer-Encoding: base64 PGh0bWw+CjxoZWFkPgo8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRl eHQvaHRtbDsgY2hhcnNldD1CaWc1Ij4KPC9oZWFkPgo8Ym9keT4KSSBhbSB0cnlpbmcgdG8gY29k ZSBhIG51bWVyaWMgY2xhc3MgaW4gd2hpY2ggc29tZSBmbG9hdCBudW1iZXJzLCANPGJyPgpsaWtl IDQuMjU3OTAzMjEsIHdpbGwgYmUgc3RvcmVkIHdpdGggdmFyeWluZyBkZWNpbWFsIHNpemVzIGFz OiANPGJyPgoNPGJyPgo0LjI1NzkwICAoZGVjaW1hbCBzaXplID0gNSkNPGJyPgo0LjI1NyAgICAg IChkZWNpbWFsIHNpemUgPSAzKQ08YnI+CjQuMSAgICAgICAgICAoZGVjaW1hbCBzaXplID0xKQ08 YnI+Cg08YnI+CmRlcGVuZGluZyBvbiBhbiBhdHRyaWJ1dGUgc2VsZi5kZWNpbWFsU2l6ZSBzZXQg YnkgdGhlIHVzZXJzLg08YnI+Cg08YnI+CkkgbGVhcm5lZCB0aGF0IHRoZSBkZWNpbWFsIHNpemUg Y2FuIGJlIHNldCBhcyBmb2xsb3dzOg08YnI+Cg08YnI+CmZsb2F0KCclLjNmJyAlbikgIDw9PSBj b252ZXJ0aW5nIHRvIHN0cmluZyByZXByZXNlbnRhdGlvbiB3aXRoDTxicj4KZGVjaW1hbCBzaXpl ID0gMyB0aGVuIGNvbnZlcnRpbmcgYmFjayB0byBmbG9hdA08YnI+Cg08YnI+CkJ1dCBpdCBzZWVt cyB0byBiZSBpbXBvc3NpYmxlIHRvIHNldCBpdCBkeW5hbWljYWxseToNPGJyPgoNPGJyPgpmbG9h dCgnJS4laWYnICUoaSxuKSkNPGJyPgpmbG9hdCgnJS4oJWkpZicgJShpLG4pKQ08YnI+Cg08YnI+ CmJvdGggZmFpbGVkLg08YnI+Cg08YnI+CkkgY2FuIGZpbmQgYSBkZXRvdXIgYnkNPGJyPgoNPGJy PgpbMV0gbXVsdGlwbHlpbmcgYnkgMTAwMCAoaWYgdGhlIHJlcXVpcmVkIGRlY2ltYWwgc2l6ZSA9 MykNPGJyPgpbMl0gdGhlbiBkZXZpZGVkIGJ5IDEwMDAuMCANPGJyPgoNPGJyPgpidXQgaXQgc2Vl bXMgdG8gYmUgdG9vIHRlZGlvdXMgdG8gbWUuDTxicj4KDTxicj4KQW55IGJldHRlciB3YXkgdG8g YWNoaWV2ZSB0aGlzPw08YnI+Cg08YnI+ClRoeCBpbiBhZHZhbmNlDTxicj4KDTxicj4KU2luY2Vy ZWx5LA08YnI+CnBhbg08YnI+Cjxicj4KCgo9PT09PT09PT09PT09PT09PT09PT09PGJyIC8+DQp+ fn5+fiBiZSBzaGFwZWxlc3Mgfn5+fn48YnIgLz4NCjxiciAvPg0KUnVuc3VuIFBhbiwgUGhEPGJy IC8+DQpEZXB0LiBvZiBFY29sb2d5ICYgRXZvbHV0aW9uPGJyIC8+DQpVLiBvZiBDaGljYWdvLCBV U0E8YnIgLz4NCj09PT09PT09PT09PT09PT09PT09PT0KPC9ib2R5PjwvaHRtbD4K --_b1fbfa0c5db46d25b9b8e12f64e4c4cde-- From pan" This is a multi-part message in MIME format. --_b32930704061231e3f26f958ecb3c7779 Content-Type: text/plain; charset="Big5" Content-Transfer-Encoding: base64 SGkgYWxsLA0KDQpJJ3ZlIGJlZW4gcmVhZGluZyBzb21ldGhpbmcgYWJvdXQgbWV0YWNsYXNzIGJ1 dCBtb3N0IG9mIHRoZSANCmRvY3VtZW50cyBJIHJlYWQgc28gZmFyIGFyZSBtb3JlIG9yIGxlc3Mg bGlrZSBNYXJ0aWFuIGNvZGVzIHRvIA0KbWUuIEVzcGVjaWFsbHksIHRoZXkgZGlkbid0IGdpdmUg bWUgYW4gaWRlYSBmb3Igd2h5IHdlIG5lZWQgdG8gDQp1c2UgYSBtZXRhY2xhc3MuIA0KDQpDYW4g c29tZW9uZSBkZXNjcmliZSB1bmRlciB3aGF0IGEgbWV0YWNsYXNzIGlzIGZvciBhbmQgdW5kZXIN CmNpcmN1bXN0YW5jZXMgZG8gd2UgbmVlZCB0byBjb25zaWRlciB1c2luZyB0aGVtPw0KDQpXaGF0 IEkgbGVhcm5lZCBzbyBmYXIgaXM6DQoNCkFuIGluc3RhbmNlIG9mIGEgJ2NsYXNzaWMnIGNsYXNz IGlzIGFuIG9iamVjdA0KQW4gaW5zdGFuY2Ugb2YgYSBtZXRhY2xhc3MgaXMgYSBjbGFzcw0KDQp3 aGF0IGFkdmFudGFnZSBvZiB0aGUgYWJvdmUgYmVoYXZpb3I/DQoNClRoeCBpbiBhZHZhbmNlLg0K DQpwYW4NCg0KDQoKCgo9PT09PT09PT09PT09PT09PT09PT09DQp+fn5+fiBiZSBzaGFwZWxlc3Mg fn5+fn4NCg0KUnVuc3VuIFBhbiwgUGhEDQpEZXB0LiBvZiBFY29sb2d5ICYgRXZvbHV0aW9uDQpV LiBvZiBDaGljYWdvLCBVU0ENCj09PT09PT09PT09PT09PT09PT09PT0K --_b32930704061231e3f26f958ecb3c7779 Content-Type: text/html; charset="Big5" Content-Transfer-Encoding: base64 PGh0bWw+CjxoZWFkPgo8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRl eHQvaHRtbDsgY2hhcnNldD1CaWc1Ij4KPC9oZWFkPgo8Ym9keT4KSGkgYWxsLA08YnI+Cg08YnI+ CkkndmUgYmVlbiByZWFkaW5nIHNvbWV0aGluZyBhYm91dCBtZXRhY2xhc3MgYnV0IG1vc3Qgb2Yg dGhlIA08YnI+CmRvY3VtZW50cyBJIHJlYWQgc28gZmFyIGFyZSBtb3JlIG9yIGxlc3MgbGlrZSBN YXJ0aWFuIGNvZGVzIHRvIA08YnI+Cm1lLiBFc3BlY2lhbGx5LCB0aGV5IGRpZG4ndCBnaXZlIG1l IGFuIGlkZWEgZm9yIHdoeSB3ZSBuZWVkIHRvIA08YnI+CnVzZSBhIG1ldGFjbGFzcy4gDTxicj4K DTxicj4KQ2FuIHNvbWVvbmUgZGVzY3JpYmUgdW5kZXIgd2hhdCBhIG1ldGFjbGFzcyBpcyBmb3Ig YW5kIHVuZGVyDTxicj4KY2lyY3Vtc3RhbmNlcyBkbyB3ZSBuZWVkIHRvIGNvbnNpZGVyIHVzaW5n IHRoZW0/DTxicj4KDTxicj4KV2hhdCBJIGxlYXJuZWQgc28gZmFyIGlzOg08YnI+Cg08YnI+CkFu IGluc3RhbmNlIG9mIGEgJ2NsYXNzaWMnIGNsYXNzIGlzIGFuIG9iamVjdA08YnI+CkFuIGluc3Rh bmNlIG9mIGEgbWV0YWNsYXNzIGlzIGEgY2xhc3MNPGJyPgoNPGJyPgp3aGF0IGFkdmFudGFnZSBv ZiB0aGUgYWJvdmUgYmVoYXZpb3I/DTxicj4KDTxicj4KVGh4IGluIGFkdmFuY2UuDTxicj4KDTxi cj4KcGFuDTxicj4KDTxicj4KDTxicj4KPGJyPgoKCj09PT09PT09PT09PT09PT09PT09PT08YnIg Lz4NCn5+fn5+IGJlIHNoYXBlbGVzcyB+fn5+fjxiciAvPg0KPGJyIC8+DQpSdW5zdW4gUGFuLCBQ aEQ8YnIgLz4NCkRlcHQuIG9mIEVjb2xvZ3kgJiBFdm9sdXRpb248YnIgLz4NClUuIG9mIENoaWNh Z28sIFVTQTxiciAvPg0KPT09PT09PT09PT09PT09PT09PT09PQo8L2JvZHk+PC9odG1sPgo= --_b32930704061231e3f26f958ecb3c7779-- From glingl@aon.at Wed Mar 5 19:07:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Wed Mar 5 19:07:01 2003 Subject: [Tutor] Dynamic decimal size References: <20030305235218.16048.qmail@station172.com> Message-ID: <3E669141.5090209@aon.at> pan schrieb: > I am trying to code a numeric class in which some float numbers, > like 4.25790321, will be stored with varying decimal sizes as: > > 4.25790 (decimal size = 5) > 4.257 (decimal size = 3) > 4.1 (decimal size =1) > > depending on an attribute self.decimalSize set by the users. > > I learned that the decimal size can be set as follows: > > float('%.3f' %n) <== converting to string representation with > decimal size = 3 then converting back to float > > But it seems to be impossible to set it dynamically: > > float('%.%if' %(i,n)) > float('%.(%i)f' %(i,n)) > > both failed. > > I can find a detour by > > [1] multiplying by 1000 (if the required decimal size =3) > [2] then devided by 1000.0 > > but it seems to be too tedious to me. > > Any better way to achieve this? Yes you can do this by using the *-notation: >>> f = 0.123456789 >>> for i in range(10): print "%.*f" % (i,f) 0 0.1 0.12 0.123 0.1235 0.12346 0.123457 0.1234568 0.12345679 0.123456789 >>> The corresponding docs are here: I:\Python22\Doc\lib\typesseq-strings.html Regards, Gregor > > Thx in advance > > Sincerely, > pan > > ====================== > ~~~~~ be shapeless ~~~~~ > > Runsun Pan, PhD > Dept. of Ecology & Evolution > U. of Chicago, USA > ====================== From dyoo@hkn.eecs.berkeley.edu Wed Mar 5 19:09:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 5 19:09:02 2003 Subject: [Tutor] Closing files / strings are immutable In-Reply-To: <5.1.0.14.0.20030305225011.02d3c028@www.thinkware.se> Message-ID: > >3. Don't forget to close files (althoug I think Python might close it > >for you, but still). > > In C-Python, this will not matter in the current implementation, since > the file will be closed directly due to the reference counting garbage > collection. In Jython, Java might well decide not to garbage collect > yet, and then you try to open a file for writing which is already open > for reading. Can you do that? Hello! When we have an open()ed file in "write" mode, it becomes more important to make sure to close the file, especially in Jython. I don't know if this is still true, but last time I checked, Jython suffered from a small implementation problem: Java's buffered IO may not flush a file when the file garbage collects, so it was very possible to lose changes to a file by forgetting to close() the file explicitely. This is in Jython's FAQ: http://www.jython.org/cgi-bin/faqw.py?req=show&file=faq03.008.htp > >Almost-- Python strings are immutable, meaning that once the read() > >method created the string it returned, that string object will never > >change. So, even though the string object does indeed have a replace() > >method, that method can't alter the string in place: instead, it > >returns a new string with the changes. > > > > Oops, we all forgot that, didn't we? It's easy to determine where a > problem lies, and copy someone elses code without really checking it... I did make the same careless mistake, too. Sorry, Ron. What was that old saying... "Do what I say, and not what I do?" *grin* Good luck! From arosado@softhome.net Wed Mar 5 19:21:01 2003 From: arosado@softhome.net (Andres Rosado) Date: Wed Mar 5 19:21:01 2003 Subject: [Tutor] Re: I have a small project I want to work on.. Message-ID: <5.2.0.9.0.20030305202620.00bf3ea0@mail.softhome.net> On 10:55 AM 3/4/2003 -0500, tutor-request@python.org feed this fish to the sharks: >Its for my work. I work in a school where we punch in and out on a time = >card, however we are also required to write out a time sheet to go = >along with this. Since I'm no wizz at math, I want to make this time = >consuming adding hours and minutes from my time card into a simple = >program that's there when we need it. >The only bad news is that my school probably will not allow the Python = >program to sit on any of the computers (security reasons), so I was = >hoping that maybe I could embed it into a Html or have it as an = >excutable, all our mechines are Windows98, so there is no = >cross-operating system to worry about. Ok. >I'm very new to python and I understand the basics. But what would you = >suggest for me to get started ? Start simple. Write something that just take care of the counting the hours. Then you can start building from there. And ask here. :) Seriously, the guys here are great. More general, I would suggest you to get the Python binaries at http://www.python.org/ and start the hour counting process. After that, get py2exe to "compile" Python. Tkinter or wxPython are good for Windows. -- Andres Rosado Email: andresr@despammed.com ICQ: 66750646 Homepage: http://andres980.tripod.com/ Get my PGP key at http://andres980.tripod.com/pgp-key.asc Someone is speaking well of you. From jeff@ccvcorp.com Wed Mar 5 19:22:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Mar 5 19:22:02 2003 Subject: [Tutor] What is the metaclass for? References: <20030306000115.6234.qmail@station172.com> Message-ID: <3E669206.4060701@ccvcorp.com> pan wrote: > Hi all, > > I've been reading something about metaclass but most of the > documents I read so far are more or less like Martian codes to > me. Especially, they didn't give me an idea for why we need to > use a metaclass. > > Can someone describe under what a metaclass is for and under > circumstances do we need to consider using them? My short answer would be that metaclasses are a mechanism for black magic -- or at least, very dark grey magic. ;) Odds are good that if what you read about metaclasses makes no sense, then you're not likely to need metaclasses for anything that you're doing -- it's a very advanced subject for advanced programmers. (Read this as -- I don't know just what to do with them either, so I'm sticking to what I can understand! ;) They're a fairly new addition to Python and I never felt limited by their absence. But they seem to make some people happy...) Jeff Shannon Technician/Programmer Credit International From pan" This is a multi-part message in MIME format. --_bf5c07200ec7f074cd37152c2a36a3400 Content-Type: text/plain; charset="Big5" Content-Transfer-Encoding: base64 DQpHZWVzLCBHcmVnb3IsIHlvdSBhcmUgcXVpY2sgaW4gaGVscGluZyBwZW9wbGUgOikgDQoNClRo eCBhIGxvdC4NCg0KcGFuDQoNCg0KICAgLS0tLS0tLU9yaWdpbmFsIE1lc3NhZ2UtLS0tLS0tDQog ICA+IEZyb206IHByb2dAcnVuc3VuLmluZm8NCiAgID4gU3ViamVjdDogUmU6IFJlOiBbVHV0b3Jd IER5bmFtaWMgZGVjaW1hbCBzaXplDQogICA+IFNlbnQ6IE1hciAwNiAyMDAzIDAwOjA3OjI5DQog ICA+DQogICA+DQogICA+ICBwYW4gc2NocmllYjoNCiAgID4NCiAgID4gID4gSSBhbSB0cnlpbmcg dG8gY29kZSBhIG51bWVyaWMgY2xhc3MgaW4gd2hpY2ggc29tZSBmbG9hdCBudW1iZXJzLA0KICAg PiAgPiBsaWtlIDQuMjU3OTAzMjEsIHdpbGwgYmUgc3RvcmVkIHdpdGggdmFyeWluZyBkZWNpbWFs IHNpemVzIGFzOg0KICAgPiAgPg0KICAgPiAgPiA0LjI1NzkwIChkZWNpbWFsIHNpemUgPSA1KQ0K ICAgPiAgPiA0LjI1NyAoZGVjaW1hbCBzaXplID0gMykNCiAgID4gID4gNC4xIChkZWNpbWFsIHNp emUgPTEpDQogICA+ICA+DQogICA+ICA+IGRlcGVuZGluZyBvbiBhbiBhdHRyaWJ1dGUgc2VsZi5k ZWNpbWFsU2l6ZSBzZXQgYnkgdGhlIHVzZXJzLg0KICAgPiAgPg0KICAgPiAgPiBJIGxlYXJuZWQg dGhhdCB0aGUgZGVjaW1hbCBzaXplIGNhbiBiZSBzZXQgYXMgZm9sbG93czoNCiAgID4gID4NCiAg ID4gID4gZmxvYXQoJyUuM2YnICVuKQ0KICAgPiAgPiBkZWNpbWFsIHNpemUgPSAzIHRoZW4gY29u dmVydGluZyBiYWNrIHRvIGZsb2F0DQogICA+ICA+DQogICA+ICA+IEJ1dCBpdCBzZWVtcyB0byBi ZSBpbXBvc3NpYmxlIHRvIHNldCBpdCBkeW5hbWljYWxseToNCiAgID4gID4NCiAgID4gID4gZmxv YXQoJyUuJWlmJyAlKGksbikpDQogICA+ICA+IGZsb2F0KCclLiglaSlmJyAlKGksbikpDQogICA+ ICA+DQogICA+ICA+IGJvdGggZmFpbGVkLg0KICAgPiAgPg0KICAgPiAgPiBJIGNhbiBmaW5kIGEg ZGV0b3VyIGJ5DQogICA+ICA+DQogICA+ICA+IFsxXSBtdWx0aXBseWluZyBieSAxMDAwIChpZiB0 aGUgcmVxdWlyZWQgZGVjaW1hbCBzaXplID0zKQ0KICAgPiAgPiBbMl0gdGhlbiBkZXZpZGVkIGJ5 IDEwMDAuMA0KICAgPiAgPg0KICAgPiAgPiBidXQgaXQgc2VlbXMgdG8gYmUgdG9vIHRlZGlvdXMg dG8gbWUuDQogICA+ICA+DQogICA+ICA+IEFueSBiZXR0ZXIgd2F5IHRvIGFjaGlldmUgdGhpcz8N CiAgID4NCiAgID4gIFllcyB5b3UgY2FuIGRvIHRoaXMgYnkgdXNpbmcgdGhlICotbm90YXRpb246 DQogICA+DQogICA+ICA+Pj4gZiA9IDAuMTIzNDU2Nzg5DQogICA+ICA+Pj4gZm9yIGkgaW4gcmFu Z2UoMTApOg0KICAgPiAgcHJpbnQgIiUuKmYiICUgKGksZikNCiAgID4NCiAgID4NCiAgID4gIDAN CiAgID4gIDAuMQ0KICAgPiAgMC4xMg0KICAgPiAgMC4xMjMNCiAgID4gIDAuMTIzNQ0KICAgPiAg MC4xMjM0Ng0KICAgPiAgMC4xMjM0NTcNCiAgID4gIDAuMTIzNDU2OA0KICAgPiAgMC4xMjM0NTY3 OQ0KICAgPiAgMC4xMjM0NTY3ODkNCiAgID4gID4+Pg0KICAgPg0KICAgPiAgVGhlIGNvcnJlc3Bv bmRpbmcgZG9jcyBhcmUgaGVyZToNCiAgID4gIEk6UHl0aG9uMjJEb2NsaWJ0eXBlc3NlcS1zdHJp bmdzLmh0bWwNCiAgID4NCiAgID4gIFJlZ2FyZHMsIEdyZWdvcg0KICAgPg0KICAgPg0KICAgPiAg Pg0KICAgPiAgPiBUaHggaW4gYWR2YW5jZQ0KICAgPiAgPg0KICAgPiAgPiBTaW5jZXJlbHksDQog ICA+ICA+IHBhbg0KICAgPiAgPg0KICAgPiAgPiA9PT09PT09PT09PT09PT09PT09PT09DQogICA+ ICA+IH5+fn5+IGJlIHNoYXBlbGVzcyB+fn5+fg0KICAgPiAgPg0KICAgPiAgPiBSdW5zdW4gUGFu LCBQaEQNCiAgID4gID4gRGVwdC4gb2YgRWNvbG9neSAmIEV2b2x1dGlvbg0KICAgPiAgPiBVLiBv ZiBDaGljYWdvLCBVU0ENCiAgID4gID4gPT09PT09PT09PT09PT09PT09PT09PQ0KICAgPg0KICAg Pg0KICAgPg0KICAgPg0KICAgPg0KICAgLS0tLS0tLU9yaWdpbmFsIE1lc3NhZ2UtLS0tLS0tDQoN Cgo= --_bf5c07200ec7f074cd37152c2a36a3400 Content-Type: text/html; charset="Big5" Content-Transfer-Encoding: base64 PGh0bWw+CjxoZWFkPgo8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRl eHQvaHRtbDsgY2hhcnNldD1CaWc1Ij4KPC9oZWFkPgo8Ym9keT4KDTxicj4KR2VlcywgR3JlZ29y LCB5b3UgYXJlIHF1aWNrIGluIGhlbHBpbmcgcGVvcGxlIDopIA08YnI+Cg08YnI+ClRoeCBhIGxv dC4NPGJyPgoNPGJyPgpwYW4NPGJyPgoNPGJyPgoNPGJyPgogICAtLS0tLS0tT3JpZ2luYWwgTWVz c2FnZS0tLS0tLS0NPGJyPgogICA+IEZyb206IHByb2dAcnVuc3VuLmluZm8NPGJyPgogICA+IFN1 YmplY3Q6IFJlOiBSZTogW1R1dG9yXSBEeW5hbWljIGRlY2ltYWwgc2l6ZQ08YnI+CiAgID4gU2Vu dDogTWFyIDA2IDIwMDMgMDA6MDc6MjkNPGJyPgogICA+DTxicj4KICAgPg08YnI+CiAgID4gIHBh biBzY2hyaWViOg08YnI+CiAgID4NPGJyPgogICA+ICA+IEkgYW0gdHJ5aW5nIHRvIGNvZGUgYSBu dW1lcmljIGNsYXNzIGluIHdoaWNoIHNvbWUgZmxvYXQgbnVtYmVycywNPGJyPgogICA+ICA+IGxp a2UgNC4yNTc5MDMyMSwgd2lsbCBiZSBzdG9yZWQgd2l0aCB2YXJ5aW5nIGRlY2ltYWwgc2l6ZXMg YXM6DTxicj4KICAgPiAgPg08YnI+CiAgID4gID4gNC4yNTc5MCAoZGVjaW1hbCBzaXplID0gNSkN PGJyPgogICA+ICA+IDQuMjU3IChkZWNpbWFsIHNpemUgPSAzKQ08YnI+CiAgID4gID4gNC4xIChk ZWNpbWFsIHNpemUgPTEpDTxicj4KICAgPiAgPg08YnI+CiAgID4gID4gZGVwZW5kaW5nIG9uIGFu IGF0dHJpYnV0ZSBzZWxmLmRlY2ltYWxTaXplIHNldCBieSB0aGUgdXNlcnMuDTxicj4KICAgPiAg Pg08YnI+CiAgID4gID4gSSBsZWFybmVkIHRoYXQgdGhlIGRlY2ltYWwgc2l6ZSBjYW4gYmUgc2V0 IGFzIGZvbGxvd3M6DTxicj4KICAgPiAgPg08YnI+CiAgID4gID4gZmxvYXQoJyUuM2YnICVuKQ08 YnI+CiAgID4gID4gZGVjaW1hbCBzaXplID0gMyB0aGVuIGNvbnZlcnRpbmcgYmFjayB0byBmbG9h dA08YnI+CiAgID4gID4NPGJyPgogICA+ICA+IEJ1dCBpdCBzZWVtcyB0byBiZSBpbXBvc3NpYmxl IHRvIHNldCBpdCBkeW5hbWljYWxseToNPGJyPgogICA+ICA+DTxicj4KICAgPiAgPiBmbG9hdCgn JS4laWYnICUoaSxuKSkNPGJyPgogICA+ICA+IGZsb2F0KCclLiglaSlmJyAlKGksbikpDTxicj4K ICAgPiAgPg08YnI+CiAgID4gID4gYm90aCBmYWlsZWQuDTxicj4KICAgPiAgPg08YnI+CiAgID4g ID4gSSBjYW4gZmluZCBhIGRldG91ciBieQ08YnI+CiAgID4gID4NPGJyPgogICA+ICA+IFsxXSBt dWx0aXBseWluZyBieSAxMDAwIChpZiB0aGUgcmVxdWlyZWQgZGVjaW1hbCBzaXplID0zKQ08YnI+ CiAgID4gID4gWzJdIHRoZW4gZGV2aWRlZCBieSAxMDAwLjANPGJyPgogICA+ICA+DTxicj4KICAg PiAgPiBidXQgaXQgc2VlbXMgdG8gYmUgdG9vIHRlZGlvdXMgdG8gbWUuDTxicj4KICAgPiAgPg08 YnI+CiAgID4gID4gQW55IGJldHRlciB3YXkgdG8gYWNoaWV2ZSB0aGlzPw08YnI+CiAgID4NPGJy PgogICA+ICBZZXMgeW91IGNhbiBkbyB0aGlzIGJ5IHVzaW5nIHRoZSAqLW5vdGF0aW9uOg08YnI+ CiAgID4NPGJyPgogICA+ICA+Pj4gZiA9IDAuMTIzNDU2Nzg5DTxicj4KICAgPiAgPj4+IGZvciBp IGluIHJhbmdlKDEwKToNPGJyPgogICA+ICBwcmludCAiJS4qZiIgJSAoaSxmKQ08YnI+CiAgID4N PGJyPgogICA+DTxicj4KICAgPiAgMA08YnI+CiAgID4gIDAuMQ08YnI+CiAgID4gIDAuMTINPGJy PgogICA+ICAwLjEyMw08YnI+CiAgID4gIDAuMTIzNQ08YnI+CiAgID4gIDAuMTIzNDYNPGJyPgog ICA+ICAwLjEyMzQ1Nw08YnI+CiAgID4gIDAuMTIzNDU2OA08YnI+CiAgID4gIDAuMTIzNDU2NzkN PGJyPgogICA+ICAwLjEyMzQ1Njc4OQ08YnI+CiAgID4gID4+Pg08YnI+CiAgID4NPGJyPgogICA+ ICBUaGUgY29ycmVzcG9uZGluZyBkb2NzIGFyZSBoZXJlOg08YnI+CiAgID4gIEk6UHl0aG9uMjJE b2NsaWJ0eXBlc3NlcS1zdHJpbmdzLmh0bWwNPGJyPgogICA+DTxicj4KICAgPiAgUmVnYXJkcywg R3JlZ29yDTxicj4KICAgPg08YnI+CiAgID4NPGJyPgogICA+ICA+DTxicj4KICAgPiAgPiBUaHgg aW4gYWR2YW5jZQ08YnI+CiAgID4gID4NPGJyPgogICA+ICA+IFNpbmNlcmVseSwNPGJyPgogICA+ ICA+IHBhbg08YnI+CiAgID4gID4NPGJyPgogICA+ICA+ID09PT09PT09PT09PT09PT09PT09PT0N PGJyPgogICA+ICA+IH5+fn5+IGJlIHNoYXBlbGVzcyB+fn5+fg08YnI+CiAgID4gID4NPGJyPgog ICA+ICA+IFJ1bnN1biBQYW4sIFBoRA08YnI+CiAgID4gID4gRGVwdC4gb2YgRWNvbG9neSAmIEV2 b2x1dGlvbg08YnI+CiAgID4gID4gVS4gb2YgQ2hpY2FnbywgVVNBDTxicj4KICAgPiAgPiA9PT09 PT09PT09PT09PT09PT09PT09DTxicj4KICAgPg08YnI+CiAgID4NPGJyPgogICA+DTxicj4KICAg Pg08YnI+CiAgID4NPGJyPgogICAtLS0tLS0tT3JpZ2luYWwgTWVzc2FnZS0tLS0tLS0NPGJyPgoN PGJyPgo8YnI+CjwvYm9keT48L2h0bWw+Cg== --_bf5c07200ec7f074cd37152c2a36a3400-- From jeff@ccvcorp.com Wed Mar 5 19:30:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Mar 5 19:30:02 2003 Subject: [Tutor] Dynamic decimal size References: <20030305235218.16048.qmail@station172.com> Message-ID: <3E66966B.3050006@ccvcorp.com> pan wrote: > I am trying to code a numeric class in which some float numbers, > like 4.25790321, will be stored with varying decimal sizes as: > [...] > Any better way to achieve this? Are you doing this because you want the functionality, or is it just an exercise? If the former, there's already a couple of packages available that provide arbitrary-precision decimals like this. Unfortunately, I don't recall any package names, but I recall some discussion a while back on comp.lang.python about a "rough" module by Tim Peters, and a more extensive attempt at an IEEE-standards-compliant module by (IIRC) Aahz. You can probably find one or both of these at the Vaults of Parnassus ( www.vex.net/parnassus ), or just google comp.lang.python for "arbitrary precision decimal". If you're doing this as an exercise, be aware that converting back and forth between floats is a lot less reliable than you might think. Floats use a binary exponent format, and there are some decimal numbers that simply cannot be exactly expressed in this format, as well as some float numbers that cannot be exactly expressed as decimals. You can get pretty decent approximations, which are good enough for most purposes, but if you look closely enough you'll find discrepancies. For instance, 0.1 (one tenth) cannot be exactly represented as a float, and an approximation must be used: >>> 0.100 0.10000000000000001 >>> If you have any need of precision, you'll be better off storing your numbers as an integer (say, 42579) and a scale factor (say, 4), the number of places to move the decimal point. When performing arithmetic on two such numbers, you convert the smaller scale factor one to match the larger scale factor. Jeff Shannon Technician/Programmer Credit International From magnus@thinkware.se Wed Mar 5 19:43:17 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Mar 5 19:43:17 2003 Subject: [Tutor] Re: Closing files / strings are immutable In-Reply-To: References: <5.1.0.14.0.20030305225011.02d3c028@www.thinkware.se> Message-ID: <5.1.0.14.0.20030306012456.02d153b0@www.thinkware.se> At 16:08 2003-03-05 -0800, Danny Yoo wrote: >When we have an open()ed file in "write" mode, it becomes more important >to make sure to close the file, especially in Jython. Yes, but is it always safe to implicitly close on read, as in "data = file(filename).read()" if we subsequently write to the same file? Or is there a risk that the file is still open when we try to open it for writing, and that the second open thus fail as in: >>> x = file('c:/autoexec.bat', 'r') >>> y = file('c:/autoexec.bat', 'w') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 13] Permission denied: 'c:/autoexec.bat' >>> x.close() It shouldn't happen in CPython, since the file object will be garbage collected at once if it's not bound to any variable etc (like x above), but as I said, Java has another type of garbage collector, and the file might still be open when we try to open it the second time there. This idiom ("d = file(fn).read()") is fairly common in Python, but then most python code is not used in Jython, and most of the time we don't write to the files we just read. As Danny also noted, it might be a good idea to save a backup of the original. If you first rename the original, then open it, and finally write your data to the file name that the input file had before you renamed it, you won't actually open the same file more then once, and then it's not an issue, but it's no big effort to explicitly type three lines: f = file(fname, mode) f.read() or f.write(x) f.close() For renaming (and deleting files) there are functions in the os module (rename, remove). Never use stuff like os.system("move %s %s" % (orgFileName, buFileName)) or os.system("del %s" % filename) etc. The proper os module calls will be portable and give proper exceptions on failure. As always, reading the library module is a rewarding effort. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From glingl@aon.at Wed Mar 5 19:52:04 2003 From: glingl@aon.at (Gregor Lingl) Date: Wed Mar 5 19:52:04 2003 Subject: [Tutor] Dynamic decimal size References: <20030306002437.16567.qmail@station172.com> Message-ID: <3E669893.8050404@aon.at> pan schrieb: > > Gees, Gregor, you are quick in helping people :) Hmmm! Sometimes. But not if metaclasses are the topic. This certainly cannot be answered in a line or two. But i'm sure, a reply will arrive soon ... I suppose you read this: http://www-106.ibm.com/developerworks/library/l-pymeta.html (via a hint from the daily python url) I'm just beginning to study it. Let's dive into it Gregor > > > Thx a lot. > > pan > > > -------Original Message------- > > From: prog@runsun.info > > Subject: Re: Re: [Tutor] Dynamic decimal size > > Sent: Mar 06 2003 00:07:29 > > > > > > pan schrieb: > > > > > I am trying to code a numeric class in which some float numbers, > > > like 4.25790321, will be stored with varying decimal sizes as: > > > > > > 4.25790 (decimal size = 5) > > > 4.257 (decimal size = 3) > > > 4.1 (decimal size =1) > > > > > > depending on an attribute self.decimalSize set by the users. > > > > > > I learned that the decimal size can be set as follows: > > > > > > float('%.3f' %n) > > > decimal size = 3 then converting back to float > > > > > > But it seems to be impossible to set it dynamically: > > > > > > float('%.%if' %(i,n)) > > > float('%.(%i)f' %(i,n)) > > > > > > both failed. > > > > > > I can find a detour by > > > > > > [1] multiplying by 1000 (if the required decimal size =3) > > > [2] then devided by 1000.0 > > > > > > but it seems to be too tedious to me. > > > > > > Any better way to achieve this? > > > > Yes you can do this by using the *-notation: > > > > >>> f = 0.123456789 > > >>> for i in range(10): > > print "%.*f" % (i,f) > > > > > > 0 > > 0.1 > > 0.12 > > 0.123 > > 0.1235 > > 0.12346 > > 0.123457 > > 0.1234568 > > 0.12345679 > > 0.123456789 > > >>> > > > > The corresponding docs are here: > > I:Python22Doclibtypesseq-strings.html > > > > Regards, Gregor > > > > > > > > > > Thx in advance > > > > > > Sincerely, > > > pan > > > > > > ====================== > > > ~~~~~ be shapeless ~~~~~ > > > > > > Runsun Pan, PhD > > > Dept. of Ecology & Evolution > > > U. of Chicago, USA > > > ====================== > > > > > > > > > > > -------Original Message------- > > From magnus@thinkware.se Wed Mar 5 20:18:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Mar 5 20:18:01 2003 Subject: [Tutor] Re: Dynamic decimal size In-Reply-To: <20030306002502.7443.37908.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030306014547.02d51a38@www.thinkware.se> >pan schrieb: First of all, pan: Please post in ASCII to the mailing list. Your mails just look like garbage in the digests and archives: See http://mail.python.org/pipermail/tutor/2003-March/021156.html > > I am trying to code a numeric class in which some float numbers, > > like 4.25790321, will be stored with varying decimal sizes as: Since I can't read your mail I'm not sure what you want, but maybe you are after something like: http://fixedpoint.sourceforge.net/ There are a number of decimal/fixed point/rational libraries for python. Please don't write one more. Use (and maybe improve/extend) one of the current instead. There is an effort underway, to include something like this in the standard library, but there is some reluctance. FixedPoint was written by Tim Peters and he's not willing to do what is needed to get it included in the std lib. Some others have said they would, but I'm not sure it's fully done, and Tim has said that he'd prefer to see an implementation that fully follows Mike Cowlishaw's proposal at www2.hursley.ibm.com/decimal/ . -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Wed Mar 5 20:22:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Mar 5 20:22:03 2003 Subject: [Tutor] Re: Tutor digest, Vol 1 #2302 - 11 msgs In-Reply-To: <20030305170007.31088.7937.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030306011509.02d3aa50@www.thinkware.se> Mic Forster wrote: >TypeError: fun() takes exactly 2 arguments (1 given) > >>> I think the error message is very clear. :) The bisect function provides one variable to the function call. What I did in my original example, if I remember coerrectly, was to do like this (although the values were different then): s = 33 j = 1. / 7861 def fun(k): return f(k, s) - j delta = 1e-9 bisect(delta, 1-delta, delta, fun) You could design the bisect function so that it takes more parameters, but it gets more complicated. If you don't like these global variables, you could use lambda I guess... I'll give you two versions, without and with lambda... def bisect(min, max, delta, function): fMax = function(max) fMin = function(min) assert fMax * fMin < 0, locals() while max - min > delta: newX = 0.5 * (min + max) fNew = function(newX) if fNew * fMax > 0: max, fMax = newX, fNew else: min, fMin = newX, fNew return newX, fNew def f(k, s, j): # I'll stick to the old equation return k / (1-k) * (1-k)**s / (1-(1-k)**s) - j delta = 1e-9 # No lambda for s, jInv in [(11, 862), (33, 7861)]: j = 1./jInv print "j = %f s = %i" % (j,s) def fun(k): return f(k, s, j) print "k = %.17f +/- %e" % bisect(delta, 1-delta, delta, fun) print # With lambda for s, jInv in [(11, 862), (33, 7861)]: j = 1./jInv print "j = %f s = %i" % (j,s) print "k = %.17f +/- %e" % bisect(delta, 1-delta, delta, lambda k: f(k, s, j)) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From tim.one@comcast.net Wed Mar 5 21:29:01 2003 From: tim.one@comcast.net (Tim Peters) Date: Wed Mar 5 21:29:01 2003 Subject: [Tutor] Re: Dynamic decimal size In-Reply-To: <5.1.0.14.0.20030306014547.02d51a38@www.thinkware.se> Message-ID: [Magnus Lycka] > ... > There are a number of decimal/fixed point/rational libraries for > python. Please don't write one more. Heh . > Use (and maybe improve/extend) one of the current instead. There is an > effort underway, to include something like this in the standard library, > but there is some reluctance. FixedPoint was written by Tim Peters and > he's not willing to do what is needed to get it included in the std lib. Not quite: I was always willing to, but I couldn't get approval to spend any work time on it, and I have no spare time. > Some others have said they would, but I'm not sure it's fully done, > and Tim has said that he'd prefer to see an implementation that fully > follows Mike Cowlishaw's proposal at www2.hursley.ibm.com/decimal/ . That's still so, and Eric Price has made great progress toward that end very recently. Some version of that should be available "soon", and IBM's proposal (spearheaded by Cowlishaw) is by far the best thought-out proposal of this ilk. From op73418@mail.telepac.pt Wed Mar 5 22:43:02 2003 From: op73418@mail.telepac.pt (Goncalo Rodrigues) Date: Wed Mar 5 22:43:02 2003 Subject: [Tutor] What is the metaclass for? References: <20030306000115.6234.qmail@station172.com> Message-ID: <002f01c2e393$46ec1590$15120dd5@violante> This is a multi-part message in MIME format. ------=_NextPart_000_002C_01C2E393.46BE4ED0 Content-Type: text/plain; charset="Big5" Content-Transfer-Encoding: quoted-printable Look: http://www-106.ibm.com/developerworks/library/l-pymeta.html >From there, the following quote: Metaclasses are deeper magic than 99% of users should ever worry about. = If you wonder whether you need them, you don't (the people who actually = need them know with certainty that they need them, and don't need an = explanation about why). -- Python Guru Tim Peters=20 ----- Original Message -----=20 From: pan=20 To: tutor@python.org=20 Sent: Thursday, March 06, 2003 12:01 AM Subject: [Tutor] What is the metaclass for? Hi all,=20 I've been reading something about metaclass but most of the=20 documents I read so far are more or less like Martian codes to=20 me. Especially, they didn't give me an idea for why we need to=20 use a metaclass.=20 Can someone describe under what a metaclass is for and under=20 circumstances do we need to consider using them?=20 What I learned so far is:=20 An instance of a 'classic' class is an object=20 An instance of a metaclass is a class=20 what advantage of the above behavior?=20 Thx in advance.=20 pan=20 =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D ~~~~~ be shapeless ~~~~~ Runsun Pan, PhD Dept. of Ecology & Evolution U. of Chicago, USA =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=20 ------=_NextPart_000_002C_01C2E393.46BE4ED0 Content-Type: text/html; charset="Big5" Content-Transfer-Encoding: quoted-printable
Look:
 
http= ://www-106.ibm.com/developerworks/library/l-pymeta.html
 
From there, the following = quote:
 
Metaclasses are deeper magic than 99% of users should ever worry = about. If=20 you wonder whether you need them, you don't (the people who actually = need them=20 know with certainty that they need them, and don't need an explanation = about=20 why). -- Python Guru Tim Peters
 
----- Original Message -----
From:=20 pan =
Sent: Thursday, March 06, 2003 = 12:01=20 AM
Subject: [Tutor] What is the = metaclass=20 for?

Hi all,

I've been reading something about = metaclass but=20 most of the
documents I read so far are more or less like Martian = codes to=20
me. Especially, they didn't give me an idea for why we need to =
use a=20 metaclass.

Can someone describe under what a metaclass is for = and=20 under
circumstances do we need to consider using them? =

What I=20 learned so far is:

An instance of a 'classic' class is an = object=20
An instance of a metaclass is a class

what advantage of = the above=20 behavior?

Thx in advance.

pan=20 =



=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D
~~~~~ be shapeless=20 ~~~~~

Runsun Pan, PhD
Dept. of Ecology & Evolution
U. = of=20 Chicago, = USA
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= ------=_NextPart_000_002C_01C2E393.46BE4ED0-- From phthenry@earthlink.net Wed Mar 5 23:27:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Wed Mar 5 23:27:01 2003 Subject: [Tutor] What is the metaclass for? In-Reply-To: <3E669206.4060701@ccvcorp.com> References: <20030306000115.6234.qmail@station172.com> <3E669206.4060701@ccvcorp.com> Message-ID: <20030305232623.H32062@localhost.localdomain> On Wed, Mar 05, 2003 at 04:10:46PM -0800, Jeff Shannon wrote: > My short answer would be that metaclasses are a mechanism for black > magic -- or at least, very dark grey magic. Very funny! -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From antonmuhin at rambler.ru" References: <20030305031600.44894.qmail@web13403.mail.yahoo.com> Message-ID: <282595572.20030306142555@rambler.ru> Hello Mic, Wednesday, March 5, 2003, 6:16:00 AM, you wrote: [snip] >>>> def fun(k, s): MF> return f(k, s) - j >>>> delta = 1e-9 >>>> bisect(delta, 1-delta, delta, fun) MF> Traceback (most recent call last): MF> File "", line 1, in ? MF> bisect(delta, 1-delta, delta, fun) MF> File "", line 2, in bisect MF> fMax = function(max) MF> TypeError: fun() takes exactly 2 arguments (1 given) >>>> Quite reasonable I must say :). Your function fun takes couple of arguments---k and s and f too althouh s argument seems to be unused. You may modify it as: def f(x): return ... def fun(k): return f(k) - j Or write a wrapper function: def wrapFun(x): return fun(x, some constant goes here) Or even with lambda: bisect(delta, 1 - delta, delta, lambda x: fun(x, smth...)) BTW, although you script is quite short, you'd better avoid global variables like j. If you need a set of functions like fun. Python can provide with better (IMHO) options: 1. def makeFun(j): def newF(x): f(x) - j return newF 2. Lambdas again: myF = lambda x: f(x) - j -- Best regards, anton mailto:antonmuhin@rambler.ru From wolf_binary@hotmail.com Thu Mar 6 09:59:16 2003 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Thu Mar 6 09:59:16 2003 Subject: [Tutor] C++ speed and special tricks Message-ID: Hi all, I know this is a bit off topic okay a lot, but this is the only place I know that has people who really want to help. Where can I go to find out things like bit shifting being faster than multiplication and division for binary numbers? These are tricks and language specific issues that C++ has. But to bring it back on topic, can you embed Python in C++? Thanks, Cameron _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From dyoo@hkn.eecs.berkeley.edu Thu Mar 6 10:25:16 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 6 10:25:16 2003 Subject: [Tutor] What is the metaclass for? In-Reply-To: <3E669206.4060701@ccvcorp.com> Message-ID: > > Can someone describe under what a metaclass is for and under > > circumstances do we need to consider using them? > > > My short answer would be that metaclasses are a mechanism for black > magic -- or at least, very dark grey magic. ;) Odds are good that if > what you read about metaclasses makes no sense, then you're not likely > to need metaclasses for anything that you're doing -- it's a very > advanced subject for advanced programmers. (Read this as -- I don't know > just what to do with them either, so I'm sticking to what I can > understand! ;) They're a fairly new addition to Python and I never felt > limited by their absence. But they seem to make some people happy...) Does anyone have the Python Cookbook (dead trees version) handy? I'm actually still in Santa Fe, and forgot to bring mine with me, but I remember seeing a really awesome example of metaclasses in one of the later chapters in the Python Cookbook. I'll be back home tomorrow, so I'll try to correctly quote the example when I return. Concrete examples often make abstract concepts less difficult to perceive. Someone had once asked if the idea of an "interface" could be handled in Python. Metaclasses allow us to extend Python's idea of a class to include interfaces: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/164901 Hope this helps! From rob@uselesspython.com Thu Mar 6 11:44:01 2003 From: rob@uselesspython.com (Rob Andrews) Date: Thu Mar 6 11:44:01 2003 Subject: [Tutor] C++ speed and special tricks In-Reply-To: Message-ID: There's a usenet group: alt.comp.lang.learn.c-c++ where you may find a community of people interested in helping people learn C++ (as well as C). For the usenet uninitiated/ambivalent, you can find the group by going to http://groups.google.com/ and typing "alt.comp.lang.learn.c-c++" in the Google Search bar. Before posting, it would be wise to read the group's FAQ, which I believe may be found here: http://snurse-l.org/acllc-c++/faq.html http://python.org/doc/current/ext/ext.html has Python embedding information. -Rob A. http://uselesspython.com > I know this is a bit off topic okay a lot, but this is the only > place I know > that has people who really want to help. Where can I go to find > out things > like bit shifting being faster than multiplication and division > for binary > numbers? These are tricks and language specific issues that C++ has. > > But to bring it back on topic, can you embed Python in C++? From op73418@mail.telepac.pt Thu Mar 6 12:14:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Mar 6 12:14:01 2003 Subject: [Tutor] What is the metaclass for? References: Message-ID: <000701c2e404$b7e1b5e0$fb100dd5@violante> ----- Original Message ----- From: "Danny Yoo" To: "Jeff Shannon" Cc: Sent: Thursday, March 06, 2003 3:22 PM Subject: Re: [Tutor] What is the metaclass for? > > > > Can someone describe under what a metaclass is for and under > > > circumstances do we need to consider using them? > > > > > > My short answer would be that metaclasses are a mechanism for black > > magic -- or at least, very dark grey magic. ;) Odds are good that if > > what you read about metaclasses makes no sense, then you're not likely > > to need metaclasses for anything that you're doing -- it's a very > > advanced subject for advanced programmers. (Read this as -- I don't know > > just what to do with them either, so I'm sticking to what I can > > understand! ;) They're a fairly new addition to Python and I never felt > > limited by their absence. But they seem to make some people happy...) > > > Does anyone have the Python Cookbook (dead trees version) handy? I'm > actually still in Santa Fe, and forgot to bring mine with me, but I > remember seeing a really awesome example of metaclasses in one of the > later chapters in the Python Cookbook. I'll be back home tomorrow, so > I'll try to correctly quote the example when I return. > > Concrete examples often make abstract concepts less difficult to perceive. > Someone had once asked if the idea of an "interface" could be handled in > Python. Metaclasses allow us to extend Python's idea of a class to > include interfaces: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/164901 > > Let me add another example, also of my doing: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/149148 <\shameless-plug> The recipes builds a metaclass whose instances are the Z_n rings of finite arithmetic. They are infinite in number so you have to use some kind of factory. Add to that the fact that I wanted each Z_n to be a class and the metaclass solution becomes obvious. All the best, G. Rodrigues From alan.gauld@bt.com Thu Mar 6 12:22:05 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Mar 6 12:22:05 2003 Subject: [Tutor] What is the metaclass for? Message-ID: > > I've been reading something about metaclass but most of the > > documents I read so far are more or less like Martian codes to > My short answer would be that metaclasses are a mechanism for black > magic -- or at least, very dark grey magic. ;) Odds are good that if > what you read about metaclasses makes no sense, then you're not likely > to need metaclasses for anything that you're doing I'd second that, but I'll have a go anyway... Metaclasses do slightly different things in different languages. Basically they can variously be thought of as factory classes, a home for class methods(ie ones which act on all instances of a class) or class generators(somewhat like higher order functions - which return other functions as a result). One example might be a meta string class from which we can instantiate multiple different string type classes. For example one string will act as normal, another converts all to lowercase, another to upper case etc. All of this ontrolled by a constructor parameter... Other things become too much like black magic to explain here, but there is a hard to find Metaclass book that goes into the darker corners... Alan G. From alan.gauld@bt.com Thu Mar 6 12:40:03 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Mar 6 12:40:03 2003 Subject: [Tutor] I have a small project I want to work on.. Message-ID: > Plus, I honestly never really bothered to learn how to do any > calculations with spreadsheet software, so although I can see all the > income on the sheet, I'd far prefer to just whip up some code While that might be fun, learning to use the spereadsheet math is probably a more useful way to spend your time! :-) Even if you only use a PDA there will be a spreadsheet that you can use on your main computer, and they are desgned for exactly this kind of job. But then again some folks program in assembler just for fun... Alan G. PS Erik I thought you used a Mac? Don't you have Apple's office suite on it complete with a spreadsheet? From alan.gauld@bt.com Thu Mar 6 12:55:04 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Mar 6 12:55:04 2003 Subject: [Tutor] C++ speed and special tricks Message-ID: > like bit shifting being faster than multiplication and > division for binary numbers? Its not always true since a good optimising compiler will often substitute a bitshift for multiplication etc anyway if one operand is a power of two... > These are tricks and language specific issues that C++ has. Actually you can do that particular trick in any language that does bit shifting - including Python! But you shouldn't... a) Because it makes the code much harder to fread and maintain and b) because in C/C++ its often wasted effort coz the compiler does the same trick as needed... > But to bring it back on topic, can you embed Python in C++? Yes, there are some articles on the Python web site. Alan G. From tim@johnsons-web.com Thu Mar 6 14:00:04 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Thu Mar 6 14:00:04 2003 Subject: [Tutor] Idle on RH 7.2 questions Message-ID: <20030306190721.GH20793@johnsons-web.com> Hello All: I am using RH 7.2 with python 1.5.2 as the default for the distribution (I believe). I would prefer to leave 1.5.2 as it is and have also installed Python 2.2.2 I would like to use idle with 2.2.2 and my current idle looks like this: # #! /usr/bin/env python import os import sys from idlelib import IdleConf idle_dir = os.path.dirname(IdleConf.__file__) IdleConf.load(idle_dir) # defer importing Pyshell until IdleConf is loaded from idlelib import PyShell PyShell.main() # and I have the idle (2.2) directory at /usr/local/lib/python2.2/site-packages/idle when I run idle, I get the following error message: Traceback (innermost last): File "/usr/bin/idle", line 5, in ? from idlelib import IdleConf ImportError: No module named idlelib I cannot 'locate' or 'find' on my machine My questions are: 1)Is idlelib a seperate distribution or 2)Have I made an error in my installation of python2.2 TIA -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From python@jaydorsey.com Thu Mar 6 15:31:41 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Thu Mar 6 15:31:41 2003 Subject: [Tutor] pycurl RETURNTRANSFER Message-ID: <3E67AFEA.2050006@jaydorsey.com> I'm trying to get a page returned in a variable using PyCurl, but it doesn't seem to have the RETURNTRANSFER option implemented. Can anyone confirm/deny this for me, or is there some other way to get the page returned as a variable instead of a having to do a filewrite? Below is how I'm currently working it, along with how I thought RETURNTRANSFER should be set, I *reallly* dont' want to have to do a file write though. f = open('myfile','w') cp = pycurl.Curl() cp.setopt(cp.URL, 'http://www.msn.com/') cp.setopt(cp.HEADER, 1) cp.setopt(cp.NOPROGRESS, 1) #cp.setopt(cp.REFERER, referer) #cp.setopt(cp.COOKIE, cookie) # the line below doesn't work #cp.setopt(cp.RETURNTRANSFER, page) # write the HTML page to a file cp.setopt(cp.WRITEFUNCTION, f.write) cp.perform() cp.close() Any help is appreciated. -- Jay Dorsey python at jay dorsey dot com From reavey@nep.net Thu Mar 6 17:50:18 2003 From: reavey@nep.net (reavey) Date: Thu Mar 6 17:50:18 2003 Subject: [Tutor] attribute references unbound method Message-ID: <3E6921E9.2050805@nep.net> Mike Reavey wrote: >>>class MyClass: "a simple example" n = 1234 def f(self): print "hello" >>>MyClass.n 1234 >>>MyClass.f >>>MyClass.f(self) NameError: name 'self' is not defined I found this trying to learn class objects in the Python Tutorial 9.3.2 I know I'm doing something wrong, but can't put my finger on it. thanks re-v From dyoo@hkn.eecs.berkeley.edu Thu Mar 6 18:13:17 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 6 18:13:17 2003 Subject: [Tutor] attribute references unbound method In-Reply-To: <3E6921E9.2050805@nep.net> Message-ID: On Fri, 7 Mar 2003, reavey wrote: > >>>class MyClass: > "a simple example" > n = 1234 > def f(self): > print "hello" > > >>>MyClass.n > 1234 > >>>MyClass.f > > >>>MyClass.f(self) > NameError: name 'self' is not defined > > I found this trying to learn class objects in the Python Tutorial 9.3.2 > I know I'm doing something wrong, but can't put my finger on it. Hi Mike, Try: ### instance = MyClass() MyClass.f(instance) ### That is, we first create an instance of a MyClass. Once we have that, then we can send it over to MyClass.f() as a parameter. Let's look back at that error message: ### >>> MyClass.f(self) NameError: name 'self' is not defined ### When Python tries to evaluate something like: MyClass.f(self) Python's first reaction is to figure out what 'self' means. (Actually, that's not quite true; Python actually tries to figure out what 'MyClass.f' is, but your experiments above show that it has no problem seeing that 'MyClass.f' is an "unbound function".) That NameError error message, then, is just saying that Python has no idea what 'self' is; it's similar to what happens when we try to use a variable name that hasn't been assigned: ### >>> foo Traceback (most recent call last): File "", line 1, in ? NameError: name 'foo' is not defined ### So the error that you were getting isn't really too related to the OOP stuff that you're experimenting with. I hope this helps! From gp@pooryorick.com Fri Mar 7 02:23:02 2003 From: gp@pooryorick.com (Poor Yorick) Date: Fri Mar 7 02:23:02 2003 Subject: [Tutor] depth first with a twist References: <269620-22003302164144825@M2W054.mail2web.com> <163115539.20030303141951@rambler.ru> <3E64516C.1020701@pooryorick.com> <648990387.20030304202637@rambler.ru> Message-ID: <3E684948.1050509@pooryorick.com> antonmuhin íà rambler.ru wrote: >Hello > >Don't you want to use more tree-ish structure? > >Sorry, I couldn't grasp well what you are going to do, but if you'll >reformulate your problem, I'll do my best to help you. > Using my original post as an example: d = {'monty': [None, None, "Monty Python's Flying Circus"], 'actors': ['monty', None, 'Actor Data'], 'sketches': ['monty', 'actors', 'Sketch Data'], 'basic': ['actors', None, 'Basic Bio'], 'filmography': ['actors', 'basic', 'Filmography']} PARENT = 0 OLDER_SIBLING = 1 NAME = 2 ORDER = 3 I am trying to come up with a tree which looks like this: Monty Python's Flying circus Actors Basic Bio Filmography Sketch Data I need to store this tree in a csv, and I decided that I need parent and older sibling data for each node in order to reconstitute the tree from the csv. For the previous example, the headers are: key, parent, older_sibling, name I am using the data to create a form, so I'm looking for an algorithm to order the nodes, depth first. Is that enough information? (My apologies to Magnus, who wrote quite a detailed response to my first request. I am still digesting your respone.) Thank you, Poor Yorick gp@pooryorick.com From erikprice@mac.com Fri Mar 7 07:51:00 2003 From: erikprice@mac.com (Erik Price) Date: Fri Mar 7 07:51:00 2003 Subject: [Tutor] Re: Dynamic decimal size In-Reply-To: Message-ID: <8221C5C8-509D-11D7-9046-00039351FE6A@mac.com> On Wednesday, March 5, 2003, at 09:27 PM, Tim Peters wrote: >> Some others have said they would, but I'm not sure it's fully done, >> and Tim has said that he'd prefer to see an implementation that fully >> follows Mike Cowlishaw's proposal at www2.hursley.ibm.com/decimal/ . > > That's still so, and Eric Price has made great progress toward that > end very > recently. Some version of that should be available "soon", and IBM's > proposal (spearheaded by Cowlishaw) is by far the best thought-out > proposal > of this ilk. Hm. There must be something about Python that attracts the Eri[c|k] Prices. (That's not me!) Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Fri Mar 7 08:05:04 2003 From: erikprice@mac.com (Erik Price) Date: Fri Mar 7 08:05:04 2003 Subject: [Tutor] What is the metaclass for? In-Reply-To: <3E669206.4060701@ccvcorp.com> Message-ID: <63133428-509F-11D7-9046-00039351FE6A@mac.com> On Wednesday, March 5, 2003, at 07:10 PM, Jeff Shannon wrote: > My short answer would be that metaclasses are a mechanism for black > magic -- or at least, very dark grey magic. ;) Odds are good that if > what you read about metaclasses makes no sense, then you're not likely > to need metaclasses for anything that you're doing -- it's a very > advanced subject for advanced programmers. (Read this as -- I don't > know > just what to do with them either, so I'm sticking to what I can > understand! ;) They're a fairly new addition to Python and I never felt > limited by their absence. But they seem to make some people happy...) There is a fairly popular article (among Python advocates) written by open source software advocate Eric Raymond where he describes a pretty easy-to-follow instance of using metaclasses. Essentially he wanted a way to let his configuration file dynamically indicate which methods should be called on his classes (he was writing a program that parses a configuration file to make it easier for people to run a mail transfer agent program called "fetchmail"). http://www.linuxjournal.com/article.php?sid=3882 He describes metaclass programming about a third of the way through the article. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From vicki@stanfield.net Fri Mar 7 11:11:20 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Fri Mar 7 11:11:20 2003 Subject: [Tutor] Displaying stdio and stdin Message-ID: <20030307081008.7337.h017.c000.wm@mail.stanfield.net.criticalpath.net> In the application that I am developing, I send commands to a device and retrieve the device's response. I want to display both what is sent and what is retrieved in some kind of widget on the GUI. What is generally used for this type of thing. I am able to redirect the stdio and stdout to a file, but I am not aware of a widget which will display a data stream. Am I dreaming? Do I have to build it myself? --vicki From ramrom@earthling.net Fri Mar 7 13:26:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Mar 7 13:26:01 2003 Subject: [Tutor] TKinter - display dialog w/o using mainloop() In-Reply-To: <20030307081008.7337.h017.c000.wm@mail.stanfield.net.critic alpath.net> Message-ID: <5.2.0.9.0.20030307112120.02e29140@66.28.54.253> --=======FB74737======= Content-Type: text/plain; x-avg-checked=avg-ok-24A13915; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit class Dialog(Frame): def __init__(self): Frame.__init__(self, None) self.pack() self.Label['text'] = 'initial text' self.Label.pack({"side": "top"}) d = Dialog() How do I get the dialog box to be visible w/o using mainloop(). I want to show the dialog and then do other things in my program, which might result in reassigning d.Label['text'] = 'new text' Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======FB74737======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-24A13915 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======FB74737=======-- From ckasso@sprynet.com Fri Mar 7 14:47:02 2003 From: ckasso@sprynet.com (Chris Kassopulo) Date: Fri Mar 7 14:47:02 2003 Subject: [Tutor] Idle on RH 7.2 questions In-Reply-To: <20030306190721.GH20793@johnsons-web.com> References: <20030306190721.GH20793@johnsons-web.com> Message-ID: <20030307150638.0b8fbd50.ckasso@sprynet.com> > Tim Johnson wrote: > Hello All: > I am using RH 7.2 with python 1.5.2 as the default > for the distribution (I believe). I would prefer to > leave 1.5.2 as it is and have also installed Python 2.2.2 > > I would like to use idle with 2.2.2 and my current idle > looks like this: > # > #! /usr/bin/env python > > import os > import sys > from idlelib import IdleConf > > idle_dir = os.path.dirname(IdleConf.__file__) > IdleConf.load(idle_dir) > > # defer importing Pyshell until IdleConf is loaded > from idlelib import PyShell > PyShell.main() > # > and I have the idle (2.2) directory at > /usr/local/lib/python2.2/site-packages/idle > > when I run idle, I get the following error message: > Traceback (innermost last): > File "/usr/bin/idle", line 5, in ? > from idlelib import IdleConf > ImportError: No module named idlelib > I cannot 'locate' or 'find' on my machine > My questions are: > 1)Is idlelib a seperate distribution > or > 2)Have I made an error in my installation of > python2.2 > > TIA Greetings Tim, Note that I am using python 2.2 under slackware. /usr/lib/python2.2/site-packages/idlelib is the directory that contains IdleConf.py and there is no site-packages/idle directory. Chris From ramrom@earthling.net Fri Mar 7 19:39:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Mar 7 19:39:01 2003 Subject: [Tutor] Displaying stdio and stdin In-Reply-To: <20030307081008.7337.h017.c000.wm@mail.stanfield.net.critic alpath.net> Message-ID: <5.2.0.9.0.20030307171639.02e248c8@66.28.54.253> --=======1003E63======= Content-Type: text/plain; x-avg-checked=avg-ok-24A13915; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 08:10 AM 3/7/2003 -0800, vicki@stanfield.net wrote: >In the application that I am developing, I send >commands to a device and retrieve the device's >response. I want to display both what is sent and what >is retrieved in some kind of widget on the GUI. What is >generally used for this type of thing. I am able to >redirect the stdio and stdout to a file, but I am not >aware of a widget which will display a data stream. Am >I dreaming? Do I have to build it myself? Here's a minimal idea of how to do this using Tkinter: create a dialog consisting of a Label, and update the Label's text with whatever segment of the data stream you want to display. This example uses a static text stream and a timer to pace the display. I think you should be able to recode these parts to handle your dynamic stream. from time import sleep from Tkinter import * class Dialog(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.Label = Label(self, width = 25, font = 'arial 8') self.Label.after_idle(self.quit) # causes immediate exit from mainloop() self.Label.pack({"side": "top"}) self.mainloop() if __name__ == '__main__': d = Dialog() stream = """This is a long stream of text. In the application that I am developing, I send commands to a device and retrieve the device's response. I want to display both what is sent and what is retrieved.""".replace('\n',' ') for t in range(len(stream)): d.Label['text'] = stream[t:t+30] d.update() sleep(.01) HTH Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======1003E63======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-24A13915 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======1003E63=======-- From Don Arnold" Message-ID: <01a301c2e526$58f0a8c0$9011ba3f@defaultcomp> ----- Original Message ----- From: "Bob Gailer" To: Sent: Friday, March 07, 2003 12:25 PM Subject: [Tutor] TKinter - display dialog w/o using mainloop() > class Dialog(Frame): > def __init__(self): > Frame.__init__(self, None) > self.pack() > self.Label['text'] = 'initial text' > self.Label.pack({"side": "top"}) > d = Dialog() > > How do I get the dialog box to be visible w/o using mainloop(). I want to > show the dialog and then do other things in my program, which might result > in reassigning d.Label['text'] = 'new text' Well, I admit I know even less about Tkinter than most other aspects of Python, but I _think_ you just need to inherit Dialog from Toplevel instead of Frame: from Tkinter import * class Dialog(Toplevel): def __init__(self,parent): Toplevel.__init__(self, parent) l = Label(self,text='initial text') l.pack(side=TOP) b = Button(self,text='close me',command=self.destroy) b.pack() class App(Frame): def __init__(self,parent): Frame.__init__(self,parent) self.pack() w = Label(self, text="Hello, world!") w.pack() b = Button(self,text='open a dialog',command=self.makeDialog) b.pack() def makeDialog(self): Dialog(self) root = Tk() theApp = App(root) theApp.mainloop() HTH, Don From phthenry@earthlink.net Sat Mar 8 01:22:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Sat Mar 8 01:22:01 2003 Subject: [Tutor] outputting long lines Message-ID: <20030308012144.N32062@localhost.localdomain> Is there a tecnique for printing out long lines that span more than the length of your script? For example, I am trying to output this line: 1 if self.__token_info == 'cw%s' % self.__footnote_count) My output is: mi2 I don't want this huge space at the beginning. I want: mi2 There are ugly ways to achieve what I want. I could output the text with several write lines. I could get rid of the space in line 3 above. But I was thinking there is probably an easeir and more elegant solution. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From abli@freemail.hu Sat Mar 8 02:15:02 2003 From: abli@freemail.hu (Abel Daniel) Date: Sat Mar 8 02:15:02 2003 Subject: [Tutor] outputting long lines In-Reply-To: <20030308012144.N32062@localhost.localdomain> References: <20030308012144.N32062@localhost.localdomain> Message-ID: <20030308071414.GA1195@hooloovoo> What about: > 1 if self.__token_info == 'cw 2 self.__write_to_foot_obj.write(\ > 3 'mi%s' % self.__footnote_count) Abel Daniel From dyoo@hkn.eecs.berkeley.edu Sat Mar 8 02:42:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 8 02:42:02 2003 Subject: [Tutor] Idle on RH 7.2 questions (fwd) Message-ID: [Hi Tim; let me forward this to the main Tutor list; I think you accidently forwarded only to tutor-admin.] ---------- Forwarded message ---------- Date: Fri, 7 Mar 2003 11:52:18 -0900 From: Tim Johnson To: Chris Kassopulo Cc: tutor-admin@python.org Subject: Re: [Tutor] Idle on RH 7.2 questions Hello Chris; * Chris Kassopulo [030307 10:57]: > > Greetings Tim, > > Note that I am using python 2.2 under slackware. > /usr/lib/python2.2/site-packages/idlelib is the > directory that contains IdleConf.py and there is > no site-packages/idle directory. Just for the heck of it, I changed the directory name to idlelib and got the same error message. Reading the docs for idle under 2.2.2, I note the the author says that idle 'needs' python 1.5.2 to run (line 38). Perhaps I need to redirect my query to ask this question: How can I use my existing working version of idle (the one that came with the install, which is now named idle1.5) to load the python2.2.2 interpreter to that I can use some of the new features, like list comprehension. that would work for me. Thanks Chris! -tim- > > Tim Johnson wrote: > > Hello All: > > I am using RH 7.2 with python 1.5.2 as the default > > for the distribution (I believe). I would prefer to > > leave 1.5.2 as it is and have also installed Python 2.2.2 > > > > I would like to use idle with 2.2.2 and my current idle > > looks like this: > > # > > #! /usr/bin/env python > > > > import os > > import sys > > from idlelib import IdleConf > > > > idle_dir = os.path.dirname(IdleConf.__file__) > > IdleConf.load(idle_dir) > > > > # defer importing Pyshell until IdleConf is loaded > > from idlelib import PyShell > > PyShell.main() > > # > > and I have the idle (2.2) directory at > > /usr/local/lib/python2.2/site-packages/idle > > > > when I run idle, I get the following error message: > > Traceback (innermost last): > > File "/usr/bin/idle", line 5, in ? > > from idlelib import IdleConf > > ImportError: No module named idlelib > > I cannot 'locate' or 'find' on my machine > > My questions are: > > 1)Is idlelib a seperate distribution > > or > > 2)Have I made an error in my installation of > > python2.2 > > Chris > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From glingl@aon.at Sat Mar 8 03:25:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Sat Mar 8 03:25:02 2003 Subject: [Tutor] outputting long lines References: <20030308012144.N32062@localhost.localdomain> <20030308071414.GA1195@hooloovoo> Message-ID: <3E69A8F1.20609@aon.at> Abel Daniel schrieb: >What about: > > >>1 if self.__token_info == 'cw>2 self.__write_to_foot_obj.write(\ >>3 'mi%s' % self.__footnote_count) >> >> In fact you can write: 1 if self.__token_info == 'cw%s' % self.__footnote_count) ... as in Python you can break lines within any kind of brackets: (), [], {} For example: >>> def f(x): ... print x ... >>> f( ... ... "a" ... ... ) a Regards, Gregor P.S.: >>> f( ... ... "a" ... ... "b" ... ... ) ab >>> From dan_nash@hotmail.com Sat Mar 8 06:47:01 2003 From: dan_nash@hotmail.com (Daniel Nash) Date: Sat Mar 8 06:47:01 2003 Subject: [Tutor] Searching for a substring within a list Message-ID: I have a list of email addresses : list1 = ["dan@company.com","fred@company.com"] and another list made up from the contents extracted from an email headers To:,Cc: & Bcc: list2 =[('', 'support@company.com'), ('jim', 'jim@company.com'), ('', 'fred@comapny.com')] I want to write a peice of code to return true if any element in the first list appears as a substring of any element in the second list. for List1Head in List1List: for List2Head in List2: if string.find(List1Head, List2Head) >= 0: print "YEP ", ListHead, " Is in the list" This code doesn't work "TypeError: expected a character buffer object" I think this means that I need to convert value of List2head to a string. But this code is very messy. Is there a better way to solve my problem? _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From glingl@aon.at Sat Mar 8 07:54:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Sat Mar 8 07:54:01 2003 Subject: [Tutor] Searching for a substring within a list References: Message-ID: <3E69E806.9060309@aon.at> Daniel Nash schrieb: > > > > I have a list of email addresses : > > list1 = ["dan@company.com","fred@company.com"] > > and another list made up from the contents extracted from an email > headers To:,Cc: & Bcc: > > list2 =[('', 'support@company.com'), ('jim', 'jim@company.com'), ('', > 'fred@comapny.com')] > > I want to write a peice of code to return true if any element in the > first list appears as a substring of any element in the second list. > > for List1Head in List1List: > for List2Head in List2: > if string.find(List1Head, List2Head) >= 0: > print "YEP ", ListHead, " Is in the list" > > This code doesn't work "TypeError: expected a character buffer object" > I think this means that I need to convert value of List2head to a > string. But this code is very messy. > > Is there a better way to solve my problem? > Hi Daniel! If I understand your question correctly, it goes (for example) like this (I'v inserted a print-statement, to show better waht's going on): >>> list1 = ["dan@company.com","fred@company.com"] >>> list2 =[('', 'support@company.com'), ('jim', 'jim@company.com'), ('', 'fred@company.com')] >>> for List1Head in list1: ... for List2Head in list2: ... print List1Head, List2Head ... if List1Head in List2Head: ... print "YEP ", List1Head, " Is in the list" ... dan@company.com ('', 'support@company.com') dan@company.com ('jim', 'jim@company.com') dan@company.com ('', 'fred@company.com') fred@company.com ('', 'support@company.com') fred@company.com ('jim', 'jim@company.com') fred@company.com ('', 'fred@company.com') YEP fred@company.com Is in the list >>> You have to test if a given email-adress (of list1) is *element* of one of the *tuples* in list2. This can be done with the boolean operator in. If you wanted to test, if the adress is contained in the string, which is the second element of the tuple, you would have to use it, namely List2Head[1] (and test via find) HTH, Gregor From reavey@nep.net Sat Mar 8 10:32:05 2003 From: reavey@nep.net (reavey) Date: Sat Mar 8 10:32:05 2003 Subject: [Tutor] viewing attributes of objects in a class Message-ID: <3E6B5E40.2090901@nep.net> Mike Reavey wrote: >>> class = Object: pass >>>personA = Object() >>> personA.name = "Ann" >>>personA.age = 31 is there a list of this object with its attributes which can be retrieved, like personA.inspect? TIA re-v From Don Arnold" Message-ID: <02f601c2e58b$6580a620$9011ba3f@defaultcomp> ----- Original Message ----- From: "reavey" To: Sent: Sunday, March 09, 2003 9:31 AM Subject: [Tutor] viewing attributes of objects in a class > Mike Reavey wrote: > > >>> class = Object: > pass > >>>personA = Object() > >>> personA.name = "Ann" > >>>personA.age = 31 > is there a list of this object with its attributes which can be retrieved, > like personA.inspect? > TIA > re-v If you're just running interactively and want to see the object's attributes, you can use the built in dir() function: class MyClass: pass personA = MyClass() personA.name = "Ann" personA.age = 31 print dir(personA) >>> ['__doc__', '__module__', 'age', 'name'] Otherwise, you can access the object's __dict__, which is the dictionary that stores its attributes: for attrib in personA.__dict__.keys(): print '%s = %s' % (attrib, personA.__dict__[attrib]) >>> age = 31 >>> name = Ann HTH, Don From erikprice@mac.com Sat Mar 8 11:57:02 2003 From: erikprice@mac.com (Erik Price) Date: Sat Mar 8 11:57:02 2003 Subject: [Tutor] outputting long lines In-Reply-To: <20030308012144.N32062@localhost.localdomain> Message-ID: <067FB495-5189-11D7-AD29-00039351FE6A@mac.com> On Saturday, March 8, 2003, at 01:21 AM, Paul Tremblay wrote: > Is there a tecnique for printing out long lines that span more than the > length of your script? One way to do it that doesn't sacrifice performance is to create a list of strings and then join them all together when they need to be treated as a single string. >>> text = [ ... 'Here is a ', ... 'really long string ', ... 'that is broken up ', ... 'over multiple lines.' ... ] >>> text ['Here is a ', 'really long string ', 'that is broken up ', 'over multiple lines.'] >>> output = ''.join(text) >>> output 'Here is a really long string that is broken up over multiple lines.' >>> Note that "output" is generated by calling the string method join() on an empty string, passing the list as the argument. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Sat Mar 8 12:11:01 2003 From: erikprice@mac.com (Erik Price) Date: Sat Mar 8 12:11:01 2003 Subject: [Tutor] viewing attributes of objects in a class In-Reply-To: <3E6B5E40.2090901@nep.net> Message-ID: On Sunday, March 9, 2003, at 10:31 AM, reavey wrote: > >>> class = Object: > pass > >>>personA = Object() > >>> personA.name = "Ann" > >>>personA.age = 31 > is there a list of this object with its attributes which can be > retrieved, > like personA.inspect? Yes, just remember that in Python, a user-defined class/object is really just a high-tech dictionary. Every attribute of the class/object is a key of the dictionary. When you set an attribute, you're setting a key/value in the dictionary. Use the __dict__ method to see these attributes: >>> class villain: ... def __init__(self, name, henchman, nemesis): ... self.name = name ... self.henchman = henchman ... self.nemesis = nemesis ... >>> skeletor = villain('Skeletor', 'Beast-Man', 'He-Man') >>> skeletor.__dict__ {'nemesis': 'He-Man', 'henchman': 'Beast-Man', 'name': 'Skeletor'} The only real difference is that when you attempt to retrieve an attribute, the processor will check the instance for an attribute, and if it doesn't find it will continue to check the class (for a class-wide attribute), and if not found then will continue to check any base classes. I may be oversimplifying something but that's the general gist of it. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From charlie@begeistert.org Sat Mar 8 12:27:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sat Mar 8 12:27:02 2003 Subject: [Tutor] outputting long lines In-Reply-To: <20030308170007.25630.55979.Mailman@mail.python.org> References: <20030308170007.25630.55979.Mailman@mail.python.org> Message-ID: <20030308182724.1096.3@.1047140704.fake> On 2003-03-08 at 18:00:07 [+0100], tutor-request@python.org wrote: > Subject: > > Is there a tecnique for printing out long lines that span more than the > length of your script? > > For example, I am trying to output this line: > > 1 if self.__token_info == 'cw 2 self.__write_to_foot_obj.write('\ > 3 mi%s' % self.__footnote_count) > > My output is: > > mi2 > > I don't want this huge space at the beginning. I want: > > mi2 > > There are ugly ways to achieve what I want. I could output the text with > several write lines. I could get rid of the space in line 3 above. But I > was thinking there is probably an easeir and more elegant solution. "easier" and "elegant" sounds like Python to me!!! You can have pretty much any number of line breaks within a function call (ie. within the brackets) allowing you to break things down as they suit you. You only need to use "\" for a new line inside a string but you can use long string quotes (either """ string """ or ''' string ''') instead if self.__token_info == 'cw%s" % self.__footnote_count ) Does that help? Charlie From gerrit@nl.linux.org Sat Mar 8 12:41:02 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Sat Mar 8 12:41:02 2003 Subject: [Tutor] outputting long lines In-Reply-To: <20030308012144.N32062@localhost.localdomain> References: <20030308012144.N32062@localhost.localdomain> Message-ID: <20030308174230.GA5329@nl.linux.org> Paul Tremblay schreef op zaterdag 8 maart om 07:22:14 +0000: > Is there a tecnique for printing out long lines that span more than the > length of your script? > > For example, I am trying to output this line: > > 1 if self.__token_info == 'cw 2 self.__write_to_foot_obj.write('\ > 3 mi%s' % self.__footnote_count) > > My output is: > > mi2 > > I don't want this huge space at the beginning. I want: > > mi2 > > There are ugly ways to achieve what I want. I could output the text with > several write lines. I could get rid of the space in line 3 above. But I > was thinking there is probably an easeir and more elegant solution. You can also do: 67 >>> if True: 67 ... if True: 67 ... if True: # 3 levels indented 67 ... sys.stdout.write(""" 67 ... I want 67 ... to write 67 ... a text 67 ... spanning 67 ... multiple 67 ... lines!""") yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From gerrit@nl.linux.org Sat Mar 8 12:52:01 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Sat Mar 8 12:52:01 2003 Subject: [Tutor] outputting long lines In-Reply-To: <20030308174230.GA5329@nl.linux.org> References: <20030308012144.N32062@localhost.localdomain> <20030308174230.GA5329@nl.linux.org> Message-ID: <20030308175346.GA5520@nl.linux.org> Gerrit Holl schreef op zaterdag 8 maart om 18:41:15 +0000: > You can also do: > > 67 >>> if True: > 67 ... if True: > 67 ... if True: # 3 levels indented > 67 ... sys.stdout.write(""" > 67 ... I want > 67 ... to write > 67 ... a text > 67 ... spanning > 67 ... multiple > 67 ... lines!""") OOPS, sorry, you can't. Please ignore this misinformation! yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From dan_nash@hotmail.com Sat Mar 8 14:11:01 2003 From: dan_nash@hotmail.com (Daniel Nash) Date: Sat Mar 8 14:11:01 2003 Subject: [Tutor] (no subject) Message-ID: I am trying to use python to insert a email into a database, storing the body plus all the attachments. I have been trying to use the following code that has an email piped in on stdin: mailfile = sys.stdin p = email.Parser.Parser() msg = p.parse(mailfile) partCounter=1 for part in msg.walk(): if part.get_main_type()=="multipart": continue name = part.get_param("name") if name == None: name = "part-%i" % partCounter partCounter+=1 #INSERT INTO DB msg is only the message body. How do I get msg to be equal to the whole message or just the body with the mime parts? Dan _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From ckasso@sprynet.com Sat Mar 8 14:57:02 2003 From: ckasso@sprynet.com (Chris Kassopulo) Date: Sat Mar 8 14:57:02 2003 Subject: [Tutor] PyGame Message-ID: <20030308151655.006584a8.ckasso@sprynet.com> Greetings, Spotted this on Freshmeat today and thought some might be interested, particularly in the tutorial. TomPong 0.5 by Tom Chance - Saturday, March 8th 2003 07:32 PST About: TomPong is a very simple implementation of the classic Pong game, using Python and Pygame. It features realistic physics for motion using vectors, not-so-realistic but very fun spin dynamics, and scoring. Changes: Various performance enhancements were made, and the accompanying tutorial for writing games in PyGame was completed. http://freshmeat.net/redir/tompong/36655/url_homepage/pong.shtml Chris From phthenry@earthlink.net Sat Mar 8 15:12:02 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Sat Mar 8 15:12:02 2003 Subject: [Tutor] outputting long lines In-Reply-To: <067FB495-5189-11D7-AD29-00039351FE6A@mac.com> References: <20030308012144.N32062@localhost.localdomain> <067FB495-5189-11D7-AD29-00039351FE6A@mac.com> Message-ID: <20030308151114.C8504@localhost.localdomain> Thanks everyone. It seems like Gregor's solution is the best. (See what he wrote in his ps.) Would the solution in this email really save a lot of time in comparison to Gregor's solution? Paul On Sat, Mar 08, 2003 at 12:11:39PM -0500, Erik Price wrote: > > > On Saturday, March 8, 2003, at 01:21 AM, Paul Tremblay wrote: > > >Is there a tecnique for printing out long lines that span more than the > >length of your script? > > One way to do it that doesn't sacrifice performance is to create a list > of strings and then join them all together when they need to be treated > as a single string. > > >>> text = [ > ... 'Here is a ', > ... 'really long string ', > ... 'that is broken up ', > ... 'over multiple lines.' > ... ] > >>> text > ['Here is a ', 'really long string ', 'that is broken up ', 'over > multiple lines.'] > >>> output = ''.join(text) > >>> output > 'Here is a really long string that is broken up over multiple lines.' > >>> > > Note that "output" is generated by calling the string method join() on > an empty string, passing the list as the argument. > > > Erik > > > > > -- > Erik Price > > email: erikprice@mac.com > jabber: erikprice@jabber.org -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From charlie@begeistert.org Sat Mar 8 17:21:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sat Mar 8 17:21:02 2003 Subject: [Tutor] Datamodelling Message-ID: <20030308232205.3042.14@.1047140704.fake> Dear list, I've got a website and I'd like to do a little cgi using Python. Python 2.1 is installed on the server but I'm not able to install any additional packages. This is as much an exercise in the mind as a real task. Example is a simple newsletter system which stores an e-mail address and a language. I want to be able to store user data but I haven't got access to a database. What are the alternatives using flat files for storage that will allow a migration to another system in the future? I was thinking of using shelve but I'm not sure about keys or doing any "work" with the list: how many users with what language. I think it might be possible to set up a class for the list and fit it out with methods to do the work but I've never created any classes from scratch so I'm a little stuck. I've got quite used to doing relational modelling but don't know how I'd implement something like that. Here's a rough description of my thoughts class Newslist(name): def __int__(self, name): self.name = name self.members = {} def addMember(member, lang): self.members[member] = lang Would it make sense to have a class for my members? class Member(email, name): def __init__(self, email, name): self.name = name self.email = email Thoughts, ideas? Thanx Charlie From borelan@wanadoo.fr Sat Mar 8 18:07:01 2003 From: borelan@wanadoo.fr (D2) Date: Sat Mar 8 18:07:01 2003 Subject: [Tutor] A tutorial on how to use regexp in python References: <3E60C5F1.8060301@wanadoo.fr> <3E60E102.4030709@aon.at> Message-ID: <3E6A7743.2040002@wanadoo.fr> Thanks Gregor, I'll read it. Andre Gregor Lingl a écrit: > D2 schrieb: > >> Hi, >> >> I'm searching a tutorial (as exhaustive as possible :), on regexp in >> Python. > > > http://www.amk.ca/python/howto/regex/ > > also as pdf-document available: > > http://www.amk.ca/files/howto/regex.pdf > > HTH, Gregor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From erikprice@mac.com Sun Mar 9 00:35:02 2003 From: erikprice@mac.com (Erik Price) Date: Sun Mar 9 00:35:02 2003 Subject: [Tutor] Datamodelling In-Reply-To: <20030308232205.3042.14@.1047140704.fake> Message-ID: On Saturday, March 8, 2003, at 05:22 PM, Charlie Clark wrote: > I want to be able to store user data but I haven't got access to a > database. > What are the alternatives using flat files for storage that will allow > a > migration to another system in the future? XML files come to mind. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From dyoo@hkn.eecs.berkeley.edu Sun Mar 9 01:01:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Mar 9 01:01:02 2003 Subject: [Tutor] ImportError: No module named idlelib (python 2.2.2) (fwd) Message-ID: Hi Tim, Tim, you need to fix your address book: you've been accidently been sending to the administrative address 'tutor-admin@python.org'. (tutor-admin only reaches at most three or four of the mailing list administrators!) Send your questions to 'tutor@python.org' instead, which will insure that everyone will be able to help answer your questions. ---------- Forwarded message ---------- Date: Fri, 7 Mar 2003 08:20:14 -0900 From: Tim Johnson To: tutor-admin@python.org Subject: ImportError: No module named idlelib (python 2.2.2) Hello All: I have installed python 2.2.2 on Linux Redhat 7.2. I am getting an ImportError when attempting to start idle Traceback (innermost last): File "/usr/local/lib/python2.2/site-packages/idle/idle", line 5, in ? from idlelib import IdleConf ImportError: No module named idlelib Any help would be really appreciated :-) P.S. No search results on "idlelib" were returned from search engine at python site. Thanks -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From dyoo@hkn.eecs.berkeley.edu Sun Mar 9 02:12:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Mar 9 02:12:02 2003 Subject: [Tutor] (getch() equivalent) [fun with imports] In-Reply-To: <5.1.0.14.0.20030220232228.01ac8830@tcapp.com> Message-ID: On Thu, 20 Feb 2003, Tony Cappellini wrote: > In your post here > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 > > why do you import msvcrt in both functions ? > Why not just import it once ? Hi Tony, Sorry for such a late reply! I hope that you still remember your question. *grin* I'm forwarding this to tutor@python.org too since this might be helpful to someone else. Let's take a quick look at the source code just so we can point a what we're talking about: ### class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() ### Your question is asking why we do the import twice. The reason is because the imports are being done locally each method, so the module's only going to be known "locally". Here's a concrete example that shows what I mean: ### >>> def test_internal_import(): ... import md5 ... m = md5.new() ... m.update("this is a ") ... m.update("test") ... return m.hexdigest() ... >>> test_internal_import >>> test_internal_import() '54b0c58c7ce9f2a8b551351102ee0938' >>> md5 Traceback (most recent call last): File "", line 1, in ? NameError: name 'md5' is not defined ### The 'import' statement introduces a new variable in the place that we're at; in almost every case, we do it "toplevel" so that the module's definition can be acccessed everywhere. But we also have the ability to do an 'import' locally in a function, if we ever feel the inclination. *grin* Just as local variables are visible only with the enclosing function, local module imports are treated with the same rule. Doing 'import' within a function very unusual: it's not often useful to localize a module to a single function, since it's probably going to be used everywhere in a program. However, I could have written that code differently to avoid the double import. Here's one way to do it: ### try: import msvcrt catch: msvcrt = None ## By this time, I can assume msvcrt is defined, ## although it might be set to None... class _GetchWindows: def __init__(self): if msvcrt == None: raise ImportError, "msvcrt module not available" def __call__(self): return msvcrt.getch() ### This attitude toward missing imports is similiar to the approach taken by the pygame folk, although pygame handles a missing module with much more sophistication. For example, pygame optionally supports a "font" library... but the client might not have the font library installed! In that case, pygame sets the 'pygame.font' library to a proxy library that doesn't do anything: ### try: import pygame.font except (ImportError,IOError), msg: font=MissingModule("font", msg, 0) ### (http://cvs.seul.org/cgi-bin/cvsweb-1.80.cgi/games/pygame/lib/__init__.py?rev=1.25&content-type=text/x-cvsweb-markup) Pygame's "MissingModule" class is actually pretty cute: it mimics a real module, but starts tossing out warnings to the user whenever we try using its functionality: ### class MissingModule: def __init__(self, name, info='', urgent=0): self.name = name self.info = str(info) self.urgent = urgent if urgent: self.warn() def __getattr__(self, var): if not self.urgent: self.warn() self.urgent = 1 MissingPygameModule = "%s module not available" % self.name raise NotImplementedError, MissingPygameModule def __nonzero__(self): return 0 def warn(self): if self.urgent: type = 'import' else: type = 'use' message = '%s %s: %s' % (type, self.name, self.info) try: import warnings if self.urgent: level = 4 else: level = 3 warnings.warn(message, RuntimeWarning, level) except ImportError: print message ### (It's a slight shame that MissingModule lives only in the __init__.py file: I think it belongs proper in the Python Cookbook as an example of permissive imports!) Sorry, I went way off tangent again, but I thought that it was interesting... *grin* Does this clear up some things? Good luck! From erikprice@mac.com Sun Mar 9 08:43:02 2003 From: erikprice@mac.com (Erik Price) Date: Sun Mar 9 08:43:02 2003 Subject: [Tutor] (getch() equivalent) [fun with imports] In-Reply-To: Message-ID: <03B2A6E4-5237-11D7-A349-00039351FE6A@mac.com> On Sunday, March 9, 2003, at 02:11 AM, Danny Yoo wrote: > Just as local variables are visible only with the enclosing function, > local module imports are treated with the same rule. Doing 'import' > within a function very unusual: it's not often useful to localize a > module > to a single function, since it's probably going to be used everywhere > in a > program. Is there a significant performance hit when importing a module twice in this fashion? Or does the Python processor keep all of the imported objects cached in memory so that if it is imported a second time, even in a separate namespace, a module will not be searched for and loaded again? Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From ramrom@earthling.net Sun Mar 9 08:52:06 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sun Mar 9 08:52:06 2003 Subject: [Tutor] (getch() equivalent) [fun with imports] In-Reply-To: <03B2A6E4-5237-11D7-A349-00039351FE6A@mac.com> References: Message-ID: <5.2.0.9.0.20030309064802.0282b698@66.28.54.253> --=======5F577F08======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-382D5B7F; boundary="=====================_7987665==.ALT" --=====================_7987665==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-382D5B7F; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 08:57 AM 3/9/2003 -0500, Erik Price wrote: >On Sunday, March 9, 2003, at 02:11 AM, Danny Yoo wrote: >>Just as local variables are visible only with the enclosing function, >>local module imports are treated with the same rule. Doing 'import' >>within a function very unusual: it's not often useful to localize a module >>to a single function, since it's probably going to be used everywhere in a >>program. >Is there a significant performance hit when importing a module twice in >this fashion? Or does the Python processor keep all of the imported >objects cached in memory so that if it is imported a second time, even in >a separate namespace, a module will not be searched for and loaded again? From the Python Language Reference (always a good place to look, (along with the Library Reference) for questions like this): "Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). The first form (without from) repeats these steps for each identifier in the list.... The system maintains a table of modules that have been initialized, indexed by module name. This table is accessible as sys.modules. When a module name is found in this table, step (1) is finished...." HTH Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=====================_7987665==.ALT Content-Type: text/html; x-avg-checked=avg-ok-382D5B7F; charset=us-ascii Content-Transfer-Encoding: 8bit At 08:57 AM 3/9/2003 -0500, Erik Price wrote:
On Sunday, March 9, 2003, at 02:11  AM, Danny Yoo wrote:
Just as local variables are visible only with the enclosing function,
local module imports are treated with the same rule.  Doing 'import'
within a function very unusual: it's not often useful to localize a module
to a single function, since it's probably going to be used everywhere in a
program.
Is there a significant performance hit when importing a module twice in this fashion?  Or does the Python processor keep all of the imported objects cached in memory so that if it is imported a second time, even in a separate namespace, a module will not be searched for and loaded again?

From the Python Language Reference (always a good place to look, (along with the Library Reference) for questions like this):

"Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). The first form (without from) repeats these steps for each identifier in the list....

The system maintains a table of modules that have been initialized, indexed by module name. This table is accessible as sys.modules. When a module name is found in this table, step (1) is finished...."

HTH

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=====================_7987665==.ALT-- --=======5F577F08======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-382D5B7F Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======5F577F08=======-- From dyoo@hkn.eecs.berkeley.edu Sun Mar 9 14:30:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Mar 9 14:30:02 2003 Subject: [Tutor] (getch() equivalent) [fun with imports] In-Reply-To: Message-ID: > ### > try: > import msvcrt > catch: ^^^^^ > msvcrt = None > ## By this time, I can assume msvcrt is defined, > ## although it might be set to None... Oh good grief, not again! I had been programming in the Java language for the past two weeks, and I've gotten my keywords confused again. Give me a few minutes to context switch... ok, there, that's better. Java uses the keyword "catch" for an exception block definition, but Python uses an alternative keyword "except". The corrected Python code should use "except": ### try: import msvcrt except: msvcrt = None ### Again, my apologies for being so sloppy about this! From alan.gauld@bt.com Sun Mar 9 17:32:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Mar 9 17:32:01 2003 Subject: [Tutor] Datamodelling Message-ID: > I was thinking of using shelve but I'm not sure about keys or doing Shelve would seem a reasonable starting point. Think of it as a single table database! You can use multiple shelves but then you have to do the joins manually. > be possible to set up a class for the list and fit it out with methods to > do the work but I've never created any classes from scratch Its definitely feasible. > class Newslist(name): > def __int__(self, name): > def addMember(member, lang): > Would it make sense to have a class for my members? Depends on what your members do. Classes should be based on behaviour rather than data where possible. If your members will add themsxelves, edit their entries or perform any other functions then by all means create classes for them If they just contain dumb data that you extract some other way then maybe a simple tuple or list or dictionary is all you need. Alan G From charlie@begeistert.org Sun Mar 9 17:42:02 2003 From: charlie@begeistert.org (charlie@begeistert.org) Date: Sun Mar 9 17:42:02 2003 Subject: [Tutor] Datamodelling In-Reply-To: References: Message-ID: <20030309234234.4116.6@wonderland.1047202147.fake> On 2003-03-09 at 23:30:30 [+0100], you wrote: > Shelve would seem a reasonable starting point. Think of it as a single > table database! > You can use multiple shelves but then you have to do the joins manually. This is what I've started to do. Once I came up with a way of generating unique IDs I started moving along quite quickly - I have an "ids" value in each table which I increment for each new entry and use a string of for the ids. It's been a lot of fun migrating the MySQL based PHP stuff to pure Python with shelve. The DB is currently ruined and I don't have the rights to change it anyway. By far the best thing has been using dispatching instead of if/elif/else. Thanx goes to the list + cookbook for pointing out this wonderful concept! > Depends on what your members do. > Classes should be based on behaviour rather than data where possible. > > If your members will add themsxelves, edit their entries or perform any > other functions then by all means create classes for them If they just > contain > dumb data that you extract some other way then maybe a simple tuple or > list or dictionary is all you need. Yeah, as soon as started trying to model what I wanted in classes I could see it wasn't going to give me the aggregate functions I can get from other data types. Wonder how object-oriented DBs do it. -- Charlie Clark Chief Chaos Coordinator BeGeistert 010 - Brave New World 26 + 27 April 2003 From micforster@yahoo.com Sun Mar 9 18:32:02 2003 From: micforster@yahoo.com (Mic Forster) Date: Sun Mar 9 18:32:02 2003 Subject: [Tutor] problems with the bisect method In-Reply-To: <282595572.20030306142555@rambler.ru> Message-ID: <20030309233119.94377.qmail@web13405.mail.yahoo.com> It's still not obtaining the value that I need. I'll go back and rethink this from first basis. --- "antonmuhin at rambler.ru" wrote: > Hello Mic, > > Wednesday, March 5, 2003, 6:16:00 AM, you wrote: > > [snip] > > >>>> def fun(k, s): > MF> return f(k, s) - j > > >>>> delta = 1e-9 > >>>> bisect(delta, 1-delta, delta, fun) > MF> Traceback (most recent call last): > MF> File "", line 1, in ? > MF> bisect(delta, 1-delta, delta, fun) > MF> File "", line 2, in bisect > MF> fMax = function(max) > MF> TypeError: fun() takes exactly 2 arguments (1 > given) > >>>> > > Quite reasonable I must say :). Your function fun > takes couple of > arguments---k and s and f too althouh s argument > seems to be unused. > > You may modify it as: > > def f(x): > return ... > > def fun(k): > return f(k) - j > > Or write a wrapper function: > > def wrapFun(x): > return fun(x, some constant goes here) > > Or even with lambda: > > bisect(delta, 1 - delta, delta, lambda x: fun(x, > smth...)) > > BTW, although you script is quite short, you'd > better avoid global > variables like j. > > If you need a set of functions like fun. Python can > provide with > better (IMHO) options: > > 1. def makeFun(j): > def newF(x): > f(x) - j > return newF > > 2. Lambdas again: myF = lambda x: f(x) - j > > -- > Best regards, > anton > mailto:antonmuhin@rambler.ru > __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, more http://taxes.yahoo.com/ From doug@idsia.ch Mon Mar 10 05:26:00 2003 From: doug@idsia.ch (Douglas Eck) Date: Mon Mar 10 05:26:00 2003 Subject: [Tutor] Capturing stdout/stderror from linked c++ program Message-ID: <3E6C6796.8010701@idsia.ch> Hello Tutor, I have a very nice neural network that is written in c++. I've wrapped a python interface around it so that I can do things like this: from dse import neuralnet neuralnet.init("params.txt") neuralnet.run() This all works beautifully. However, the c++ code prints some important information to stdout (cout << info << endl;) during the run of the network. Is there a way to capture this standard output so that I can display it using wxLogMessage() (from wxPython) in my python GUI? You may ask, why? Why not just look at the terminal you used to start the python gui? Answer: because once I have about 5 of them running it becomes a headache... each simulation has it's own python gui and it's own terminal. If I spawn all of them from the same terminal, the stdout messages get jumbled up. If I give each GUI it's own terminal, then I've got to keep the terminals lined up with the python guis or I no longer know which is which. In addition, I would strongly prefer not to have to replace all of the "cout" calls in the c++ code with special python calls. I say this becuase I also have a non-python command-line wrapper as well. But if that's the only way (to use a callback function) then I'll do it. Suggestions. Isn't there some magic I can do that just tells python to grab (even a copy of) the stdout/stderr of the terminal that called it? Thanks, Doug Eck From erikprice@mac.com Mon Mar 10 08:38:02 2003 From: erikprice@mac.com (Erik Price) Date: Mon Mar 10 08:38:02 2003 Subject: [Tutor] Capturing stdout/stderror from linked c++ program In-Reply-To: <3E6C6796.8010701@idsia.ch> Message-ID: <82FABCA9-52FF-11D7-AF68-00039351FE6A@mac.com> On Monday, March 10, 2003, at 05:23 AM, Douglas Eck wrote: > Suggestions. Isn't there some magic I can do that just tells python to > grab (even a copy of) the stdout/stderr of the terminal that called > it? Will the os.popen() function do what you need? Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From lugoteehalt@yahoo.co.uk Mon Mar 10 08:45:03 2003 From: lugoteehalt@yahoo.co.uk (=?iso-8859-1?q?Lugo=20Teehalt?=) Date: Mon Mar 10 08:45:03 2003 Subject: [Tutor] newbie-class differs from function? Message-ID: <20030310134450.43367.qmail@web14802.mail.yahoo.com> --0-889527383-1047303890=:43184 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit Sorry completely moronic. Have got very stuck and it might help if I understood the difference, in hyper-simple terms, between a class and a conventional, programmer defined function. They seem the same to me. Thanks. --------------------------------- With Yahoo! Mail you can get a bigger mailbox -- choose a size that fits your needs --0-889527383-1047303890=:43184 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: 8bit

Sorry completely moronic.

Have got very stuck and it might help if I

understood the difference, in hyper-simple terms, between

a class and a conventional, programmer defined function.

They seem the same to me.

Thanks.



With Yahoo! Mail you can get a bigger mailbox -- choose a size that fits your needs
--0-889527383-1047303890=:43184-- From erikprice@mac.com Mon Mar 10 09:19:01 2003 From: erikprice@mac.com (Erik Price) Date: Mon Mar 10 09:19:01 2003 Subject: [Tutor] newbie-class differs from function? In-Reply-To: <20030310134450.43367.qmail@web14802.mail.yahoo.com> Message-ID: <48974032-5305-11D7-AF68-00039351FE6A@mac.com> On Monday, March 10, 2003, at 08:44 AM, Lugo Teehalt wrote: > Have got very stuck and it might help if I > > understood the difference, in hyper-simple terms, between > > a class and a conventional, programmer defined function. > > They seem the same to me. Similar, but different. At its simplest level, I tend to think of a function as a named, reuseable piece of code that you can explicitly call to perform some action or return some value. (There are exceptions, such as unnamed functions with lambda, but whatever.) You can put a function anywhere in your code, but you have to "call" it (in Python this is done by putting parentheses and possibly arguments after the function) in order to get it to work. At its simplest level, I tend to think of a class as a template of sorts -- a description. Using this template or description, I can crank out any number of objects that are defined by this template or description. Each object conforms to the class that defines or describes it. A class description generally consists of attributes (each attribute being a variable specific to any given instance, or object, of a class), and methods (each method being a function specific to any given instance, or object, of a class). While all members of class "Foo" have all attributes and methods defined in "Foo", the actual data *in* those attributes or *returned by* those methods may be different depending on the instance, or object, in particular. That's just my 2 cents worth of a brief introduction, others on this list are better at explaining it. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From doug@idsia.ch Mon Mar 10 09:34:02 2003 From: doug@idsia.ch (Douglas Eck) Date: Mon Mar 10 09:34:02 2003 Subject: [Tutor] Capturing stdout/stderror from linked c++ program In-Reply-To: <82FABCA9-52FF-11D7-AF68-00039351FE6A@mac.com> References: <82FABCA9-52FF-11D7-AF68-00039351FE6A@mac.com> Message-ID: <3E6CA1C1.5020101@idsia.ch> Erik Wrote: >Will the os.popen() function do what you need? Hi Erik, Thanks for the reponse. According to the documentation, no, popen() won't work. I'm calling a linked C++ object file that has python bindings, not a system command. For example, here is a snippet of python that would init a net, run it, and then get activations. Notice that no system calls are made at all... neuranet is not an executable. It's an object file with python bindings. from dse import neuralnet %my neural net python interface neuralnet.init("params.txt") neuralnet.run() %here is where the stdout stuff happens. a=neuralnet.getActs() So as I understand it popen() is set up to run a unix command, not something like "neuralnet" in the example here. Or maybe I'm missing something? I hope I am. Thanks! Doug From vicki@stanfield.net Mon Mar 10 11:06:08 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Mon Mar 10 11:06:08 2003 Subject: [Tutor] passing widgets Message-ID: <20030310073711.6624.h003.c000.wm@mail.stanfield.net.criticalpath.net> If I want a textbox to display the input and output from several other functions, must I pass it around as a parameter or is it better to make it global? I've always been taught to minimize the amount of global objects, but when is it warranted? Passing the widget requires that I use a shim callback function, amd that seems like a lot of fuss. --vicki From borelan@wanadoo.fr Mon Mar 10 12:11:22 2003 From: borelan@wanadoo.fr (D2) Date: Mon Mar 10 12:11:22 2003 Subject: [Tutor] Trying to find a value in a function. Message-ID: <3E6CC6DF.4020002@wanadoo.fr> I'm trying to find a value in a fonction given the name of the function and the name of the variable. The variable is not an attribute nor an argument. Here is the function --------- def some_func(self): props=['a', 'b', 'c'] --------- I tried to use some_func.func_code.co_varnames but it only returned the tuple below. --------- ('self', '_props') --------- How can i get the value of the _props variable ? TIA From R. Alan Monroe" References: <20030310134450.43367.qmail@web14802.mail.yahoo.com> Message-ID: <181120312049.20030310123510@columbus.rr.com> > Sorry completely moronic. > Have got very stuck and it might help if I > understood the difference, in hyper-simple terms, between > a class and a conventional, programmer defined function. > They seem the same to me. Usually, a class is a just a combination of a structure (like a "struct" in C), and some functions that do stuff to the structure, into a single object. Alan From alan.gauld@bt.com Mon Mar 10 12:31:46 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Mar 10 12:31:46 2003 Subject: [Tutor] newbie-class differs from function? Message-ID: This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C2E72A.B0C2E300 Content-Type: text/plain; charset="ISO-8859-1" > ... understood the difference, in hyper-simple terms, between > a class and a conventional, programmer defined function. A function is a block of executable code that may take parameters and return a value. A class is a collection of data and functions that operate on the data - all wrapped up in a single bundle. You can create a class which only contains functions(known as methods in OO speak) and then call those methods via the class. If you do that there is no real advantage over conventional functions - Java does this a lot... Real OOP comes when you create multiple instances of a class. Each can have its own set of iinternal data values and they share a common set of methods. The instances become like little mini processes which communicate with each other. For more information and examples look at my web tutor under the OOP section. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ PS The web site was down again at the weekend but is back up again now. Dunno what's happening with freenet just now! ------_=_NextPart_001_01C2E72A.B0C2E300 Content-Type: text/html; charset="ISO-8859-1"
 > ... understood the difference, in hyper-simple terms, between 
>  a class and a conventional, programmer defined function. 
 
A function is a block of executable code that may take parameters and return a value.
 
A class is a collection of data and functions that operate on the data - all wrapped
up in a single bundle.
 
You can create a class which only contains functions(known as methods in OO speak)
and then call those methods via the class. If you do that there is no real advantage
over conventional functions - Java does this a lot...
 
Real OOP comes when you create multiple instances of a class. Each can have its
own set of iinternal data values and they share a common set of methods. The
instances become like little mini processes which communicate with each other.
 
For more information and examples look at my web tutor under the OOP section.

Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/

 
PS
The web site was down again at the weekend but is back up again now.
Dunno what's happening with freenet just now!
------_=_NextPart_001_01C2E72A.B0C2E300-- From alan.gauld@bt.com Mon Mar 10 12:37:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Mar 10 12:37:02 2003 Subject: [Tutor] Capturing stdout/stderror from linked c++ program Message-ID: > won't work. I'm calling a linked C++ object file that has python > bindings, not a system command. In that case can't you just redirect stdout/stderr to a file using the usual sys.stdout = foo technique? foo could even be dynamically allocvated or passed in as an argument in sys.argv.... > from dse import neuralnet %my neural net python interface import sys oldout = sys.stdout # so we can restore later... sys.stdout = file(sys.argv[1]) # or whatever > neuralnet.init("params.txt") > neuralnet.run() #%here is where the stdout stuff happens. # Hopefully now to a new file? > a=neuralnet.getActs() sys.stdout = oldout Does that work? Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Mon Mar 10 12:40:19 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Mar 10 12:40:19 2003 Subject: [Tutor] passing widgets Message-ID: > If I want a textbox to display the input and output > from several other functions, must I pass it around as > a parameter or is it better to make it global? Thats the advantage of iusing an OPOP approach. If the text box is a member of the same class as the callback functions(or more correctly callback methods) then the methods can see the widget as self.textbox... Kind of like a controlled global variable. Indeed you could even instantiate several such classes and each would write to its own textbox. > always been taught to minimize the amount of global > objects, but when is it warranted? If its only ever going to be a single textbox then global is probably ok. In general the class approach is better IMHO. Alan G. From glingl@aon.at Mon Mar 10 12:50:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Mon Mar 10 12:50:02 2003 Subject: [Fwd: Re: [Tutor] Trying to find a value in a function.] Message-ID: <3E6CCFEB.80400@aon.at> D2 schrieb: > I'm trying to find a value in a fonction given the name of the function > and the name of the variable. > The variable is not an attribute nor an argument. > > Here is the function > > --------- > def some_func(self): > props=['a', 'b', 'c'] > --------- > > I tried to use some_func.func_code.co_varnames but it only returned the > tuple below. > > --------- > ('self', '_props') > --------- Hi D2! I suggest that you be more careful in youre questions (and possibly in your programs) Apparently you use props and _props for the same thing (a variable name)? Your some_func.func_code.co_varnames is heavy stuff, which is rarely necessary to use. I wonder what you want to accomplish. Your function is a rather strange and useless thing. It does nothing and it returns nothing (namely None). Did you invent it only to serve as an example? For what? As props in your example is a local name, the variable (i. e. name + reference to an object) only exists during runtime of the function. So I think. it makes no sense to ask for the value of props except after the assignment to it (in the function body) and before the execution of some_func is done. So you had to insert an appropriate statement in the function body ?!? For me it's hard to give an appropriate answer, because I can't figure out for what purpose you need it. What sources (books, tutorials, examples) do you use when working with Python? Please excuse, if my statement is totally irrelevant for you Regards, Gregor > > How can i get the value of the _props variable ? > > TIA > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From ramrom@earthling.net Mon Mar 10 14:07:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Mar 10 14:07:01 2003 Subject: [Tutor] newbie-class differs from function? In-Reply-To: Message-ID: <5.2.0.9.0.20030310115608.02f03cb0@66.28.54.253> --=======C6B7988======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-50E424E; boundary="=====================_7342027==.ALT" --=====================_7342027==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-50E424E; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 05:30 PM 3/10/2003 +0000, alan.gauld@bt.com wrote: > > ... understood the difference, in hyper-simple terms, between > > a class and a conventional, programmer defined function. > A function is a block of executable code that may take parameters and > return a value. > >A class is a collection of data and functions that operate on the data - >all wrapped >up in a single bundle. > >You can create a class which only contains functions(known as methods in >OO speak) >and then call those methods via the class. If you do that there is no real >advantage >over conventional functions - Java does this a lot... > >Real OOP comes when you create multiple instances of a class. Each can >have its >own set of iinternal data values and they share a common set of methods. The >instances become like little mini processes which communicate with each other. I'd like to put in a vote for "singleton" classes, in which exactly one instance is created. I use this technique frequently. For each module (where this is applicable) I define one (main) class, and make one instance of it after importing. Then I make all my references to the class's properties and methods thru the instance. It is a (IMHO) nicer alternative than referencing (what would otherwise be) a bunch of module-level global variables and functions. Also the various methods easily reference the instance date thru 'self' I also take advantage of shelve to save the contents of the instance, for restoration later. In fact I have a modulemanager module that handles the mechanics of loading/reloading/saving/restoring modules; it's main class's "public" method returns an instance of the desired module's main class. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=====================_7342027==.ALT Content-Type: text/html; x-avg-checked=avg-ok-50E424E; charset=us-ascii Content-Transfer-Encoding: 8bit At 05:30 PM 3/10/2003 +0000, alan.gauld@bt.com wrote:
 > ... understood the difference, in hyper-simple terms, between
> a class and a conventional, programmer defined function.
 A function is a block of executable code that may take parameters and return a value.
 
A class is a collection of data and functions that operate on the data - all wrapped
up in a single bundle.
 
You can create a class which only contains functions(known as methods in OO speak)
and then call those methods via the class. If you do that there is no real advantage
over conventional functions - Java does this a lot...
 
Real OOP comes when you create multiple instances of a class. Each can have its
own set of iinternal data values and they share a common set of methods. The
instances become like little mini processes which communicate with each other.

I'd like to put in a vote for "singleton" classes, in which exactly one instance is created. I use this technique frequently.

For each module (where this is applicable) I define one (main) class, and make one instance of it after importing.

Then I make all my references to the class's properties and methods thru the instance. It is a (IMHO) nicer alternative than referencing (what would otherwise be) a bunch of module-level global variables and functions. Also the various methods easily reference the instance date thru 'self'

I also take advantage of shelve to save the contents of the instance, for restoration later.

In fact I have a modulemanager module that handles the mechanics of loading/reloading/saving/restoring modules; it's main class's "public" method returns an instance of the desired module's main class.

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=====================_7342027==.ALT-- --=======C6B7988======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-50E424E Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======C6B7988=======-- From doug@idsia.ch Mon Mar 10 15:42:05 2003 From: doug@idsia.ch (Douglas Eck) Date: Mon Mar 10 15:42:05 2003 Subject: [Tutor] Capturing stdout/stderror from linked c++ program In-Reply-To: References: Message-ID: <3E6CF899.5040302@idsia.ch> Hi Alan, Thanks for the response. This is a good trick to know about, but it didn't work. It does capture the output from "print" in the python gui but it doesn't capture the output from "cout" in the linked c++ file. The output from "cout" still goes to the terminal that spawned the python gui. And it is not copied into the file. Cheers, Doug >In that case can't you just redirect stdout/stderr to a file >using the usual > >sys.stdout = foo > >technique? foo could even be dynamically allocvated or passed >in as an argument in sys.argv.... > > > >>from dse import neuralnet %my neural net python interface >> >> >import sys >oldout = sys.stdout # so we can restore later... >sys.stdout = file(sys.argv[1]) # or whatever > > > >>neuralnet.init("params.txt") >>neuralnet.run() #%here is where the stdout stuff happens. >> >> > ># Hopefully now to a new file? > > > >>a=neuralnet.getActs() >> >> > >sys.stdout = oldout > > > >Does that work? > >Alan g. >Author of the Learn to Program website >http://www.freenetpages.co.uk/hp/alan.gauld/ > > > From Matthew_Johnson@mcgraw-hill.com Mon Mar 10 16:38:02 2003 From: Matthew_Johnson@mcgraw-hill.com (Johnson, Matthew) Date: Mon Mar 10 16:38:02 2003 Subject: [Tutor] Enter: Matt Message-ID: <03F7B19A96475B428E2726B7B5E053788308@mhepolmsg01.MHE.MHC> Hi all, My name is Matt, a newbie to Python and the list. I am in the Seattle WA area, and looking for someone willing to tutor me. Are there such folks out there who would consider such thing? Anyway, Hi to all! --Matt From ramrom@earthling.net Mon Mar 10 17:02:20 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Mar 10 17:02:20 2003 Subject: [Tutor] Enter: Matt In-Reply-To: <03F7B19A96475B428E2726B7B5E053788308@mhepolmsg01.MHE.MHC> Message-ID: <5.2.0.9.0.20030310145025.02dc29b8@66.28.54.253> --=======4E6561F5======= Content-Type: text/plain; x-avg-checked=avg-ok-50E424E; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 04:38 PM 3/10/2003 -0500, you wrote: >My name is Matt, a newbie to Python and the list. I am in the Seattle WA >area, and looking for someone willing to tutor me. I'd love an excuse to visit Seattle (I lived there for about 14 years). How's your budget :-) See http://www.python.org/doc/Newbies.html for a fairly comprehensive list of resources. There are some good tutorials that have been mentioned on this mail list; search the archives.... We'll be happy to answer specific questions. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======4E6561F5======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-50E424E Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======4E6561F5=======-- From freemyer@NorcrossGroup.com Mon Mar 10 17:38:02 2003 From: freemyer@NorcrossGroup.com (Greg Freemyer) Date: Mon Mar 10 17:38:02 2003 Subject: [Tutor] py2exe and python 2.2.2 in cygwin Message-ID: <20030310223915.KEJS7319.imf48bis.bellsouth.net@tiger2> I want to create a windows executable. I found py2exe. (Better ways??) I am running python 2.2.2 from inside cygwin and added import py2exe to = setup.py It does not look like I have py2exe available?? I thought it was standard? =3D=3D When try=20 $ python setup.py py2exe --help Traceback (most recent call last): File "setup.py", line 5, in ? import py2exe ImportError: No module named py2exe =3D=3D =20 Do I need to install distutils? Or possibly run a Windows native python? TIA Greg --=20 Greg Freemyer From glingl@aon.at Mon Mar 10 17:53:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Mon Mar 10 17:53:01 2003 Subject: [Tutor] py2exe and python 2.2.2 in cygwin References: <20030310223915.KEJS7319.imf48bis.bellsouth.net@tiger2> Message-ID: <3E6D1781.6030900@aon.at> Greg Freemyer schrieb: >I want to create a windows executable. > >I found py2exe. (Better ways??) > >I am running python 2.2.2 from inside cygwin and added import py2exe to setup.py > >It does not look like I have py2exe available?? I thought it was standard? > It isn't: http://starship.python.net/crew/theller/py2exe/ Alternative: http://www.mcmillan-inc.com/install1.html HTH, Gregor > >== >When try >$ python setup.py py2exe --help >Traceback (most recent call last): > File "setup.py", line 5, in ? > import py2exe >ImportError: No module named py2exe >== > >Do I need to install distutils? Or possibly run a Windows native python? > >TIA >Greg > > From dyoo@hkn.eecs.berkeley.edu Mon Mar 10 18:07:09 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 10 18:07:09 2003 Subject: [Tutor] Enter: Matt In-Reply-To: <5.2.0.9.0.20030310145025.02dc29b8@66.28.54.253> Message-ID: On Mon, 10 Mar 2003, Bob Gailer wrote: > At 04:38 PM 3/10/2003 -0500, you wrote: > >My name is Matt, a newbie to Python and the list. I am in the Seattle WA > >area, and looking for someone willing to tutor me. > > I'd love an excuse to visit Seattle (I lived there for about 14 years). > How's your budget :-) > > See http://www.python.org/doc/Newbies.html for a fairly comprehensive > list of resources. > > There are some good tutorials that have been mentioned on this mail > list; search the archives.... We'll be happy to answer specific > questions. Hi Matt, welcome aboard! Please feel free to ask questions on the list; we're a small community, but we'd be happy to help learning Python be a pleasant experience. By the way, those archives live here: http://mail.python.org/pipermail/tutor/ (There is a searchable interface of the archives from: http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor but it's somewhat inadequate and misses some things at times. If I have some time, I'd love to write something in Jython that uses Jakarta's Lucene search engine so we have a more robust archival search for Python-Tutor...) From freemyer@NorcrossGroup.com Mon Mar 10 18:30:03 2003 From: freemyer@NorcrossGroup.com (Greg Freemyer) Date: Mon Mar 10 18:30:03 2003 Subject: re[2]: [Tutor] py2exe and python 2.2.2 in cygwin Message-ID: <20030310233103.JDWJ15538.imf14bis.bellsouth.net@tiger2> >> Greg Freemyer schrieb: >> >I want to create a windows executable. >> > >> >I found py2exe. (Better ways??) >> > >> >I am running python 2.2.2 from inside cygwin and added import py2exe to >> setup.py >> > >> >It does not look like I have py2exe available?? I thought it was >> standard? >> > >> It isn't: >> http://starship.python.net/crew/theller/py2exe/ >> Alternative: >> http://www.mcmillan-inc.com/install1.html >> HTH, Gregor Gregor, That did not to apply to the cygwin version of python, so I now have the win32 = native version installed. I guess I get to figure out IDLE now. Greg From phthenry@earthlink.net Tue Mar 11 00:00:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Tue Mar 11 00:00:01 2003 Subject: [Tutor] docutils--what is the status? Message-ID: <20030310235957.M8504@localhost.localdomain> Someone on this mailing list suggested that the best way to include documentation within a script or module was by using ReStructrued text. I downloaded the docutils and have looked at a few examples and seem to pretty much understand it. That is, I understand how to create standalone documents and use docutils to create XML of XHTML. However, the FAQ.txt states that the utility to generate XML or XHTML from a script is not yet implemented: It supports multiple types of input, such as standalone files (implemented), inline documentation from Python modules and packages (under development), `PEPs (Python Enhancement Proposals)`_ (implemented), and others as discovered. So if I am understanding things right, there is no way to type a command and get a document for a script. For example, in perl, you can type perldoc script.pl and see a complete list of information about the script in manpage format. Am I reading things right? It would be easy to create my own simple script to extract all the text before the first and second tripple quotes, output this to a file, and then run ReStructured text. That would be kind of a hack--good for my use, but still not providing python users with a sure way to get good documentation about a script. (Just having the tool to create a nice format does not insure that the programmer actually wrote good documentation--one of the most important elements to whether a module is usable, in my opinion.) I like the idea of ReStructured text and will use it in my scripts. I suppose it is a matter of time before the full implementation comes out. Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From syrinx@simplecom.net Tue Mar 11 01:59:02 2003 From: syrinx@simplecom.net (Scott) Date: Tue Mar 11 01:59:02 2003 Subject: [Tutor] Program Security Message-ID: <20030311005157.3edadce0.syrinx@simplecom.net> I'm putting together my first "major" Python app. It's a network application. (Specifically, a desktop internet program.) Anyone want to give advice on network security in Python programs? Maybe this is a little off-topic, but the newsgroup aren't as helpful as they used to be. From johnca@ourpla.net Tue Mar 11 02:21:01 2003 From: johnca@ourpla.net (John Abbe) Date: Tue Mar 11 02:21:01 2003 Subject: [Tutor] Global/Local confusions In-Reply-To: <5.1.0.14.0.20030304221324.02ce49d0@www.thinkware.se> References: <5.1.0.14.0.20030304221324.02ce49d0@www.thinkware.se> Message-ID: Thanks for engaging me on this. My questions continue... At 11:15 PM +0100 2003-03-04, Magnus Lycka wrote: >John Abbe wrote: >>In my continuing effort to understand global / local interactions -- > >For instance, the following will print 5 and then 3: > >x = 3 >def f(): > x = 5 > print x >f() >print x > >Ok? I assume you have no problem with this. Since x is >defined in the local scope, a lookup of the name x will >find the local variable x, not the global variable x, >right? Back in the global scope, we will find the global >variable x, which is not the same. > >Scopes always have clear boundries. The local scope of >a function contains the "def...:" line and all the >following indented lines. A local scope won't start at >any arbitrary line in the file. > >So, if you swap the lines in the function body above, >like this: > >x = 3 >def f(): > print x > x = 5 >f() > >You will still have a local variable x in the local scope >of the function f. This variable will hide the global >variable x just as in the first example. In other words, you >can't see the global x while you are inside the definition of >function f. Since you do 'print x' before you do 'x = 5', you >are trying to print something that you don't (yet) know the >value of. Thus the error message. The name (x here, b in your >example) is defined in the local scope, but at this point, it >hasn't been bound to any object yet. Sometimes the parser decides i mean a global variable even when i do not explicitly label it. E.g.: x = [3] def f(): if x[0] == 3: print "spam" f() This assumption-of-global-ness seems to be limited to cases when there is no plain assignment to the variable anywhere in the local context. Why not extend the assumption-of-global-ness to cases when assignment only occurs after any reference? >If you intend to use the global variable x inside a function >where you make assignments to it, you must say so explicitly: > >x = 3 >def f(): > global x > print x > x = 5 >f() Obviously the "must" is not quite true, given my example above. Making it an absolute requirement might well be cleaner. To confuse things further, while Python complains about plain assignment: x = [3] def f(): if x[0] == 3: print "spam" x = [3, 5] f() x ...assignment by object method is okay: x = [3] def f(): if x[0] == 3: print "spam" x.append(5) f() x Why? And is there anything else i should know about recognizing when a variable will be auto-recognized as global? >This might seem silly in a tiny program, but when you are at >line 2376 of a large file, and the global variable was defined >at line 72, you will be very happy that Python behaves just >the way it does... > >Imagine this case: > >x = 3 > >def f(i): > if i == 'x': > ... > x = None > ... > elif i is None > ... > x = 6 > ... > print x > ... > >f() > >In this case, if i is neither 'x' or None, you will >get an UnboundLocalError again. For me it would certainly >be strange if the same "print x" would either print a >local or a global variable depending on how the if- >statements evaluated. The current implementation does a >lot to help programmers stay sane in the long run.. I definitely agree that conditionally interpreting a variable as global or local would not be desirable. But in this case, Python could see that assignment is possible before reference, and assume that i meant x to be a local variable. Any problem with that? Life, John -- All you /\/\ John Abbe "If you don't like the news, need \ / CatHerder go out and make some of your own." is... \/ http://ourpla.net/john/ --Wes Nisker From borelan@wanadoo.fr Tue Mar 11 02:47:01 2003 From: borelan@wanadoo.fr (D2) Date: Tue Mar 11 02:47:01 2003 Subject: [Fwd: Re: [Tutor] Trying to find a value in a function.] References: <3E6CCFEB.80400@aon.at> Message-ID: <3E6D93B1.6050807@wanadoo.fr> Hi Gregor, Gregor Lingl a écrit: > > Hi D2! > > I suggest that you be more careful in youre questions (and > possibly in your programs) > Apparently you use props and _props for the same thing (a > variable name)? about props, it's just a typo. > > Your some_func.func_code.co_varnames is heavy stuff, which is > rarely necessary to use. I wonder what you want to accomplish. > > Your function is a rather strange and useless thing. It does nothing > and it returns nothing (namely None). Did you invent it only to serve > as an example? For what? > This function is really useless and strange :) it's just to show i wanted to get something from -inside- the function. but you answered below. I wanted to know if it was possible to extract information from functions as it is possible from classes. I think you noticed that i am new to python. > As props in your example is a local name, the variable (i. e. name > + reference to an object) only exists during runtime of the function. > So I think. it makes no sense to ask for the value of props except > after the assignment to it (in the function body) and before the > execution of some_func is done. So you had to insert an appropriate > statement in the function body ?!? > > For me it's hard to give an appropriate answer, because I can't > figure out for what purpose you need it. > The case : In an attempt to write a small application in Python, i want to allow different users to import data from their closed legacy systems in an object database. The only way they can do that is by using text files. The applications don't work the same way and don't export the data in the same format but always in txt. The users can't change the export format. (the story begins before neanderthal :) I want to automatize the process of creating objects by reading the text files. My first thought is to proceed as below. 1) Given the class name and constructor, describe the class's required arguments, arguments with default values. 2) Display a form where the user can describe the structure of his text file (field separator or length of the fields, etc.), and associate his text files fields with the argument of the class' constructor.(for example the 1st argument of the constructor correspond to the third field of the text, etc.) 3) Read the text file, apply the description, and create an object for each line by using constructor_function(*args, **keywords), the class being an argument of the constructor. But, the class and the constructor are not explicitely described so i have to get the information from the source that the reason why i use co_varnames, func_defaults, argcount, and so on. In the state of my knowledge, i didn't find a way to display separately the required arguments and the arguments with default values so i'm using workarounds. By comparing the length of the arguments list to the length of the default values list, i'll be able to determine how many postional arguments are mandatory and then find their names in the list. I'll be able to display a correct description of the constructor and to call it with the correct *args list and **keywords dictionary. There may be a better solution but that's my first attempt. > What sources (books, tutorials, examples) do you use when > working with Python? > I'm searching in Python's documentation (library reference, reference, tutorial), tutorials on the web and so on. > Please excuse, if my statement is totally irrelevant for you > Don't worry, i just want to learn and there's always something in an answer even if the question is .... let's say, a newbie's one :) Andre > Regards, Gregor > > > >> >> How can i get the value of the _props variable ? >> >> TIA >> >> >> >> >> >> _______________________________________________ >> 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 magnus@thinkware.se Tue Mar 11 04:14:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Mar 11 04:14:01 2003 Subject: [Tutor] Searching for a substring within a list In-Reply-To: <20030308170007.25630.55979.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030311093130.02b64e60@www.thinkware.se> At Sat, 08 Mar 2003 06:46:06 -0500, Daniel Nash wrote: >I have a list of email addresses : > >list1 = ["dan@company.com","fred@company.com"] > >and another list made up from the contents extracted from an email headers >To:,Cc: & Bcc: > >list2 =[('', 'support@company.com'), ('jim', 'jim@company.com'), ('', >'fred@comapny.com')] > >I want to write a peice of code to return true if any element in the first >list appears as a substring of any element in the second list. You got some replies already, I just want to add two things: 1. For detecting substrings, the normal python idiom is: bigString = "sldkfkjhgksdhfksdhf" subString = "ks" if bigString.find(subString) != -1: print "I found", subString, "in", bigString x.find(y) returns the position in x where the first sequence matching y begins, so 'ba'.find.('a') will return 1 and 'a'.find('a') will return 0. -1 indicates "not found". 2. Email addresses are a bit tricky. I guess you get list2 from some routine that strips off extra information, as in "Santa Claus" There are still case issues though. Santa@NorthPole.INT is the same address as santa@northpole.int. If you do the stripping as in list2, x.lower() == y.lower() might be an appropriate test, rather than a sub string search, but if you want a substring search, you might actually want if bigString.lower().find(subString.lower()) != -1: If there are performance issues, there are a number of further improvements one might do, but then we have to look at more of the program. If performance is ok, don't bother. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Tue Mar 11 04:42:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Mar 11 04:42:02 2003 Subject: [Tutor] outputting long lines In-Reply-To: <20030309135206.19691.77484.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030311093411.036875f0@www.thinkware.se> Paul Tremblay wrote: >It seems like Gregor's solution is the best. (See what he wrote in his >ps.) Would the solution in this email really save a lot of time in >comparison to Gregor's solution? It probably won't matter in this case. But don't ask *us* about *your* performance. Just measure! The performance gain is mainly when there are many strings involved, as in: y = '' for x in longSequence: y += x with y = [] for x in longSequence: y.append(x) y = "".join(y) If it's just a handful of strings, don't bother. >On Sat, Mar 08, 2003 at 12:11:39PM -0500, Erik Price wrote: > > > > One way to do it that doesn't sacrifice performance is to create a list > > of strings and then join them all together when they need to be treated > > as a single string. > > > > >>> text = [ > > ... 'Here is a ', > > ... 'really long string ', > > ... 'that is broken up ', > > ... 'over multiple lines.' > > ... ] > > >>> text > > ['Here is a ', 'really long string ', 'that is broken up ', 'over > > multiple lines.'] > > >>> output = ''.join(text) > > >>> output > > 'Here is a really long string that is broken up over multiple lines.' To measure something like this, wrap up what you want to measure in a function. It's probably good if the function can take a parameter which is a number, and repeat the test that many times, otherwise you might just measure the time 0.000 all the time. For instance: >>> import profile >>> def f1(): ... a = ('asd' ... 'asdasd' ... 'asdasdadsad' ... 'asdadasdasdasdasd' ... 'sdfsfsdfsdfsdf' ... 'sadasdasdasd') ... >>> def f2(): ... a = ['asd', ... 'asdasd', ... 'asdasdadsad', ... 'asdadasdasdasdasd', ... 'sdfsfsdfsdfsdf', ... 'sadasdasdasd'] ... a = "".join(a) ... >>> def m(f,n): ... for i in xrange(n): ... f() >>> profile.run('m(f1,1000)') 1003 function calls in 0.414 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1000 0.009 0.000 0.009 0.000 :1(f1) 1 0.013 0.013 0.023 0.023 :1(m) 1 0.000 0.000 0.023 0.023 :1(?) 1 0.391 0.391 0.414 0.414 profile:0(m(f1,1000)) 0 0.000 0.000 profile:0(profiler) We can bump up n a bit to get more precision. >>> profile.run('m(f1,100000)') 100003 function calls in 2.338 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 100000 1.008 0.000 1.008 0.000 :1(f1) 1 1.330 1.330 2.338 2.338 :1(m) 1 0.000 0.000 2.338 2.338 :1(?) 1 0.001 0.001 2.338 2.338 profile:0(m(f1,100000)) 0 0.000 0.000 profile:0(profiler) >>> profile.run('m(f2,100000)') 100003 function calls in 2.945 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 100000 1.560 0.000 1.560 0.000 :1(f2) 1 1.384 1.384 2.945 2.945 :1(m) 1 0.000 0.000 2.945 2.945 :1(?) 1 0.001 0.001 2.945 2.945 profile:0(m(f2,100000)) 0 0.000 0.000 profile:0(profiler) In this case, using a list increased execution time for f2/f1 by roughly 50%. But look at a case where we have plenty of strings: >>> def f3(): ... a = "" ... for i in xrange(10000): ... a += str(i) ... >>> profile.run('m(f3,1)') 4 function calls in 0.218 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.217 0.217 0.217 0.217 :1(f3) 1 0.000 0.000 0.217 0.217 :1(m) 1 0.000 0.000 0.217 0.217 :1(?) 1 0.001 0.001 0.218 0.218 profile:0(m(f3,1)) 0 0.000 0.000 profile:0(profiler) >>> def f4(): ... a = [] ... for i in xrange(10000): ... a.append(str(i)) ... a = "".join(a) ... >>> profile.run('m(f4,1)') 4 function calls in 0.107 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.106 0.106 0.106 0.106 :1(f4) 1 0.000 0.000 0.106 0.106 :1(m) 1 0.000 0.000 0.106 0.106 :1(?) 1 0.001 0.001 0.107 0.107 profile:0(m(f4,1)) 0 0.000 0.000 profile:0(profiler) Here, the list strategy reduced the execution time by 50%. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Tue Mar 11 04:50:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Mar 11 04:50:01 2003 Subject: [Tutor] Capturing stdout/stderror from linked c++ program In-Reply-To: <20030310170007.25050.1363.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030311093707.03683d00@www.thinkware.se> Douglas Eck wrote: >This all works beautifully. However, the c++ code prints some important >information to stdout (cout << info << endl;) during the run of the >network. Is there a way to capture this standard output so that I can >display it using wxLogMessage() (from wxPython) in my python GUI? This does rings a bell... Ask at the wxPython-users mailing list, and I think you might get a better reply. I realize that this isn't really a wxPython issue, but I'd try anyway. Subscribe by mailing to wxPython-users-subscribe@lists.wxwindows.org If there isn't any pure python solution, might it be possible to do some trick in the wrapper code for the C++ program? Perhaps cout could be redirected to another stream, and that could be made available from python as a file object? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From scot@possum.in-berlin.de Tue Mar 11 04:52:01 2003 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Tue Mar 11 04:52:01 2003 Subject: [Tutor] Searching for a substring within a list In-Reply-To: <5.1.0.14.0.20030311093130.02b64e60@www.thinkware.se> References: <5.1.0.14.0.20030311093130.02b64e60@www.thinkware.se> Message-ID: <200303111056.43810.scot@possum.in-berlin.de> Hello Magnus, My apologies if this has already been pointed out, I didn't see it: > For detecting substrings, the normal python idiom is: > > bigString = "sldkfkjhgksdhfksdhf" > subString = "ks" > > if bigString.find(subString) != -1: > print "I found", subString, "in", bigString Which I always thought was terribly counterintuitive (waddaya mean, "-1"? ). I remember trying if subString in bigString: print "I found", subString, "in", bigString which _doesn't_ work, much to my surprise; only single character substrings are found this way. However, I have been told that this will change in a future release, thereby bringing even more clarity to the language, and we can do away with this strange "-1" stuff. Y, Scot -- Verbing weirds language Scot W. Stevenson - Zepernick, Germany From alan.gauld@bt.com Tue Mar 11 04:56:23 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Mar 11 04:56:23 2003 Subject: [Tutor] Capturing stdout/stderror from linked c++ program Message-ID: > Thanks for the response. This is a good trick to know about, but it > didn't work. rats! :-( I assume you've tried the obvious trick using operating system redirection? C:\> python foo.py > myfile.txt Other than that I think you may be stuck. Alan G From charlie@begeistert.org Tue Mar 11 05:46:22 2003 From: charlie@begeistert.org (charlie@begeistert.org) Date: Tue Mar 11 05:46:22 2003 Subject: [Tutor] Datamodelling In-Reply-To: References: Message-ID: <20030311114633.2704.2@wonderland.1047372136.fake> On 2003-03-09 at 23:30:30 [+0100], Alan Gauld wrote: > > I was thinking of using shelve but I'm not sure about keys or doing > > Shelve would seem a reasonable starting point. Think of it as a single > table database! > > You can use multiple shelves but then you have to do the joins manually. How do I deal with "fixed" columns? Shelve won't enforce this for me, will it? I assume I just have to do this in the script. I've done my development and everything works fine until I try it on the server: I get a permissions error Traceback (most recent call last): File "...", line 109, in ? id = begeistert.store_addr(t_reg, 'register') File "/_web/begeistert.org/cgi-bin/begeistert.py", line 12, in store_addr shelf = shelve.open("../" + db, 'c') File "/usr/lib/python2.1/shelve.py", line 158, in open return DbfilenameShelf(filename, flag) File "/usr/lib/python2.1/shelve.py", line 148, in __init__ Shelf.__init__(self, anydbm.open(filename, flag)) File "/usr/lib/python2.1/anydbm.py", line 86, in open return mod.open(file, flag, mode) File "/usr/lib/python2.1/dbhash.py", line 16, in open return bsddb.hashopen(file, flag, mode) bsddb.error: (13, 'Permission denied') Does anybody know how to work around this? It looks like my script isn't allowed to create files. Charlie From magnus@thinkware.se Tue Mar 11 06:21:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Mar 11 06:21:02 2003 Subject: [Tutor] newbie-class differs from function? In-Reply-To: <20030310170007.25050.1363.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030311093840.0371d3b8@www.thinkware.se> lugoteehalt@yahoo.co.uk wrote: >Have got very stuck and it might help if I >understood the difference, in hyper-simple terms, between >a class and a conventional, programmer defined function. >They seem the same to me. Remember the mail recently with the subject "Trying to find a value in a function"? The poster made his life hard since he tried to get context out of a function. He would have been much better off using a class... They are not the same thing at all. You can say that a computer program consists of two things: Data and instructions. Object-oriented programming has gained it's popularity because it makes it easier to structure programs with related instructions and data bundled together. The main tool to achieve this is the class. A python function is what you might more generically call a subroutine. It's a sequence of instructions, and some local data needed to perform whatever it is intended to do. It often takes input parameters, and often returns some data, but it's really completely decoupled from the parameters and non-local variables it uses. The main data structures in the program, that are used in several functions, are typically defined outside of the functions. Classes are used to bundle closely related data structures and functions together. It's difficult to explain the advantage of this in hyper-simple terms, since you don't need classes in hyper-simple programs. They help when things get difficult and complex. This isn't a Python issue, you can for instance look at http://java.sun.com/docs/books/tutorial/java/concepts/ for some explanations. Here is a little example: A counter class that can be used to count things. A counter instance will be reset when it's created, it can count if you call its incr() method, and reset if you call its reset() method. It's also capable of showing its current state if you convert it to a string (e.g. with print or str()). You create a Counter instance by calling the Counter class. If you create several instances, they will all share the same methods, but they will have their own context. >>> class Counter: ... def __init__(self): ... self.reset() ... def incr(self): ... self.counter += 1 ... def reset(self): ... self.counter = 0 ... def __str__(self): ... return str(self.counter) ... >>> c1 = Counter() >>> c2 = Counter() >>> print c1, c2 0 0 >>> c1.incr() >>> c1.incr() >>> print c1, c2 2 0 >>> c2.incr() >>> print c1, c2 2 1 >>> c2.incr() >>> c2.incr() >>> print c1, c2 2 3 There are a few magic things happening here. "c1 = Counter()" means that a new instance of the Counter class is created, and the variable c1 refers to that. If there is an __init__ method, this will then be executed to give the instance the desired initial state. The instance object is passed in as the first parameter, typically called self. c1 = Counter() c1.incr() is really a shorter (and preferred) form for c1 = Counter() Counter.incr(c1) Finally, "print c1" or for instance "str(c1)" will cause the Python interpreter to call Counter.__str__(c1). As you see, the class encapsulates several functions/methods and an attribute. Most classes have several attributes that are closely related. Often, a class represents a noun in the specification for a program, such as Customer, Invoice or AirlineTicket. In the case of an Invoice, it will have attributes such as buyer, seller, items, sum, salesTax, issueDate, daysToPay etc. It might have methods like .isPaid() returning True or False and .lastPayDate() returning issueDate + daysToPay etc. Do classes still seem to be just like functions? An important aspect of classes is inheritence! You can create so-called subclasses that are specialized versions of existing classes. Let's create a Counter that ticks when it's incremented! We do that by overriding the incr() method in our subclass. >>> class TickingCounter(Counter): ... def incr(self): ... print "Tick" ... Counter.incr(self) ... The above means: TickingCounter is a Counter, but the incr() method is implemented like this instead. Note that TickingCounter.incr() calls Counter.incr(), passing on the parameter self, which is the actual instance object. >>> tc1 = TickingCounter() >>> tc1.incr() Tick >>> tc1.incr() Tick >>> tc1.incr() Tick >>> print tc1 3 Hang on! We never tried the reset method! >>> print tc1 3 >>> tc1.reset() >>> print tc1 0 >>> tc1.incr() Tick >>> print tc1 1 Hm... Sometimes I want the counter to be associated to a name. Let's create a NamedCounter class. >>> class NamedCounter(Counter): ... def __init__(self, name): ... self.name = name ... Counter.reset(self) ... def __str__(self): ... return self.name + ": " + str(self.counter) ... >>> rats = NamedCounter('Rats') >>> rats.incr() >>> rats.incr() >>> mice = NamedCounter('Mice') >>> rats.incr() >>> mice.incr() >>> print mice Mice: 1 >>> print rats Rats: 3 See? Just beacause we *can* use inheritance, doesn't mean we always should. In this case, it might be better to modify the counter class so that it will take an optional name, and print it if it exists, and otherwise skip it. That makes it easier to create a Named Ticking Counter class for instance. Actually, a class can inherit from several classes. This is called multiple inheritence, but it's a misused feature, that often causes problems. Some languages, such as Java, has refrained from allowing it. The Java designers claim that it's on purpose, to reduce the risk of error. (Who knows...) Let's look at multiple inheritence. (It's not hyper simple any more I guess...) You then give several base classes, and if there is an ambiguity between them, the behavaiour of the one listed first will be used. We'll try to make a Named Ticking Counter by subclassing NamedCounter and TickingCounter. >>> class NamedTickingCounter(TickingCounter, NamedCounter): ... pass ... >>> x = NamedTickingCounter('Hello') Traceback (most recent call last): File "", line 1, in ? TypeError: __init__() takes exactly 1 argument (2 given) Rats! This didn't work. Since TickingCounter is listed first, its version of __init__ is used, and that it the __init__ in Counter, which doesn't know about the name. Let's switch order between the base classes. >>> class NamedTickingCounter(NamedCounter, TickingCounter): ... pass ... >>> x = NamedTickingCounter('Hello') >>> x.incr() >>> x.incr() Sigh... Now we obviously got a plain NamedCounter. The incr() method in TickingCounter is'nt used, since an incr-method (inherited from Counter) is available in NamedCounter, which is listed forst... :( Actually, you can get around this in Python version 2.2 and later by using the new style classes. You make Counter into a new style class by inheriting (directly or indirectly) from object. Then a more elaborate method will be used for determining what method to use! >>> class Counter(object): ... def __init__(self): ... self.reset() ... def incr(self): ... self.counter += 1 ... def reset(self): ... self.counter = 0 ... def __str__(self): ... return str(self.counter) Ah! A new style Counter class. :) No big change... >>> class NamedCounter(Counter): ... def __init__(self, name): ... self.name = name ... Counter.reset(self) ... def __str__(self): ... return self.name + ": " + str(self.counter) ... >>> class TickingCounter(Counter): ... def incr(self): ... print "Tick" ... Counter.incr(self) I have to redefine these two since they will still refer to the old Counter class. They still look exactly the same though. >>> class NamedTickingCounter(TickingCounter, NamedCounter): ... pass ... >>> x = NamedTickingCounter('Hello') >>> x.incr() Tick >>> print x Hello: 1 It works now :) but my general advice is still to stay away from multiple inheritance. What I just did is generally not a good idea. I'm much more likely to shoot myself in the foot in the further development of my Counter classes if I use multiple inheritance, than if I manage to get away without it. Especially if there are several base classes with common ancestors like here. On the other hand, multiple inheritance might be useful for adding features such as logging, persistence etc from so- called mixin classes. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Tue Mar 11 06:29:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Mar 11 06:29:01 2003 Subject: [Tutor] passing widgets In-Reply-To: <20030310170007.25050.1363.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030311093923.036653c0@www.thinkware.se> vicki@stanfield.net wrote: >If I want a textbox to display the input and output >from several other functions, must I pass it around as >a parameter or is it better to make it global? Neither! There are other options than global and parameter passing... This seems to be another program that wants to be object oriented. Perhaps there should be a class that encapsulates some reasonable abstraction, and the functions should be methods, and the textbox should be an attribute. Or better, make a method in the class that updates the textbox when it's invoked with a string. One day, you might want to display that stuff in some other control, maybe in the status line. It's best to leave the details in one place... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Tue Mar 11 06:39:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Mar 11 06:39:01 2003 Subject: [Tutor] Trying to find a value in a function. In-Reply-To: <20030310230709.5688.81735.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030311094018.036de538@www.thinkware.se> >I'm trying to find a value in a fonction given the name of the function >and the name of the variable. >The variable is not an attribute nor an argument. You're not really supposed to do this... Can you tell us what it is you are trying to achieve? We might suggest a better approach. A variable has variable values, that vary over time. Python functions are not static, they don't keep any values in their local scope until you run them. In other words, props inside some_func only exists when you run some_func, and then the value is initially undefined, and later ['a', 'b', 'c']. I don't see any other way to get what you want without calling some_func than to get to the source code of it, and then do the same text processing as with any other text file. To keep context in variables between function calls, create a class, and make the values you need to persist attributes in the class. >Here is the function > >--------- >def some_func(self): > props=['a', 'b', 'c'] >--------- > >I tried to use some_func.func_code.co_varnames but it only returned the >tuple below. > >--------- >('self', '_props') >--------- > >How can i get the value of the _props variable ? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Tue Mar 11 07:03:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Mar 11 07:03:01 2003 Subject: [Tutor] docutils--what is the status? In-Reply-To: <20030311104622.28424.19357.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030311124313.03683e48@www.thinkware.se> Paul Tremblay wrote: >So if I am understanding things right, there is no way to type a command >and get a document for a script. For example, in perl, you can type > >perldoc script.pl > >and see a complete list of information about the script in manpage >format. I don't know what it is that perldoc prints out, but look at http://www-106.ibm.com/developerworks/linux/library/l-cpmod.html See also http://web.pydoc.org/ Pdx at http://www.seanet.com/~hgg9140/comp/ http://epydoc.sourceforge.net/ http://happydoc.sourceforge.net/ -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From abli@freemail.hu Tue Mar 11 07:59:01 2003 From: abli@freemail.hu (Abel Daniel) Date: Tue Mar 11 07:59:01 2003 Subject: [Tutor] Global/Local confusions In-Reply-To: References: <5.1.0.14.0.20030304221324.02ce49d0@www.thinkware.se> Message-ID: <20030311125759.GA988@hooloovoo> On Tue, Mar 11, 2003 at 01:15:02PM +0630 John Abbe (johnca@ourpla.net) wrote: > Sometimes the parser decides i mean a global variable even when i do > not explicitly label it. E.g.: > > x = [3] > def f(): > if x[0] == 3: > print "spam" > > f() > > This assumption-of-global-ness seems to be limited to cases when > there is no plain assignment to the variable anywhere in the local > context. Why not extend the assumption-of-global-ness to cases when > assignment only occurs after any reference? IIRC the rationale is that cases like this are often programmer errors. Typos, leaving out a line and so on. Of course continuing this line of thought, you might demand an explicit "global" everywhere a global variable is used. Which would also follow the idea that "Explicit is better than implicit." (from the zen of python) However, in the same contains the line "[...]practicality beats purity." (http://www.python.org/doc/Humor.html#zen) and in this case, the current state is a compromise. > [.. snipped some ..] > To confuse things further, while Python complains about plain assignment: > > x = [3] > def f(): > if x[0] == 3: > print "spam" > x = [3, 5] > > f() > x > > ...assignment by object method is okay: > > x = [3] > def f(): > if x[0] == 3: > print "spam" > x.append(5) > > f() > x > > Why? And is there anything else i should know about recognizing when > a variable will be auto-recognized as global? In this case you don't modify x. Try printing id(x) before and after. In the second case x's content changes, but the identity of x doesn't. For more explanation see http://effbot.org/guides/python-objects.htm and http://starship.python.net/crew/mwh/hacks/objectthink.html -- Abel Daniel From borelan@wanadoo.fr Tue Mar 11 09:11:24 2003 From: borelan@wanadoo.fr (D2) Date: Tue Mar 11 09:11:24 2003 Subject: [Tutor] newbie-class differs from function? References: <5.1.0.14.0.20030311093840.0371d3b8@www.thinkware.se> Message-ID: <3E6DED4A.80104@wanadoo.fr> Magnus Lycka a écrit: > lugoteehalt@yahoo.co.uk wrote: > >> Have got very stuck and it might help if I >> understood the difference, in hyper-simple terms, between >> a class and a conventional, programmer defined function. >> They seem the same to me. > > > Remember the mail recently with the subject > "Trying to find a value in a function"? > > The poster made his life hard since he tried to get > context out of a function. He would have been much > better off using a class... They are not the same thing > at all. > Just for precision purpose, when you want to create an instance of a class you must use a function with parameters to set the instance properties. You may use the class's __init__ method or create the instance by calling the class without parameters or __init__ method, but in any way you'll have to use some functions to set the instance's properties though, as you said, "it's really completely decoupled from the parameters and non-local variables the function uses". What i want is to verify what parameters are used to construct an instance of a class, and how, given the class and assuming that i only know the name of the class and the initial constructor. I want to do that before creating an instance, to pass the description to a computer program which will provide the necessary data to create an instance. Let's take the example of human being. I think i don't need to explain the __init__ method of the HumanBeing class. Do i ? :). Knowing it, i can find the parameters to pass to build an instance of HumanBeing class. But what if i want to set the HumanBeing.knowledge property ? What are the methods ? So i'll have to search in the source files. That's what my example was not saying but what i want to do with my small application. Andre From borelan@wanadoo.fr Tue Mar 11 09:23:01 2003 From: borelan@wanadoo.fr (D2) Date: Tue Mar 11 09:23:01 2003 Subject: [Tutor] Trying to find a value in a function. References: <5.1.0.14.0.20030311094018.036de538@www.thinkware.se> Message-ID: <3E6DEFCC.6090202@wanadoo.fr> Magnus Lycka a écrit: > >> I'm trying to find a value in a fonction given the name of the function >> and the name of the variable. >> The variable is not an attribute nor an argument. > > > You're not really supposed to do this... Can you > tell us what it is you are trying to achieve? We > might suggest a better approach. > > A variable has variable values, that vary over time. > Python functions are not static, they don't keep any > values in their local scope until you run them. In > other words, props inside some_func only exists when > you run some_func, and then the value is initially > undefined, and later ['a', 'b', 'c']. > > I don't see any other way to get what you want without > calling some_func than to get to the source code of > it, and then do the same text processing as with any > other text file. That's the way i'm going but i thought there was a statement to get the description of an assignation in a function, without processing the source. See my answer to Gregor Lingl and my answer to your message in newbie-class differs from function. (sorry, i got your mail after having posted my comment). > > To keep context in variables between function calls, > create a class, and make the values you need to persist > attributes in the class. That's the way i'm doing it. I use mixin classes too as you describe them in your class explanation. Andre, waiting for an advice. > >> Here is the function >> >> --------- >> def some_func(self): >> props=['a', 'b', 'c'] >> --------- >> >> I tried to use some_func.func_code.co_varnames but it only returned the >> tuple below. >> >> --------- >> ('self', '_props') >> --------- >> >> How can i get the value of the _props variable ? > > > From ramrom@earthling.net Tue Mar 11 10:48:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Mar 11 10:48:02 2003 Subject: [Tutor] Datamodelling In-Reply-To: <20030311114633.2704.2@wonderland.1047372136.fake> References: Message-ID: <5.2.0.9.0.20030311083750.034b1148@66.28.54.253> --=======6F3299B======= Content-Type: text/plain; x-avg-checked=avg-ok-56465677; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:46 AM 3/11/2003 +0100, charlie@begeistert.org wrote: >Does anybody know how to work around this? It looks like my script isn't >allowed to create files. You've made several references to all the things the server can't/won't do. Can you migrate to a more friendly server? Is this an ISP that you're buying site hosting from? A client's server for which client you're doing work? In any case it seems to me that you would greatly benefit from better server support. How can you get that? Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======6F3299B======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-56465677 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======6F3299B=======-- From charlie@begeistert.org Tue Mar 11 12:11:49 2003 From: charlie@begeistert.org (charlie@begeistert.org) Date: Tue Mar 11 12:11:49 2003 Subject: [Tutor] Datamodelling In-Reply-To: <5.2.0.9.0.20030311083750.034b1148@66.28.54.253> References: <5.2.0.9.0.20030311083750.034b1148@66.28.54.253> Message-ID: <20030311181147.3936.6@wonderland.1047372136.fake> On 2003-03-11 at 16:40:05 [+0100], you wrote: > You've made several references to all the things the server can't/won't > do. Can you migrate to a more friendly server? Is this an ISP that you're > buying site hosting from? A client's server for which client you're doing > work? In any case it seems to me that you would greatly benefit from > better server support. How can you get that? I've got *lots* of space on the current server and know the sys admin quite well and my website has too little traffic for a real ISP. My sys admin is normally good but he's too much to do recently :-(. I've solved the problem: use a folder where everyone can write a bit of a security risk, I know. Doing the work with shelve has been very instructive so even though I know I created a problem in order to solve it, I'm glad I was able to solve it in the end. Charlie From ramrom@earthling.net Tue Mar 11 13:01:09 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Mar 11 13:01:09 2003 Subject: [Tutor] newbie-class differs from function? In-Reply-To: <3E6DED4A.80104@wanadoo.fr> References: <5.1.0.14.0.20030311093840.0371d3b8@www.thinkware.se> Message-ID: <5.2.0.9.0.20030311095058.034a29c0@66.28.54.253> --=======37B9FA1======= Content-Type: text/plain; x-avg-checked=avg-ok-56465677; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 10:06 AM 3/11/2003 -0400, D2 wrote: >[snip] The "straightforward answer" (written last but appearing first): to get the __init__ (or any other) method's parameters: class c: def __init__(self,a,b):pass c.__init__.im_func.func_code.co_varnames # returns ('self', 'a', 'b') (CHEERS to PythonWin autocompletion for getting this sequence quickly w/o having to look it up.) >when you want to create an instance of a class you must use a function >with parameters to set the instance properties. Here are the alternatives, including ways that don't require functions: direct assignment: class a:pass # class with no methods or properties b = a() # instance b.newproperty = 313 # give the instance a property and set its value My approach for setting properties via a method is: class a: def setprop(self, name, value): # setprop is an arbitrary name setattr(self, name, value) # setattr is a built-in function b = a() # instance b.setprop('newproperty', 313) # give the instance a property and set its value direct assignment and setattr both in effect do the following: b.__dict__['newproperty'] = 313 since instance properties are really dictionary entries. There is also the 'magic' method __setattr__(self, name, value). If this method is defined in the class, then direct assignment and setattr each call: b.__setattr__(self, name, value). In this case you have a place where you can make tests and perform actions on name and value. In order to actually set the property you MUST use self.__dict__[name] = value, since direct assignment and setattr used within __setattr__ will recursively call __setattr__. class a: def __setattr__(self, name, value) : # process name, value? self.__dict__[name] = value b = a() # instance b.newproperty = 313 # calls __setattr__(b, 'newproperty', 313) In all of these cases except __dict__ assignment, one must ensure that name is an "identifier" e.g. _A-Za-z followed by _A-Za-z0-9. When assigning directly to the dictionary, the key can be any hashable object. Of course, if it is not an identifier (e.g 5), then it can't be referenced by b.propertyname. This can also cause problems and/or anomalies in IDEs that offer autocompletion. For example, in PythonWin, given that b is a class instance: >>> b.__dict__[(4, 5)] = 5 >>> b. at which point auto complete offers: (4, 5) which is not correct, and not usable! >What i want is to verify what parameters are used to construct an instance >of a class, and how, given the class and assuming that i only know the >name of the class and the initial constructor. >I want to do that before creating an instance, to pass the description to >a computer program which will provide the necessary data to create an instance. >Let's take the example of human being. >I think i don't need to explain the __init__ method of the HumanBeing >class. Do i ? :). Knowing it, i can find the parameters to pass to build >an instance of HumanBeing class. >But what if i want to set the HumanBeing.knowledge property ? What are the >methods ? So i'll have to search in the source files. That's what my >example was not saying but what i want to do with my small application. Given what I've said above I think you can let go of the idea of "knowing" what parameters are "required", and use some other easier way to manage associations between different kinds of input and class properties, e.g. a dictionary keyed by the input type and having tuples of parameter names as values. OTOH if you REALLY want to associate the parameter names with the class, do this: class c: a=0 b=0 c.__dict__ # returns {'a': 0, '__module__': '__main__', 'b': 0, '__doc__': None} You'll have to ignore the __module__, __main__ and __doc__ entries; the rest are your "parameters". You'd set them using any of the above mentioned methods, or all at once by defining a method in the class to set them all at once: Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======37B9FA1======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-56465677 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======37B9FA1=======-- From freemyer@NorcrossGroup.com Tue Mar 11 13:50:02 2003 From: freemyer@NorcrossGroup.com (Greg Freemyer) Date: Tue Mar 11 13:50:02 2003 Subject: [Tutor] Debugger and pythonwin (newbie) Message-ID: <20030311185102.CBIC4426.imf15bis.bellsouth.net@tiger2> I've just installed python 2.2 and pythonwin. I got a "hello world" app to run, so I did something right. I'm trying to go thru the "Pythonwin Debugger Tutorial" but I'm stuck right at = step 1) =3D=3D=3D Starting the Debugger >From Pythonwin or Python.exe At the interactive window, type: import pywin.debugger.fail =3D=3D=3D I can do that and if comes back with =3D=3D=3D >>> import pywin.debugger.fail Can not perform post-mortem debugging while the debugger is active. =3D=3D=3D The tutorial says a full screen debugger window should magically appear. No = luck. Should this work, or is the tutorial out of date. TIA Greg --=20 Greg Freemyer =20 From dyoo@hkn.eecs.berkeley.edu Tue Mar 11 17:22:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 11 17:22:01 2003 Subject: [Tutor] Capturing stdout/stderror from linked c++ program In-Reply-To: <5.1.0.14.0.20030311093707.03683d00@www.thinkware.se> Message-ID: On Tue, 11 Mar 2003, Magnus Lycka wrote: > Douglas Eck wrote: > >This all works beautifully. However, the c++ code prints some important > >information to stdout (cout << info << endl;) during the run of the > >network. Is there a way to capture this standard output so that I can > >display it using wxLogMessage() (from wxPython) in my python GUI? > > > If there isn't any pure python solution, might it be possible to do some > trick in the wrapper code for the C++ program? Perhaps cout could be > redirected to another stream, and that could be made available from > python as a file object? I did a quick hunt, and found something useful using the rdbuf() method in C++'s iostreams: http://www.cplusplus.com/ref/iostream/ios/rdbuf.html This might do the trick! rdbuf() allows us to redirect cout to a standard file, so you might be able to just do the redirection into a file, and then use Python afterwards to suck the data from that file. From wesc@fuzzyorange.com Tue Mar 11 17:39:02 2003 From: wesc@fuzzyorange.com (Wesley Chun) Date: Tue Mar 11 17:39:02 2003 Subject: [Tutor] ANN: BayPIGgies mtg Wed Mar 12 7:30pm In-Reply-To: Message-ID: BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group When: March 12, 2002 @ 7:30pm Where: Stanford University, Palo Alto, CA Agenda: PyChecker and Friends Speaker: Phil Lindsay "PyChecker and friends: Easing the transition from ad hoc scripts to stable, maintainable Python applications" PyChecker can be thought of as "Lint" for Python, and is a tool for finding bugs in Python source code. This talk will introduce PyChecker, show some of its functionality and discuss some of the lessons learned from its use in a commercial software development environment. The presentation will be from the perspective of a happy user & interested hacker. Some of the future goals of the project's authors will also be described. If time permits, the speaker will demonstrate a couple of small tools he has developed to also help in the creation of stable, maintainable applications. # Call For Talks: We are actively seeking speakers for BayPIGgies! If you would like to give a talk at one of our 2003 meetings (any Python related topic), contact us to coordinate! more info including directions: http://www.baypiggies.net hope 2 c u tomorrow nite! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, =A9 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://baypiggies.net wesley.j.chun :: wesc at deirdre.org or wesc at fuzzyorange.com cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://www.roadkill.com/~wesc/cyberweb/ From aicolburn@yahoo.com Tue Mar 11 18:54:13 2003 From: aicolburn@yahoo.com (Alan Colburn) Date: Tue Mar 11 18:54:13 2003 Subject: [Tutor] Parsing HTML ... where to start? Message-ID: <20030311235309.56267.qmail@web41601.mail.yahoo.com> Eventually, many miles/km down the road, I'd like to be able to download my personal financial information from a web site, storing various balance numbers in variables that I can go on to manipulate, display, etc. The web sites will require passwords to access and, presumably, are https:// I know there's a module out there somewhere that will help, with particular methods that I'd want to learn about, but I don't know what they are or where to look to find the modules and help in using them. I'm familiar with basic Python and HTML -- it's just the importing data from a web site aspect of the problem I need to learn. Suggestions on a starting point? As always, thanks for your help! -- Al C. __________________________________________________ Do you Yahoo!? Yahoo! Web Hosting - establish your business online http://webhosting.yahoo.com From missive@hotmail.com Tue Mar 11 22:12:02 2003 From: missive@hotmail.com (Lee Harr) Date: Tue Mar 11 22:12:02 2003 Subject: [Tutor] Re: Program Security Message-ID: >I'm putting together my first "major" Python app. It's a network >application. (Specifically, a desktop internet program.) Anyone want >to give advice on network security in Python programs? Well... you might want to be a _little_ more specific. Are you writing a server? Seems like no... but not really clear. I do not think there is much that is python-specific when it comes to security, unless you are planning on using rexec which I think is being deprecated. _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From johnca@ourpla.net Wed Mar 12 05:46:58 2003 From: johnca@ourpla.net (John Abbe) Date: Wed Mar 12 05:46:58 2003 Subject: [Tutor] class wrapper question (from Dive into Python) Message-ID: I'm going through , and highly recommend it to all the other newbies out there. I'm halfway through chapter 3 before a serious question occurred to me. This, like not noticing the technology in computer animation movies, is a good thing. Okay... From , the old UserDict class: > def clear(self): self.data.clear() 1 > def copy(self): 2 > if self.__class__ is UserDict: 3 > return UserDict(self.data) > import copy 4 > return copy.copy(self) > def keys(self): return self.data.keys() 5 > def items(self): return self.data.items() > def values(self): return self.data.values() My question is, in copy, why bother with checking if it's a UserDict...why isn't it just like this? def copy(self): import copy return copy.copy(self) Life, John -- ------===>> AbbeNormal <<===------ | ..:::.. A wiki-weblog, somewhere under the | .:::::::*:::. multi-dimensional normal curve | ..:::::::::::::::.. http://ourpla.net/cgi/pikie |....::::::::::*:::::::::::*.... From johnca@ourpla.net Wed Mar 12 05:48:05 2003 From: johnca@ourpla.net (John Abbe) Date: Wed Mar 12 05:48:05 2003 Subject: [Tutor] Global/Local confusions In-Reply-To: <20030311125759.GA988@hooloovoo> References: <5.1.0.14.0.20030304221324.02ce49d0@www.thinkware.se> <20030311125759.GA988@hooloovoo> Message-ID: At 1:57 PM +0100 2003-03-11, Abel Daniel wrote: >On Tue, Mar 11, 2003 at 01:15:02PM +0630 John Abbe (johnca@ourpla.net) wrote: >> Sometimes the parser decides i mean a global variable even when i do >> not explicitly label it. E.g.: >> >> x = [3] >> def f(): >> if x[0] == 3: >> print "spam" >> >> f() >> >> This assumption-of-global-ness seems to be limited to cases when >> there is no plain assignment to the variable anywhere in the local >> context. Why not extend the assumption-of-global-ness to cases when >> assignment only occurs after any reference? >IIRC the rationale is that cases like this are often programmer errors. >Typos, leaving out a line and so on. > >Of course continuing this line of thought, you might demand an explicit >"global" everywhere a global variable is used. Which would also follow >the idea that >"Explicit is better than implicit." (from the zen of python) >However, in the same contains the line >"[...]practicality beats purity." >(http://www.python.org/doc/Humor.html#zen) >and in this case, the current state is a compromise. Well, i feel better knowing that the things that led me to annoyance is a compromise. :) >[.. snipped some ..] > > To confuse things further, while Python complains about plain assignment: >> >> x = [3] >> def f(): >> if x[0] == 3: >> print "spam" >> x = [3, 5] >> >> f() >> x >> >> ...assignment by object method is okay: >> >> x = [3] >> def f(): >> if x[0] == 3: >> print "spam" >> x.append(5) >> >> f() >> x >> >> Why? And is there anything else i should know about recognizing when >> a variable will be auto-recognized as global? >In this case you don't modify x. Try printing id(x) before and after. >In the second case x's content changes, but the identity of x doesn't. >For more explanation see >http://effbot.org/guides/python-objects.htm >and >http://starship.python.net/crew/mwh/hacks/objectthink.html Thanks...i'm beginning to get how important this identity/contents distinction is. Life, John -- All you /\/\ John Abbe "If you don't like the news, need \ / CatHerder go out and make some of your own." is... \/ http://ourpla.net/john/ --Wes Nisker From johnca@ourpla.net Wed Mar 12 05:49:02 2003 From: johnca@ourpla.net (John Abbe) Date: Wed Mar 12 05:49:02 2003 Subject: [Tutor] re: class wrapper... (URL correction) Message-ID: At 4:47 PM +0630 2003-03-12, John Abbe wrote: >From ... That should be: From magnus@thinkware.se Wed Mar 12 05:49:12 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Mar 12 05:49:12 2003 Subject: [Tutor] Trying to find a value in a function. In-Reply-To: <3E6DEFCC.6090202@wanadoo.fr> References: <5.1.0.14.0.20030311094018.036de538@www.thinkware.se> Message-ID: <5.1.0.14.0.20030312114325.036d3428@www.thinkware.se> At 10:16 2003-03-11 -0400, D2 wrote: >Andre, waiting for an advice. I think I need to understand what you are trying to achieve at a higher level to give any useful advice. What is the purpose of all this? Why do you want the code to be able to know how to program? Are you trying to make the program write itself? ;) The normal approach is that the programmer reads the code using eyes and brain with some help from search functions etc, and thus figures out how to set the HumanBeing.knowledge property etc. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo@hkn.eecs.berkeley.edu Wed Mar 12 13:12:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 12 13:12:02 2003 Subject: [Tutor] class wrapper question (from Dive into Python) [copy.copy()] In-Reply-To: Message-ID: On Wed, 12 Mar 2003, John Abbe wrote: > I'm going through , and highly > recommend it to all the other newbies out there. I'm halfway through > chapter 3 before a serious question occurred to me. This, like not > noticing the technology in computer animation movies, is a good thing. > > Okay... > > From , > the old UserDict class: > > > def clear(self): self.data.clear() 1 > > def copy(self): 2 > > if self.__class__ is UserDict: 3 > > return UserDict(self.data) > > import copy 4 > > return copy.copy(self) > > def keys(self): return self.data.keys() 5 > > def items(self): return self.data.items() > > def values(self): return self.data.values() > > My question is, in copy, why bother with checking if it's a > UserDict...why isn't it just like this? > > def copy(self): > import copy > return copy.copy(self) Hi John, Interesting question! One example with the default copy.copy() function might help show why they're doing that: ### >>> class Foo: ... def __init__(self): ... self.d = {} ... def copy(self): ... import copy ... return copy.copy(self) ... >>> x = Foo() >>> x.d[42] = 'The answer!' >>> y = x.copy() >>> y.d {42: 'The answer!'} >>> x.d[13] = 'unlucky' >>> y.d {42: 'The answer!', 13: 'unlucky'} ### The example above shows that the 'y' copy shares the same dictionary as 'x'. copy.copy(), by default, does a shallow copy of an object. This explains why we use: return UserDict(self.data) when we're trying to copy a UserDict -- we want to make a fresh new copy of the internals, so that the copy isn't Siamese, so that it doesn't share the internal structures with the original. Hope this helps! I sorta rushed this one; please feel free to ask questions on any confusing points. From garnaez@yahoo.com Wed Mar 12 13:33:02 2003 From: garnaez@yahoo.com (Gerardo Arnaez) Date: Wed Mar 12 13:33:02 2003 Subject: [Tutor] What does '>>' pr '>' do? Message-ID: <20030312183210.95398.qmail@web20207.mail.yahoo.com> hi all. I've been having a nice time with python. I read an interview with guido in which he mentioned one of the most useful things he liked was you could 'pipr' info into a file. I think it was either '>' or '>>' but can not find it in the documention. Any clues please? Thank you __________________________________________________ Do you Yahoo!? Yahoo! Web Hosting - establish your business online http://webhosting.yahoo.com From ramrom@earthling.net Wed Mar 12 14:47:08 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Mar 12 14:47:08 2003 Subject: [Tutor] What does '>>' pr '>' do? In-Reply-To: <20030312183210.95398.qmail@web20207.mail.yahoo.com> Message-ID: <5.2.0.9.0.20030312124221.03492950@66.28.54.253> --=======43AE35D2======= Content-Type: text/plain; x-avg-checked=avg-ok-4B3B7BC2; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 10:32 AM 3/12/2003 -0800, Gerardo Arnaez wrote: >'pipr' info into a file. >I think it was either '>' or '>>' but can not find it in documentation I think this refers to things you can do in the WIndows command line or the *ux shell. Example someprompt>python foo.py > somefile.txt directs any stdout from the python program to somefile.txt. >> does same except appends to somefile.txt Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======43AE35D2======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-4B3B7BC2 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======43AE35D2=======-- From freemyer@NorcrossGroup.com Wed Mar 12 15:06:30 2003 From: freemyer@NorcrossGroup.com (Greg Freemyer) Date: Wed Mar 12 15:06:30 2003 Subject: [Tutor] Is there some way to tell which interpreter is in use? Message-ID: <20030312194853.GLNS27725.imf52bis.bellsouth.net@tiger2> All, Is there some way to tell which interpreter is in use? =20 i.e. if win32 : =20 process_uid =3D ??? process_gid =3D ??? else=20 process_uid =3D os.getuid() process_gid =3D os.getgid() And the obvious follow up. What is the win32 equivalent of getuid(). I looked at all the win32 os methods and did not see anything similar. Thanks Greg --=20 Greg Freemyer From francois.granger@free.fr Wed Mar 12 15:22:02 2003 From: francois.granger@free.fr (Francois Granger) Date: Wed Mar 12 15:22:02 2003 Subject: [Tutor] What does '>>' pr '>' do? In-Reply-To: <5.2.0.9.0.20030312124221.03492950@66.28.54.253> References: <5.2.0.9.0.20030312124221.03492950@66.28.54.253> Message-ID: At 12:46 -0700 12/03/2003, in message Re: [Tutor] What does '>>' pr '>' do?, Bob Gailer wrote: >Content-Type: text/plain; x-avg-checked=avg-ok-4B3B7BC2; >charset=us-ascii; format=flowed >Content-Transfer-Encoding: 8bit > >At 10:32 AM 3/12/2003 -0800, Gerardo Arnaez wrote: >>'pipr' info into a file. >>I think it was either '>' or '>>' but can not find it in documentation > >I think this refers to things you can do in the WIndows command line >or the *ux shell. Example > >someprompt>python foo.py > somefile.txt > >directs any stdout from the python program to somefile.txt. >> does >same except appends to somefile.txt I think that it refers to this: http://python.org/peps/pep-0214.html -- Hofstadter's Law : It always takes longer than you expect, even when you take into account Hofstadter's Law. From ramrom@earthling.net Wed Mar 12 15:34:05 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Mar 12 15:34:05 2003 Subject: [Tutor] Is there some way to tell which interpreter is in use? In-Reply-To: <20030312194853.GLNS27725.imf52bis.bellsouth.net@tiger2> Message-ID: <5.2.0.9.0.20030312132429.03512020@66.28.54.253> --=======3C52430E======= Content-Type: text/plain; x-avg-checked=avg-ok-4B3B7BC2; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 02:50 PM 3/12/2003 -0500, Greg Freemyer wrote: >Is there some way to tell which interpreter is in use? Do you mean "operating system"? Try: import sys sys.platform # returns 'win32' on my Win2K system > What is the win32 equivalent of getuid(). import getpass getpass.getuser() # returns (in my case) 'Administrator "This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order, and returns the value of the first one which is set to a non-empty string." HTH Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======3C52430E======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-4B3B7BC2 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======3C52430E=======-- From ramrom@earthling.net Wed Mar 12 15:42:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Mar 12 15:42:02 2003 Subject: [Tutor] What does '>>' pr '>' do? In-Reply-To: References: <5.2.0.9.0.20030312124221.03492950@66.28.54.253> <5.2.0.9.0.20030312124221.03492950@66.28.54.253> Message-ID: <5.2.0.9.0.20030312134036.034fb798@66.28.54.253> --=======780C31AF======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-4B3B7BC2; boundary="=====================_35565931==.ALT" --=====================_35565931==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-4B3B7BC2; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 09:21 PM 3/12/2003 +0100, Francois Granger wrote: >At 12:46 -0700 12/03/2003, in message Re: [Tutor] What does '>>' pr '>' >do?, Bob Gailer wrote: >>Content-Type: text/plain; x-avg-checked=avg-ok-4B3B7BC2; >>charset=us-ascii; format=flowed >>Content-Transfer-Encoding: 8bit >> >>At 10:32 AM 3/12/2003 -0800, Gerardo Arnaez wrote: >>>'pipr' info into a file. >>>I think it was either '>' or '>>' but can not find it in documentation >> >>I think this refers to things you can do in the WIndows command line or >>the *ux shell. Example >> >>someprompt>python foo.py > somefile.txt >> >>directs any stdout from the python program to somefile.txt. >> does same >>except appends to somefile.txt > >I think that it refers to this: > >http://python.org/peps/pep-0214.html Its even in the documentation! print_stmt ::= "print" ( [expression ("," expression)* [","]] | ">>" expression [("," expression)+ [","]] ) Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=====================_35565931==.ALT Content-Type: text/html; x-avg-checked=avg-ok-4B3B7BC2; charset=us-ascii Content-Transfer-Encoding: 8bit At 09:21 PM 3/12/2003 +0100, Francois Granger wrote:

At 12:46 -0700 12/03/2003, in message Re: [Tutor] What does '>>' pr '>' do?, Bob Gailer wrote:
Content-Type: text/plain; x-avg-checked=avg-ok-4B3B7BC2; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 10:32 AM 3/12/2003 -0800, Gerardo Arnaez wrote:
'pipr' info into a file.
I think it was either '>' or '>>' but can not find it in documentation

I think this refers to things you can do in the WIndows command line or the *ux shell. Example

someprompt>python foo.py > somefile.txt

directs any stdout from the python program to somefile.txt. >> does same except appends to somefile.txt

I think that it refers to this:

http://python.org/peps/pep-0214.html

Its even in the documentation!
print_stmt  ::=  "print" ( [expression ("," expression)* [","]]
  | ">>" expression [("," expression)+ [","]] )

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=====================_35565931==.ALT-- --=======780C31AF======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-4B3B7BC2 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======780C31AF=======-- From freemyer@norcrossgroup.com Wed Mar 12 16:25:12 2003 From: freemyer@norcrossgroup.com (Greg Freemyer) Date: Wed Mar 12 16:25:12 2003 Subject: re[2]: [Tutor] Is there some way to tell which interpreter is in use? Message-ID: <20030312211743.FOOK7626.imf56bis.bellsouth.net@tiger2> Thanks. That got me what I needed. BTW: In my case, I only sort of meant OS. i.e. The 2 values I got were "win32" and "cygwin" both on the same server. So = they have different methods available. Greg >> At 02:50 PM 3/12/2003 -0500, Greg Freemyer wrote: >> >Is there some way to tell which interpreter is in use? >> Do you mean "operating system"? Try: >> import sys >> sys.platform # returns 'win32' on my Win2K system >> > What is the win32 equivalent of getuid(). >> import getpass >> getpass.getuser() # returns (in my case) 'Administrator >> "This function checks the environment variables LOGNAME, USER, LNAME and=20 >> USERNAME, in order, and returns the value of the first one which is set to >> =20 >> a non-empty string." >> HTH >> Bob Gailer >> mailto:ramrom@earthling.net >> 303 442 2625 >> -- NextPart -- >> --- >> Outgoing mail is certified Virus Free. >> Checked by AVG anti-virus system (http://www.grisoft.com). >> Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 From drewp@bigasterisk.com Thu Mar 13 01:49:01 2003 From: drewp@bigasterisk.com (Drew Perttula) Date: Thu Mar 13 01:49:01 2003 Subject: [Tutor] Parsing HTML ... where to start? In-Reply-To: Your message of "Tue, 11 Mar 2003 15:53:09 PST." <20030311235309.56267.qmail@web41601.mail.yahoo.com> Message-ID: <200303130648.h2D6mJs32662@bang.houseoflove> > Eventually, many miles/km down the road, I'd like to > be able to download my personal financial information > from a web site, storing various balance numbers in > variables that I can go on to manipulate, display, > etc. The web sites will require passwords to access > and, presumably, are https:// > I just did that very project Sunday night! I now have a cron job that fetches the balances of two bank accounts every day and puts them in a log for my enjoyment and analysis. The hurdles for my bank's site were SSL (of course), and a cookie that had to be presented on each page access. My program submits the login page with my user/passwd; "presses a button" on the next page that appears; then fetches the contents of another frame. I quickly tear up the HTML of that result to get the balances I want. Then I "press" the logout button. All accesses are http POST operations. I used httpsession from http://webunit.sourceforge.net/ because it does do SSL with cookies, whereas the stdlib modules don't have an automatic cookie system that I could find. The core of my program is this class: import httpsession class Pagefetcher: def __init__(self,hostname): self.sess=httpsession.HTTPSession(debug_level=0,use_cookies=1) self.sess.add_header('user-agent','auto balance fetcher by drewp@bigasterisk.com') self.sess.add_header('Host',hostname) def fetchpage(self,formdict,url): """url should include the hostname given above. formdict is a python dict of form names and values to be POSTed to the site. the result page is returned.""" req=self.sess.post(url) [req.add_param(k,v) for k,v in formdict.items()] pagedata=req.getfile() return pagedata.read() My main code is specific to my bank, of course. It's just a sequence of fetchpage() calls with the right form variables. I send the last page through my friend's table extracting module TableParse.py (http://bebop.bigasterisk.com/python/). That module works for me, but htmllib or HTMLParser from the stdlib might be better choices. Finally, you should be aware of recording proxies. These are http proxy programs that you point your browser to, and they record all the requests and returned page data for later analysis. The advantage is that you can use an ordinary browser, surf for the data you want, and quickly get an automatic trace of what urls need to be fetched. If there's dynamic data in the requests, you'd replace it with a dynamically inserted value, etc. The disadvantage is that these proxies can't be used with SSL- that's the point of SSL: an intermediate program can't see the unencrypted data. So I, and probably you, will have to work out the requests one at a time by hand. -Drew From craig@eigentone-solo-collective.net Thu Mar 13 09:53:03 2003 From: craig@eigentone-solo-collective.net (Craig Davey) Date: Thu Mar 13 09:53:03 2003 Subject: [Tutor] newbie: trouble importing email module Message-ID: <5C211136-5563-11D7-958B-0050E4B07533@eigentone-solo-collective.net> Hey folks I'm very new to python, but I'm trying to create a simple cgi script that will send an email message. So I started out trying to construct a message using the email.Message module, unfortunately it seems like my isp is missing this module. Example: >>> import email Traceback (most recent call last): File "", line 1, in ? ImportError: No module named email >>> The version I am using is 2.1.2 on an OpenBSD system. I'm wondering if I'm doing something completely wrong or not because I thought the email module was part of the standard distribution. And if not, I'm wondering if the name of the module has changed, or if it's possible to list all available modules in some way. Any help would be most appreciated. Thanks. ----- seeyame From vicki@stanfield.net Thu Mar 13 10:07:28 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Thu Mar 13 10:07:28 2003 Subject: [Tutor] newbie: trouble importing email module Message-ID: <20030313070521.25696.h014.c000.wm@mail.stanfield.net.criticalpath.net> If you bring up idle and then type in help(), you will get to the help prompt. Then type modules to get a list of all available modules. >>help() help> modules --vicki From jeff@ccvcorp.com Thu Mar 13 13:11:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Mar 13 13:11:01 2003 Subject: [Tutor] newbie: trouble importing email module References: <5C211136-5563-11D7-958B-0050E4B07533@eigentone-solo-collective.net> Message-ID: <3E70C9B9.5080503@ccvcorp.com> Craig Davey wrote: > I'm very new to python, but I'm trying to create a simple cgi script > that will send an email message. So I started out trying to construct > a message using the email.Message module, unfortunately it seems like > my isp is missing this module. Example: > > >>> import email > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named email > >>> > > The version I am using is 2.1.2 on an OpenBSD system. IIRC, the email module was added to the standard distribution starting with Python 2.2 -- you're not doing anything wrong, it's just that you're trying use a brand-new module and your ISP is using a slightly dated version of Python. (At least they're not still using 1.5.2, though!) You can try to encourage your ISP to upgrade to Python 2.2, or if they're not interested, then I believe that this module was also made available as a separate package for 2.1, you can try to track that down (through the python.org website or through Google). (Note that it *is* possible to send email messages without the email module, it's just much more of a nuisance, especially if you're doing anything like MIME or attachements. Failing both of the above options, post here again and I'll share some of my old email code.) Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Thu Mar 13 13:17:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 13 13:17:01 2003 Subject: [Tutor] newbie: trouble importing email module In-Reply-To: <5C211136-5563-11D7-958B-0050E4B07533@eigentone-solo-collective.net> Message-ID: On Thu, 13 Mar 2003, Craig Davey wrote: > I'm very new to python, but I'm trying to create a simple cgi script > that will send an email message. So I started out trying to construct a > message using the email.Message module, unfortunately it seems like my > isp is missing this module. Example: > > >>> import email > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named email > >>> > > The version I am using is 2.1.2 on an OpenBSD system. I'm wondering if > I'm doing something completely wrong or not because I thought the email > module was part of the standard distribution. And if not, I'm wondering > if the name of the module has changed, or if it's possible to list all > available modules in some way. Any help would be most appreciated. Hi Craig, Hmmm... I think that the 'email' module was introduced in Python 2.2, so it might not be available for your ISP. Let me check... http://www.python.org/doc/lib/module-email.html Yeah, it came out in Python 2.2 as a convenience module that grouped a lot of common functionality (email/mime stuff) into a single module. Since you're working with 2.1, you may want to use the 'smtplib' library instead: http://www.python.org/doc/lib/module-smtplib.html The standard library documentation has an example of the smtplib library, and should help you get started: http://www.python.org/doc/lib/SMTP-example.html I hope this helps! Please feel free to ask more questions on Tutor; we'll be happy to listen. From magnus@thinkware.se Thu Mar 13 13:31:25 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Mar 13 13:31:25 2003 Subject: [Tutor] newbie: trouble importing email module In-Reply-To: <20030313170006.19395.50478.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030313185315.02b6e008@www.thinkware.se> Craig Davey wrote: >I'm very new to python, but I'm trying to create a simple cgi script >that will send an email message. Hi Craig, and welcome! Just a little warning. Don't make available a service that allows anonymous people to send arbitrary emails. It's likely to be abused by spammers, and then it will certainly be shut down, and your ISP will probably not be very happy... Otherwise, this is a simple thing to do... >So I started out trying to construct a >message using the email.Message module, unfortunately it seems like my >isp is missing this module. Look at the library reference: http://www.python.org/doc/current/lib/module-email.html "The email package is a library for managing email messages, including MIME and other RFC 2822-based message documents. It subsumes most of the functionality in several older standard modules such as rfc822, mimetools, multifile, and other non-standard packages such as mimecntl. It is specifically not designed to do any sending of email messages to SMTP (RFC 2821) servers; that is the function of the smtplib module." You might want to use this if you are assembling a multi part MIME message etc, but not for simple text emails. It not needed for that, and it's not at all involved in *sending* emails. So, I don't think you will miss the email module. You can install it separately for Python 2.1.3 if you like, but not for 2.1.2. :( >The version I am using is 2.1.2 on an OpenBSD system. I'm wondering if >I'm doing something completely wrong or not because I thought the email >module was part of the standard distribution. It is now... The documentation for 2.1.2 is here: http://www.python.org/doc/2.1.2/ As you see here, http://www.python.org/doc/2.1.2/lib/modindex.html , the email module wasn't in 2.1.2. It came with 2.2. But the smtplib has been with us for ages! See http://www.python.org/doc/2.1.2/lib/module-smtplib.html and http://www.python.org/doc/2.1.2/lib/SMTP-example.html That example is slightly dated though. Now, you can change import string ... string.join(toaddrs, ", ") to just ", ".join(toaddrs) Otherwise I think this example is just what the doctor ordered... ;) To get data into your email, I guess you will want to examine the contents of some kind of HTML form. For that, you use http://www.python.org/doc/2.1.2/lib/module-cgi.html See http://www.python.org/doc/2.1.2/lib/Using_the_cgi_module.html for usage examples. From 2.2, there is also a nice cgitb module that helps with debugging cgi scripts, but that's not available in 2.1. Python 2.2 has been available for quite some time, and it will be supported for long, so it's probably a good idea to upgrade... You can always ask your ISP... CGI debugging it often a bit tricky. You need to set up environment variables correponding to what the web server sees, to run the scripts from command line, and when you run it as CGI, it will be as another user, and it might not work--and typically all you see is "internal server error". cgitb is helpful then, and that requires 2.2... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From randy.corbin@wtok.com Thu Mar 13 15:58:01 2003 From: randy.corbin@wtok.com (Randy Corbin) Date: Thu Mar 13 15:58:01 2003 Subject: [Tutor] Going from one program to another. Message-ID: <001601c2e9a3$41f743a0$6300290a@server> This is a multi-part message in MIME format. ------=_NextPart_000_0013_01C2E970.F736AE00 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I'm new to Python so this is one of those "most basic" questions. When I try to run a .pyw program from another program it lists the = program instead of running it. Here is an example of what I mean. >From an HTML page, I wrote a form and under the action I had it open a = program call test.pyw which is the name of my program. The form worked fine but when it should have run the program I called = test.pyw it just listed it. What am I doing wrong? P.S. For my my first program I wrote a stock markets getter that gets a = portfolio of stocks and generates an HTML page with the information. It = might be good for a web site seeing that the users could have their own = portfollios. I don't know how to a good place to post it by I'd be happy = to e-mail it to anyone for free. ------=_NextPart_000_0013_01C2E970.F736AE00 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I'm new to Python so this is one of = those "most=20 basic" questions.
When I try to run a .pyw program from = another=20 program it lists the program instead of running it. Here is an example = of what I=20 mean.
 
From an HTML page, I wrote a form and = under the=20 action I had it open a program call test.pyw which is the name of my=20 program.
The form worked fine but when it should = have run=20 the program I called test.pyw it just listed it.
What am I doing wrong?
 
P.S. For my my first program I wrote a = stock=20 markets getter that gets a portfolio of stocks and generates an HTML = page with=20 the information. It might be good for a web site seeing that the users = could=20 have their own portfollios. I don't know how to a good place to post it = by I'd=20 be happy to e-mail it to anyone for free.
 
------=_NextPart_000_0013_01C2E970.F736AE00-- From dan_nash@hotmail.com Thu Mar 13 16:49:02 2003 From: dan_nash@hotmail.com (Daniel Nash) Date: Thu Mar 13 16:49:02 2003 Subject: [Tutor] Python and postgreSQL qurey? Message-ID: When you do a qurey on an SQL databse what form is the result of the qurey returned to you in? Is it a list? Does anyone have a simple example? Dan _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From dyoo@hkn.eecs.berkeley.edu Thu Mar 13 17:04:37 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 13 17:04:37 2003 Subject: [Tutor] Python and postgreSQL qurey? In-Reply-To: Message-ID: On Thu, 13 Mar 2003, Daniel Nash wrote: > When you do a qurey on an SQL databse what form is the result of the > query returned to you in? Hi Daniel, When we do queries, we talk to the database by getting a 'cursor'. Here's an example in MySQLdb (PostgreSQL should be very similar): ### >>> import MySQLdb >>> conn = MySQLdb.connect(db="pub") >>> cursor = conn.cursor() >>> cursor.execute("select distinct type from term") 7L ### Now that we've executed our statement, we can now start grabbing row results from the cursor. We can grab them, one at a time, by using the fetchone() method: ### >>> cursor.fetchone() ('comp',) >>> cursor.fetchone() ('gene',) >>> cursor.fetchone() ('func',) >>> cursor.fetchone() ('proc',) >>> cursor.fetchone() ('anat',) >>> cursor.fetchone() ('root',) >>> cursor.fetchone() ('deve',) >>> cursor.fetchone() >>> cursor.fetchone() ### (When we run out of results, fetchone() will return the None value.) Alternatively, we have the option of grabbing the whole result set as a list of tuples: ### >>> cursor.execute("select distinct type from term") 7L >>> cursor.fetchall() (('comp',), ('gene',), ('func',), ('proc',), ('anat',), ('root',), ('deve',)) ### It might make more sense now why we get individual cursors from the database connection: getting separate cursors allows us to interleave different database queries without getting the results mixed up! A.M. Kuckling has written a small tutorial on the DB-API that you might like: http://www.amk.ca/python/writing/DB-API.html Also, if you're interested, you may want to take a look at the Python Database API 2.0: http://www.python.org/topics/database/ http://www.python.org/topics/database/DatabaseAPI-2.0.html which has more of the hardcore details about the DB-API standard; the stuff in there should apply to both MySQL and PostgreSQL database programming. If you have more questions, please feel free to ask on Tutor; we'll do what we can to help! From dman@dman.ddts.net Thu Mar 13 20:31:27 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Thu Mar 13 20:31:27 2003 Subject: [Tutor] Re: Closing files / strings are immutable In-Reply-To: <5.1.0.14.0.20030306012456.02d153b0@www.thinkware.se> References: <5.1.0.14.0.20030305225011.02d3c028@www.thinkware.se> <5.1.0.14.0.20030306012456.02d153b0@www.thinkware.se> Message-ID: <20030314013141.GA16119@dman.ddts.net> --gKMricLos+KVdGMg Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Mar 06, 2003 at 01:41:55AM +0100, Magnus Lycka wrote: | At 16:08 2003-03-05 -0800, Danny Yoo wrote: | >When we have an open()ed file in "write" mode, it becomes more important | >to make sure to close the file, especially in Jython. |=20 | Yes, but is it always safe to implicitly close on read, | as in "data =3D file(filename).read()" if we subsequently | write to the same file? Or is there a risk that the | file is still open when we try to open it for writing, | and that the second open thus fail as in: |=20 | >>> x =3D file('c:/autoexec.bat', 'r') | >>> y =3D file('c:/autoexec.bat', 'w') | Traceback (most recent call last): | File "", line 1, in ? | IOError: [Errno 13] Permission denied: 'c:/autoexec.bat' | >>> x.close() FWIW this is an OS issue. UNIX systems won't care if the file is opened more than once. Windows does. Nonetheless it is best not to leave resources hanging in production software. | It shouldn't happen in CPython, since the file object | will be garbage collected at once Maybe, maybe not. It probably will in the current implementation, but the implementation isn't specified in the language spec. Guido could change the implementation any time he wants to. -D --=20 The wise in heart are called discerning, and pleasant words promote instruction. Proverbs 16:21 =20 http://dman.ddts.net/~dman/ --gKMricLos+KVdGMg Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj5xMP0ACgkQO8l8XBKTpRS1jACgyMb82mUTde9VR+wfram4lIu0 ibUAn2m34FG7t1j6PUTkS6fNmLeLj3of =pp9K -----END PGP SIGNATURE----- --gKMricLos+KVdGMg-- From dman@dman.ddts.net Thu Mar 13 20:32:05 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Thu Mar 13 20:32:05 2003 Subject: [Tutor] Re: CVS Version Number in __version__ In-Reply-To: <1551201350515.20030305103243@sfsu.edu> References: <1551201350515.20030305103243@sfsu.edu> Message-ID: <20030314013259.GB16119@dman.ddts.net> --1LKvkjL3sHcu1TtY Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, Mar 05, 2003 at 10:32:43AM -0800, Sean Abrahams wrote: | How do I get CVS to automatically input the version of the file and | the date into __version__ and __date__, respectively? In the python code, put this : __version__ =3D '$Revision$'[11:-2] Then just configure cvs correctly. (hint: don't use '-kb' for text files) HTH, -D --=20 "...Deep Hack Mode--that mysterious and frightening state of consciousness where Mortal Users fear to tread." (By Matt Welsh) =20 http://dman.ddts.net/~dman/ --1LKvkjL3sHcu1TtY Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj5xMUsACgkQO8l8XBKTpRQvCACfcFZ10MIot5lCHJkNbNurh3VC u7IAoKWCxk+iO5wnffuJY13vilbCe60c =ODSU -----END PGP SIGNATURE----- --1LKvkjL3sHcu1TtY-- From borelan@wanadoo.fr Fri Mar 14 09:23:02 2003 From: borelan@wanadoo.fr (D2) Date: Fri Mar 14 09:23:02 2003 Subject: [Tutor] Trying to find a value in a function. References: <5.1.0.14.0.20030311094018.036de538@www.thinkware.se> <5.1.0.14.0.20030312114325.036d3428@www.thinkware.se> Message-ID: <3E71E414.7010301@wanadoo.fr> Magnus Lycka a écrit: > Are you trying to make the program write itself? ;) That's true in some way. What i want to do is to create objects from text files without having to program this simple task and to avoid filling forms repeatedly. So i imagine a solution with three components : Import structure, the description of the object being created and the description of its constructor, Format structure, the description of the source text file, Relation structure, the description of the relationship between an Import and a Format Structure. Import structure must contain : the class the constructor function the required positional arguments : named args the arguments with default values : named defs meaningful labels for the arguments. additional properties. Format structure will describe a source text file containing the necessary data to create objects described in the import structure. The separation used between fields (separator, field legth, ...) unique or multiple lines records, unique or multiple fields lines in mutiple lines records, etc. The Relation strcture will describe the association between the fields in the source text file and the object's properties. The labels in the Import Structure will help to build this relationship. The usof the function. So i think i'll have to get the source lines of the function, and parse it to find assignation and generate a list of them. Does that make sense ? Andre From magnus@thinkware.se Fri Mar 14 10:02:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Mar 14 10:02:03 2003 Subject: [Tutor] Trying to find a value in a function. In-Reply-To: <3E71E414.7010301@wanadoo.fr> References: <5.1.0.14.0.20030311094018.036de538@www.thinkware.se> <5.1.0.14.0.20030312114325.036d3428@www.thinkware.se> Message-ID: <5.1.0.14.0.20030314154328.03685e48@www.thinkware.se> At 10:15 2003-03-14 -0400, D2 wrote: >Magnus Lycka a écrit: > >>Are you trying to make the program write itself? ;) >That's true in some way. > >What i want to do is to create objects from text files Do you mean to create instances of a predefined class from data in a texts file (that's a fairly normal thing to do) or do you mean that the text files should contain some kind of descriptions that you use to create new classes (which is more like black magic)? I have a feeling that what you want to do is fairly simple in python, but you haven't quite seen the (eventually) simple and obvious way to do it, and we don't quite know what you want... But maybe I'm wrong... ... >Does that make sense ? I'm not sure... Could you please show us a simple example of such a text file, and tell us what you want to happen with it. I think I need something very concrete here... If the text file contains python code, the obvious solution is to *run* this code, not to try to analyze it. Perhaps your "text files" should just contain class definitions that inherit base classes that supply the bulk of the code? If it's just data to be placed into instances of predefined python classes, I don't see what's so complicated. I also have a feeling that python dictionaries might be part of the solution to your problems... >Andre -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From lugoteehalt@yahoo.co.uk Fri Mar 14 11:15:04 2003 From: lugoteehalt@yahoo.co.uk (=?iso-8859-1?q?Lugo=20Teehalt?=) Date: Fri Mar 14 11:15:04 2003 Subject: [Tutor] Creating multiple instance names In-Reply-To: <3E6DED4A.80104@wanadoo.fr> Message-ID: <20030314161232.88663.qmail@web14809.mail.yahoo.com> --0-2096850781-1047658352=:88177 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit Is it possible to use 'for' or 'while' or the like to create arbitrarilly many named class instances? Tried to do something like: for i in ['a', 'b', 'c', 'd']: i = Counter() #Counter being a class print a.y, b.y, c.y, d.y # y is a thing from the class e.g. self.y = 0. (i.e. I'm trying to create four instances named a, b, c and d.) This sort of thing does't work. Assume it just shoves a new 'value' into the single 'pidgeon hole' named i every time. Is this just a special case of the general problem of how to name a sequence of 'cubby-holes', and put a specific value into each one, instead of naming one cubby-hole and putting a sequence of new values into it? I know how to create a sequence of pidgeon hole contents but not how to create a sequence of named pidgeon holes. Don't think this is bollocks; hope not. --------------------------------- With Yahoo! Mail you can get a bigger mailbox -- choose a size that fits your needs --0-2096850781-1047658352=:88177 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: 8bit

 

Is it possible to use 'for' or 'while' or the like to create

arbitrarilly many named class instances? Tried to do something

like:

for i in ['a', 'b', 'c', 'd']:

i = Counter() #Counter being a class

print a.y, b.y, c.y, d.y # y is a thing from the class e.g. self.y = 0.

(i.e. I'm trying to create four instances named a, b, c and d.)

This sort of thing does't work. Assume it just shoves a new 'value'

into the single 'pidgeon hole' named i every time.

Is this just a special case of the general problem of how to name

a sequence of 'cubby-holes', and put a specific

value into each one, instead of naming one cubby-hole and putting a

sequence of new values into it? I know how to create a sequence of pidgeon

hole contents but not how to create a sequence of named pidgeon holes.

Don't think this is bollocks; hope not.



With Yahoo! Mail you can get a bigger mailbox -- choose a size that fits your needs
--0-2096850781-1047658352=:88177-- From lugoteehalt@yahoo.co.uk Fri Mar 14 11:27:02 2003 From: lugoteehalt@yahoo.co.uk (=?iso-8859-1?q?Lugo=20Teehalt?=) Date: Fri Mar 14 11:27:02 2003 Subject: [Tutor] newbie-class differs from function? In-Reply-To: <5.1.0.14.0.20030311093840.0371d3b8@www.thinkware.se> Message-ID: <20030314162648.16355.qmail@web14803.mail.yahoo.com> --0-90400980-1047659208=:16079 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit I put in origional question and have been greatly helped. So these things really work, surprisingly perhaps. Putting in print statements helped, very simply, to work out what the computer does with a class >>> class Counter: def __init__(self): print "__init__ method called" self.reset() def incr(self): print "incr ?method called" self.counter += 1 def reset(self): print "reset called" self.counter = 0 def __str__(self): print "__str__ method called" return str(self.counter) >>> instance1 = Counter() __init__ method called reset called >>> instance2 = Counter() __init__ method called reset called >>> instance1.incr() incr ?method called >>> instance2.incr() incr ?method called >>> instance2.incr() incr ?method called >>> print instance1, instance2 __str__ method called 1 __str__ method called 2 >>> instance1 <__main__.Counter instance at 0x82e74ac> >>> instance1.reset() reset called >>> str(instance1) __str__ method called '0' even roughly understand inheritance: >>> class addcounters(Counter): def __add__(self, other=0): print "addcounters' __add__ method called" return (string.atoi(str(self)) + string.atoi(str(other)),"__add") >>> instnc1 = addcounters() __init__ method called reset called >>> instnc2 = addcounters() __init__ method called reset called >>> # addcounters() has inherited the incr ?method: >>> instnc1.incr() incr ?method called >>> instance1 + instance2 Traceback (most recent call last): File "", line 1, in ? instance1 + instance2 TypeError: unsupported operand types for +: 'instance' and 'instance' >>> instnc1 + instnc2 addcounters' __add__ method called __str__ method called __str__ method called (1, '__add') >>> instnc1 - instnc2 Traceback (most recent call last): File "", line 1, in ? instnc1 - instnc2 TypeError: unsupported operand type(s) for -: 'instance' and 'instance' >>> All of this stuff is news to me. --------------------------------- With Yahoo! Mail you can get a bigger mailbox -- choose a size that fits your needs --0-90400980-1047659208=:16079 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: 8bit

 

I put in origional question and have been greatly helped. So these

things really work, surprisingly perhaps.

Putting in print statements helped, very simply, to work out what the computer

does with a class

>>> class Counter:

def __init__(self):

print "__init__ method called"

self.reset()

def incr(self):

print "incr ?method called"

self.counter += 1

def reset(self):

print "reset called"

self.counter = 0

def __str__(self):

print "__str__ method called"

return str(self.counter)

>>> instance1 = Counter()

__init__ method called

reset called

>>> instance2 = Counter()

__init__ method called

reset called

>>> instance1.incr()

incr ?method called

>>> instance2.incr()

incr ?method called

>>> instance2.incr()

incr ?method called

>>> print instance1, instance2

__str__ method called

1 __str__ method called

2

>>> instance1

<__main__.Counter instance at 0x82e74ac>

>>> instance1.reset()

reset called

>>> str(instance1)

__str__ method called

'0'

even roughly understand inheritance:

>>> class addcounters(Counter):

def __add__(self, other=0):

print "addcounters' __add__ method called"

return (string.atoi(str(self)) + string.atoi(str(other)),"__add")

>>> instnc1 = addcounters()

__init__ method called

reset called

>>> instnc2 = addcounters()

__init__ method called

reset called

>>> # addcounters() has inherited the incr ?method:

>>> instnc1.incr()

incr ?method called

>>> instance1 + instance2

Traceback (most recent call last):

File "<pyshell#27>", line 1, in ?

instance1 + instance2

TypeError: unsupported operand types for +: 'instance' and 'instance'

>>> instnc1 + instnc2

addcounters' __add__ method called

__str__ method called

__str__ method called

(1, '__add')

>>> instnc1 - instnc2

Traceback (most recent call last):

File "<pyshell#29>", line 1, in ?

instnc1 - instnc2

TypeError: unsupported operand type(s) for -: 'instance' and 'instance'

>>>

All of this stuff is news to me.

 

 



With Yahoo! Mail you can get a bigger mailbox -- choose a size that fits your needs
--0-90400980-1047659208=:16079-- From ramrom@earthling.net Fri Mar 14 11:36:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Mar 14 11:36:01 2003 Subject: [Tutor] Creating multiple instance names In-Reply-To: <20030314161232.88663.qmail@web14809.mail.yahoo.com> References: <3E6DED4A.80104@wanadoo.fr> Message-ID: <5.2.0.9.0.20030314092953.01a1e410@66.28.54.253> --=======14D47B1C======= Content-Type: text/plain; x-avg-checked=avg-ok-48D13BA; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 04:12 PM 3/14/2003 +0000, Lugo Teehalt wrote: >Is it possible to use 'for' or 'while' or the like to create >arbitrarilly many named class instances? Tried to do somethinglike: > >for i in ['a', 'b', 'c', 'd']: >i = Counter() #Counter being a class >print a.y, b.y, c.y, d.y # y is a thing from the class e.g. self.y = 0. > >(i.e. I'm trying to create four instances named a, b, c and d.) >[snip] for i in ['a', 'b', 'c', 'd']: exec(i + ' = Counter()') --OR-- for i in ['a', 'b', 'c', 'd']: globals[i] = Counter() (you can also say for i in 'abcd':) Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======14D47B1C======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-48D13BA Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======14D47B1C=======-- From hsteiger@comcast.net Fri Mar 14 11:39:01 2003 From: hsteiger@comcast.net (Henry Steigerwaldt) Date: Fri Mar 14 11:39:01 2003 Subject: [Tutor] Executing a program from within a Python Program Message-ID: <000501c2ea48$01485e20$0201a8c0@eagle> To All: I asked a similar question in the past and did get a response, but now that I have tried to do what was mentioned, I can't get it to work. For example, the following code indeed starts the Windows Wordpad program without a problem: import os os.system("start wordpad.exe") But when I attempt to start a program like Paint Shop Pro that is NOT part of Windows, I get an error that Python cannot find the program, examples: import os os.system("start c:\\program files\\jasc software inc\\paint shop pro 7\\psp.exe") I even tried it with just one slant, as... import os os.system("start c:\program files\jasc software inc\paint shop pro 7\psp.exe") The Paint Shop Pro program (i.e. the executable psp.exe) is indeed in the directory I listed in the above examples. Can anyone tell me how to start up this program that is not part of Microsoft Windows from within a Python program? Please also send any response to my email address directly. Thanks much! Henry Steigerwaldt Hermitage, TN Email: hsteiger@comcast.net From borelan@wanadoo.fr Fri Mar 14 11:39:10 2003 From: borelan@wanadoo.fr (D2) Date: Fri Mar 14 11:39:10 2003 Subject: [Tutor] Trying to find a value in a function. References: <5.1.0.14.0.20030311094018.036de538@www.thinkware.se> <5.1.0.14.0.20030312114325.036d3428@www.thinkware.se> <5.1.0.14.0.20030314154328.03685e48@www.thinkware.se> Message-ID: <3E7203F9.5080204@wanadoo.fr> Magnus Lycka a écrit: > Could you please show us a simple example of such a text file, > and tell us what you want to happen with it. I think I need > something very concrete here... The text file only contains properties of the instance to be created and is exported from a database. Let's take an example In our program, the class user: name adress job homedir the constructor (addaUser) will : create an instance, create the home directory, update the company's tree, update the company's directory, update the payroll verify the email, notify the sysadmin in case of failure or notify the users of the creation of their homedir, notify the financial services etc... The constructor not only creates instances of the product. Provided by the customer, a user file containing name, adress, job, department, home directory, email, which structure may be different for each customer. Bob, 15 parkway, CEO, Headquarters, bobdir, bob@thecorp.com Jim, Washington, CTO, Technical division, jimdir, jim@thecorp.com or Bob 15 ParkWay CEO Headquarters bobdir bob@thecorp.com Jim Washington CTO Technical division jimdir jim@thecorp.com or Bob bobdir, bob@thecorp.com 15 ParkWay CEO, Headquarters The application will be used by non-programers. To update it, they'll import the data by choosing the ImportStructure of what they are importing, describing their FormatStructure in a form, (in the last example the format will be : multiple lines record field separator in a line : ',' 4 lines per record (there may be a record separator) and associate the object properties to their files via a form. instance.name = field1 instance.adress = field4 instance.job = field5 instance.department = field6 instance.homedir = field2 instance.email = field3 My application will use the FormatStructure to identify each field and the user will associate the fields to the instance via the RelationshipStructure. Notice that the application will be used by different companies, that we won't know the structure of their files. We will provide a clear description of the object in a form for them being able to update their application without external assistance. > I also have a feeling that python dictionaries might be part > of the solution to your problems... I use dictionaries to associate defaults values to their arguments or labels to arguments names or imported fields to arguments and so on. What i want too, is to use this application to provide an evolutive documentation on fonctions and classes used in an application at the property level (what is the property, where it is coming from, how it is involved in the application, in what other functions it is used, etc.) updated by programers and technical users. For example i'm trying to understand a python application, i'll be happy to have a structured description of the application and to store my understanding of every element of the application via a form. I don't think it's so complicated and there may be simpler ways to do that (perhaps provided by python functions) so i'd follow the tracks you'd indicate to me. I wanted to know how deep i'd be able to automate the analysis of a function. Notice that my last programing experience occured 20 years ago and that i learnt the name of python 4 months ago. I knew that OOP existed. :) That may explain that, to me, a hill may look like the Everest. Andre. From borelan@wanadoo.fr Fri Mar 14 11:39:21 2003 From: borelan@wanadoo.fr (D2) Date: Fri Mar 14 11:39:21 2003 Subject: [Tutor] newbie-class differs from function? References: <5.1.0.14.0.20030311093840.0371d3b8@www.thinkware.se> <5.2.0.9.0.20030311095058.034a29c0@66.28.54.253> Message-ID: <3E7203FE.3030400@wanadoo.fr> Bob Gailer a écrit: > At 10:06 AM 3/11/2003 -0400, D2 wrote: > >> [snip] > > > The "straightforward answer" (written last but appearing first): to get > the __init__ (or any other) method's parameters: > > class c: > def __init__(self,a,b):pass > c.__init__.im_func.func_code.co_varnames # returns ('self', 'a', 'b') > Notice that if there's another name in the function's body, it will appear in the tuple returned by co_varnames. So you'll have to use co_argcount to know the exact number of arguments, and func_defaults to know the defaults values of arguments and deduct the number of them. [snip] > OTOH if you REALLY want to associate the parameter names with the class, > do this: > > class c: > a=0 > b=0 > > c.__dict__ # retu5 > > > ------------------------------------------------------------------------ > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 From ramrom@earthling.net Fri Mar 14 12:07:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Mar 14 12:07:02 2003 Subject: [Tutor] Executing a program from within a Python Program In-Reply-To: <000501c2ea48$01485e20$0201a8c0@eagle> Message-ID: <5.2.0.9.0.20030314100551.034b7b70@66.28.54.253> --=======19A31081======= Content-Type: text/plain; x-avg-checked=avg-ok-48D13BA; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 10:37 AM 3/14/2003 -0600, Henry Steigerwaldt wrote: >[snip] >when I attempt to start a program like Paint Shop Pro that >is NOT part of Windows, I get an error that Python cannot >find the program, examples: > > import os > os.system("start c:\\program files\\jasc software inc\\paint shop pro >7\\psp.exe") Try os.system("c:\\program files\\jasc software inc\\paint shop pro7\\psp.exe") Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======19A31081======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-48D13BA Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======19A31081=======-- From ramrom@earthling.net Fri Mar 14 12:23:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Mar 14 12:23:01 2003 Subject: [Tutor] Executing a program from within a Python Program Message-ID: <5.2.0.9.0.20030314101058.03560008@66.28.54.253> --=======7694C21======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-48D13BA; boundary="=====================_9924220==.ALT" --=====================_9924220==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-48D13BA; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 10:37 AM 3/14/2003 -0600, Henry Steigerwaldt wrote: >[snip] >when I attempt to start a program like Paint Shop Pro that >is NOT part of Windows, I get an error that Python cannot >find the program, examples: > > import os > os.system("start c:\\program files\\jasc software inc\\paint shop pro >7\\psp.exe") Try os.system("c:\\program files\\jasc software inc\\paint shop pro7\\psp.exe") MORE LATE BREAKING NEWS: Did you read the error message? I'll bet it said Cannot find the file 'c:\\program files\\jasc' (or one.... Notice that the first blank in the path is seen as the end of the program. If you were entering this command at at DOS prompt you'd need to put it in "" to have the OS take the entire path name. So let's put it in quotes: os.system('start "c:\\program files\\jasc software inc\\paint shop pro7\\psp.exe"') Which gives us a DOS window with c:\program files\jasc software inc\paint shop pro7\\psp.exe in the title bar! Look up start in help: Starts a separate window to run a specified program or command. start ["title"] [/dpath] [/i] [/min] [/max] [/separate| /shared] [/low|/normal|/high|/realtime] [/wait] [/b] [filename] [parameters] So the first quoted string is taken as the title. That leads to: os.system('start "arbitrary title" "c:\\program files\\jasc software inc\\paint shop pro7\\psp.exe"') and Bob's your Uncle. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=====================_9924220==.ALT Content-Type: text/html; x-avg-checked=avg-ok-48D13BA; charset=us-ascii Content-Transfer-Encoding: 8bit At 10:37 AM 3/14/2003 -0600, Henry Steigerwaldt wrote:
[snip]
when I attempt to start a program like Paint Shop Pro that
is NOT part of Windows, I get an error that Python cannot
find the program, examples:

     import os
     os.system("start c:\\program files\\jasc software inc\\paint shop pro
7\\psp.exe")

Try os.system("c:\\program files\\jasc software inc\\paint shop pro7\\psp.exe")

MORE LATE BREAKING NEWS:

Did you read the error message? I'll bet it said Cannot find the file 'c:\\program files\\jasc' (or one.... Notice that the first blank in the path is seen as the end of the program. If you were entering this command at at DOS prompt you'd need to put it in "" to have the OS take the entire path name. So let's put it in quotes:
os.system('start "c:\\program files\\jasc software inc\\paint shop pro7\\psp.exe"')
Which gives us a DOS window with c:\program files\jasc software inc\paint shop pro7\\psp.exe in the title bar!

Look up start in help:

Starts a separate window to run a specified program or command.
start ["title"] [/dpath] [/i] [/min] [/max] [/separate| /shared] [/low|/normal|/high|/realtime] [/wait] [/b] [filename] [parameters]

So the first quoted string is taken as the title. That leads to:

os.system('start "arbitrary title" "c:\\program files\\jasc software inc\\paint shop pro7\\psp.exe"')

and Bob's your Uncle.

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=====================_9924220==.ALT-- --=======7694C21======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-48D13BA Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======7694C21=======-- From gerrit@nl.linux.org Fri Mar 14 12:44:02 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Fri Mar 14 12:44:02 2003 Subject: [Tutor] newbie: trouble importing email module In-Reply-To: <5C211136-5563-11D7-958B-0050E4B07533@eigentone-solo-collective.net> References: <5C211136-5563-11D7-958B-0050E4B07533@eigentone-solo-collective.net> Message-ID: <20030314174510.GA7207@nl.linux.org> Craig Davey schreef op donderdag 13 maart om 15:53:23 +0000: > if the name of the module has changed, or if it's possible to list all > available modules in some way. Any help would be most appreciated. You can list all modules by typing help('modules') in the interactive prompt: 4 >>> help('modules') Please wait a moment while I gather a list of all available modules... (...) I'm not sure when the online help was added, but IIRC it was 2.1. yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From slray@dow.com Fri Mar 14 12:55:06 2003 From: slray@dow.com (Ray, Scott (Dow AgroSciences)) Date: Fri Mar 14 12:55:06 2003 Subject: [Tutor] Extensions in C - numeric arrays & pointers Message-ID: <24E34B7B296AD411815300805F578D9401AB10@elnte4.nam.dow.com> As part of my Python education, I decided to turn a handful of simple numerical C functions into a small Python extension. I first selected a simple C function that takes one scalar input (a float or a double) and returns one scalar output (same). I followed the guidance in Guido and Drake's "Extending and Embedding" guide and, much to my delight, the extension worked on the first try. Then I moved to C functions that work with numeric arrays and their associated pointers. This has not gone so smoothly. After much experimentation, re-reading of documentation, searching mailing list archives, and scanning through other people's source code, I'm still stuck and in need of some guidance. So, I now turn to the experts. Here's a simple C function that is representative of what I'm trying to work with. double average(double *xvec, int numpts) { int n; double xbar; xbar = 0.0; for (n = 0; n < numpts; ++n) { xbar += xvec[n]; } return xbar/numpts; } Given C's argument passing mechanism (pass by value) , this routine expects its first argument to be a pointer to an array of doubles. What I want to be able to do is include this C function in a Python extension module (call it "ezmath") and use it in Python as: import ezmath z = [3.1416, 2.71828, 42] ezmath.average(z,3) I'm thinking that the C wrapper function should look something like, static PyObject * ezmath_average(PyObject *self, PyObject *args) { PyObject *x; int num; double *xa; double y; if (!PyArg_ParseTuple(args, "Oi", &x, &num)) { return NULL; } /* big mystery here */ y = average(xa, num); return Py_BuildValue("d",y); } But I haven't figured out what goes in the middle to connect or otherwise convert the Python list + PyObject pointer to the C array and its pointer. Or, perhaps, my mental model is all wrong and I need to go about this in some other way. What I have tried is various combinations of: - using the "array" extension module (under the assumption that Python array objects are somehow "closer" to C arrays) e.g. import ezmath import array z = [3.1416, 2.71828, 42] cz = array.array('d',z) ezmath.average(cz,3) - C pointer casts (e.g. xa = (double*) x ) - using PySequence_Size(x) to test whether the argument parsing operation worked (seems to have) - using PySequence_GetItem(x,i) to attempt to get at the i'th element in the list or array (though the outcome is not making sense to me) and lots of other more hare-brained ideas. Nothing seems to work and it feels like I must be missing something simple. Any help / guidance / pointers / redirection that more experienced Python/C developers can provide will be greatly appreciated. Please note that - I'm new to Python and to OOP. My advanced C skills are rusty at best. Advising me to read the NumPy or SciPy source code probably won't help. I'd like to work up to this, but I'm not there now. - My real goal here is learning, I know I could compute a numeric average in a multitude of ways. - I'm aware of the existence of NumPy and SWIG and of their advantages (for numerical work and extension development, respectively). If my current Python experiments work out positively, I'll be headed in those directions. Perhaps the right answer is to go there sooner rather than later. Right now though I'd prefer, if possible, to solve this puzzle without additional modules and objects types. It seems to me like there ought to be a solution with Python's lists and/or arrays. Then again, perhaps I'm being stubborn. - Finally, I notice in scanning through the mailing list archives that questions on this issue seem to come up periodically. Maybe I haven't dug far enough, but I have not found the answers provided to be fully illuminating. If I find instructive ways to solve this problem, I could maybe write a tutorial and post it on one of the Python websites, perhaps tacking on some additional stuff on like converting C result arrays back out to Python, doing it all over with NumPy, etc. Thanks, Scott Ray slray@dow.com From jeff@ccvcorp.com Fri Mar 14 13:11:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Mar 14 13:11:02 2003 Subject: [Tutor] Creating multiple instance names References: <20030314161232.88663.qmail@web14809.mail.yahoo.com> Message-ID: <3E721B2D.7020704@ccvcorp.com> Lugo Teehalt wrote: > Is it possible to use 'for' or 'while' or the like to create > > arbitrarilly many named class instances? > Yes, you can, but if you need to create a group of class instances, then odds are that you're better off keeping them in some sort of collection -- either a list or a dictionary. >>> class Counter: ... def __init__(self): ... self.count = 0 ... def incr(self): ... self.count += 1 ... >>> counters = {} >>> for i in ['a', 'b', 'c', 'd']: ... counters[i] = Counter() ... >>> counters['a'] <__main__.Counter instance at 0x01798378> >>> counters['a'].incr() >>> counters['a'].incr() >>> counters['c'].incr() >>> for name, ctr in counters.items(): ... print "%s - %d" % (name, ctr.count) ... a - 2 c - 1 b - 0 d - 0 >>> While it's possible to futz about with exec and/or globals(), as Bob Gailer suggested, I really don't recommend it. It will lead to code that's hard to follow (because it makes it difficult to know what is/will be in your namespace), which will lead to bugs. Those features should be reserved for situations where nothing else works, and in this situation a collection works splendidly -- I'd even argue that it works *better*, by keeping your namespace cleaner and better-organized. It's a good principle to never use black magic when it's not absolutely necessary, and I consider both exec and (writing to) globals() to be black magic -- or, as I've joked previously, at least very dark grey magic. ;) Jeff Shannon Technician/Programmer Credit International From reggie@merfinllc.com Fri Mar 14 13:50:03 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Fri Mar 14 13:50:03 2003 Subject: [Tutor] Extensions in C - numeric arrays & pointers In-Reply-To: <24E34B7B296AD411815300805F578D9401AB10@elnte4.nam.dow.com> References: <24E34B7B296AD411815300805F578D9401AB10@elnte4.nam.dow.com> Message-ID: <1047667762.26675.25.camel@pika.merfinllc.com> Scott, I think the mystery you're looking for is PyArray_ContiguousFromObject. There's a short tutorial on NumPy array in C extensions at http://starship.python.net/crew/hinsen/NumPyExtensions.html that I think you'll find helpful. Modifying your example to use this, it would look something like: static PyObject * ezmath_average(PyObject *self, PyObject *args) { PyObject *x; PyArrayObject *xa; double y; if (!PyArg_ParseTuple(args, "O", &x)) return NULL; xa = (PyArrayObject *)PyArray_ContiguousFromObject(x, PyArray_DOUBLE, 1, 1); if (xa == NULL) return NULL; y = average(xa->data, xa->dimensions[0]); return PyFloat_FromDouble(y); } On Fri, 2003-03-14 at 09:53, Ray, Scott (Dow AgroSciences) wrote: > As part of my Python education, I decided to turn a handful of simple numerical C functions into a small Python extension. I first selected a simple C function that takes one scalar input (a float or a double) and returns one scalar output (same). I followed the guidance in Guido and Drake's "Extending and Embedding" guide and, much to my delight, the extension worked on the first try. > > Then I moved to C functions that work with numeric arrays and their associated pointers. This has not gone so smoothly. After much experimentation, re-reading of documentation, searching mailing list archives, and scanning through other people's source code, I'm still stuck and in need of some guidance. So, I now turn to the experts. > > Here's a simple C function that is representative of what I'm trying to work with. > > double average(double *xvec, int numpts) { > int n; > double xbar; > > xbar = 0.0; > for (n = 0; n < numpts; ++n) { > xbar += xvec[n]; > } > return xbar/numpts; > } > > Given C's argument passing mechanism (pass by value) , this routine expects its first argument to be a pointer to an array of doubles. > > What I want to be able to do is include this C function in a Python extension module (call it "ezmath") and use it in Python as: > > import ezmath > z = [3.1416, 2.71828, 42] > ezmath.average(z,3) > > I'm thinking that the C wrapper function should look something like, > > static PyObject * > ezmath_average(PyObject *self, PyObject *args) { > PyObject *x; > int num; > double *xa; > double y; > > if (!PyArg_ParseTuple(args, "Oi", &x, &num)) { > return NULL; > } > > /* big mystery here */ > > y = average(xa, num); > return Py_BuildValue("d",y); > } Good Luck! -- Reggie Dugard Merfin, LLC From jeff@ccvcorp.com Fri Mar 14 14:02:05 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Mar 14 14:02:05 2003 Subject: [Tutor] Trying to find a value in a function. References: <5.1.0.14.0.20030311094018.036de538@www.thinkware.se> <5.1.0.14.0.20030312114325.036d3428@www.thinkware.se> <5.1.0.14.0.20030314154328.03685e48@www.thinkware.se> <3E7203F9.5080204@wanadoo.fr> Message-ID: <3E722750.2040701@ccvcorp.com> D2 wrote: > The text file only contains properties of the instance to be created > and is exported from a database. > > Let's take an example [...] So, if I understand this right, you have a standard class, which does various standard actions, and you are looking to create instances of this class from a variety of (nonstandard) text files? In this case, you need to have a flexible way to parse the text files. This does *not* require background access to variable names. (Btw, any time I *do* need access to something by both name and value, I automatically think dictionary. If I need to know a set of variables' names, then I plug them all into a data dictionary with those names as keys.) So, you need to be able to specify a) how to break the text file into records, b) how to break each record into fields, and c) how to map those fields to the attributes of your class. Let's look at a simple case, where each record is a single comma-separated line -- > Bob, 15 parkway, CEO, Headquarters, bobdir, bob@thecorp.com > Jim, Washington, CTO, Technical division, jimdir, jim@thecorp.com For simplicity's sake, I'll assume these files are small enough that memory won't be a concern. If the files are over a few MB, there's steps that can be taken to improve memory efficiency, but I won't worry about those now. So, you open the file and separate it by line. infile = file('datafile.txt', 'r') contents = infile.read() infile.close() lines = contents.split('\n') Now, for each line (record), you break it up into fields, pass that to a factory function (which we'll look at in a moment), and then add your resulting class instance to a new list (or dictionary). users = [] for line in lines: fields = line.split(',') instance = MakeUser(fields, cookie) users.append(instance) Notice that the MakeUser() function has an extra argument, which I've called 'cookie' here. This would be a special data structure that will help MakeUser map fields to instance attributes. In fact, this data structure can be something as simple as a dictionary, using the names of the attributes as keys, and the order of that attribute in the field list as values. (I'll use zero-based indexing to match with Python standards.) Then, we can use the setattr() function to set all of these attributes on a new user instance. cookie = { 'name':0, 'address':1, 'title':2, 'department':3, 'homedir':4, 'email':5 } def MakeUser(fields, cookie): instance = User() for attr, index in cookie.items(): setattr(instance, attr, fields[index]) return instance Now all you need is to define the User class. Actually, you don't even need an __init__() on it, since you're dynamically writing attributes onto it. All you need is a method that takes all of this data and does the processing you need (creating directories, modifying customer tree, etc). Once you've created a list of User objects, you can iterate through the list and run this method on each item. for user in users: user.do_processing() This should let you do what you want for one particular type of text file. Now you need to parameterize three parts -- the part that splits the file into records, the part that splits records into fields, and the part that maps fields to attributes. In the example above, these parts are, respectively: contents.split('\n') line.split(',') cookie = { ... } So, two functions and a dictionary. How to go from here depends on what sort of variations you expect from different customers. If each customer will have a single file format, you can set up dictionaries based off of customer name. Or, if multiple customers may have a single format and/or one customer might use multiple formats, you can name each file format and set up dictionaries based on that. For instance, to parameterize splitting the file into records, write a series of functions that take the text of the file as an argument, and return a list of records. Then put those functions into a dictionary. def split_by_line(text): return text.split('\n') def two_line_records(text): results = [] text = text.split('\n') for i in range(0, len(text), 2): record = text[i:i+1] record = '\n'.join(record) results.append(record) return results [...] record_separate = { 'single_line': split_by_line, 'two_line': two_line_records, .... } Now, way back where we're reading the file in and splitting it into records, we can do this: filetype = 'single_line' ... text = infile.read() lines = record_separate[filetype](text) ... If you can provide a handful of record-separating functions and a handful of field-separating functions that will handle all (or almost all) of your customers' file formats, you can probably also write something that'll easily let customers define the mapping dictionary themselves. Hopefully this gives you a good idea of what direction to proceed in... Jeff Shannon Technician/Programmer Credit International From magnus@thinkware.se Fri Mar 14 16:53:10 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Mar 14 16:53:10 2003 Subject: [Tutor] Creating multiple instance names In-Reply-To: <20030314170006.14775.40667.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030314214938.036879a8@www.thinkware.se> Bob Gailer wrote: >At 04:12 PM 3/14/2003 +0000, Lugo Teehalt wrote: > >Is it possible to use 'for' or 'while' or the like to create > >arbitrarilly many named class instances? Tried to do somethinglike: Sure, but don't "name" them by giving then a variable each! > >for i in ['a', 'b', 'c', 'd']: > >i = Counter() #Counter being a class > >print a.y, b.y, c.y, d.y # y is a thing from the class e.g. self.y = 0. Let's see what's happening: >>> for i in ['a', 'b', 'c', 'd']: ... print repr(i) ... i = Counter() ... print repr(i) ... 'a' <__main__.Counter object at 0x0171F5B0> 'b' <__main__.Counter object at 0x0171F5B0> 'c' <__main__.Counter object at 0x0171F5B0> 'd' <__main__.Counter object at 0x0171F5B0> The variable 'i' will first be assigned to the string "a", then to a counter, then to "b" and so on. When you think about it, I guess you are happy that a = 8 a = 19 doesn't mean that 8 becomes 19... ;) > >(i.e. I'm trying to create four instances named a, b, c and d.) > >[snip] > >for i in ['a', 'b', 'c', 'd']: > exec(i + ' = Counter()') exec is not a function, it's a statement. Please write it as such: exec i + ' = Counter()' Better yet! Don't use it at all! In the entire 44755 non-empty, non-comment lines of code python22/Lib/ there are totally 15 occurences of exec, and I don't think I've ever used it in any "real" code in almost seven years of python programming. If you think you would be better off using exec, odds are that you are mistaken. >for i in ['a', 'b', 'c', 'd']: > globals[i] = Counter() I wouldn't do this either... Returning those 44755 LoC in python22/Lib, globals() is accessed 5 times, and *never* assigned to. (Looking at the standard lib is probably a good way to learn decent python coding style and idioms.) Both are correct python, but I'd say it's not a good things to do. This kind of programming will make the code more difficult to understand, and it will probably also confuse code checking programs such as pyChecker. A string is a string, and a variable name is a variable name. Sure, on a technical level, variable names are strings that act as keys in some special forms of dictionaries, but it's a good idea to keep the hood closed and avoid "getting dirty" with these kinds of technicalities as long as we can. If we do have a reasonable number of objects, that we want to use in a uniform way, then *don't* assign a varable name for each object. Put them in a list or dict instead. It's going to be easier to work with, and it doesn't restrict us in any way. Like this: counters = [] for i in range(4): counters.append(Counter) or like this: counters = {} for c in "abcd": counters[c] = Counter() If you absolutely want to have four variables called a, b, c and d bount to four different counter objects, please type: a = Counter() b = Counter() c = Counter() d = Counter() This is much more obvious than for i in 'abcd': globals()[i] = Counter() or for i in 'abcd': locals()[i] = Counter() Saving two lines of code just to avoid using the obvious solution is not very pythonic... As I said, if there are many counters involved, use a list or a dictionary. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From amd@atlas.ucpel.tche.br Fri Mar 14 17:29:02 2003 From: amd@atlas.ucpel.tche.br (Aurelio Magalhaes Dias) Date: Fri Mar 14 17:29:02 2003 Subject: [Tutor] newbie: trouble importing email module In-Reply-To: <20030314174510.GA7207@nl.linux.org> References: <5C211136-5563-11D7-958B-0050E4B07533@eigentone-solo-collective.net> <20030314174510.GA7207@nl.linux.org> Message-ID: On Fri, 14 Mar 2003, Gerrit Holl wrote: > > I'm not sure when the online help was added, but IIRC it was 2.1. > It was on 2.2. See http://www.python.org/doc/current/lib/built-in-funcs.htm= l > yours, > Gerrit. > Aur=E9lio. From magnus@thinkware.se Fri Mar 14 19:22:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Mar 14 19:22:03 2003 Subject: [Tutor] Trying to find a value in a function. In-Reply-To: <20030314170006.14775.40667.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030314225254.0369e348@www.thinkware.se> Warning: subjective opinions and untested code below... Andre wrote: >Magnus Lycka a écrit: > > > Could you please show us a simple example of such a text file, > > and tell us what you want to happen with it. I think I need > > something very concrete here... > >The text file only contains properties of the instance to be created and >is exported from a database. > >Let's take an example > >In our program, >the class >user: > name > adress > job > homedir But the code defining the class, "class User: ...", will be in your program, right? >the constructor (addaUser) will : The word constructor is typically used to mean the method __init__ which is executed when a class is instanciated. It's probably a good thing not to do too much there. It reduces the flexibility of the class. >create an instance, >create the home directory, >update the company's tree, >update the company's directory, >update the payroll >verify the email, > notify the sysadmin in case of failure or > notify the users of the creation of their homedir, >notify the financial services >etc... I'm a little confused here, because it seems to me that you are mixing different conceptual levels. Creating home directory and updating the payroll seems like functional requirements. Create an instance seems like a technicality in the program, and something that will only have relevance during a short run of a program unless I misunderstand you. But never mind that, I think we'll sort this out. >The constructor not only creates instances of the product. Constructor... Hm... This can be arranged in many ways. Let's see below. >Provided by the customer, a user file containing name, adress, job, >department, home directory, email, which structure may be different for >each customer. Ok, no problem, as long as we know what the structure is. >Bob, 15 parkway, CEO, Headquarters, bobdir, bob@thecorp.com >Jim, Washington, CTO, Technical division, jimdir, jim@thecorp.com > >or > >Bob 15 ParkWay CEO Headquarters bobdir bob@thecorp.com >Jim Washington CTO Technical division jimdir jim@thecorp.com > >or > >Bob >bobdir, bob@thecorp.com >15 ParkWay >CEO, Headquarters The second version assumes that you know the positions where each column starts, since there are spaces in the text. The third is a rather boring mix with one or two params per row, but I get your point... But let's look at this part of the problem separately: From either of these files, you should be able to get a list of tuples, or a list of dictionares, that you can feed to your User class to get instances. Either userList = [ ('Bob', '15 parkway', 'CEO', 'Headquarters', 'bobdir', 'bob@thecorp.com'), ('Jim', 'Washington', 'CTO', 'Technical division', 'jimdir', 'jim@thecorp.com') ] or userList = [ ({'name': 'Bob', 'address': '15 parkway', 'position': 'CEO', 'dept': 'Headquarters', 'homedir': 'bobdir', 'email': 'bob@thecorp.com'}, {'name': 'Jim', 'address': 'Washington', 'position': 'CTO', 'dept': 'Technical division', 'homedir': 'jimdir', 'email': 'jim@thecorp.com'} ] Ok? This transformation from various kinds of text files (or read via a database interface from an Oracle database or whatever) is the first step, and we shouldn't mix this with the rest. If you need help with that, we can return to it, but is has nothing to do with instanciating classes. Now you could do something like: for userData in l: try: u = User(userData) u.createHome() updateTree(u) updateDirectory(u) updatePayroll(u) u.verifyEmail() notifyFinancialServices(u) except Exception, e: alertSysAdmin(userData, e) As you see, I envision some functions as methods in the User class, and other as functions in your program that take a User instance as a parameter. This depends on how you want to configure the code. All this could be methods in User. Assuming a list of tuples, your class could look something like this: class User: def __init__(self, userData): (self.name, self.address, self.position, self.dept, self.homedir, self.email) = userData def createHome(self): try: os.mkdir(self.homedir) email(self.email, HOME_DIR_CREATED_MSG % (self.name, self.homedir)) except OSError: email(self.email, HOME_DIR_CREATE_FAILED_MSG % (self.name, self.homedir)) email(SYS_ADM, HOME_DIR_CREATE_FAILED_MSG % (self.name, self.homedir)) With a list of tuples, you'd have an __init__ like this instead: def __init__(self, userData): for attr in ('name', 'address', 'position', 'dept', 'homedir', 'email'): setattr(self, attr, userData[attr]) If there are both compulsory and optional parameters that the users can provide to the program, it might get a bit more complicated, but not very. The easiest solution is to always provide all attributes to the __init__ method, but to set left out values to Null, and to handle that in the code. (You have to handle the optional values the same way either way once the instance is constructed.) >The application will be used by non-programers. >To update it, they'll import the data by choosing the ImportStructure of >what they are importing, describing their FormatStructure in a form, > (in the last example the format will be : > multiple lines record > field separator in a line : ',' > 4 lines per record (there may be a record separator) To be honest, I doubt that this will work very well... People will use comma separated formats, and still have commas in fields etc. Non-programmers rarely understand just how stupid computers are, and assume that things that are obvious to a person reading a texts is obvious for a computer to parse. But as I said, this is a separate problem from the instanciation and execution of classes and methods. Create a list of tuples or dictionaries from the user supplied data! >and associate the object properties to their files via a form. > instance.name = field1 > instance.adress = field4 > instance.job = field5 > instance.department = field6 > instance.homedir = field2 > instance.email = field3 Well, eventually, but that's handled in the conventional way by init above. >My application will use the FormatStructure to identify each field and >the user will associate the fields to the instance via the >RelationshipStructure. This sounds overly complicated to me. May I suggest that people stick to either: name: Jim address: Washington etc or a conventional CSV format as in name,address,job... Bob,"15 Parkway",CEO... For reading the latter, there are several readymade python modules (CSV etc, see http://www.thinkware.se/cgi-bin/thinki.cgi/UsefulPythonModules) Regular expressions might also be useful to find out how to extract data. You might well be able to get your list of lists with something like... import re userFormat = re.compile(...something...) userList = userFormat.findall(file(inFileName, 'r').read()) Look at http://www.amk.ca/python/howto/regex/ and http://www.python.org/doc/current/lib/module-re.html >Notice that the application will be used by different companies, that we >won't know the structure of their files. Ok. But make sure that transformation from custom files to a uniform format is a small separate code that has nothing to do with the actual business logic. Only solve one problem at a time... >We will provide a clear description of the object in a form for them >being able to update their application without external assistance. Don't have your customers understand the internals of your code. First of all, it's a technicality they shouldn't need to be involved in, and secondly it locks you up. Just define an interface. "For each user, you should provide these attributes in this format..." >What i want too, is to use this application to provide an evolutive >documentation on fonctions and classes used in an application at the >property level (what is the property, where it is coming from, how it is > involved in the application, in what other functions it is used, etc.) >updated by programers and technical users. >For example i'm trying to understand a python application, i'll be happy >to have a structured description of the application and to store my >understanding of every element of the application via a form. In my opinion. Well written Python source code is probably one of the best ways to describe program logic. By all means, add general comments on the purpose of this and that to the code, but for typical high level business logic, python code usually speaks for itself, and it's easy to modify etc. I'm not sure your "forms" will be useful though. As I have indicated, the normal python collection types: list, tuple, dictionary, are very useful for these kinds of things. If it's difficult to follow the business logic in the main routines, you should probably factor out pieces into separate functions/classes/modules. Obviously, python source code will be confusing for any non-programmer, but it's my experience that someone who can't write a program is unlikely to create a functioning system by setting up some kind of non-trivial configuration. It's much, much easier for you to fix the conversion from any potential format to the generic format above, than to predict all the kinds of possible formats that might occur, and to construct a general solution that will handle all these situations. I wouldn't even try. With some experience, you should be able to write a converter for any reasonable format in a matter of minutes. As the number of customers grow, you will be assemble a catalog of converters, and most of the time you will be able to use an existing one, or possibly make a tiny modification to an existing one. Unless you plan to ship this as shrinkwrap software, be a sport and help each customer. I think you need a lot of customers to save money with a generic solution. Besides, it will be much easier to write a good generic solution when you have solved the problem for a number of real customers. It's not until then that you can really know where the real problems lie, and what kind of requirements there are from the customers. Why just text files? You could also write converters that fetch data from databases, web pages of web services! You might also want to take a look at these resources if you are interested in simple descriptions of structured data: http://yaml.org/ http://www.scottsweeney.com/projects/slip >I don't think it's so complicated and there may be simpler ways to do >that (perhaps provided by python functions) so i'd follow the tracks >you'd indicate to me. >I wanted to know how deep i'd be able to automate the analysis of a >function. You can to a lot there, but I don't think it's the right path for you to follow. If you have a class where you want to inspect that you have the required attributes, you can either do as I did above in the two __init__ methods. In both those cases, you will get an exception when you try to instanciate the object if you lack needed parameters (you can add assertions to make sure properties are correct) and you can catch the exception and act upon that. Another option is to do something like: class User: attributes = (('name', str), ('address', str), ('position', str), ('dept', str), ('homedir', PathName), ('email', EmailAddress)) def __init__(self, userData): for attr, typeOrClass in self.attributes: setattr(self, attr, typeOrClass(userData[attr])) In this case you can if you want access User.attributes to find out what parameters you need to provide and what requirements they need to fulfil. The first parameter is the name, and the second is a type (assuming python 2.2 or later) or class that takes the value as it's single argument on instanciation. That way you can test that values exist and are ok before you instanciate the class if you prefer that to catching exceptions on instanciation. If you really want a more generic way of converting data (which might pay off if you have many involved classes) it's much better to design the relevant classes so that they provide an explicit interface for the information you need, rather than to try to use introspection magic. There is really no way you can know for certain what to provide to an arbitrary class, whatever you might extract through introspection. Look at the __init__ above. Nothing about the attributes of the class is revealed from the code in the __init__ method. It's all driven from the User.attributes list, which is clear when you look at the code, but hopeless to find out programmatically unless you are prepared for it... >Notice that my last programing experience occured 20 years ago and that >i learnt the name of python 4 months ago. >I knew that OOP existed. :) >That may explain that, to me, a hill may look like the Everest. I hope it looks a little less steep now... >Andre. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From pijus@virketis.com Fri Mar 14 22:41:31 2003 From: pijus@virketis.com (Pijus Virketis) Date: Fri Mar 14 22:41:31 2003 Subject: [Tutor] setting EOF symbol Message-ID: <465CE444-56B1-11D7-9086-000A9575F08A@virketis.com> Dear all, After a while away from Python, I decided to write a little weekend project: a spider to download all the articles and comments from one newspaper website (www.lrytas.lt). I successfully opened the url: import urllib lr = urllib.urlopen("http://www.lrytas.lt/20030314") But when it came time to read the html in, there was a problem: while lr: print(lr.readline()) Obviously, I will be doing more than just echoing the source, but this is sufficient to show the issue. The EOF does not seem to be hit, and I have an infinite loop. The tag just rolls by, and Python eventually hangs. I am using Python 2.2.2 on Mac OS X. My hypothesis is that the Mac/Unix EOF is different from the EOF in the webpage source. So I was wondering how to change the EOF (it's not a parameter in the readline() function), or more generally, how to read in the source of the webpage? Thank you! Pijus From python@jaydorsey.com Sat Mar 15 10:17:02 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Sat Mar 15 10:17:02 2003 Subject: [Tutor] setting EOF symbol In-Reply-To: <465CE444-56B1-11D7-9086-000A9575F08A@virketis.com> References: <465CE444-56B1-11D7-9086-000A9575F08A@virketis.com> Message-ID: <3E7343D6.6000601@jaydorsey.com> Pijus Virketis wrote: .... > import urllib > lr = urllib.urlopen("http://www.lrytas.lt/20030314") .... > I am using Python 2.2.2 on Mac OS X. My hypothesis is that the Mac/Unix > EOF is different from the EOF in the webpage source. So I was wondering > how to change the EOF (it's not a parameter in the readline() function), > or more generally, how to read in the source of the webpage? Instead of readlines, try lr.read(): import urllib lr = urllib.urlopen("http://www.lrytas.lt/20030314") x = lr.read() print x hth jay -- Jay Dorsey python at jay dorsey dot com From borelan@wanadoo.fr Sat Mar 15 12:07:01 2003 From: borelan@wanadoo.fr (D2) Date: Sat Mar 15 12:07:01 2003 Subject: [Tutor] Trying to find a value in a function. References: <5.1.0.14.0.20030311094018.036de538@www.thinkware.se> <5.1.0.14.0.20030312114325.036d3428@www.thinkware.se> <5.1.0.14.0.20030314154328.03685e48@www.thinkware.se> <3E7203F9.5080204@wanadoo.fr> <3E722750.2040701@ccvcorp.com> Message-ID: <3E735CC1.7020507@wanadoo.fr> That's it. Thank's a lot I appreciated the cookie :), it's what i called the Relationship_structure, and record_separate is my Format_structure I'd make some changes, instead of, > record_separate = { 'single_line': split_by_line, 'two_line': > two_line_records, .... } i'd use a dictionary of dictionaries : formatting={'single_line':{'lines_per_record':1, 'field separator':','}, 'two_line_record':{'lines_per_record':2, 'field_separator':','}} in the following function, i'd use : record = ','.join(record) instead of '\n'.join, so each record will be a single line of fields to ease the use of 'cookie' and i'll modify the function to use 'formatting' instead of record_separate. Quite final script : from some_module import User #Object importation script #this dictionary may be defined by the user via a form. cookie = { 'name':0, 'address':1, 'title':2, 'department':3, 'homedir':4, 'email':5 } #Formats may be defined by user and stored in this dictionary formatting={'single_line':{'lines_per_record':1, 'field separator':','}, 'two_line_record':{'lines_per_record':2, 'field_separator':','}} def makeRecords(filetype, text): results = [] text = text.split('\n') for i in range(0, len(text), step): record = text[i:i+1] record = sep.join(record) results.append(record) return results def MakeInstance(klass, fields, cookie): instance = klass() for attr, index in cookie.items(): setattr(instance, attr, fields[index]) return instance filetype = 'single_line' file_name= 'datafile.txt' klass=User def importFile(file_name, file_type, klass, cookie) infile = file(file_name, 'r') text = infile.read() infile.close() step=formatting[filetype]['lines_per_record'] sep=formatting[filetype]['field separator'] lines = makeRecords(filetype, text) users = [] for line in lines: fields = line.split(sep) instance = MakeInstance(klass, fields, cookie) instances.append(instance) for each_instance in instances: each_instance.do_processing() print 'Well done! Thanks to Jeff Shannon' # I will post it here in its final version. Thanks, Andre From dyoo@hkn.eecs.berkeley.edu Sat Mar 15 12:27:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 15 12:27:01 2003 Subject: [Tutor] setting EOF symbol In-Reply-To: <465CE444-56B1-11D7-9086-000A9575F08A@virketis.com> Message-ID: > import urllib > lr = urllib.urlopen("http://www.lrytas.lt/20030314") > > But when it came time to read the html in, there was a problem: > > while lr: > print(lr.readline()) Hi Pijus, The bug is that you're assuming that 'lr' will be set to None when we run out of bytes to suck in. However, it's not our 'lr' file object that gets set to None, but the return value of lr.readline(). The loop can be fixed by checking the return value of lr.readline(): ### while 1: line = lr.readline() if not line: break # rest of block ### This might look a little weird, to set up what looks like an infinite loop, but it's a fairly common way to process a file by lines. Even so, can we make this look nicer? We can make the loop look nicer if we use Python 2.2's iterators. When Python 2.2 came out, regular file objects could be walked across --- iterated --- directly with a 'for' loop: ### >>> for line in f: ... print len(line) ... 10 18 15 1 37 21 72 45 19 1 1 35 19 ### And this looks nicer than that 'while 1/break' sort of thing that we did above. It would be nice to do the same with the file-like object from urllib.urlopen()! But does it work? ### >>> f = urllib.urlopen('http://python.org') >>> i = iter(f) Traceback (most recent call last): File "", line 1, in ? TypeError: iteration over non-sequence ### Doh. Unfortunately, not yet. However, we can make it work with a little bit of code: ### >>> def fileLikeIter(f): ... """A generator that returns an iterator to a file-like object. ... We expect to use this on file-like objects, like ... urllib.urlopen(), when we want to iterate line by line.""" ... while 1: ... line = f.readline() ... if not line: raise StopIteration ... yield line ### The code above is called a 'generator', and it wraps around an existing file-like object and makes it look like an iterator. Let's try it out! ### >>> for line in fileLikeIter(urllib.urlopen('http://python.org')): ... print len(line), ... 64 60 7 61 34 27 35 29 31 1 4 1 7 39 73 46 59 35 60 55 65 61 11 50 34 50 65 8 39 39 38 23 29 64 29 5 31 66 1 9 18 27 58 64 29 25 50 35 31 32 26 5 27 12 10 27 31 10 27 35 10 27 35 10 10 27 31 10 27 32 10 27 31 10 27 27 10 6 41 1 28 32 39 32 64 32 63 26 52 15 22 27 47 11 27 35 11 27 225 11 27 38 11 27 32 11 27 32 11 27 51 11 27 61 11 27 87 11 27 25 11 27 25 11 27 62 11 33 52 14 22 27 35 11 27 63 11 27 37 11 27 41 11 27 40 11 27 49 11 27 46 11 27 71 11 27 66 11 33 52 9 22 27 47 11 27 44 11 27 40 11 27 50 11 27 83 18 11 27 36 11 33 52 6 22 27 82 11 27 57 11 27 49 11 27 56 11 27 66 11 27 78 11 33 52 17 22 27 53 11 27 56 11 27 51 11 27 51 11 27 69 11 27 50 11 27 57 11 27 72 11 27 50 11 27 46 11 27 45 11 27 58 11 27 61 11 27 46 11 27 61 11 33 52 12 22 27 53 11 27 58 11 33 52 9 22 27 63 11 27 7 11 27 13 9 27 55 5 11 27 7 11 27 12 11 27 68 11 38 1 6 46 29 28 47 83 1 4 33 51 1 5 1 8 1 5 19 1 65 65 66 69 54 13 52 1 6 6 1 9 1 39 1 14 1 1 77 77 77 1 38 5 1 83 42 61 12 15 19 1 5 1 70 46 21 1 71 10 1 71 21 1 78 80 66 1 68 65 1 76 46 80 47 50 1 6 5 1 11 1 9 1 1 65 71 1 5 68 74 61 70 49 68 26 70 63 21 66 27 6 1 33 1 5 64 34 71 46 74 16 64 46 66 42 66 66 36 68 51 6 1 33 1 5 1 92 1 7 65 56 1 64 46 1 58 14 1 68 1 57 69 6 1 63 70 46 1 93 54 1 6 1 39 70 1 46 60 18 1 10 1 31 38 35 15 ### That's better. *grin* Please feel free to ask more questions about this. I hope this helps! From ramrom@earthling.net Sat Mar 15 12:31:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Mar 15 12:31:02 2003 Subject: [Tutor] setting EOF symbol In-Reply-To: <465CE444-56B1-11D7-9086-000A9575F08A@virketis.com> Message-ID: <5.2.0.9.0.20030315095849.034dd428@66.28.54.253> --=======5E774635======= Content-Type: text/plain; x-avg-checked=avg-ok-7CB96DA9; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 10:42 PM 3/14/2003 -0800, Pijus Virketis wrote: > I decided to write a little weekend project: a spider to download all > the articles and comments from one newspaper website (www.lrytas.lt). I > successfully opened the url: > >import urllib >lr = urllib.urlopen("http://www.lrytas.lt/20030314") > >But when it came time to read the html in, there was a problem: > >while lr: lr is an instance (in my case, >) and therefore will always test True. The same is true of any file-like object. The way to loop until no more lines is: while 1: line = lr.readline() if line: print(line) else: break Since Python does not support embedded assignment, there's no way to read and test at the same time. SIGH. >Obviously, I will be doing more than just echoing the source, but this is >sufficient to show the issue. The EOF does not seem to be hit, and I have >an infinite loop. The tag just rolls by, and Python eventually hangs. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======5E774635======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-7CB96DA9 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======5E774635=======-- From dyoo@hkn.eecs.berkeley.edu Sat Mar 15 12:36:31 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 15 12:36:31 2003 Subject: [Tutor] setting EOF symbol In-Reply-To: <5.2.0.9.0.20030315095849.034dd428@66.28.54.253> Message-ID: > Since Python does not support embedded assignment, there's no way to > read and test at the same time. SIGH. Hi Bob, There is a set-and-test sort of recipe in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66061 Hope this helps! From erikprice@mac.com Sat Mar 15 12:41:01 2003 From: erikprice@mac.com (Erik Price) Date: Sat Mar 15 12:41:01 2003 Subject: [Tutor] setting EOF symbol In-Reply-To: Message-ID: <636F166D-570F-11D7-9E5D-00039351FE6A@mac.com> On Saturday, March 15, 2003, at 12:26 PM, Danny Yoo wrote: > The code above is called a 'generator', and it wraps around an existing > file-like object and makes it look like an iterator. Let's try it out! Apart from the argument that in Python everything is an object, is a "generator" an object? I mean, in other languages? I've never seen or heard of generators outside of Python. It looks like a function that maintains state. In Python this is probably not too difficult since I'm guessing that the generator is represented by an object. But, speaking only of the "theory" of generators, how does the function maintain its state? Or do they only exist in Python. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Sat Mar 15 13:38:01 2003 From: erikprice@mac.com (Erik Price) Date: Sat Mar 15 13:38:01 2003 Subject: [Tutor] crazy black magic Message-ID: <56EF2D1C-5717-11D7-9E5D-00039351FE6A@mac.com> Just last week someone was asking about meta-class programming on this list. I've been reading through "Python Cookbook" in my spare time, and it's really really good -- I'm learning a LOT about advanced techniques in Python (which is exactly what I was looking for when I bought the book, so I'm very satisfied so far) -- and I wanted to share this crazy code I just read, on page 55. It's really not crazy in the literal sense ("insane"), what I really mean is that it's very powerful and works in ways that I do not normally think. So I consider it pretty educational. This is one way that you can subclass a parent class (in this case, "list", available in Python 2.2) and use meta-class programming (reflection) to wrap each of its methods without actually coding out those methods by hand. (The purpose of the wrap is to add some code to them, in this case to reset a simple flag.) The recipe is credited to Alex Martelli. class FunkyList(list): def __init__(self, initlist=None): list.__init__(self, initlist) self._simple_flag = 0 def _wrapMethod(methname): _method = getattr(list, methname) def wrapper(self, *args): # reset simple flag to 0, then delegate # remaining method coding to base class self._simple_flag = 0 return _method(self, *args) setattr(FunkyList, methname, wrapper) for meth in 'setitem delitem setslice delslice iadd'.split(' '): _wrapMethod('__%s__' % meth) for meth in 'append insert pop remove extend'.split(' '): _wrapMethod(meth) del _wrapMethod Here's my interpretation of how it works: The class itself (FunkyList) simply subclasses the regular list class and adds a simple flag (which could be used for any purpose) to the class. Note the constructor calls the parent constructor, to make sure that any code in the parent constructors get called as well (this is always a good idea when subclassing). Then a throwaway function called "_wrapMethod" is defined, which, when passed a string containing a method name, fetches the object representing that method from the parent class (list), and calls "wrapper", a quickie-function that simply resets the simple flag and then returns that very method, which is then added to the derived class (FunkyList). The end result of this is that the flag is reset and the method is added to FunkyList. This is a great way to extend a parent class and add a bunch of methods. The only drawback to it is that it's not immediately obvious what is going on, which is kind of anti-pythonic. In contrast, the benefit (as Martelli points out in the recipe itself) is that it's unlikely that a typo or mistake will be made in reproducing the "boilerplate" of the parent class. Both are good points, I think. The throwaway function "_wrapMethod" is called on every method which must be added to the subclass. I bet there's a way to introspect the parent class (list) and determine all of its methods, then simply iterate over this list, but I'm guessing there's probably a reason why Martelli didn't use that particular technique. Finally the throwaway function is actually thrown away. I would never have thought of doing this, and it makes sense (because you don't want it to stick around in to be accidentally called by future client code). This isn't even the recipe's main point -- the main point is to give a high-performance means of doing a membership test on a sequence -- but I thought that this tiny chunk of code was valuable enough to warrant its own recipe! Namely, you can use the meta-class programming/reflection/"black magic" to save yourself a lot of work and potential mistake-making when subclassing large parent classes like "list". This is a great book so far. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From tony@tcapp.com Sat Mar 15 16:40:03 2003 From: tony@tcapp.com (Tony Cappellini) Date: Sat Mar 15 16:40:03 2003 Subject: [Tutor] Why does print add spaces ? Message-ID: <5.1.0.14.0.20030315133327.05031cf0@smtp.sbcglobal.net> --=====================_8812681==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed In this example mystr="abcdefghi" for x in range(1,len(mystr)): print "%s," % mystr[x], a, b, c, d, e, f, g, h, i, why does print add an implied space ?? How would i change this if I didn't want any spaces between each printed character ? --=====================_8812681==_.ALT Content-Type: text/html; charset="us-ascii"

In this example


mystr="abcdefghi"

for x in range(1,len(mystr)):
   print "%s," % mystr[x],


a, b, c, d, e, f, g, h, i,

why does print add an implied space ??
How would i change this if I didn't want any spaces between each printed character ?


--=====================_8812681==_.ALT-- From afterimage@gmx.net Sat Mar 15 17:31:02 2003 From: afterimage@gmx.net (Kristian Rink) Date: Sat Mar 15 17:31:02 2003 Subject: [Tutor] rfc822.Message Message-ID: <20030315232421.255b9b6a.afterimage@gmx.net> Hi all,... ...for what I see now, I've ran into some trouble using the rfc822 module while trying to dissect e-mail messages and to store the attachments they're carrying to be able to import them into a document management system. Basically, here's what I tried: >>> import rfc822 >>> mailmessage=3Drfc822.Message("2") Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/rfc822.py", line 106, in __init__ self.readheaders() File "/usr/lib/python2.2/rfc822.py", line 153, in readheaders line =3D self.fp.readline() AttributeError: 'str' object has no attribute 'readline' Btw Message "2" is a mail file inside a MH mail spool directory. Basically, it's kinda late now around here and perhaps I'm too tired to see the point, but seems I can't get along with this, here. Can someone give me a hint what's wrong here? TIA, have a nice evening wherever you are... Cheers, Kris --=20 F=FCr Freiheit und die Wahrung demokratischer Grundrechte im=20 Informationszeitalter - gegen Zensur, Manipulation und digitale Entm=FCndigung. Sch=FCtze Deine Rechte - sag _DEINE_ Meinung!=20 --------------- http://www.stop1984.org ---------------------- From Don Arnold" Message-ID: <0ae901c2eb50$0dbc23e0$7fe1b241@defaultcomp> ----- Original Message ----- From: "Tony Cappellini" To: Sent: Saturday, March 15, 2003 3:48 PM Subject: [Tutor] Why does print add spaces ? > > > In this example > > > mystr="abcdefghi" > > for x in range(1,len(mystr)): > print "%s," % mystr[x], > > > a, b, c, d, e, f, g, h, i, > > why does print add an implied space ?? I can't really answer as to the 'why', since it seems like a language design issue. Like it or not, that's how the print command behaves. > How would i change this if I didn't want any spaces between each printed > character ? > You can write directly to stdout: >>> import sys >>> for a in 'this is a test': sys.stdout.write(a) this is a test HTH, Don From ramrom@earthling.net Sat Mar 15 19:32:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Mar 15 19:32:01 2003 Subject: [Tutor] Why does print add spaces ? In-Reply-To: <0ae901c2eb50$0dbc23e0$7fe1b241@defaultcomp> References: <5.1.0.14.0.20030315133327.05031cf0@smtp.sbcglobal.net> Message-ID: <5.2.0.9.0.20030315172617.01a1ebc8@66.28.54.253> --=======5E1E58D======= Content-Type: text/plain; x-avg-checked=avg-ok-900D57; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit > > In this example > > > > > > mystr="abcdefghi" > > > > for x in range(1,len(mystr)): > > print "%s," % mystr[x], > > > > > > a, b, c, d, e, f, g, h, i, > > > > why does print add an implied space ?? An (obvious) alternative is to construct the desired output as one string, then print it. If the desired output is a,b,c,d,e,f,g,h,i, you could: out = '' for x in range(1,len(mystr)): out += "%s," % mystr[x] print out Since mystr is a sequence this simplifies to: out = '' for x in mystr: out += "%s," % x print out Even simpler: print ','.join(mystr) + ',' Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======5E1E58D======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-900D57 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======5E1E58D=======-- From tim.one@comcast.net Sat Mar 15 23:11:02 2003 From: tim.one@comcast.net (Tim Peters) Date: Sat Mar 15 23:11:02 2003 Subject: [Tutor] setting EOF symbol In-Reply-To: <636F166D-570F-11D7-9E5D-00039351FE6A@mac.com> Message-ID: [Erik Price] > Apart from the argument that in Python everything is an object, is a > "generator" an object? Yes -- everything in Python is an object . > I mean, in other languages? I've never seen or heard of generators > outside of Python. It looks like a function that maintains state. In > Python this is probably not too difficult since I'm guessing that the > generator is represented by an object. But, speaking only of the > "theory" of generators, how does the function maintain its state? > > Or do they only exist in Python. Most of your questions are answered in the generator PEP: http://www.python.org/peps/pep-0255.html Generators in Python are most like those in the Icon language: http://www.cs.arizona.edu/icon/ Icon is also a free language, and highly recommended if you want to exercise your mind against a different view of the world. Note that the definitive book about Icon can be downloaded for free: http://www.cs.arizona.edu/icon/books.htm From ramrom@earthling.net Sun Mar 16 00:21:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sun Mar 16 00:21:01 2003 Subject: [Tutor] setting EOF symbol In-Reply-To: References: <636F166D-570F-11D7-9E5D-00039351FE6A@mac.com> Message-ID: <5.2.0.9.0.20030315214902.034d82c8@66.28.54.253> --=======3EFB1188======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-900D57; boundary="=====================_50142090==.ALT" --=====================_50142090==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-900D57; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:10 PM 3/15/2003 -0500, Tim Peters wrote: >[snip] >Generators in Python are most like those in the Icon language: > > http://www.cs.arizona.edu/icon/ > >Icon is also a free language, and highly recommended if you want to exercise >your mind against a different view of the world. Note that the definitive >book about Icon can be downloaded for free: > > http://www.cs.arizona.edu/icon/books.htm And, viola, there's embedded assignment in Icon as early examples show: if i := find(s1, s2) then write(i) while line := read() do process(line) Furthermore the example: every i := find(s1, s2) do write(i) parallels Python's (in effect) embedded assignment as in for x in foo: I guess I'm on the soapbox for having embedded assignment in Python. (Along with some other goodies). As soon as I learn how to write effective PEPs I guess I'll propose some. I also like until exp do, and repeat. Not that I'm championing Icon; it seems top heavy with braces and end statements. OTOH I like the concept of failure. Also the interactive expression interpreter (qei) seems limited. And NO OOP! and less libraries and more work. In the forward Mitchell says: "A simple fact keeps me coming back to Icon: With Icon, I can write programs I don't have the time to write in C or C++. Without Icon, those programs wouldn't be written and tasks that could be automated would be done manually instead." I'd add "with Python I can write programs I don't have the time to write in Icon." ;-) Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=====================_50142090==.ALT Content-Type: text/html; x-avg-checked=avg-ok-900D57; charset=us-ascii Content-Transfer-Encoding: 8bit At 11:10 PM 3/15/2003 -0500, Tim Peters wrote:

[snip]
Generators in Python are most like those in the Icon language:

    http://www.cs.arizona.edu/icon/

Icon is also a free language, and highly recommended if you want to exercise
your mind against a different view of the world.  Note that the definitive
book about Icon can be downloaded for free:

    http://www.cs.arizona.edu/icon/books.htm

And, viola, there's embedded assignment in Icon as early examples show:

if i := find(s1, s2) then write(i)

while line := read() do
  process(line)

Furthermore the example:

every i := find(s1, s2) do write(i)

parallels Python's (in effect) embedded assignment as in

for x in foo:

I guess I'm on the soapbox for having embedded assignment in Python. (Along with some other goodies). As soon as I learn how to write effective PEPs I guess I'll propose some.

I also like until exp do, and repeat.

Not that I'm championing Icon; it seems top heavy with braces and end statements. OTOH I like the concept of failure. Also the interactive expression interpreter (qei) seems limited. And NO OOP! and less libraries and more work. In the forward Mitchell says:

"A simple fact keeps me coming back to Icon: With Icon, I can write programs I don’t
have the time to write in C or C++. Without Icon, those programs wouldn’t be
written and tasks that could be automated would be done manually instead."

I'd add "with Python I can write programs I don’t have the time to write in Icon." ;-)

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=====================_50142090==.ALT-- --=======3EFB1188======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-900D57 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======3EFB1188=======-- From johnca@ourpla.net Sun Mar 16 00:28:02 2003 From: johnca@ourpla.net (John Abbe) Date: Sun Mar 16 00:28:02 2003 Subject: [Tutor] class wrapper question (from Dive into Python) [copy.copy()] In-Reply-To: References: Message-ID: At 10:11 AM -0800 2003-03-12, Danny Yoo wrote: >On Wed, 12 Mar 2003, John Abbe wrote: > > From , > > the old UserDict class: > > > > > def copy(self): 2 > > > if self.__class__ is UserDict: 3 >> > return UserDict(self.data) >> > import copy 4 > > > return copy.copy(self) > > > > why bother checking if it's a UserDict...why isn't it just like this? > > >> def copy(self): >> import copy > > return copy.copy(self) > >Interesting question! One example with the default copy.copy() function >might help show why they're doing that: > >### > >>> class Foo: >... def __init__(self): >... self.d = {} >... def copy(self): >... import copy >... return copy.copy(self) >... >>>> x = Foo() >>>> x.d[42] = 'The answer!' >>>> y = x.copy() >>>> y.d >{42: 'The answer!'} >>>> x.d[13] = 'unlucky' >>>> y.d >{42: 'The answer!', 13: 'unlucky'} >### > > >The example above shows that the 'y' copy shares the same dictionary as >'x'. copy.copy(), by default, does a shallow copy of an object. This >explains why we use: > > return UserDict(self.data) > >when we're trying to copy a UserDict -- we want to make a fresh new copy >of the internals, so that the copy isn't Siamese, so that it doesn't share >the internal structures with the original. Thanks, and now i have more questions... Why not just use copy.deepcopy()? -- it avoids the Foo problem When a subclass is created that doesn't have it's own copy method, why doesn't it fail the "if self.__class__ is UserDict" test and have the same problem? >>> class Eggs(UserDict): ... pass ... >>> x=Eggs() >>> x.__class__ >>> x[42]='answer' >>> y=x.copy() >>> y {42: 'answer'} >>> x[13]='unlucky' >>> y {42: 'answer'} Life, (yes that is my regular sign-off... :) John -- All you /\/\ John Abbe "If you don't like the news, need \ / CatHerder go out and make some of your own." is... \/ http://ourpla.net/john/ --Wes Nisker From dyoo@hkn.eecs.berkeley.edu Sun Mar 16 03:11:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Mar 16 03:11:01 2003 Subject: [Tutor] rfc822.Message [reading emails from mailboxes] In-Reply-To: <20030315232421.255b9b6a.afterimage@gmx.net> Message-ID: On Sat, 15 Mar 2003, Kristian Rink wrote: > ...for what I see now, I've ran into some trouble using the rfc822 > module while trying to dissect e-mail messages and to store the > attachments they're carrying to be able to import them into a > document management system. Basically, here's what I tried: > > > >>> import rfc822 > >>> mailmessage=rfc822.Message("2") > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/rfc822.py", line 106, in __init__ > self.readheaders() > File "/usr/lib/python2.2/rfc822.py", line 153, in readheaders > line = self.fp.readline() > AttributeError: 'str' object has no attribute 'readline' > > Btw Message "2" is a mail file inside a MH mail spool directory. Hi Kristian, Wait. There is definitely something missing in the program... The main problem is that Python has no way of guessing where your MH mail spool directory is located! Some part of your code will need to point that location to Python by directory name. Instead of directly using rfc822, you probably want to use the 'mailbox' module: http://www.python.org/doc/lib/module-mailbox.html The mailbox.MHMailbox class knows how to pull individual rfc822 messages out of MH spools --- it should have a next() method that will let you pull out individual Message objects. If you'd like, I can post up a somewhat extended example of 'mailbox' use tomorrow. I've been working on a Jython program to run the Jakarta Lucene text indicer on the Tutor mailing list. So your question is nicely timed... *grin* The code is still very very rough, so I need another afternoon to polish it up and comment it nicely, but if it looks ok, I'd be happy to share it on Tutor for feedback. From afterimage@gmx.net Sun Mar 16 03:57:02 2003 From: afterimage@gmx.net (Kristian Rink) Date: Sun Mar 16 03:57:02 2003 Subject: [Tutor] rfc822.Message [reading emails from mailboxes] References: Message-ID: <22629.1047804944@www35.gmx.net> Hi Danny, and thanks lots for the reply... [snip] > > >>> mailmessage=rfc822.Message("2") > > Traceback (most recent call last): [snip] > > > > Btw Message "2" is a mail file inside a MH mail spool directory. > The main problem is that Python has no way of guessing where your MH mail > spool directory is located! Some part of your code will need to point > that location to Python by directory name. Hmmm, I already thought of something like this, as well. Then again, the traceback I got used to appear while interactively running python inside the MH folder, inside the same folder where the "2" file is / was located so I thought python would try to open the file in the current working directory. Seems it ain't working this way... > Instead of directly using rfc822, you probably want to use the 'mailbox' > module: > > http://www.python.org/doc/lib/module-mailbox.html Okay, I'll take a look at it, thanks. :) Then again, in the end the progam is thought to be used to run over messages inside a directory structure created by the cyrus IMAP daemon so I wonder if those will be accepted as "mailboxes"... > If you'd like, I can post up a somewhat extended example of 'mailbox' use > tomorrow. I've been working on a Jython program to run the Jakarta Lucene > text indicer on the Tutor mailing list. So your question is nicely > timed... *grin* > > The code is still very very rough, so I need another afternoon to polish > it up and comment it nicely, but if it looks ok, I'd be happy to share it > on Tutor for feedback. Would be really appreciated, if you don't mind :) Even an uncommented listing would do. Thanks again, have a nice sunday... Cheers from Dresden, Kris -- +++ GMX - Mail, Messaging & more http://www.gmx.net +++ Bitte lächeln! Fotogalerie online mit GMX ohne eigene Homepage! From erikprice@mac.com Sun Mar 16 09:07:02 2003 From: erikprice@mac.com (Erik Price) Date: Sun Mar 16 09:07:02 2003 Subject: [Tutor] rfc822.Message [reading emails from mailboxes] In-Reply-To: Message-ID: <965D09AC-57BA-11D7-A5FC-00039351FE6A@mac.com> On Sunday, March 16, 2003, at 03:09 AM, Danny Yoo wrote: > If you'd like, I can post up a somewhat extended example of 'mailbox' > use > tomorrow. I've been working on a Jython program to run the Jakarta > Lucene > text indicer on the Tutor mailing list. So your question is nicely > timed... *grin* > > The code is still very very rough, so I need another afternoon to > polish > it up and comment it nicely, but if it looks ok, I'd be happy to share > it > on Tutor for feedback. I would like to see it. I like Java and use it at work, so I've been meaning to learn more about Jython. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Sun Mar 16 10:01:32 2003 From: erikprice@mac.com (Erik Price) Date: Sun Mar 16 10:01:32 2003 Subject: [Tutor] setting EOF symbol In-Reply-To: Message-ID: <395B9D10-57C2-11D7-A5FC-00039351FE6A@mac.com> On Saturday, March 15, 2003, at 11:10 PM, Tim Peters wrote: > Most of your questions are answered in the generator PEP: > > http://www.python.org/peps/pep-0255.html Thanks, that is exactly the kind of document I was looking for. > Generators in Python are most like those in the Icon language: > > http://www.cs.arizona.edu/icon/ And thanks for that too (an example of another language that uses generators). Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From tim@johnsons-web.com Sun Mar 16 10:15:01 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Sun Mar 16 10:15:01 2003 Subject: [Tutor] Problems running idle Message-ID: <20030316152232.GC4589@johnsons-web.com> I have installed python 2.2.2 on Linux Redhat 7.2. I am getting an ImportError when attempting to start idle Traceback (innermost last): File "/usr/local/lib/python2.2/site-packages/idle/idle", line 5, in ? from idlelib import IdleConf ImportError: No module named idlelib Any help would be really appreciated :-) P.S. No search results on "idlelib" were returned from search engine at python site. On the other handle, idle1.5 seems to load fine. could idle 1.5 be configured to load the python 2.2 interpreter? Thanks -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From Don Arnold" <5.1.0.14.0.20030315234454.01aa08d8@tcapp.com> Message-ID: <0bc801c2ebf2$eabb4670$7fe1b241@defaultcomp> ----- Original Message ----- From: "Tony Cappellini" To: "Don Arnold" Sent: Sunday, March 16, 2003 1:46 AM Subject: Re: [Tutor] Why does print add spaces ? > > > > > > > > > > In this example > > > > > > > > > mystr="abcdefghi" > > > > > > for x in range(1,len(mystr)): > > > print "%s," % mystr[x], > > > > > > > > > a, b, c, d, e, f, g, h, i, > > > > > > why does print add an implied space ?? > > > > >>I can't really answer as to the 'why', since it seems like a language > > design > > >>issue. Like it or not, that's how the print command behaves. > > I should have asked "How are we supposed to know when print will add a > space or not" ? > I've used it many times, when it does not add the extra space. > I'm pretty sure that without messing around with stdout's softspace attribute, print always puts a space between comma-separated arguments. But then again, I'm pretty much a Python newbie, myself. Can you give an example where the space isn't inserted? Thanks, Don From dyoo@hkn.eecs.berkeley.edu Sun Mar 16 23:56:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Mar 16 23:56:01 2003 Subject: [Tutor] rfc822.Message [making Python-tutor more searchable] In-Reply-To: <965D09AC-57BA-11D7-A5FC-00039351FE6A@mac.com> Message-ID: On Sun, 16 Mar 2003, Erik Price wrote: > I would like to see it. I like Java and use it at work, so I've been > meaning to learn more about Jython. Hi Erik, Argh. I wasted all my time today watching TV. *grin* But since I did promise I'd put something up, I'd better not renege on that. I've written two Jython scripts: one reads in a mailbox and, using the Jakarta Lucene engine, creates a directory of message indices. The second script tests to see if the indexing actually worked out ok. Since the files are a bit large, I'll just post temporary urls to them: http://hkn.eecs.berkeley.edu/~dyoo/jython/load_indices.jy http://hkn.eecs.berkeley.edu/~dyoo/jython/test_searching.jy As a sample source of messages, I used the Python-Tutor archive: http://mail.python.org/pipermail/tutor.mbox/tutor.mbox To run the engine, you'll need to grab the Jakarta Lucene library; it's located here: http://jakarta.apache.org/lucene/docs/index.html I have to admit that my scripts are really really messy and not quite... umm... commented yet. But I hope to fix that. *grin* Please feel free to read and give feedback on anything that looks silly about the program. If the indexing itself looks robust, I'd love to set this up as an improved search engine for Python-Tutor; does anyone have a machine they'd be willing to put something like this on? To whet people's appetite, here's a sample of the kinds of queries we can do: ### query? from:erik AND jython 2 hits found. 14153 Erik Price tutor@python.org [Tutor] jython and dynamic typing 20707 Erik Price alan.gauld@bt.com Re: [Tutor] Sun says: Don't use Java, use Python! query? danny AND lucene 1 hits found. 21230 Danny Yoo Bob Gailer Re: [Tutor] Enter: Matt query? "hello world" 344 hits found. ... [cut short, since output was a bit long... *grin*] query? subject:"help" 1134 hits found. ... [cut short for obvious reasons. *grin*] query? body:"hope this helps" 990 hits found. ### Let's make that one more. *grin* Hope this helps! From erikprice@mac.com Mon Mar 17 08:22:02 2003 From: erikprice@mac.com (Erik Price) Date: Mon Mar 17 08:22:02 2003 Subject: [Tutor] rfc822.Message [making Python-tutor more searchable] In-Reply-To: Message-ID: On Sunday, March 16, 2003, at 11:54 PM, Danny Yoo wrote: > Hi Erik, > > Argh. I wasted all my time today watching TV. *grin* Oh no big deal, I spent a lot of the day playing video games! > To whet people's appetite, here's a sample of the kinds of queries we > can > do: > query? subject:"help" > 1134 hits found. > ... [cut short for obvious reasons. *grin*] LOL. Thanks for the scripts, I have cURLed them and the Lucene library. Now I just need to set up Jython! I'll give it a whirl tonight after work. Erik PS: Just curious about line 28, why you chose UnixMailbox over PortableUnixMailbox. -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From reggie@merfinllc.com Mon Mar 17 10:07:02 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Mon Mar 17 10:07:02 2003 Subject: [Tutor] rfc822.Message In-Reply-To: <20030315232421.255b9b6a.afterimage@gmx.net> References: <20030315232421.255b9b6a.afterimage@gmx.net> Message-ID: <1047913587.25959.6.camel@pika.merfinllc.com> Kris, I believe the problem you're having is that the rfc822.Message constructor expects an instance of a file object and not a filename. If you try something like the following I think you'll have better luck. >>> mailmessage=rfc822.Message(open("2")) On Sat, 2003-03-15 at 14:24, Kristian Rink wrote: > Hi all,... > > > ...for what I see now, I've ran into some trouble using the rfc822 > module while trying to dissect e-mail messages and to store the > attachments they're carrying to be able to import them into a > document management system. Basically, here's what I tried: > > > >>> import rfc822 > >>> mailmessage=rfc822.Message("2") > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/rfc822.py", line 106, in __init__ > self.readheaders() > File "/usr/lib/python2.2/rfc822.py", line 153, in readheaders > line = self.fp.readline() > AttributeError: 'str' object has no attribute 'readline' > > > Btw Message "2" is a mail file inside a MH mail spool directory. > Basically, it's kinda late now around here and perhaps I'm too tired > to see the point, but seems I can't get along with this, here. Can > someone give me a hint what's wrong here? > > TIA, have a nice evening wherever you are... > Cheers, > Kris -- Reggie From reggie@merfinllc.com Mon Mar 17 11:12:04 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Mon Mar 17 11:12:04 2003 Subject: [Tutor] rfc822.Message In-Reply-To: <20030317075224.16304.h006.c000.wm@mail.stanfield.net.criticalpath.net> References: <20030317075224.16304.h006.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <1047917428.25966.24.camel@pika.merfinllc.com> Vicki, Sorry I wasn't clearer. In my example, "2" is just the name of a file in the current directory. Maybe I misremember, but I thought I saw another post from Kris that said he was running this code in the directory that contained the mail file. In any case, there is an mhlib module in python, which I've never had occasion to use, but which seems to provide the functionality to find and read MH mailboxes. The doc string of the module should provide you with enough information to get started. Hope this clarifies things. On Mon, 2003-03-17 at 07:52, vicki@stanfield.net wrote: > Reggie Dugard wrote: > > > > >>> import rfc822 > > > >>> mailmessage=rfc822.Message("2") > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > File "/usr/lib/python2.2/rfc822.py", line 106, in > > __init__ > > > self.readheaders() > > > File "/usr/lib/python2.2/rfc822.py", line 153, in > > readheaders > > > line = self.fp.readline() > > > AttributeError: 'str' object has no attribute > > 'readline' > > > > > > > > > Btw Message "2" is a mail file inside a MH mail > spool > > directory. > > Reggie > > Hey Reggie, > What tells the program that Message "2" is a mail file > inside a MH mail spool directory? Is that a variable > somewhere within the program? > > --vicki -- Reggie From Doug.Shawhan@gecits.ge.com Mon Mar 17 11:28:03 2003 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Mon Mar 17 11:28:03 2003 Subject: [Tutor] Finding items in list of lists. Message-ID: <47B6167F8E69D31194BA0008C7918D42076FEAD3@msxcvg02itscge.gecits.ge.com> I am confusing myself. I have a list that contains the following: l = [["joe", "moe", "schmoe"], ["fee", "foo", "bar"]] I wish to check for the existence of both "moe" and "foo" in l. Is there a clear way to do so using list comprehension, or must I result to something less friendly? d From ramrom@earthling.net Mon Mar 17 11:50:03 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Mar 17 11:50:03 2003 Subject: [Tutor] Finding items in list of lists. In-Reply-To: <47B6167F8E69D31194BA0008C7918D42076FEAD3@msxcvg02itscge.ge cits.ge.com> Message-ID: <5.2.0.9.0.20030317094317.03503330@66.28.54.253> --=======2BF832A7======= Content-Type: text/plain; x-avg-checked=avg-ok-5F9349D3; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:27 AM 3/17/2003 -0500, Doug.Shawhan@gecits.ge.com wrote: >I am confusing myself. > >I have a list that contains the following: > >l = [["joe", "moe", "schmoe"], ["fee", "foo", "bar"]] > >I wish to check for the existence of both "moe" and "foo" in l. Is there a >clear way to do so using list comprehension, or must I result to something >less friendly? A nested list needs nested comprehension: [[y for y in x if y in ("moe", "foo")] for x in l] will return [['moe'], ['foo']]. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======2BF832A7======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-5F9349D3 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======2BF832A7=======-- From William.Yee@hvbasia.com Mon Mar 17 12:55:03 2003 From: William.Yee@hvbasia.com (William Yee) Date: Mon Mar 17 12:55:03 2003 Subject: [Tutor] William Yee is out of office Message-ID: I will be out of the office starting 17/03/2003 and will not return until 19/03/2003. You can contact RIT at +65 64133834 for general enquiries. For urgent matters, kindly forward your email to Saleh.Saad@hvbasia.com. Otherwise, I will respond to your message when I return. Thank you and have a nice day. From Doug.Shawhan@gecits.ge.com Mon Mar 17 13:23:02 2003 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Mon Mar 17 13:23:02 2003 Subject: [Tutor] Finding items in list of lists. Message-ID: <47B6167F8E69D31194BA0008C7918D42076FEAD5@msxcvg02itscge.gecits.ge.com> >> l = [["joe", "moe", "schmoe"], ["fee", "foo", "bar"]] >> I wish to check for the existence of both "moe" and "foo" in l. Is there a >> clear way to do so using list comprehension, or must I result to something >> less friendly? > A nested list needs nested comprehension: > [[y for y in x if y in ("moe", "foo")] for x in l] > will return [['moe'], ['foo']]. This is really cool and helps me to understand list comprehension somewhat better, but it does not actually do what I need (sorry, I am dense!). Perhaps list comprehension muddied the trail, since I _expected_ it to be able to solve the problem. What I need to do is check for the existence of two items in the list of lists so I can filter them out. Say I have a set of critera that can be matched: (fat, skinny), (hairy, bald), (ugly, svelte), (smelly, sweet). These criteria are spread through several lists that are contained in other lists: I need to match the criteria like so: ------------------------- in: [['joe', 'fat', 'light', 'dark'], ['joe','hairy','nekkid','ugly'], ['joe', 'skinny', 'ugly', 'sweet'], ['joe','bald','silly','wacky]] out: [['joe', 'fat', 'light', 'dark'],['joe', 'skinny', 'ugly', 'sweet']] [['joe','hairy','nekkid','ugly'], ['joe','bald','silly','wacky]] ------------------------- .. and would like to avoid a mass of if loops. Or do I just need to suck it up? :-) From dyoo@hkn.eecs.berkeley.edu Mon Mar 17 13:50:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 17 13:50:03 2003 Subject: [Tutor] Mailbox.UnixMailbox vs Mailbox.PortableUnixMailbox In-Reply-To: Message-ID: > PS: Just curious about line 28, why you chose UnixMailbox over > PortableUnixMailbox. Hi Erik, There's a reason: PortableUnixMailbox was much too permissive in what it considered to be "boundaries" between emails in a mail file, and broke when I tried feeding it the total wisdom of the Tutor mailing archive. A mailbox file consists of all the emails, concatenated to each other end by end. How does the system distinguish where one message begins and another ends? One way is to look for anything that begins with, From: ... and treat that as the start of a new message. This is probably the strategy that UnixMailbox takes (although I think it does a few more checks to see that it's really seeing the start of an email header). PortableUnixMailbox is a little looser: it looks for anything like From ... At first, I tried PortableUnixMailbox because it sounded, well, more portable. *grin* But I ran into severe problems because people like to use the word "From" in their own emails, so that, in a pathological case where a line began with the sentence "From...", PortableMailbox wasn't able to reliably distinguish between emails! A concrete example of this was on line 8928 of the tutor archive file (http://mail.python.org/pipermail/tutor.mbox/tutor.mbox): """ 8927: Great, isn't it? 8928: From here on, you can continue endlessly and keep it fun 8929: to the audience. """ PortableUnixMailbox broke when it saw that "From here on" line, and thought that it was the start of a new mail message. The documentation on the 'mailbox' module does mention this, http://www.python.org/doc/lib/module-mailbox.html so at least I was warned. Hmmm... now that you mention it, I should definitely comment why I'm using UnixMailbox rather than PortableUnixMailbox in the code. *grin* Thanks for the question! From Janssen@rz.uni-frankfurt.de Mon Mar 17 15:11:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Mon Mar 17 15:11:02 2003 Subject: [Tutor] Mailbox.UnixMailbox vs Mailbox.PortableUnixMailbox In-Reply-To: Message-ID: On Mon, 17 Mar 2003, Danny Yoo wrote: > There's a reason: PortableUnixMailbox was much too permissive in what it > considered to be "boundaries" between emails in a mail file, and broke > when I tried feeding it the total wisdom of the Tutor mailing archive. > > > A mailbox file consists of all the emails, concatenated to each other end > by end. How does the system distinguish where one message begins and > another ends? One way is to look for anything that begins with, > > From: ... > > and treat that as the start of a new message. This is probably the > strategy that UnixMailbox takes (although I think it does a few more > checks to see that it's really seeing the start of an email header). > PortableUnixMailbox is a little looser: it looks for anything like > > From ... In a unixmailbox every message starts with the "unixfrom". Example: >From janssen@rz.uni-frankfurt.de Mon Mar 17 20:41:35 2003 Escaping any "From[space]" in the mailbody (at start of line) is left to the MTA's. "From me" should be made into "From=20me". The tutor archiv isn't fed by such a clever programm, it seems ;-) This way you can use a very lazy check for unixfromness. PortableUnixMailbox checks indeed only for a starting From[space] (never "From:" which would be the From-Header). UnixMailbox checks further if this line continues with an mail address and a date. In case the mailclient add some more infos (pine for example adds timezone date) this test fails and no message is found. UnixMailbox doesn't check for dubble newlines (or start of file) befor unixfrom wich would be the proper behaviour. UnixMailbox provides a nice mechanism to substitude the default regular expression for testing unixfromness with an own one. Example class UnixMailboxWithAdditionalData(mailbox.UnixMailbox): _regexp = re.compile(r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+" \ r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*") instead of r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+" \ r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*$" Note the missing "$" at the end of the regexp to let the mailclient add additional informations or something like this. All this is mentioned in the mailbox.py file (as comment not docstring). Another thing that follows is that one can trick UnixMailbox with putting a line like "From janssen@rz.uni-frankfurt.de Mon Mar 17 20:41:35 2003" into ones mail (Ouh, I really should put quotes around it ;-) Michael From ramrom@earthling.net Mon Mar 17 15:21:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Mar 17 15:21:02 2003 Subject: [Tutor] Finding items in list of lists. In-Reply-To: <47B6167F8E69D31194BA0008C7918D42076FEAD5@msxcvg02itscge.ge cits.ge.com> Message-ID: <5.2.0.9.0.20030317131710.030ab988@66.28.54.253> --=======43E4748F======= Content-Type: text/plain; x-avg-checked=avg-ok-30CD20FC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 01:21 PM 3/17/2003 -0500, Doug.Shawhan@gecits.ge.com wrote: >[snip] >Say I have a set of critera that can be matched: (fat, skinny), (hairy, >bald), (ugly, svelte), (smelly, sweet). > >These criteria are spread through several lists that are contained in other >lists: > >I need to match the criteria like so: > >------------------------- >in: [['joe', 'fat', 'light', 'dark'], ['joe','hairy','nekkid','ugly'], >['joe', 'skinny', 'ugly', 'sweet'], ['joe','bald','silly','wacky]] > >out: [['joe', 'fat', 'light', 'dark'],['joe', 'skinny', 'ugly', 'sweet']] > [['joe','hairy','nekkid','ugly'], ['joe','bald','silly','wacky]] >------------------------- Now I'm really confused. It looks like you want the sub-lists rearranged in some way, but it's not clear from the example what you want. I see the two lists that "match" (fat, skinny) are in 1st and 2nd place, and the two that match (hairy, bald) are in 3rd and 4th place. What do you wnat if there are more or less matches? Can you give us an algorithm instead of examples? Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 --=======43E4748F======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-30CD20FC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======43E4748F=======-- From jeff@ccvcorp.com Mon Mar 17 15:33:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Mar 17 15:33:01 2003 Subject: [Tutor] Why does print add spaces ? References: <5.1.0.14.0.20030315133327.05031cf0@smtp.sbcglobal.net> <5.1.0.14.0.20030315234454.01aa08d8@tcapp.com> <0bc801c2ebf2$eabb4670$7fe1b241@defaultcomp> Message-ID: <3E76310A.5000206@ccvcorp.com> Don Arnold wrote: >----- Original Message ----- >From: "Tony Cappellini" > > >>I should have asked "How are we supposed to know when print will add a >>space or not" ? >>I've used it many times, when it does not add the extra space. >> >> > >I'm pretty sure that without messing around with stdout's softspace >attribute, print always puts a space between comma-separated arguments. > That's my understanding as well. Using a single argument to print implies that a newline should be added to the end, using a comma (after a single argument or to separate multiple arguments) implies a space. However, it's complicated a bit by the use of softspace -- basically, this is a mechanism to prevent print from adding a space to something that already ends with a space. If you type 'print "spaced ",' you won't end up with two trailing spaces, you'll only have one -- exactly the same as if you typed 'print "unspaced",'. The print keyword does a moderate amount of fiddling to try to make things look pretty. If you want direct control over your output, you can use (as was suggested elsewhere) sys.stdout.write(). By the way, the code as originally posted: mystr="abcdefghi" for x in range(1,len(mystr)): print "%s," % mystr[x], a, b, c, d, e, f, g, h, i, Is not accurate, and will not have that result. Here's a cut-and-paste from actually running it: >>> mystr = "abcdefghi" >>> for i in range(1,len(mystr)): ... print "%s," % mystr[i], ... b, c, d, e, f, g, h, i, >>> Where'd "a" go? The problem is that almost everything in Python uses zero-based indexing. The first character of mystr isn't mystr[1], it's mystr[0]. This is *why* range() defaults to starting at 0. And while you may think that 1-based indexing is more "intuitive", it results in a lot more need to adjust things by one, which in turn results in a lot more off-by-one errors. Besides, there's an easier way to get each character of a string (or each element of a list or tuple): >>> mystr = "abcdefghi" >>> for char in mystr: ... print "%s," % char, ... a, b, c, d, e, f, g, h, i, >>> Jeff Shannon Technician/Programmer Credit International From Doug.Shawhan@gecits.ge.com Mon Mar 17 15:34:03 2003 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Mon Mar 17 15:34:03 2003 Subject: FW: [Tutor] Finding items in list of lists. Message-ID: <47B6167F8E69D31194BA0008C7918D42076FEADB@msxcvg02itscge.gecits.ge.com> Yep. Turns out (surprise) that I wanted python to do my thinking for me. The following seems to do what I want- So sorry to be so confusing. On the bright side, you folks _really_ helped me with list comprehensions! :-) (I am posting this from outlook, so I hope the linewrap doesn't look to bad...) ------------------------snip------------------------- import string import xreadlines # Grab data from disk f=open("\\tmp\\sample.txt","r") rawData=[] for line in xreadlines.xreadlines(f): rawData.append(string.split(line,'\t')) # Get rid of the top "row", since it contains no useful data by default del rawData[0] # We want to sort by the shared value which is in the tenth "column" db = {} gather = [] for lines in rawData: parentItem = lines[9] for line in rawData: if line[9] == parentItem: gather.append(line) db[parentItem]=gather gather = [] # Now we take the data that have been sorted by parentItem and further sort them by # what type of item they are. For example, if the line has both a printer and a duplex unit # therein, the printer and duplex are sorted out and given an entry of their own. This # enables the items to be uploaded into dam with no issues. cookedData = {} # <-- new dictionary for the second sort. for each in db.keys(): sortdb = {} # <-- new dictionary for the item sort for item in db[each]: sortdb[item[12]] = item # filter out the Printer/Duplex combinations if sortdb.has_key('DPLX') and sortdb.has_key('PRT'): print '%s printer // duplexer match'%each filtered=[sortdb['PRT'], sortdb['DPLX']] signify = sortdb['PRT'] signify = signify[8] cookedData[signify]=filtered del sortdb['PRT'] del sortdb['DPLX'] # and the Laptop/Keyboard combinations elif sortdb.has_key('KBD') and sortdb.has_key('LAP'): print '%s laptop // keyboard match'%each filtered=[sortdb['LAP'], sortdb['KBD']] signify = sortdb['LAP'] signify = signify[8] cookedData[signify]=filtered del sortdb['LAP'] del sortdb['KBD'] # now sort out the leftover items (usually Cpu/Monitor combinations) else: old_potato = [] # <--A type of leftover (I crack me up.) for leftover in sortdb.keys(): old_potato.append(sortdb[leftover]) # and finally add the leftovers to the cookedData. cookedData[item[8]]=old_potato # Now we place the various data into a single long string suitable for DAM to ingest for item in cookedData.keys(): print item, cookedData[item] --------------------snip----------------------- Any suggestions for cleanup or concision are welcomed! d From mike@daboyz.org Mon Mar 17 17:07:02 2003 From: mike@daboyz.org (Michael Barrett) Date: Mon Mar 17 17:07:02 2003 Subject: [Tutor] httplib & keep-alive Message-ID: <20030317220418.GE65161@daboyz.org> Hi, can someone please post how to successfully re-use a HTTP/1.1 connection viah httplib? The code below doesn't seem to work- the exception is below the code. ############## #!/usr/local/bin/python import httplib, sys httpcon = httplib.HTTPConnection('') httpcon.debuglevel = 1 httpcon.putrequest('GET', 'http:///ocd/') httpcon.putheader('Connection','Keep-Alive') httpcon.endheaders() reply = httpcon.getresponse() redirLoc = reply.getheader('Location') if redirLoc: print "Found Location header, redirecting to " + redirLoc httpcon.putrequest('GET', redirLoc) httpcon.putheader('Connection', 'close') httpcon.endheaders() newreply = httpcon.getresponse() ############## ######### Exception connect: (, 80) send: 'GET http:///ocd/ HTTP/1.1\r\nHost: \r\nAccept-Encoding: identity\r\nConnection: Keep-Alive\r\n\r\n' reply: 'HTTP/1.1 302 Found\r\n' header: Date: Mon, 17 Mar 2003 22:03:00 GMT header: Server: Apache/1.3.27 (Unix) header: Location: http:///ocd/index.py header: Keep-Alive: timeout=15, max=100 header: Connection: Keep-Alive header: Transfer-Encoding: chunked header: Content-Type: text/html; charset=iso-8859-1 Found Location header, redirecting to http:///ocd/index.py send: 'GET http:///ocd/index.py HTTP/1.1\r\nHost: \r\nAccept-Encoding: identity\r\nConnection: close\r\n\r\n' Traceback (most recent call last): File "./redirect.py", line 21, in ? newreply = httpcon.getresponse() File "/usr/local/lib/python2.2/httplib.py", line 752, in getresponse raise ResponseNotReady() httplib.ResponseNotReady -- ________________________________________________________________________ Mike Barrett | "I used to read, now I go to raves." mike@daboyz.org | -- Random MUNI Rider, speaking www.daboyz.org | to my friend Allison. ------------------------+----------------------------------------------- From reavey@nep.net Mon Mar 17 18:26:33 2003 From: reavey@nep.net (reavey) Date: Mon Mar 17 18:26:33 2003 Subject: [Tutor] full screen turtle.py Message-ID: <3E7658A8.6020906@nep.net> Re: [Tutor] full screen turtle.py add this thread to my home page by Gregor Lingl other posts by this author Feb 11 2003 10:38PM messages near this date << Re: [Tutor] Sun says: Don't use Java, use Python! | RE: [Tutor] List exercise >> reavey schrieb: > is there a way to display a full screen when turtle.py initializes? As a default-canvas is created the first time when you call an arbitrary turtle-graphics function, there is no way to pass information about its size to the canvas. But: (1) There is the possibility to create turtle-objects on your own Tkinter-Canvas which may have any size you want. more precisely, you have to create an object of the RawPen class, which goes like this: >>> from Tkinter import Canvas >>> cv = Canvas(width=800, height=600) >>> cv.pack() >>> t = RawPen(cv) >>> t.forward(100) you may reset the size of cv with something like: >>> cv["width"]=400 >>> cv["height"] = 500 and recenter t by calling t.reset (which works essentially the same way you used when resizing the default-canvas manually) (2) Another way to accomplish what you want ist do decide to rewrite the reset-function of the turtle-module in order to pass information about the size of the canvas. (If these arguments are not given, it works the old way): First you have to change the reset-method of RawPen (approx line 40): def reset(self, width = None, height = None): canvas = self._canvas if width: canvas["width"] = width if height: canvas["height"] = height self._canvas.update() # .... and so on. as before Then you have to modify the reset - function (approx line 350): def reset(width=None, height=None): _getpen().reset(width,height) I've attached a modified turtle.py With these changes the following will be possible: >>> from turtle import * >>> reset(800,600) >>> forward(50) >>> reset(200,200) Regards, Gregor P.S. I didn't extensively test these changes, so maybe there will be some unwanted side-effects, especially when using RawPen. Maybe I'll have a look at this sometimes later ... > > The first canvas takes up a small portion of the display (around 10%). > When I hit the expand button on the canvas it doesn't recenter. > The drawing still uses the inititial canvas coordinates. > > btw: this is not a problem using the interactive interpreter as a > turtle.reset() > issued after you expand works as expected. > > thanks > re-v I have tried part two being the better solution. I get the following error traceback(most recent call last) file "",line 1 in? ############## the reader of this message will please from this point on replace the word file with File "usr/lib/python2.2/lib-tk/turtle.py################# file line 314, in reset def reset(width=None,height=None)::_getpen().reset(height,width) file line 308 in_getpen_pen=pen=Pen() file line 292, in__init__RawPen.__init__(self._canvas) file line 16, in__init__self.reset() file line 34 , in reset self._origin = float(width)/2.0,float(height)/2.0 type error: float() needs a strong argument from turtle import * ####works reset() ###produces the above failure reset(200,200) ####error as above reset("200","200") ###error as above Thanks re-v From zouli79@hotmail.com Mon Mar 17 18:27:04 2003 From: zouli79@hotmail.com (Ian shaw) Date: Mon Mar 17 18:27:04 2003 Subject: [Tutor] (no subject) Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0007_01C2EB12.DD46D260 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I would like a demonstration on computer programming. =20 Thank you. ------=_NextPart_000_0007_01C2EB12.DD46D260 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

I would like a demonstration on = computer=20 programming. 
Thank you.
------=_NextPart_000_0007_01C2EB12.DD46D260-- From bgailer@alum.rpi.edu Mon Mar 17 18:27:16 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Mon Mar 17 18:27:16 2003 Subject: FW: [Tutor] Finding items in list of lists. In-Reply-To: <47B6167F8E69D31194BA0008C7918D42076FEADB@msxcvg02itscge.ge cits.ge.com> Message-ID: <5.2.0.9.0.20030317143353.030636d8@66.28.54.253> --=======D2071AE======= Content-Type: text/plain; x-avg-checked=avg-ok-30CD20FC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:32 PM 3/17/2003 -0500, Doug.Shawhan@gecits.ge.com wrote: >------------------------snip------------------------- > >import string >import xreadlines ># Grab data from disk >f=open("\\tmp\\sample.txt","r") >rawData=[] >for line in xreadlines.xreadlines(f): > rawData.append(string.split(line,'\t')) ># Get rid of the top "row", since it contains no useful data by default >del rawData[0] ># We want to sort by the shared value which is in the tenth "column" First, it looks like you are collating rather than sorting. Sorting implies putting in order and all I see this code doing is creating dictionary entries. >db = {} >gather = [] >for lines in rawData: > parentItem = lines[9] > for line in rawData: > if line[9] == parentItem: > gather.append(line) > db[parentItem]=gather > gather = [] Immediate observation and refinement: once a parentItem is found we don't need to find and process it again, so after parentItem = lines[9] add if parentItem not in db: then continue with: for line in rawData: etc. Also you could use list comprehension: db[parentItem] = [line for line in rawData if line[9] == parentItem] ># Now we take the data that have been sorted by parentItem and >further sort them by ># what type of item they are. For example, if the line has both a >printer and a duplex unit ># therein, the printer and duplex are sorted out and given an entry >of their own. This ># enables the items to be uploaded into dam with no issues. > >cookedData = {} # <-- new dictionary for the second sort. >for each in db.keys(): > sortdb = {} # <-- new dictionary for the item sort > for item in db[each]: > sortdb[item[12]] = item > # filter out the Printer/Duplex combinations > if sortdb.has_key('DPLX') and sortdb.has_key('PRT'): > print '%s printer // duplexer match'%each > filtered=[sortdb['PRT'], sortdb['DPLX']] > signify = sortdb['PRT'] > signify = signify[8] > cookedData[signify]=filtered > del sortdb['PRT'] > del sortdb['DPLX'] > # and the Laptop/Keyboard combinations > elif sortdb.has_key('KBD') and sortdb.has_key('LAP'): > print '%s laptop // keyboard match'%each > filtered=[sortdb['LAP'], sortdb['KBD']] > signify = sortdb['LAP'] > signify = signify[8] > cookedData[signify]=filtered > del sortdb['LAP'] > del sortdb['KBD'] > # now sort out the leftover items (usually Cpu/Monitor >combinations) > else: > old_potato = [] # <--A type of leftover (I crack me up.) > for leftover in sortdb.keys(): > old_potato.append(sortdb[leftover]) > # and finally add the leftovers to the cookedData. > cookedData[item[8]]=old_potato > ># Now we place the various data into a single long string suitable for DAM >to ingest >for item in cookedData.keys(): > print item, cookedData[item] > >--------------------snip----------------------- > >Any suggestions for cleanup or concision are welcomed! An idea (untested). Assumes there will be a pair of records for each shared value. If there could be less or more then some modifications are needed. sortableData = map((lambda x:list((x[9],x[12]))+x), rawData) # copy the major and minor sort items to the front of each list. sortableData.sort() # do the desired major/minor sort; all items of one shared value will now be together and the types within each shared value will be in order. types = {'DPLX': ('PRT', '%s printer // duplexer match', 0), 'KBD': ('LAB', '%s laptop // keyboard match', 0), etc.} # key is the alphabetically earlier of the types # 1st element of each tuple is the alphabetically later of the types # 2nd element of each tuple is the message to print # 3rd element of each tuple is the significantOffset. If 'DPLX' were the signifyng item insted of 'PRT' then this offset would be -1 sharevalue = None index = 0 old_potato = [] while index < len(sortableData): # instead of a for loop, so we can access more than one item item = sortableData[index] if item[0] != sharevalue: # start processing first or next shared value sharevalue = item[0] if old_potato: # left ove from previous shared value set coookedData[sortableData[index-1][10] = old_potato if item[1] in types: expect, msg, significantOffset = types[item[1]] old_potato = [] else: # must be a leftover old_potato = [item] else: # continue with next item of current shared value if old_potato : # add next leftover old_potato.append(item) else: if item[1] == expect: # we have a pair print msg%item[0] filtered=sortableData[index-1:index+1] # keep in mind that the shared value and type appear at the head of the list signify = sortableData[index + significantOffset] signify = signify[10] cookedData[signify]=filtered else: # deal with unmatched pair index += 1 if old_potato: # left over from last shared value set coookedData[sortableData[index-1][10] = old_potato Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======D2071AE======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-30CD20FC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======D2071AE=======-- From reggie@merfinllc.com Mon Mar 17 19:08:01 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Mon Mar 17 19:08:01 2003 Subject: FW: [Tutor] Finding items in list of lists. In-Reply-To: <47B6167F8E69D31194BA0008C7918D42076FEADB@msxcvg02itscge.gecits.ge.com> References: <47B6167F8E69D31194BA0008C7918D42076FEADB@msxcvg02itscge.gecits.ge.com> Message-ID: <1047946052.25959.67.camel@pika.merfinllc.com> --=-DS31AKYzfctNT4VhVYoF Content-Type: text/plain Content-Transfer-Encoding: quoted-printable Doug, I took your code and modified it to make it a bit more "Pythonic" to illustrate a few points. I'm assuming you have a fairly recent version of Python since you mentioned list comprehensions earlier so I've used features that were introduced in Python 2.2. Also I haven't tested this code so take it with a grain of salt. First, I placed the entire thing inside a function definition and I call this function if the file is run from the command line. This allows me to check the syntax of the code without actually attempting to open the sample file and I can use the routine in another module later on by importing the function from this file. Next, I simplified the creation of db by creating it while I'm reading in the data and using the dictionary setdefault() method Then I changed sortdb to be created using a list comprehension and the dict constructor. I removed the calls to has_key() and used "in" to check containment. I'm not sure I understand how the leftovers should be handled, so that part may be meaningless. I also replaced your calls to the dict keys() method with the items() method (I could really have used the iteritems() method, but that's another story) so you no longer have to do an extra lookup with the key to get the value. There are some other minor changes as well, but hopefully they're obvious. Let me know if you have any questions on my changes. Hope this can be of some help. -------------------------------- snip --------------------------------- def main(file): # Grab data from disk first =3D True db =3D {}=20 for line in open(file): # Get rid of the top "row", since it contains no useful data by # default if first: first =3D False else: line =3D line.split('\t') db.setdefault(line[9], []).append(line)=20 # Now we take the data that have been classified by shared value and # further classify them by what type of item they are. For example,=20 # if the line has both a printer and a duplex unit therein, the # printer and duplex are sorted out and given an entry of their own. # This enables the items to be uploaded into dam with no issues. cookedData =3D {} # <-- new dictionary for the second classification. for each, items in db.items(): # new dictionary for the item sort sortdb =3D dict([ (item[12], item) for item in items ]) # filter out the Printer/Duplex combinations if 'DPLX' in sortdb and 'PRT' in sortdb: print '%s printer // duplexer match' % each filtered =3D (sortdb['PRT'], sortdb['DPLX']) signify =3D sortdb['PRT'][8] cookedData[signify] =3D filtered del sortdb['PRT'], sortdb['DPLX'] # and the Laptop/Keyboard combinations elif 'KBD' in sortdb and 'LAP' in sortdb: print '%s laptop // keyboard match' % each filtered =3D (sortdb['LAP'], sortdb['KBD']) signify =3D sortdb['LAP'][8] cookedData[signify] =3D filtered del sortdb['LAP'], sortdb['KBD'] # now sort out the leftover items (usually Cpu/Monitor=20 # combinations) and finally add the leftovers to the cookedData. for leftover in sortdb.values(): cookedData[leftover[8]] =3D leftover # Now we place the various data into a single long string suitable # for DAM to ingest for item, data in cookedData.items(): print item, data if __name__ =3D=3D '__main__': main("/tmp/sample.txt") On Mon, 2003-03-17 at 12:32, Doug.Shawhan@gecits.ge.com wrote: > Yep. Turns out (surprise) that I wanted python to do my thinking for me. = The > following seems to do what I want-=20 >=20 > So sorry to be so confusing. On the bright side, you folks _really_ helpe= d > me with list comprehensions! :-) >=20 > (I am posting this from outlook, so I hope the linewrap doesn't look to > bad...) --=20 Reggie --=-DS31AKYzfctNT4VhVYoF Content-Type: application/pgp-signature; name=signature.asc Content-Description: This is a digitally signed message part -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQA+dmNEkeFt9Tpkup0RApEIAJwNqY5sliwWr9fb7ch2/bjzfAtfpQCgqe1k bLTci4yFyJakt4mfTc8UasA= =QtDA -----END PGP SIGNATURE----- --=-DS31AKYzfctNT4VhVYoF-- From glingl@aon.at Tue Mar 18 02:17:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Mar 18 02:17:02 2003 Subject: [Tutor] Finding items in list of lists. Message-ID: <3E76C808.8020604@aon.at> Doug.Shawhan@gecits.ge.com schrieb: >I am confusing myself. > >I have a list that contains the following: > >l = [["joe", "moe", "schmoe"], ["fee", "foo", "bar"]] > >I wish to check for the existence of both "moe" and "foo" in l. Is there a >clear way to do so using list comprehension, or must I result to something >less friendly? > Hi Doug! You could mix it with something "less friendly" (???) and first flatten your list of lists l by using reduce: from operator import add >>> reduce(add,l) ['joe', 'moe', 'schmoe', 'fee', 'foo', 'bar'] With this a single comprehension would do it: >>> [y for y in reduce(add,l) if y in ("moe", "foo")] ['moe', 'foo'] >>> Regards, Gregor > >d > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From mike@daboyz.org Tue Mar 18 03:33:01 2003 From: mike@daboyz.org (Michael Barrett) Date: Tue Mar 18 03:33:01 2003 Subject: [Tutor] Why does print add spaces ? In-Reply-To: <5.1.0.14.0.20030315133327.05031cf0@smtp.sbcglobal.net> References: <5.1.0.14.0.20030315133327.05031cf0@smtp.sbcglobal.net> Message-ID: <20030318083022.GA71723@daboyz.org> Using list comprehension you could do the following: >>> x = 'abcdefghi' >>> print ','.join([i for i in x]) a,b,c,d,e,f,g,h,i As to why python prints the spaces? It's just the way print works in the language. Can't really answer why, but I'm sure the developers felt they had a reason. Sorry I couldn't be more help. On Sat, Mar 15, 2003 at 01:48:44PM -0800, Tony Cappellini wrote: > > > In this example > > > mystr="abcdefghi" > > for x in range(1,len(mystr)): > print "%s," % mystr[x], > > > a, b, c, d, e, f, g, h, i, > > why does print add an implied space ?? > How would i change this if I didn't want any spaces between each printed > character ? > > -- ________________________________________________________________________ Mike Barrett | "I used to read, now I go to raves." mike@daboyz.org | -- Random MUNI Rider, speaking www.daboyz.org | to my friend Allison. ------------------------+----------------------------------------------- From alan.gauld@bt.com Tue Mar 18 05:07:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Mar 18 05:07:02 2003 Subject: [Tutor] (no subject) Message-ID: > I would like a demonstration on computer programming. Everytime you use a computer program you have a demonstration of computer programming, including the email or web browser program you use to read this message! To see how to produce some very simple programs for yourself try visiting my online tutor. It covers programming for beginners and the concepts sections explains what exactly a program is, how they are created and then moves on to teach programming using Python, Basic and Tcl - 3 different programming languages. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From Doug.Shawhan@gecits.ge.com Tue Mar 18 09:47:02 2003 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Tue Mar 18 09:47:02 2003 Subject: FW: [Tutor] Finding items in list of lists. Message-ID: <47B6167F8E69D31194BA0008C7918D42076FEAE6@msxcvg02itscge.gecits.ge.com> Much food for thought. Thanks for the clarification vis. collating. -----Original Message----- From: Bob Gailer [mailto:bgailer@alum.rpi.edu] Sent: Monday, March 17, 2003 5:08 PM To: Shawhan, Doug (CAP, ITS, US); tutor@python.org Subject: Re: FW: [Tutor] Finding items in list of lists. At 03:32 PM 3/17/2003 -0500, Doug.Shawhan@gecits.ge.com wrote: >------------------------snip------------------------- > >import string >import xreadlines ># Grab data from disk >f=open("\\tmp\\sample.txt","r") >rawData=[] >for line in xreadlines.xreadlines(f): > rawData.append(string.split(line,'\t')) ># Get rid of the top "row", since it contains no useful data by default >del rawData[0] ># We want to sort by the shared value which is in the tenth "column" First, it looks like you are collating rather than sorting. Sorting implies putting in order and all I see this code doing is creating dictionary entries. >db = {} >gather = [] >for lines in rawData: > parentItem = lines[9] > for line in rawData: > if line[9] == parentItem: > gather.append(line) > db[parentItem]=gather > gather = [] Immediate observation and refinement: once a parentItem is found we don't need to find and process it again, so after parentItem = lines[9] add if parentItem not in db: then continue with: for line in rawData: etc. Also you could use list comprehension: db[parentItem] = [line for line in rawData if line[9] == parentItem] ># Now we take the data that have been sorted by parentItem and >further sort them by ># what type of item they are. For example, if the line has both a >printer and a duplex unit ># therein, the printer and duplex are sorted out and given an entry >of their own. This ># enables the items to be uploaded into dam with no issues. > >cookedData = {} # <-- new dictionary for the second sort. >for each in db.keys(): > sortdb = {} # <-- new dictionary for the item sort > for item in db[each]: > sortdb[item[12]] = item > # filter out the Printer/Duplex combinations > if sortdb.has_key('DPLX') and sortdb.has_key('PRT'): > print '%s printer // duplexer match'%each > filtered=[sortdb['PRT'], sortdb['DPLX']] > signify = sortdb['PRT'] > signify = signify[8] > cookedData[signify]=filtered > del sortdb['PRT'] > del sortdb['DPLX'] > # and the Laptop/Keyboard combinations > elif sortdb.has_key('KBD') and sortdb.has_key('LAP'): > print '%s laptop // keyboard match'%each > filtered=[sortdb['LAP'], sortdb['KBD']] > signify = sortdb['LAP'] > signify = signify[8] > cookedData[signify]=filtered > del sortdb['LAP'] > del sortdb['KBD'] > # now sort out the leftover items (usually Cpu/Monitor >combinations) > else: > old_potato = [] # <--A type of leftover (I crack me up.) > for leftover in sortdb.keys(): > old_potato.append(sortdb[leftover]) > # and finally add the leftovers to the cookedData. > cookedData[item[8]]=old_potato > ># Now we place the various data into a single long string suitable for DAM >to ingest >for item in cookedData.keys(): > print item, cookedData[item] > >--------------------snip----------------------- > >Any suggestions for cleanup or concision are welcomed! An idea (untested). Assumes there will be a pair of records for each shared value. If there could be less or more then some modifications are needed. sortableData = map((lambda x:list((x[9],x[12]))+x), rawData) # copy the major and minor sort items to the front of each list. sortableData.sort() # do the desired major/minor sort; all items of one shared value will now be together and the types within each shared value will be in order. types = {'DPLX': ('PRT', '%s printer // duplexer match', 0), 'KBD': ('LAB', '%s laptop // keyboard match', 0), etc.} # key is the alphabetically earlier of the types # 1st element of each tuple is the alphabetically later of the types # 2nd element of each tuple is the message to print # 3rd element of each tuple is the significantOffset. If 'DPLX' were the signifyng item insted of 'PRT' then this offset would be -1 sharevalue = None index = 0 old_potato = [] while index < len(sortableData): # instead of a for loop, so we can access more than one item item = sortableData[index] if item[0] != sharevalue: # start processing first or next shared value sharevalue = item[0] if old_potato: # left ove from previous shared value set coookedData[sortableData[index-1][10] = old_potato if item[1] in types: expect, msg, significantOffset = types[item[1]] old_potato = [] else: # must be a leftover old_potato = [item] else: # continue with next item of current shared value if old_potato : # add next leftover old_potato.append(item) else: if item[1] == expect: # we have a pair print msg%item[0] filtered=sortableData[index-1:index+1] # keep in mind that the shared value and type appear at the head of the list signify = sortableData[index + significantOffset] signify = signify[10] cookedData[signify]=filtered else: # deal with unmatched pair index += 1 if old_potato: # left over from last shared value set coookedData[sortableData[index-1][10] = old_potato Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 From Doug.Shawhan@gecits.ge.com Tue Mar 18 09:48:06 2003 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Tue Mar 18 09:48:06 2003 Subject: [Tutor] Finding items in list of lists. Message-ID: <47B6167F8E69D31194BA0008C7918D42076FEAE5@msxcvg02itscge.gecits.ge.com> "Reduce", my new favorite action now that I have grown used to "zip". :-) > Hi Doug! > You could mix it with something "less friendly" (???) and first > flatten your list of lists l by using reduce: > from operator import add > >>> reduce(add,l) > ['joe', 'moe', 'schmoe', 'fee', 'foo', 'bar'] > With this a single comprehension would do it: > >>> [y for y in reduce(add,l) if y in ("moe", "foo")] > ['moe', 'foo'] > >>> > Regards, Gregor From a_abdi406@yahoo.com Tue Mar 18 21:38:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Tue Mar 18 21:38:02 2003 Subject: [Tutor] about regular expressions in python Message-ID: <20030319023735.52867.qmail@web14507.mail.yahoo.com> --0-1832794071-1048041455=:51775 Content-Type: text/plain; charset=us-ascii Dear Tuor, Can anyone give me an idea how I can implement a regular expression that can process a large text by using minimum number of regular expression considering some xml tags, double quotes, single quotes, whitespaces,full stops, commas and ecc. ? my problem is I am not very familiar with RE(Regular Expressions) thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1832794071-1048041455=:51775 Content-Type: text/html; charset=us-ascii

Dear Tuor,

Can anyone give me an idea how I can implement a regular expression

that can process  a large text by using minimum number of regular expression

considering some xml tags, double quotes, single quotes, whitespaces,full stops, commas and ecc. ?

my problem is I am not very familiar with  RE(Regular Expressions)

thanks in advance

 



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1832794071-1048041455=:51775-- From erikprice@mac.com Tue Mar 18 22:07:01 2003 From: erikprice@mac.com (Erik Price) Date: Tue Mar 18 22:07:01 2003 Subject: [Tutor] about regular expressions in python In-Reply-To: <20030319023735.52867.qmail@web14507.mail.yahoo.com> Message-ID: On Tuesday, March 18, 2003, at 09:37 PM, Abdirizak abdi wrote: > Can anyone give me an idea how I can implement a regular expression > > that can process=A0 a large text by using minimum number of regular=20 > expression > > considering some xml tags, double quotes, single quotes,=20 > whitespaces,full stops, commas and ecc. ? Abdirizak, Someone was just complaining about how insufficient regular expressions=20= are for parsing XML earlier today: http://tbray.org/ongoing/When/200x/2003/03/16/XML-Prog I recommend trying one of the XML modules instead. (Of course, he was=20= complaining about -those- too... :) Erik --=20 Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From phthenry@earthlink.net Wed Mar 19 00:19:02 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Wed Mar 19 00:19:02 2003 Subject: [Tutor] about regular expressions in python In-Reply-To: <20030319023735.52867.qmail@web14507.mail.yahoo.com> References: <20030319023735.52867.qmail@web14507.mail.yahoo.com> Message-ID: <20030319001828.Y8504@localhost.localdomain> I would suggest you use one of the python modules that parses XML. Using regular expressions to parse XML is like having a healthy tooth pulled. You can do it, but only with unnecessary pain. Of course, I'm not sure what your exact needs are. Paul On Tue, Mar 18, 2003 at 06:37:35PM -0800, Abdirizak abdi wrote: > > > Dear Tuor, > > Can anyone give me an idea how I can implement a regular expression > > that can process a large text by using minimum number of regular expression > > considering some xml tags, double quotes, single quotes, whitespaces,full stops, commas and ecc. ? > > my problem is I am not very familiar with RE(Regular Expressions) > > thanks in advance > > > > > > --------------------------------- > Do you Yahoo!? > Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From dyoo@hkn.eecs.berkeley.edu Wed Mar 19 01:37:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 19 01:37:01 2003 Subject: [Tutor] Why does print add spaces ? In-Reply-To: <20030318083022.GA71723@daboyz.org> Message-ID: On Tue, 18 Mar 2003, Michael Barrett wrote: > Using list comprehension you could do the following: > > >>> x = 'abcdefghi' > >>> print ','.join([i for i in x]) > a,b,c,d,e,f,g,h,i > > As to why python prints the spaces? It's just the way print works in > the language. Can't really answer why, but I'm sure the developers felt > they had a reason. Hello! I think the 'print' statement is designed for simple output; it's definitely "special" in the sense that it really pays attention to trailing commas. For example: ### >>> def print_numbers(): ... for i in range(10): ... print i, ... >>> print_numbers() 0 1 2 3 4 5 6 7 8 9 ### Python's print statement introduces spaces to visually keep variable values from bleeding into each other unless we try really hard to do so... *grin* ### >>> x, y, z = 3, 1, 4 >>> print x, y, z 3 1 4 >>> import sys >>> sys.stdout.write("%s%s%s" % (x, y, z)) 314>>> ### (Notice that if we use sys.stdout.write(), we're able to escape the special newline-adding behavior of the 'print' statement.) Newcomers to a language may get caught off guard if they print variables without spaces in between. Python's 'print' statement simply makes that misake impossible. *grin* And the design is concious, although sometimes the designers wonder if they should have done something more uniform and less special. In: http://aspn.activestate.com/ASPN/Mail/Message/pypy-dev/1521115 the main developer of Python (Guido) admits that: """While punctuation is concise, and often traditional for things like arithmetic operations, giving punctuation too much power can lead to loss of readability. (So yes, I regret significant trailing commas in print and tuples -- just a little bit.)""" But I still like Python's "print" statement for it's simplicity, even though it is slightly special. And if we need more fine control over the way we print things, sys.stdout() is a good tool. Anyway, I hope this helps! From dyoo@hkn.eecs.berkeley.edu Wed Mar 19 01:41:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 19 01:41:01 2003 Subject: [Tutor] (no subject) In-Reply-To: Message-ID: On Tue, 18 Mar 2003 alan.gauld@bt.com wrote: > > I would like a demonstration on computer programming. > > Everytime you use a computer program you have a demonstration of > computer programming, including the email or web browser program you use > to read this message! Hi Ian, If you mean the question: "I want to see examples of computer programming", that's something that we might be able to help with. Have you seen the Useless Python web site? http://uselesspython.com Useless Python collects a lot of mini-programs and examples of fun programming. The programs are often short enough that it's easy to understand what's going on, and many of them have been written by folks on this list! Is there any kind of thing in particular that you're interested in? We might be able to find a Python computer program that is relevant to your interests. If you have more questions, please feel free to ask on Tutor. Good luck! From a_abdi406@yahoo.com Wed Mar 19 08:59:23 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed Mar 19 08:59:23 2003 Subject: [Tutor] about a program Message-ID: <20030319135623.17526.qmail@web14506.mail.yahoo.com> --0-1088473177-1048082183=:16986 Content-Type: text/plain; charset=us-ascii Hi everyone, I was developing a little program that uses regular expression, initially I set up an expression which looks like this :buf = re.compile("[a-zA-Z]+\s+") this was to match the followint string: str = 'Data sparseness is an inherent problem in statistical methods for natural language processing.' the result gets is it gets all the tokens except the last last one with the dot(full stop at the back) can anyone suggest how I can achieve to handle all the cases with the above RE. thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1088473177-1048082183=:16986 Content-Type: text/html; charset=us-ascii

Hi everyone,

I was developing a little program that uses regular expression, initially I set up

an expression which looks like this :buf = re.compile("[a-zA-Z]+\s+")  this was to

match the followint string:

str = 'Data sparseness is an inherent problem in statistical methods for natural language processing.'

the result gets is it gets all the tokens except the last last one with the dot(full stop at the back)

can anyone suggest how I can achieve to handle all the cases with the above

RE.

thanks in advance 

 



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1088473177-1048082183=:16986-- From a_abdi406@yahoo.com Wed Mar 19 09:06:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed Mar 19 09:06:02 2003 Subject: [Tutor] about a program Message-ID: <20030319140557.70391.qmail@web14501.mail.yahoo.com> --0-1537960010-1048082757=:68194 Content-Type: text/plain; charset=us-ascii Hi everyone, I was developing a little program that uses regular expression, initially I set up an expression which looks like this : buf = re.compile("[a-zA-Z]+\s+") this was to match the followint string: str = 'Data sparseness is an inherent problem in statistical methods for natural language processing.' Result: ['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', 'statistical', ' methods', 'for', 'natural', 'language'] the result is that, it gets all the tokens except the last one with the processing+ dot (full stop at the back) can anyone suggest how I can achieve to handle all the cases with the above RE. Reposted for some correction thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1537960010-1048082757=:68194 Content-Type: text/html; charset=us-ascii

Hi everyone,

I was developing a little program that uses regular expression, initially I set up

an expression which looks like this :

buf = re.compile("[a-zA-Z]+\s+") 

this was to match the followint string:

str = 'Data sparseness is an inherent problem in statistical methods for natural language processing.'

Result:

['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', 'statistical', '
methods', 'for', 'natural', 'language']

the result is that, it gets all the tokens except the last one with the processing+ dot (full stop at the back)

can anyone suggest how I can achieve to handle all the cases with the above

RE.

Reposted for some correction

thanks in advance 

 



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1537960010-1048082757=:68194-- From glingl@aon.at Wed Mar 19 09:43:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Wed Mar 19 09:43:01 2003 Subject: [Tutor] about a program References: <20030319140557.70391.qmail@web14501.mail.yahoo.com> Message-ID: <3E78821A.7050602@aon.at> Abdirizak abdi schrieb: > Hi everyone, > > I was developing a little program that uses regular expression, > initially I set up > > an expression which looks like this : > > /buf = re.compile("[a-zA-Z]+\s+") / > > this was to match the followint string: > > /str = 'Data sparseness is an inherent problem in statistical methods > for natural language *processing*.'/ > > /*Result:*/ > > /['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', > 'statistical', ' > methods', 'for', 'natural', 'language']/ > > the result is that, it gets all the tokens except the last one with > the */processing+ dot /*(full stop at the back) > Hi Abdirizak abdi! I found, that buf.findall(str) results in ['Data ', 'sparseness ', 'is ', 'an ', 'inherent ', 'problem ', 'in ', 'statistical ', 'methods ', 'for ', 'natural ', 'language '] including the space at the end of each word. (It searches for patterns ending at least with one space! While >>> buf = re.compile("[a-zA-Z]+") >>> buf.findall(str) ['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', 'statistical', 'methods', 'for', 'natural', 'language', 'processing'] >>> delivers what you want. (Did I understand correctly?) Regards, Gregor > can anyone suggest how I can achieve to handle all the cases with the > above > > RE. > > Reposted for some correction > > thanks in advance > > > > > ------------------------------------------------------------------------ > Do you Yahoo!? > Yahoo! Platinum > > - Watch CBS' NCAA March Madness, live on your desktop > ! From Janssen@rz.uni-frankfurt.de Wed Mar 19 09:43:09 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed Mar 19 09:43:09 2003 Subject: [Tutor] about a program In-Reply-To: <20030319140557.70391.qmail@web14501.mail.yahoo.com> Message-ID: On Wed, 19 Mar 2003, Abdirizak abdi wrote: > > Hi everyone, Hi Abdirizak > I was developing a little program that uses regular expression, initially I set up > > an expression which looks like this : > > buf = re.compile("[a-zA-Z]+\s+") > > this was to match the followint string: > > str = 'Data sparseness is an inherent problem in statistical methods for natural language processing.' first: do not use str as a variable name. str is already the builtin function str(). You will overwrite it otherwise and can't access the str() function without much more efforts. second: regular expressions should be written as "raw-strings": r"[a-zA-Z]+\s+" (put a little "r" before) ----> this way "escape sequences" didn't get interpreted: e.g. "\n" stays "\n" and isn't converted to newline and the like. Compare {pythondoc}/ref/strings.html for full list (you're lucky: \s isn't in this list, but you shouldn't count on that) ----- str = 'Data sparseness is an inherent problem in statistical methods for \ natural language processing.' buf = re.compile(r"[a-zA-Z]+") buf.findall(s) will already do the job for you: "find any (nonoverleaping) sequence of letters (not containig spaces, fullstops or the like)" In case you really need to look for an End Of Word, you should use \b (this special re sequence *must* be prevented from interpretation: a string like "\b[A-Za-z]+\b" would be transformed in "ASCII Backslash[A-Za-z]+ASCII Backslash" before the re-module get a glimps on. Use: r"\b[A-Za-z]+\b" or (when you want a harder life ;-) "\\b[A-Za-z]+\\b") greetings Michael > > Result: > > ['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', 'statistical', ' > methods', 'for', 'natural', 'language'] > > the result is that, it gets all the tokens except the last one with the processing+ dot (full stop at the back) > > can anyone suggest how I can achieve to handle all the cases with the above > > RE. > > Reposted for some correction > > thanks in advance > > > > > > --------------------------------- > Do you Yahoo!? > Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! From norvell@houseofspearman.org Wed Mar 19 12:12:10 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Wed Mar 19 12:12:10 2003 Subject: [Tutor] Fraction class Message-ID: <20030319171148.GA6490@houseofspearman.org> These questions are related to ``How to Think Like a Computer Scientist: Learning with Python,'' Appendix B ``Creating a new data type.'' This part of the book shows how to overload operators so that expressions like >>> print Fraction(1, 2) + Fraction(3, 4) # 1/2 + 3/4 = ? output the expected results (5/4 in this case). The authors show how to implement fraction addition, multiplication, and comparison. They leave the following as exercises: subtraction (__sub__ and __rsub__), division (__div__ and __rdiv__), exponentiation, and the ability to use long integers for numerators and denominators. I've got subtraction and division working with no problem, but the exponentiation is posing some difficulties for me. From the text: We can compute powers by overriding __pow__, but the implementation is a little tricky. If the exponent isn't an integer, then it may not be possible to represent the result as a Fraction. For example, Fraction(2)**Fraction(1, 2) is the square root of 2, which is an irrational number (it can't be represented as a fraction). So it's not easy to write the most general version of __pow__. So would it be best to just have Python raise an exception when it's given a fractional exponent? There are, of course, fractions (or otherwise) to fractional powers that return fractions ((4/9)**(1/2), (1/27)**(2/3), for example) but I'm not sure how to handle these cases. If I convert the numerators and denominators to floats and do regular exponentiation, how can I be sure I'll get back to the correct int/int representation of the fraction? For example: >>> (3**(1./3.))**3 2.9999999999999996 If the result had been 3.0000000000000001 I could convert it to int and get the right answer. If I convert 2.999999... to int, though, I get 2. The other part of the exercise is handling long ints as numerators and denominators. I tried ``print Fraction(1L, 2L)'' with just the code given in the book and got ``1/2'' as a result. Earlier in this same book the authors try to give an example of regular int overflow but their example is handled gracefully by the version of Python I'm using (2.2.2) whereas the book's solution requires extra code to handle long ints. So the only reason I'd need to include code for long ints in this Fraction class is for backwards compatibility, right? Thanks in advance for any answers to this and all apologies for being long-winded. -- Norvell Spearman From bgailer@alum.rpi.edu Wed Mar 19 13:08:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed Mar 19 13:08:01 2003 Subject: [Tutor] about a program In-Reply-To: <20030319140557.70391.qmail@web14501.mail.yahoo.com> Message-ID: <5.2.0.9.0.20030319104914.03209b30@66.28.54.253> --=======4521194F======= Content-Type: text/plain; x-avg-checked=avg-ok-2DDA7BEE; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 06:05 AM 3/19/2003 -0800, Abdirizak abdi wrote: >buf = re.compile("[a-zA-Z]+\s+") > >this was to match the followint string: > >str = 'Data sparseness is an inherent problem in statistical methods for >natural language processing.' > >Result: ['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', >'statistical', ' >methods', 'for', 'natural', 'language'] > >the result is that, it gets all the tokens except the last one with the >processing+ dot (full stop at the back) The problem is that \s+ expects whitespace after each word. There is no whitespace after 'processing'. Also you should put the pattern in a raw string, otherwise some \x sequences will be taken as special character. One solution is to specify whitespace OR end of string: buf = re.compile(r"[a-zA-Z]+(?:\s+|$)"). \s+|$ says whitespace OR end of string. I put that in () due to the precedence of |, and added ?: to make it a "A non-grouping version of regular parentheses." A completely different approach is to use \b to match start or end of word: buf = re.compile(r"\b[a-zA-Z]+\b"). If you just want to create a list of space separated words, str.split('). Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======4521194F======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2DDA7BEE Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======4521194F=======-- From dyoo@hkn.eecs.berkeley.edu Wed Mar 19 14:48:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 19 14:48:01 2003 Subject: [Tutor] Why does print add spaces ? In-Reply-To: <5.1.0.14.0.20030318231834.04598148@tcapp.com> Message-ID: On Tue, 18 Mar 2003, Tony Cappellini wrote: > Doesn't Guido think we are experienced enough to know that we can add > our own spaces by using the formatted print, as in > > print"%d" % varname, Hi Tony, I do not think it's a matter of trust, but that of convenience: in the common case, we want to use spaces to delimit variable values when we print them. The print statement, in a sense, optimizes for this common case. The fact that it's easy for beginners to use does not automatically imply that it's inappropriate for experienced programmers to use it too... *grin* I personally like it. > What bugs me about the space, is that it is implied, which is just poor > design. Users can add/remove spaces at will in the example above, and > the person debugging the code will SEE them. Perhaps. There's no doubt that it's a shortcut, and that we could have lived without it. At the same time, it is pretty convenient, and it was not added haphazardly: there are good reasons behind it. Here's more quotes about Python's 'print' statement: """About 10 years ago I debated with myself whether to make the most basic form of output a function or a statement; basically I was trying to decide between "print(item, ...)" and "print item, ...". I chose to make it a statement because printing needs to be taught very early on, and is very important in the programs that beginners write. Also, because ABC, which lead the way for so many things, made it a statement. In a move that's typical for the interaction between ABC and Python, I changed the name from WRITE to print, and reversed the convention for adding newlines from requiring extra syntax to add a newline (ABC used trailing slashes to indicate newlines) to requiring extra syntax (the trailing comma) to suppress the newline. I kept the feature that items are separated by whitespace on output. Full example: in ABC, WRITE 1 WRITE 2/ has the same effect as print 1, print 2 has in Python, outputting in effect "1 2\n". I'm not 100% sure that the choice for a statement was right (ABC had the compelling reason that it used statement syntax for anything with side effects, but Python doesn't have this convention), but I'm also not convinced that it's wrong. I certainly like the economy of the print statement. (I'm a rabid Lisp-hater -- syntax-wise, not semantics-wise! -- and excessive parentheses in syntax annoy me. Don't ever write return(i) or if(x==y): in your Python code! :-) """ (Quotation taken from http://www.python.org/peps/pep-0214.html) That being said, it is possible to set things up so that using the sys.stdout.write() method isn't wordy at all: ### >>> import sys >>> write = sys.stdout.write >>> write("hello world!") hello world!>>> ### What the snippet above shows is that it's almost ludicrously easy to set up a toplevel function called 'write()' that's just an alias for sys.stdout.write(). Is this what you're looking for? I hope this helps! From gerrit@nl.linux.org Wed Mar 19 16:03:38 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Wed Mar 19 16:03:38 2003 Subject: [Tutor] full screen turtle.py In-Reply-To: <3E7658A8.6020906@nep.net> References: <3E7658A8.6020906@nep.net> Message-ID: <20030319210436.GA2673@nl.linux.org> reavey schreef op dinsdag 18 maart om 00:26:57 +0000: > reavey schrieb: > > is there a way to display a full screen when turtle.py initializes? You may want to look at the Turtle module coming with Pygsear. Pygsear is a library created on top of Pygame. Pygame is a wrapper for SDL, and SDL is a cross-platform graphics library. Pygsear contains a lot of modules, one of which has turtle graphics. Pygame can then be told to use it fullscreen. Pygsear can be found at: http://www.nongnu.org/pygsear/ Pygame can be found at: http://pygame.org/ SDL can be found at: http://www.libsdl.org/ If you are using Unix, however, you'll probably have SDL already. yours, Gerrit. -- 209. If a man strike a free-born woman so that she lose her unborn child, he shall pay ten shekels for her loss. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From gerrit@nl.linux.org Wed Mar 19 16:23:01 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Wed Mar 19 16:23:01 2003 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <20030319212400.GA2786@nl.linux.org> Ian shaw schreef op dinsdag 18 maart om 00:27:27 +0000: > I would like a demonstration on computer programming. You can do *a lot* with computer programming. Have a look at http://www.python.org/, and especially at http://www.python.org/doc/Newbies.html A python program typically consists of a line of source lines. The Python interpreter, a program which can be downloaded, reads those lines and sees what to do. But in the end, *you* will do the programming! Good luck! yours, Gerrit. -- 131. If a man bring a charge against one's wife, but she is not surprised with another man, she must take an oath and then may return to her house. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From shalehperry@attbi.com Wed Mar 19 21:05:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed Mar 19 21:05:02 2003 Subject: [Tutor] Fraction class In-Reply-To: <20030319171148.GA6490@houseofspearman.org> References: <20030319171148.GA6490@houseofspearman.org> Message-ID: <200303191803.33293.shalehperry@attbi.com> On Wednesday 19 March 2003 09:11, Norvell Spearman wrote: > > I've got subtraction and division working with no problem, but the > exponentiation is posing some difficulties for me. From the text: > > We can compute powers by overriding __pow__, but the implementation > is a little tricky. If the exponent isn't an integer, then it may > not be possible to represent the result as a Fraction. For example= , > Fraction(2)**Fraction(1, 2) is the square root of 2, which is an > irrational number (it can't be represented as a fraction). So it's > not easy to write the most general version of __pow__. > > So would it be best to just have Python raise an exception when it's > given a fractional exponent? yes, an exception here seems like the right thing to do. > There are, of course, fractions (or > otherwise) to fractional powers that return fractions ((4/9)**(1/2), > (1/27)**(2/3), for example) but I'm not sure how to handle these cases. > If I convert the numerators and denominators to floats and do regular > exponentiation, how can I be sure I'll get back to the correct int/int > > representation of the fraction? For example: > >>> (3**(1./3.))**3 > > 2.9999999999999996 > > If the result had been 3.0000000000000001 I could convert it to int and > get the right answer. If I convert 2.999999... to int, though, I get 2= =2E > this is harder and there are no truly good solutions. > The other part of the exercise is handling long ints as numerators and > denominators. I tried ``print Fraction(1L, 2L)'' with just the code > given in the book and got ``1/2'' as a result. Earlier in this same > book the authors try to give an example of regular int overflow but > their example is handled gracefully by the version of Python I'm using > (2.2.2) whereas the book's solution requires extra code to handle long > ints. So the only reason I'd need to include code for long ints in thi= s > Fraction class is for backwards compatibility, right? > mostly, yes. From a_abdi406@yahoo.com Wed Mar 19 23:21:43 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed Mar 19 23:21:43 2003 Subject: [Tutor] about python RE Message-ID: <20030320042003.44229.qmail@web14501.mail.yahoo.com> --0-1663472150-1048134003=:43871 Content-Type: text/plain; charset=us-ascii hi everyone, can anyone give me an idea how to setup a regular expression that deals with full stops after the last word is read and commas after the words and double quotes in words. I am having a go, any given idea will be helpfull. thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1663472150-1048134003=:43871 Content-Type: text/html; charset=us-ascii

hi everyone,

can anyone give me an idea how to setup a regular expression that deals with full stops after the last word is read and commas after the words and double quotes in words. I am having a go, any given idea  will be helpfull.

thanks in advance

 



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1663472150-1048134003=:43871-- From Janssen@rz.uni-frankfurt.de Thu Mar 20 03:49:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Mar 20 03:49:01 2003 Subject: [Tutor] about python RE In-Reply-To: <20030320042003.44229.qmail@web14501.mail.yahoo.com> Message-ID: On Wed, 19 Mar 2003, Abdirizak abdi wrote: > hi everyone, > > can anyone give me an idea how to setup a regular expression that > deals with full stops after the last word is read and commas after the > words and double quotes in words. I am having a go, any given idea > will be helpfull. Hello Abdirizak, you want to know, how to find all "words" from a natural language sentence, right? A "word" is, what stands between whitespace (and Start/ End Of Sentence) without leading or trailing quotes, commas and so on, right? You will need a set of characters, which are allowed for words: "[-a-zA-Z0-9]" # correct? note: leading "-" means to take this character as itself, despite of its special meaning in character sets. This can be enhanced (obviously). Compare the \w sequence or string.letters . re.findall("[-a-zA-Z0-9]+", sentence) now already finds any "word" and leave whitespace and punctuation alone. The regular expression "comsumes" (while iterate through sentence) any character given in [-a-zA-Z0-9]. It stops when coming to a character not given (that means: you needn't to explicitly forbid "not-word-characters"). In case you want to *preserve* punctuation and/or quotes, put it into your character set. Is this sufficient for you? If, not please give us an example, where it isn't. Michael > > thanks in advance > > > > > > --------------------------------- > Do you Yahoo!? > Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! From GREENDAY31087@aol.com Thu Mar 20 05:09:11 2003 From: GREENDAY31087@aol.com (GREENDAY31087@aol.com) Date: Thu Mar 20 05:09:11 2003 Subject: [Tutor] my noob prog Message-ID: <31.35d024cc.2baaed17@aol.com> --part1_31.35d024cc.2baaed17_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Hey people. I made this little program and it's like the biggest thing I've made. I only started learning the hello world thing last month. Is this a good start or what?? Haha.. Well, the password is '1337' and remember to add the extension when writing/reading a file(.txt, .py, etc.). Tell me what you think! ********** password = "foobar" while password != "1337": password = raw_input("Password:") print "Welcome in" print "please select:" print "1 Wayne's calculator" print "2 create a file" print "3 read that file" choice=input() if choice==1: print 'please select:' print '1 rectangle area' print ' 2 circle circumference' print ' 3 circle area' shape=input(' ') if shape==1: height=input('please enter the height:') width=input('please enter the width:') area=height*width print 'the area is', area if shape==2: diameter=input('please enter the diameter:') circumference=3.14*diameter print 'the circumference is', circumference if shape==3: radius=input('please enter the radius:') area=3.14*(radius**2) print 'the area is', area raw_input('press enter to quit') if choice==2: name=raw_input('what do you want to name it?') out_file = open(name,"w") content=raw_input('what do you want the file to say?') out_file.write(content) out_file.close() if choice==3: what=raw_input('what is the file named?') in_file = open(what,"r") text = in_file.read() in_file.close() print text raw_input() ********** -WaYnE --part1_31.35d024cc.2baaed17_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable Hey people.
I made this little program and it's like the biggest thing I've made. I only= started learning the hello world thing last month. Is this a good start or=20= what?? Haha.. Well, the password is '1337' and remember to add the extension= when writing/reading a file(.txt, .py, etc.). Tell me what you think!
**********
password =3D "foobar"
while password !=3D "1337":
    password =3D raw_input("Password:")
print "Welcome in"
print "please select:"
print "1 Wayne's calculator"
print "2 create a file"
print "3 read that file"
choice=3Dinput()
if choice=3D=3D1:
    print 'please select:'
    print '1 rectangle area'
    print ' 2 circle circumference'
    print '  3 circle area'
    shape=3Dinput('=0B')
    if shape=3D=3D1:
height=3Dinput('please enter the height:')
width=3Dinput('please enter the width:')
area=3Dheight*width
print 'the area is', area
    if shape=3D=3D2:
diameter=3Dinput('please enter the diameter:')
circumference=3D3.14*diameter
print 'the circumference is', circumference
    if shape=3D=3D3:
        radius=3Dinput('please enter the=20= radius:')
area=3D3.14*(radius**2)
print 'the area is', area
    raw_input('press enter to quit')
if choice=3D=3D2:
    name=3Draw_input('what do you want to name it?')
    out_file =3D open(name,"w")
    content=3Draw_input('what do you want the file to say?')<= BR>     out_file.write(content)
    out_file.close()
if choice=3D=3D3:
    what=3Draw_input('what is the file named?')
    in_file =3D open(what,"r")
    text =3D in_file.read()
    in_file.close()
    print text
    raw_input()
**********

-WaYnE
--part1_31.35d024cc.2baaed17_boundary-- From reavey@nep.net Thu Mar 20 07:09:02 2003 From: reavey@nep.net (reavey) Date: Thu Mar 20 07:09:02 2003 Subject: [Tutor] turtle.py reset screen dimensions Message-ID: <3E79AE83.9000500@nep.net> Hi Perhaps this problem could be answered if it were possible to know from which file the turtle request the window manager geometry. Despite many attempts all receiving the same error, I haven't given up on the idea that I have misread or input Gregor's fix incorrectly, . TIA re-v Re: [Tutor] full screen turtle.py add this thread to my home page by Gregor Lingl other posts by this author Feb 11 2003 10:38PM messages near this date << Re: [Tutor] Sun says: Don't use Java, use Python! | RE: [Tutor] List exercise >> reavey schrieb: > is there a way to display a full screen when turtle.py initializes? As a default-canvas is created the first time when you call an arbitrary turtle-graphics function, there is no way to pass information about its size to the canvas. But: (1) There is the possibility to create turtle-objects on your own Tkinter-Canvas which may have any size you want. more precisely, you have to create an object of the RawPen class, which goes like this: >>> from Tkinter import Canvas >>> cv = Canvas(width=800, height=600) >>> cv.pack() >>> t = RawPen(cv) >>> t.forward(100) you may reset the size of cv with something like: >>> cv["width"]=400 >>> cv["height"] = 500 and recenter t by calling t.reset (which works essentially the same way you used when resizing the default-canvas manually) (2) Another way to accomplish what you want ist do decide to rewrite the reset-function of the turtle-module in order to pass information about the size of the canvas. (If these arguments are not given, it works the old way): First you have to change the reset-method of RawPen (approx line 40): def reset(self, width = None, height = None): canvas = self._canvas if width: canvas["width"] = width if height: canvas["height"] = height self._canvas.update() # .... and so on. as before Then you have to modify the reset - function (approx line 350): def reset(width=None, height=None): _getpen().reset(width,height) I've attached a modified turtle.py With these changes the following will be possible: >>> from turtle import * >>> reset(800,600) >>> forward(50) >>> reset(200,200) Regards, Gregor P.S. I didn't extensively test these changes, so maybe there will be some unwanted side-effects, especially when using RawPen. Maybe I'll have a look at this sometimes later ... > > The first canvas takes up a small portion of the display (around 10%). > When I hit the expand button on the canvas it doesn't recenter. > The drawing still uses the inititial canvas coordinates. > > btw: this is not a problem using the interactive interpreter as a > turtle.reset() > issued after you expand works as expected. > > thanks > re-v I have tried part two being the better solution. I get the following error traceback(most recent call last) file "",line 1 in? ############## the reader of this message will please from this point on replace the word file with File "usr/lib/python2.2/lib-tk/turtle.py################# file line 314, in reset def reset(width=None,height=None)::_getpen().reset(height,width) file line 308 in_getpen_pen=pen=Pen() file line 292, in__init__RawPen.__init__(self._canvas) file line 16, in__init__self.reset() file line 34 , in reset self._origin = float(width)/2.0,float(height)/2.0 type error: float() needs a strong argument from turtle import * ####works reset() ###produces the above failure reset(200,200) ####error as above reset("200","200") ###error as above Thanks re-v From reavey@nep.net Thu Mar 20 08:13:02 2003 From: reavey@nep.net (reavey) Date: Thu Mar 20 08:13:02 2003 Subject: [Tutor] pygsear turtle graphics Message-ID: <3E79BDA3.5000504@nep.net> I can't find the package. Does it have another name? I see turtle packages in lib-tk... none in pygame or pygsear. TIA re-v From reavey@nep.net Thu Mar 20 09:09:01 2003 From: reavey@nep.net (reavey) Date: Thu Mar 20 09:09:01 2003 Subject: [Tutor] [Fwd: pygsear turtle graphics] Message-ID: <3E79CAB9.5020201@nep.net> This is a multi-part message in MIME format. --------------070008080007080609010505 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit I found the turtle. It's in the subdirectory examples of pygsear under pengiun. I found this by reading the intro in the subdirectory doc. I had trouble getting pygsear to run several times in the past and I'm happy to report that the install ran smothly on a linux box downloading the source file. At this point, it appears that /lib-tk/turtle.py will retire. Thanks again. --------------070008080007080609010505 Content-Type: message/rfc822; name="pygsear turtle graphics" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="pygsear turtle graphics" Message-ID: <3E79BDA3.5000504@nep.net> Date: Thu, 20 Mar 2003 08:09:55 -0500 From: reavey User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) Gecko/20021130 X-Accept-Language: en-us, en MIME-Version: 1.0 To: tutor@python.org Subject: pygsear turtle graphics Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit I can't find the package. Does it have another name? I see turtle packages in lib-tk... none in pygame or pygsear. TIA re-v --------------070008080007080609010505-- From a_abdi406@yahoo.com Thu Mar 20 09:15:08 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Thu Mar 20 09:15:08 2003 Subject: [Tutor] about RE + python Message-ID: <20030320141417.77318.qmail@web14502.mail.yahoo.com> --0-1980350925-1048169657=:76558 Content-Type: text/plain; charset=us-ascii thanks jenssen for your contribution. I tried by including the stop punctuation in my character set as follows buf = re.compile(r"[-a-zA-Z0-9\.]+") te = buf.findall(test) print te this is the result >>> import re >>> test = 'Data sparseness is an inherent problem in statistical methods for natural language processin g.' >>> buf = re.compile(r"[-a-zA-Z0-9.]+") >>> te = buf.findall(test) >>> print te ['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', 'statistical', 'methods', 'for', 'natura l', 'language', 'processing.'] >>> lok at the last line processing is followed by fullstop, but Iwant to have ...'processing', '.' ] i.e quoted processing followed by quoted fullstop which also means toconside the full stop as separate token thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1980350925-1048169657=:76558 Content-Type: text/html; charset=us-ascii

thanks jenssen for your contribution.

I tried by including the stop punctuation in my character set as follows

buf = re.compile(r"[-a-zA-Z0-9\.]+")
te = buf.findall(test)
print te

this is the result

>>> import re
>>> test = 'Data sparseness is an inherent problem in statistical methods for natural language processin
g.'
>>> buf = re.compile(r"[-a-zA-Z0-9.]+")
>>> te = buf.findall(test)
>>> print te


['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', 'statistical', 'methods', 'for', 'natura
l', 'language', 'processing.']
>>>

lok at the last line processing is followed by fullstop, but Iwant to have

 ...'processing', '.' ]

i.e quoted processing followed by quoted fullstop which also means toconside the full stop as separate token

thanks in advance



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1980350925-1048169657=:76558-- From a_abdi406@yahoo.com Thu Mar 20 09:22:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Thu Mar 20 09:22:02 2003 Subject: [Tutor] about pyhton + regular expression Message-ID: <20030319161648.48799.qmail@web14506.mail.yahoo.com> --0-177324236-1048090608=:47956 Content-Type: text/plain; charset=us-ascii Hi everyone, thanks gregor and Michael for your contribution: While >>> buf = re.compile("[a-zA-Z]+") >>> buf.findall(str) ['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', 'statistical', 'methods', 'for', 'natural', 'language', 'processing'] >>> this is the result that I want: ['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', 'statistical', 'methods', 'for', 'natural', 'language', 'processing', '.'] gregor yes it was what I wanted but also including the full stop, commas,double quote and also single quote. I need to tokenize each of these individually as other tokens that appear in the list. Do I have to to do it separate RE and evaluate a condtional statement or only one RE (regular expression) can be done ? Another question when you are reading a text from a file is it really necesary to scan by using while loop or the following is enough and then scan with a loop to manipulate what is the real difference ? infile = open(' file.txt ') buffer = infile.readline() --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-177324236-1048090608=:47956 Content-Type: text/html; charset=us-ascii

Hi everyone,

thanks gregor and Michael for your contribution:

While

>>> buf = re.compile("[a-zA-Z]+")
>>> buf.findall(str)
['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in',
'statistical', 'methods', 'for', 'natural', 'language', 'processing']
>>>
this is the result that I want:

['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in',
'statistical', 'methods', 'for', 'natural', 'language', 'processing', '.']

gregor yes it was what I wanted but also including the full stop, commas,double quote and also single quote. I need to tokenize each of these individually as other tokens  that appear in the list. Do I have to to do it separate RE and evaluate a condtional statement or only one RE (regular expression) can be done ? 

Another question

 when you are reading a text from a file  is it really necesary to scan by using while loop or the following is enough and then scan with a loop to manipulate what is the real difference ?

infile = open(' file.txt ')
buffer = infile.readline()



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-177324236-1048090608=:47956-- From bgailer@alum.rpi.edu Thu Mar 20 11:06:45 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu Mar 20 11:06:45 2003 Subject: [Tutor] TKinter display dialog 2nd time? Message-ID: <5.2.0.9.0.20030320114922.0370f1d8@66.28.54.253> --=======1C334F31======= Content-Type: text/plain; x-avg-checked=avg-ok-40B47E0; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit I find it amusing that, having stated a month or so ago that I have no interest in TKinter, now I'm using it. I find the various reference materials to be inadequate to help me really understand what's going on. The immediate problem is, I want to display a dialog, allow the user to close it, then display it again. Attempts to display it again lead to no results or errors class App(Frame): def __init__(self, txt='Start', parent=Tk()): Frame.__init__(self, parent) self.pack() self.Label = Label(self, font = 'arial 8, txt') self.Label.pack({"side": "top"}) self.QUIT = Button(self, text = "OK", command = self.quit) self.QUIT.pack({"side": "top"}) if __name__ == '__main__': app = App('txt') app.mainloop() So far so good. If I follow this with another app.mainloop(), nothing happens. If I follow this with app = App('txt') I get: .... File "P:\Python22\lib\lib-tk\Tkinter.py", line 2257, in __init__ Widget.__init__(self, master, 'frame', cnf, {}, extra) File "P:\Python22\lib\lib-tk\Tkinter.py", line 1764, in __init__ self.tk.call( clError: can't invoke "frame" command: application has been destroyed What am I missing. What do I need to do to redisplay the dialog? Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======1C334F31======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-40B47E0 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======1C334F31=======-- From Janssen@rz.uni-frankfurt.de Thu Mar 20 11:42:10 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Mar 20 11:42:10 2003 Subject: [Tutor] about pyhton + regular expression In-Reply-To: <20030319161648.48799.qmail@web14506.mail.yahoo.com> Message-ID: On Wed, 19 Mar 2003, Abdirizak abdi wrote: > > Hi everyone, > > thanks gregor and Michael for your contribution: > > While > > >>> buf = re.compile("[a-zA-Z]+") > >>> buf.findall(str) > ['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', > 'statistical', 'methods', 'for', 'natural', 'language', 'processing'] > >>> > this is the result that I want: > > ['Data', 'sparseness', 'is', 'an', 'inherent', 'problem', 'in', > 'statistical', 'methods', 'for', 'natural', 'language', 'processing', '.'] exp_token = re.compile(r""" ([-a-zA-Z0-9_]+| # a token can be a word [\"\'.,;:!\?]) # *or* a single character of this character set """, re.VERBOSE) # VERBOSE ignores all this whitespace and comments character sets must be finetuned > > Another question > > when you are reading a text from a file is it really necesary to scan > by using while loop or the following is enough and then scan with a > loop to manipulate what is the real difference ? > > infile = open(' file.txt ') > buffer = infile.readline() both not. In recent version (otherwise while loop, correct) of Python, you can do: for line in open('file.txt'): # process line # modern spelling is: for line in file('file.txt'): # process line readline() reads one line of the file. read() the whole file as a string. readlines() the whole file as a list of lines. Michael > > > > > --------------------------------- > Do you Yahoo!? > Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! From antonmuhin at rambler.ru" References: <20030320141417.77318.qmail@web14502.mail.yahoo.com> Message-ID: <8410858383.20030320202036@rambler.ru> Hello Abdirizak, Thursday, March 20, 2003, 5:14:17 PM, you wrote: Aa> lok at the last line processing is followed by fullstop, but Iwant to have Aa> ...'processing', '.' ] Aa> i.e quoted processing followed by quoted fullstop which also means toconside the full stop as separate token Aa> thanks in advance Try: buf = re.compile(r"(?:[-a-zA-Z0-9]+)|\.") -- Best regards, anton mailto:antonmuhin@rambler.ru From jeff@ccvcorp.com Thu Mar 20 12:40:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Mar 20 12:40:01 2003 Subject: [Tutor] about pyhton + regular expression References: Message-ID: <3E79FD2D.6050004@ccvcorp.com> Michael Janssen wrote: >both not. In recent version (otherwise while loop, correct) of Python, you >can do: >for line in open('file.txt'): > # process line > ># modern spelling is: >for line in file('file.txt'): > # process line > > >readline() reads one line of the file. read() the whole file as a string. >readlines() the whole file as a list of lines. > > It should also be noted that, in both new and older versions of Python, there's a special pseudo-iterator that can be used. If you use the standard idiom infile = open('file.txt') for line in infile.readlines(): [...] infile.close() then the entire contents of the file is read into a list of lines. If the file is large, this may swamp available memory. You can use the special xreadlines() method instead -- for line in infile.xreadlines(): [...] This uses a small amount of behind-the-scenes magic to only read a small amount of the file at once, so you can use this to comfortably iterate through files that are considerably larger than available memory. Also note that I prefer to save a reference to my file-object and explicitly close it when done. In general, a file is automatically closed when the file-object representing it is destroyed, so allowing this to happen implictly usually works -- but the catch here is "usually". The problem is that file-objects aren't necessarily destroyed right away when the last reference for them is deleted -- it happens right away in the current implementation of CPython, but not in Jython, and it's not guaranteed in *any* implementation. Typically, with files that are read once and never written to, this won't matter much, but if you're reading in a file and then later writing to the same file, it could cause problems. I feel that it's a good habit to explicitly close files, whether strictly necessary or not, so that I don't have to worry about which circumstances may be problematic and which are safe. Jeff Shannon Technician/Programmer Credit International From phthenry@earthlink.net Thu Mar 20 14:57:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Thu Mar 20 14:57:01 2003 Subject: [Tutor] about pyhton + regular expression In-Reply-To: <3E79FD2D.6050004@ccvcorp.com> References: <3E79FD2D.6050004@ccvcorp.com> Message-ID: <20030320145613.G8504@localhost.localdomain> On Thu, Mar 20, 2003 at 09:41:01AM -0800, Jeff Shannon wrote: > > It should also be noted that, in both new and older versions of Python, > there's a special pseudo-iterator that can be used. If you use the > standard idiom > > infile = open('file.txt') > for line in infile.readlines(): > [...] > infile.close() > > then the entire contents of the file is read into a list of lines. If > the file is large, this may swamp available memory. You can use the > special xreadlines() method instead -- > > for line in infile.xreadlines(): > [...] > Nifty. I had been doing: line_to_read = '1' while line_to_read: line_to_read = infile.readline() > destroyed right away when the last reference for them is deleted -- it > happens right away in the current implementation of CPython, but not in > Jython, and it's not guaranteed in *any* implementation. Typically, > with files that are read once and never written to, this won't matter > much, but if you're reading in a file and then later writing to the same > file, it could cause problems. I feel that it's a good habit to > explicitly close files, whether strictly necessary or not, so that I > don't have to worry about which circumstances may be problematic and > which are safe. I strongly second this. Even in CPython I have had problems when I didn't close a file: file_obj.close I had meant to close the file, but forgot the parenthesis, and couldn't figure out for the life of me why the rest of the program didn't work. Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From abli@freemail.hu Thu Mar 20 15:25:02 2003 From: abli@freemail.hu (Abel Daniel) Date: Thu Mar 20 15:25:02 2003 Subject: [Tutor] TKinter display dialog 2nd time? In-Reply-To: <5.2.0.9.0.20030320114922.0370f1d8@66.28.54.253> References: <5.2.0.9.0.20030320114922.0370f1d8@66.28.54.253> Message-ID: <20030320202402.GA2048@hooloovoo> Bob Gailer wrote: > > I find it amusing that, having stated a month or so ago that I have no > interest in TKinter, now I'm using it. I find the various reference > materials to be inadequate to help me really understand what's going on. > The immediate problem is, I want to display a dialog, allow the user to > close it, then display it again. Attempts to display it again lead to no > results or errors > [snipped code] > So far so good. > > If I follow this with another app.mainloop(), nothing happens. > > If I follow this with app = App('txt') I get: > .... [snipped traceback] I'm not much of a Tkinter expert, so what I say might be wrong. I added an 'from Tkinter import *' at the top. The font = 'arial 8, txt' thing didnt work, so i got rid of that. with these modifications, the following works: from Tkinter import * class App(Frame): def __init__(self, txt='Start', parent=Tk()): Frame.__init__(self, parent) self.pack() self.Label = Label(self, text = 'arial 8, txt') self.Label.pack({"side": "top"}) self.QUIT = Button(self, text = "OK", command = self.quit) self.QUIT.pack({"side": "top"}) if __name__ == '__main__': app = App('txt') app.mainloop() print 'hi' #app = App('txt') app.mainloop() This shows the dialog, after clicking on OK, 'hi' gets printed to the console. The dialog looks unchanged, but after clicking on it, the program exits. I don't get the problems you mention. (even if I uncomment the second app=App(txt) line). Anyway, I don't think you should be doing this. First some observations to the code you posted: If you want to display a dialog box, you should inherit form Toplevel, not Frame. If you inherit any widget, you shouldn't pack() it in it's __init__, as that should be the responsibility of the class that uses it. Standard widgets don't pack themselves, so yours shouldn't, either. (For example what if I want to use grid instead of pack?) Personally I wouldn't hardcode font information like that. (Imagine having to change the font if you have more than a handfull of classes like this. Not to mention that this gave an error for me on python version 2.1.3 : TclError: expected integer but got "8,") I think that parent=Tk() trick is wrong. I would do it like this: class App(Toplevel): def __init__(self, txt='Start'): Toplevel.__init__(self) self.Label = Label(self, text = 'txt') self.Label.pack({"side": "top"}) self.QUIT = Button(self, text = "OK", command = self.quit) self.QUIT.pack({"side": "top"}) if __name__ == '__main__': app = App('txt') app.mainloop() But even this is not what you need. You want to show a dialog window, close it, then show it again. The 'have to calls to mainloop' idea won't fly, because the window stays visible. (Try it with 'import time' adding a 'time.sleep(0.5)' call between the to calls to mainloop.) I think what you really need is the tkMessageBox module. With that, you can do things like if tkMessageBox.askyesno('title of dialog', 'do this?'): # do it else: # dont do it I think this would be the simplest way of adding a few dialog windows to an otherwise non-gui program. (Thats what you are doing, right?) Hope this helps, Abel Daniel From jeff@ccvcorp.com Thu Mar 20 15:28:08 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Mar 20 15:28:08 2003 Subject: [Tutor] about pyhton + regular expression References: <3E79FD2D.6050004@ccvcorp.com> <20030320145613.G8504@localhost.localdomain> Message-ID: <3E7A2468.5080905@ccvcorp.com> Paul Tremblay wrote: >On Thu, Mar 20, 2003 at 09:41:01AM -0800, Jeff Shannon wrote: > > >>for line in infile.xreadlines(): >> [...] >> > >Nifty. I had been doing: > >line_to_read = '1' >while line_to_read: > line_to_read = infile.readline() > > Another common idiom is this: while 1: line = infile.readline() if not line: break [...] There's arguments back and forth about this being preferable to what you'd been doing (your code sets the same variable in two different places, which is usually considered poor design, but it's shorter and some people dislike 'while 1' ...) but for most purposes xreadlines() does exactly what's desired. Jeff Shannon Technician/Programmer Credit International From alan.gauld@bt.com Thu Mar 20 18:38:07 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Mar 20 18:38:07 2003 Subject: [Tutor] TKinter display dialog 2nd time? Message-ID: > The immediate problem is, I want to display a dialog, allow > the user to close it, then display it again. Sounds like you want to wrap it as a class inheriting from TopLevel (rather than Frame) and start the mainloop directly from Tk() > self.Label.pack({"side": "top"}) > self.QUIT.pack({"side": "top"}) The dictionary approach is depracated, its more normal to use named parameters, like: self.Label.pack(side="top") self.QUIT.pack(side="top") > app.mainloop() Use top = Tk() top.mainloop() # start the Tkinter event loop running dlog = app(top) # create the dialog object dlog.pack() # show it dlog.unpack() # hide it dlog.pack() # show it again Or Something like that.... Alan G From bgailer@alum.rpi.edu Thu Mar 20 19:21:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu Mar 20 19:21:02 2003 Subject: [Tutor] TKinter display dialog 2nd time? In-Reply-To: <20030320202402.GA2048@hooloovoo> References: <5.2.0.9.0.20030320114922.0370f1d8@66.28.54.253> <5.2.0.9.0.20030320114922.0370f1d8@66.28.54.253> Message-ID: <5.2.0.9.0.20030320171815.03782e40@66.28.54.253> --=======32974A78======= Content-Type: text/plain; x-avg-checked=avg-ok-5DDC6A43; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 09:24 PM 3/20/2003 +0100, Abel Daniel wrote: >[snip] >I think what you really need is the tkMessageBox module. With that, >you can do things like > >if tkMessageBox.askyesno('title of dialog', 'do this?'): > # do it >else: That was the nudge I needed. It led to tkMessageBox.showwarning(title, nmsg) which does exactly what I want. Thanks. How does one learn about modules like these that are in the distribution but not in the documentation? Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======32974A78======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-5DDC6A43 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======32974A78=======-- From bgailer@alum.rpi.edu Thu Mar 20 19:28:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu Mar 20 19:28:01 2003 Subject: [Tutor] TKinter display dialog 2nd time? Message-ID: <5.2.0.9.0.20030320172604.0378aae8@66.28.54.253> --=======2013481D======= Content-Type: text/plain; x-avg-checked=avg-ok-5DDC6A43; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 09:24 PM 3/20/2003 +0100, Abel Daniel wrote: >[snip] >I think what you really need is the tkMessageBox module. With that, >you can do things like > >if tkMessageBox.askyesno('title of dialog', 'do this?'): > # do it >else: One of the drawbacks of this approach is that a blank TK window opens in the background, with the message box in a 2nd window. The blank window does not go away until the program terminates. SIGH. Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======2013481D======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-5DDC6A43 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======2013481D=======-- From bgailer@alum.rpi.edu Thu Mar 20 19:38:04 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu Mar 20 19:38:04 2003 Subject: [Tutor] TKinter display dialog 2nd time? In-Reply-To: Message-ID: <5.2.0.9.0.20030320173726.037b3e88@66.28.54.253> --=======58E34178======= Content-Type: text/plain; x-avg-checked=avg-ok-5DDC6A43; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:30 PM 3/20/2003 +0000, alan.gauld@bt.com wrote: > > The immediate problem is, I want to display a dialog, allow > > the user to close it, then display it again. > >Sounds like you want to wrap it as a class inheriting from >TopLevel (rather than Frame) and start the mainloop directly >from Tk() > > > > self.Label.pack({"side": "top"}) > > self.QUIT.pack({"side": "top"}) > >The dictionary approach is depracated, its more normal to use >named parameters, like: > > self.Label.pack(side="top") > self.QUIT.pack(side="top") > > > app.mainloop() > >Use >top = Tk() >top.mainloop() # start the Tkinter event loop running >dlog = app(top) # create the dialog object >dlog.pack() # show it >dlog.unpack() # hide it >dlog.pack() # show it again I am sufficiently new to TKinter that I do not understand your proposal. Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======58E34178======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-5DDC6A43 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======58E34178=======-- From missive@hotmail.com Thu Mar 20 21:34:01 2003 From: missive@hotmail.com (Lee Harr) Date: Thu Mar 20 21:34:01 2003 Subject: [Tutor] Re: pygsear turtle graphics Message-ID: >I found the turtle. It's in the subdirectory examples of pygsear under >pengiun. I found this by reading the intro in the subdirectory doc. >I had trouble getting pygsear to run several times in the past and I'm >happy to report that the install ran smothly on a linux box >downloading >the source file. Hi; Glad to hear it went more smoothly now. I never thought about someone looking for turtle and not thinking to open up penguin... hmmm :o) Let me know if you come up with any cool penguin... er turtle graphics scripts. I have a blast with that thing! http://www.nongnu.org/pygsear/ http://savannah.nongnu.org/files/?group=pygsear _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From arion@uselesspython.com Thu Mar 20 22:07:02 2003 From: arion@uselesspython.com (Rob Andrews) Date: Thu Mar 20 22:07:02 2003 Subject: [Tutor] py2exe example Message-ID: I seem to be having some odd problems with email tonight, so if you get fifteen hundred copies of this message just ignore the other one thousand, four hundred and ninety nine. ;) >From time to time someone will post a question about how to make a stand-alone executable from a Python program. This seemed like a worthy project, so I've given it a stab for posterity. On http://www.uselesspython.com/newsite/tutorials.html there is a text file detailing the process from start to finish, including relevant URLs and walking through what appears to have been a successful and painless process. -Rob From pijus@virketis.com Thu Mar 20 23:18:02 2003 From: pijus@virketis.com (Pijus Virketis) Date: Thu Mar 20 23:18:02 2003 Subject: [Tutor] ipconfig on a MacOS X Message-ID: <5EC16D9A-5B6D-11D7-A250-000A9575F08A@virketis.com> Dear all, I need to check my computer's IP address in my script. In the terminal, I can do this just fine with "ipconfig getifaddr en0". When I try to make this call from Python, though, things get tricky: 1. If I use MacPython (the GUI version), then the function system() is neither in module "os" nor "mac". How can I execute the system call without system()? 2. If I use the terminal Python, then strangely enough system() is available in "os" module. This is what I get: >>> os.system("ipconfig getifaddr en0") 127.0.0.1 #my ip address here 0 >>> ip = os.system("ipconfig getifaddr en0") >>> print(a) 0 Oops ... So I get the right output, but I cannot seem to be able to capture it in a variable, instead grabbing only what I presume is the exit code. So, I would like to ask two questions: how do I grab the output in terminal Python? And, how do I accomplish the whole task in MacPython? How come there is this schizophrenic split between the two Pythons? (I guess that's a third question, we can all fondly remember the Spanish Inquisition at this point :)). Thank you! Pijus From j.ezequiel@spitech.com Fri Mar 21 01:06:39 2003 From: j.ezequiel@spitech.com (Ezequiel, Justin) Date: Fri Mar 21 01:06:39 2003 Subject: [Tutor] Automating MSWord (error if run from command line; no error if ru n within PythonWin) Message-ID: <0F757892D113D611BD2E0002559C1FF40300BAB0@email.spitech.com> I am getting the following message when running my program from the command line (X:\>python DelStyles.py jd002790.doc). The program runs file under PythonWin (Ctrl-R)! I am using Python 2.2.2 on WinXP Service Pack 1. I've installed py2exe-0.3.3.win32-py2.2.exe and win32all-152.exe in that order, if it matters. Ultimately, I would like to package my program using py2exe. I can attach the entire program if you like (104 lines). Thanks in advance. Processing jd002790.doc Saving as RTF... Traceback (most recent call last): File "DelStyles.py", line 101, in ? process(sys.argv[1]) File "DelStyles.py", line 90, in process SaveFile(sFile, sRTFFile, 6) File "DelStyles.py", line 82, in SaveFile doc = win32com.client.GetObject(sOldFile) File "D:\PYTHON22\lib\site-packages\win32com\client\__init__.py", line 73, in GetObject return Moniker(Pathname, clsctx) File "D:\PYTHON22\lib\site-packages\win32com\client\__init__.py", line 89, in Moniker dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147287038, 'STG_E_FILENOTFOUND', None, None) From abli@freemail.hu Fri Mar 21 01:53:02 2003 From: abli@freemail.hu (Abel Daniel) Date: Fri Mar 21 01:53:02 2003 Subject: [Tutor] TKinter display dialog 2nd time? In-Reply-To: <5.2.0.9.0.20030320172604.0378aae8@66.28.54.253> References: <5.2.0.9.0.20030320172604.0378aae8@66.28.54.253> Message-ID: <20030321065250.GA1551@hooloovoo> Bob Gailer wrote: > One of the drawbacks of this approach is that a blank TK window opens in > the background, with the message box in a 2nd window. The blank window does > not go away until the program terminates. SIGH. Try: import Tkinter import tkMessageBox root_window=Tkinter.Tk() root_window.withdraw() tkMessageBox.showwarning('warn','danger') The background of the problem is that tkMessageBox creates the dialogs as the instances of the Toplevel class. The extra blank window comes from the 'root window' (also a Toplevel) which you automatically get when initializing tkinter. The above work-around works by hiding this window as soon as it is made. Abel Daniel From j.ezequiel@spitech.com Fri Mar 21 06:07:01 2003 From: j.ezequiel@spitech.com (Ezequiel, Justin) Date: Fri Mar 21 06:07:01 2003 Subject: [Tutor] Automating MSWord (error if run from command line; no error if ru n within PythonWin) Message-ID: <0F757892D113D611BD2E0002559C1FF40301F5A9@email.spitech.com> I am attaching a trimmed-down version of my code. I am using MS Word XP, Win XP, Python 2.2.2. Works from within PythonWin but not from the command prompt. X:\>python forPost.py omc00055.doc Processing omc00055.doc Saving as RTF... Traceback (most recent call last): File "forPost.py", line 29, in ? process(sys.argv[1]) File "forPost.py", line 25, in process SaveFile(sFile, sRTFFile, 6) File "forPost.py", line 17, in SaveFile doc = win32com.client.GetObject(sOldFile) File "D:\PYTHON22\lib\site-packages\win32com\client\__init__.py", line 73, in GetObject return Moniker(Pathname, clsctx) File "D:\PYTHON22\lib\site-packages\win32com\client\__init__.py", line 89, in Moniker dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147287038, 'STG_E_FILENOTFOUND', None, None) ## my code starts here import sys import win32com.client import os usage = """ Usage: python forPost.py YourFile.ext """ def GetRTFFile(sFile): return os.path.splitext(sFile)[0] + ".rtf" def SaveFile(sOldFile, sNewFile, nFormat): """nFormat = 0 to save as MS Word format nFormat = 6 to save as RTF format""" doc = win32com.client.GetObject(sOldFile) doc.SaveAs(sNewFile, nFormat) doc.Close(0) def process(sFile): print "Processing", sFile sRTFFile = GetRTFFile(sFile) print "Saving as RTF..." SaveFile(sFile, sRTFFile, 6) if __name__ == "__main__": if len(sys.argv) > 1: process(sys.argv[1]) else: print usage ## end of code From oplin_eater@yahoo.com Fri Mar 21 06:39:01 2003 From: oplin_eater@yahoo.com (Not Important) Date: Fri Mar 21 06:39:01 2003 Subject: [Tutor] lists and s.split Message-ID: <20030320194338.16452.qmail@web20505.mail.yahoo.com> --0-145160292-1048189418=:16055 Content-Type: text/plain; charset=us-ascii i am trying to create a script that will make dirs for a part of a selected file name using string.split but can only make it work for one file name not many import os import string os.chdir("dir") list = os.listdirs("dir") for name in list dir_name string.split(name " - ")[1] i can only get dir_name to represent on of the file names in directory but i would like it to be a list of all the names how if possible. --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-145160292-1048189418=:16055 Content-Type: text/html; charset=us-ascii

i am trying to create a script that will make dirs for a part of a selected file name using string.split but can only make it work for one file name not many

import os
import string

os.chdir("dir")

list = os.listdirs("dir")

for name in list
    dir_name string.split(name " - ")[1]

i can only get dir_name to represent on of the file names in directory but i would like it to be a list of all the names

how if possible. 



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-145160292-1048189418=:16055-- From reavey@nep.net Fri Mar 21 07:01:02 2003 From: reavey@nep.net (reavey) Date: Fri Mar 21 07:01:02 2003 Subject: [Tutor] pygsear turtle-graphics Message-ID: <3E7AFE35.1070704@nep.net> Hello again, He's a penguin/turtle on steroids. (Great job) I think the problem with the install of pygsear was that I had trouble getting pygame to configure. Perhaps the README could contain an example of how to configure pygame if you are not running a sound card. Show in an example how to read config errors and take care of them by removing their respective flags, in the text file Setup-- found in the pygame directory. The python tutorial in pygsear is excellent. However, I think I might have deleted it as I can't find it in the file structure. I have a hunch it's in there under another name? A pointer would be helpful. TIA re-v From Janssen@rz.uni-frankfurt.de Fri Mar 21 07:09:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Mar 21 07:09:02 2003 Subject: [Tutor] lists and s.split In-Reply-To: <20030320194338.16452.qmail@web20505.mail.yahoo.com> Message-ID: On Thu, 20 Mar 2003, Not Important wrote: > import os > import string > > os.chdir("dir") > > list = os.listdirs("dir") > > for name in list > dir_name string.split(name " - ")[1] > > i can only get dir_name to represent one of the file names in directory but i would like it to be a list of all the names > > how if possible. dir_name_list = [] # create it early, otherwise "+=" won't work for name in list: dir_name_list += string.split(name, "-")[1] NB: [1] takes the *second* split-string. "+=" needs recent version of python, otherwise: dir_name_list = dir_name_list + string.split(name, "-")[1] Michael > > > > --------------------------------- > Do you Yahoo!? > Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! From adamg@mailbox.hu Fri Mar 21 08:07:02 2003 From: adamg@mailbox.hu (Adam Groszer) Date: Fri Mar 21 08:07:02 2003 Subject: [Tutor] How to measure memory usage Message-ID: Dear all, I'd like to measure the memory usage of all objects in python. Or better said, I'd like to know 'how big is my application'. I think I have some problems with memory leaks in my app, this I have to solve. any help is appreciated Adam From missive@hotmail.com Fri Mar 21 09:20:02 2003 From: missive@hotmail.com (Lee Harr) Date: Fri Mar 21 09:20:02 2003 Subject: [Tutor] Re: pygsear turtle-graphics Message-ID: >He's a penguin/turtle on steroids. (Great job) > Thanks :o) >I think the problem with the install of pygsear was that I had trouble >getting pygame to configure. Perhaps the README could contain an example >of how to configure pygame if you >are not running a sound card. Show in an example how to read config >errors and take care of them by removing their respective flags, in >the >text file Setup-- found in the pygame directory. I think installing software is still very tricky. I don't have a soundcard either, but I never had any problem with that.... I use the FreeBSD port, though, which really makes it pretty easy. >The python tutorial in pygsear is excellent. However, I think I might >have deleted it as I can't >find it in the file structure. I have a hunch it's in there under >another name? A pointer would be helpful. > Actually, the book is not included with pygsear. I think there is a link to it in the docs though. I have been considering including snapshots of the book, but it is under very active development, so I am not sure I am ready to do that yet. pygsear: http://www.nongnu.org/pygsear/ the book (Start Programming): http://staff.easthighschool.net/lee/computers/book/ _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From shalehperry@attbi.com Fri Mar 21 10:01:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri Mar 21 10:01:02 2003 Subject: [Tutor] lists and s.split In-Reply-To: References: Message-ID: <200303210700.21113.shalehperry@attbi.com> On Friday 21 March 2003 04:07, Michael Janssen wrote: > > "+=3D" needs recent version of python, otherwise: > dir_name_list =3D dir_name_list + string.split(name, "-")[1] > or use dir_name_list.append(string.split(name, "-")[1]) which is perhaps = more=20 efficient. From bgailer@alum.rpi.edu Fri Mar 21 10:16:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Fri Mar 21 10:16:01 2003 Subject: [Tutor] Automating MSWord (error if run from command line; no error if ru n within PythonWin) In-Reply-To: <0F757892D113D611BD2E0002559C1FF40300BAB0@email.spitech.com > Message-ID: <5.2.0.9.0.20030321080238.02809e58@66.28.54.253> --=======22BE3BCE======= Content-Type: text/plain; x-avg-checked=avg-ok-1A195FEA; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 02:06 PM 3/21/2003 +0800, Ezequiel, Justin wrote: >I am getting the following message when running my program from the >command line (X:\>python DelStyles.py jd002790.doc). >The program runs file under PythonWin (Ctrl-R)! >I am using Python 2.2.2 on WinXP Service Pack 1. >I've installed py2exe-0.3.3.win32-py2.2.exe and win32all-152.exe in that >order, if it matters. >Ultimately, I would like to package my program using py2exe. >I can attach the entire program if you like (104 lines). >Thanks in advance. > >Processing jd002790.doc >Saving as RTF... >Traceback (most recent call last): > File "DelStyles.py", line 101, in ? > process(sys.argv[1]) > File "DelStyles.py", line 90, in process > SaveFile(sFile, sRTFFile, 6) > File "DelStyles.py", line 82, in SaveFile > doc = win32com.client.GetObject(sOldFile) > File "D:\PYTHON22\lib\site-packages\win32com\client\__init__.py", line > 73, in >GetObject > return Moniker(Pathname, clsctx) > File "D:\PYTHON22\lib\site-packages\win32com\client\__init__.py", line > 89, in >Moniker > dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch) >pywintypes.com_error: (-2147287038, 'STG_E_FILENOTFOUND', None, None) >>> doc = win32com.client.GetObject(sOldFile) works for me if I provide the entire path name. Otherwise I get a VARIETY of errors depending on the value. Other interesting things happen with doc: the document opened by GetObject is not visible (Word 2000). >>> doc.application.visible 1 >>> doc.application.visible=1 After this the document IS visible! but its name is NOT in the title bar! Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======22BE3BCE======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1A195FEA Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======22BE3BCE=======-- From bgailer@alum.rpi.edu Fri Mar 21 10:25:15 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Fri Mar 21 10:25:15 2003 Subject: [Tutor] TKinter display dialog 2nd time? In-Reply-To: <20030321065250.GA1551@hooloovoo> References: <5.2.0.9.0.20030320172604.0378aae8@66.28.54.253> <5.2.0.9.0.20030320172604.0378aae8@66.28.54.253> Message-ID: <5.2.0.9.0.20030321082404.0373a9d0@66.28.54.253> --=======57C67FFD======= Content-Type: text/plain; x-avg-checked=avg-ok-1A195FEA; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 07:52 AM 3/21/2003 +0100, Abel Daniel wrote: >import Tkinter >import tkMessageBox > >root_window=Tkinter.Tk() >root_window.withdraw() Thanks. That does it and advances my understanding of TKinter. Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======57C67FFD======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1A195FEA Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======57C67FFD=======-- From Janssen@rz.uni-frankfurt.de Fri Mar 21 10:45:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Mar 21 10:45:02 2003 Subject: [Tutor] lists and s.split In-Reply-To: <200303210700.21113.shalehperry@attbi.com> Message-ID: On Fri, 21 Mar 2003, Sean 'Shaleh' Perry wrote: > On Friday 21 March 2003 04:07, Michael Janssen wrote: > > > > "+=" needs recent version of python, otherwise: > > dir_name_list = dir_name_list + string.split(name, "-")[1] > > > > or use dir_name_list.append(string.split(name, "-")[1]) which is perhaps more > efficient. of course. I must have dreaming. My version would generate a new list every time. append works on the same list. Michael From vicki@stanfield.net Fri Mar 21 12:04:23 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Fri Mar 21 12:04:23 2003 Subject: [Tutor] Program style Message-ID: <20030321090316.12422.h015.c000.wm@mail.stanfield.net.criticalpath.net> This is a multi-part message in MIME format... ------------=_1048266195-12422-0 Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: binary I have a program which I have begun writing, and the code works but is not in appropriate OOP format (or doesn't seem to be). I am new to writing Python and OOP, having written C programs and the like for several years. If any of you experienced Python programmers could take a quick look and advise me on how to get this program into the appropriate style/format before it gets so large that it is a major job to revamp it, I would greatly appreciate it. --vicki P.S. I would like to create an __init__ function and change the root stuff to self. Should this whole thing be a class? ------------=_1048266195-12422-0 Content-Type: text/plain; name="ComTool.py" Content-Disposition: attachment; filename="ComTool.py" Content-Transfer-Encoding: 7bit # File: ComTool.py import Tkinter import serial, stdio, os, sys, string #Creates a callback shim based on code by Scott David Daniels class SimpleCallback: def __init__(self, callback, *firstArgs): self.__callback = callback self.__firstArgs = firstArgs def __call__(self, *args): return self.__callback (*(self.__firstArgs + args)) def NewCallback(): print "Hit new callback." def OpenCallback(): print "Hit open callback." def HelpCallback(): Helpwindow = Tkinter.Toplevel(root) Tkinter.Message(Helpwindow, background='White',text_color='DarkBlue',text= "You're beyond help!").pack() def AboutCallback(): Pmw.aboutversion('0.1') Pmw.aboutcopyright('Copyright Roche Diagnostics 2003\nAll rights reserved') Pmw.aboutcontact( 'For information about this application contact:\n' + ' Vicki Stanfield\n' + ' Phone: 317-521-2378 \n' + ' email: vicki.stanfield@roche.com' ) Aboutwindow = Tkinter.Toplevel(root) about = Pmw.AboutDialog(Aboutwindow, applicationname = 'CommTool') about.withdraw() def EntryCallback(entry): value=entry.getvalue() print value if value: SendCommand(value) def SendCommand(command): for command in ('\x09','\x06'): port = serial.Serial(0, 9600, 8, 'N', 2, timeout=2) port.write(command) old=outputbox.getvalue() new=string.join([old, hex(ord(command))]) outputbox.setvalue(new) input=port.read() print input if input: returnedval=hex(ord(input)) if returnedval: print returnedval old=outputbox.getvalue() new=string.join([old, returnedval]) outputbox.setvalue(new) port.close() def CommandCallback(self): string=(Pmw.ScrolledListBox.getcurselection(self))[0] if string: print string SendCommand(string) def ReadAndClearStatus(): port = serial.Serial(0, 9600, 8, 'N', 2, timeout=2) list="'\x09', 2, 2, '\x06', '\x15'" port.write(list) input=port.read() if input: print hex(ord(input)) port.close() def ExitCallback(): sys.exit(1) #if __name__ == '__main__': # import sys # compare(sys.argv[1], sys.argv[2]) root=Tkinter.Tk() root.title('SSS Communication Tool') import Pmw Pmw.initialise(root) #stdio.setup_stdout() #f = open('ComToolOutput', 'w') #sys.stdout.redirect(f) #stdio.setup_stdin() #sys.stdin.redirect(f) # create a menu menu=Tkinter.Menu(root) root.config(menu=menu) Filemenu = Tkinter.Menu(menu) menu.add_cascade(label="File", menu=Filemenu) Filemenu.add_command(label="New", command=NewCallback) Filemenu.add_command(label="Open...", command=OpenCallback) Filemenu.add_separator() Filemenu.add_command(label="Exit", command=ExitCallback) Helpmenu = Tkinter.Menu(menu) menu.add_cascade(label="Help", menu=Helpmenu) Helpmenu.add_command(label="Help...", command=HelpCallback) Helpmenu.add_command(label="About...", command=AboutCallback) Frame1=Tkinter.Frame(root) Frame1.pack() Frame2=Tkinter.Frame(Frame1) Frame2.pack() # Create the Command Window. outputbox=Pmw.ScrolledText(Frame2, labelpos = 'n', label_text = 'Command Window', vscrollmode='static') outputbox.pack(padx = 38, pady = 38) outputbox.setvalue('test') entry = Pmw.EntryField(Frame2, label_text='Enter command:',labelpos='w') callback=SimpleCallback(EntryCallback,entry) entry.configure(command=callback) entry.pack(pady=25) separator1 = Tkinter.Frame(relief="ridge", height=4, bg="darkgrey") separator1.pack(padx=5, pady=5) Frame3=Tkinter.Frame(Frame1) Frame3.pack() Listbox1=Pmw.ScrolledListBox(Frame3, listbox_height = 5,labelpos='w',label_text='Select Command', items=("06", "09", "10", "1D", "5A", "0B", "58", "43", "49", "53", "0C", "60", "61", "4D", "57", "56", "11")) callback=SimpleCallback(CommandCallback,Listbox1) Listbox1.configure(selectioncommand=callback) Listbox1.pack(padx=20) Pmw.alignlabels([entry,Listbox1]) Tkinter.mainloop() ------------=_1048266195-12422-0-- From dyoo@hkn.eecs.berkeley.edu Fri Mar 21 12:17:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 21 12:17:01 2003 Subject: [Tutor] Automating MSWord (error if run from command line; no error if ru n within PythonWin) In-Reply-To: <0F757892D113D611BD2E0002559C1FF40301F5A9@email.spitech.com> Message-ID: On Fri, 21 Mar 2003, Ezequiel, Justin wrote: > I am attaching a trimmed-down version of my code. > I am using MS Word XP, Win XP, Python 2.2.2. > Works from within PythonWin but not from the command prompt. > > > X:\>python forPost.py omc00055.doc > Processing omc00055.doc > Saving as RTF... > Traceback (most recent call last): > File "forPost.py", line 29, in ? > process(sys.argv[1]) > File "forPost.py", line 25, in process > SaveFile(sFile, sRTFFile, 6) > File "forPost.py", line 17, in SaveFile > doc = win32com.client.GetObject(sOldFile) > File "D:\PYTHON22\lib\site-packages\win32com\client\__init__.py", line 73, in > GetObject > return Moniker(Pathname, clsctx) > File "D:\PYTHON22\lib\site-packages\win32com\client\__init__.py", line 89, in > Moniker > dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch) > pywintypes.com_error: (-2147287038, 'STG_E_FILENOTFOUND', None, None) Hi Justin, I'm not too familiar with the win32 API, but the error message is saying that it's having a hard time finding the 'omc00055.doc' file. Are you sure it's located at 'X:\omc00055.doc'? We can add a small check in the code to see if it can find the source file before letting Word get at it: ### def process(sFile): """Reads a Microsoft Word document, and writes it as RTF.""" print "Processing", sFile sRTFFile = GetRTFFile(sFile) if os.path.isfile(sFile): print "Saving as RTF..." SaveFile(sFile, sRTFFile, 6) else: print "I can't find the file", os.path.abspath(sFile) ### The extra code checks to see if the file can be accessed by Python; if not, at least we'll know that it's a path problem, and not something more sinister. *grin* Good luck! From Janssen@rz.uni-frankfurt.de Fri Mar 21 12:33:26 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Mar 21 12:33:26 2003 Subject: [Tutor] Program style In-Reply-To: <20030321090316.12422.h015.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: On Fri, 21 Mar 2003 vicki@stanfield.net wrote: > I have a program which I have begun writing, > and the code works but is not in appropriate OOP format > (or doesn't seem to be). I am new to writing Python and > OOP, having written C programs and the like for several > years. If any of you experienced Python programmers > could take a quick look and advise me on how to get > this program into the appropriate style/format > before it gets so large that it is a major job to > revamp it, I would greatly appreciate it. I'm not in GUI-Programming and not that much OOP but you have done two *evil* things ;-) * do not mix tabs and spaces for indentation. Do not mix four spaces indentation with eigth spaces (I can't even fix this with emacs). * please, when you need some non standart modules (serial, stdio and Pnm are non standart for my python) give the novice user a hint, where those modules reside. The rest *looks* good to me (until line 80): In python you needn't stuff anything into OOP structures (you can mix OOP and functional programming). Michael > > --vicki > > P.S. I would like to create an __init__ function and > change the root stuff to self. Should this whole thing > be a class? From reggie@merfinllc.com Fri Mar 21 13:12:01 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Fri Mar 21 13:12:01 2003 Subject: [Tutor] ipconfig on a MacOS X In-Reply-To: <5EC16D9A-5B6D-11D7-A250-000A9575F08A@virketis.com> References: <5EC16D9A-5B6D-11D7-A250-000A9575F08A@virketis.com> Message-ID: <1048270208.1543.11.camel@pika.merfinllc.com> In answer to your first question, you can use os.popen: >>> import os >>> ip = os.popen("ipconfig getifaddr en0").read() >>> print ip os.popen returns a file object which, in this case, I simply read into ip. This should work in any version of python. As to the "split" you mention, I know nothing about the Mac, but I do know that David Beazley noted in his book "Python Essential Reference" (excellent reference book, by the way) that os.system is only available on UNIX and Windows. On Thu, 2003-03-20 at 23:18, Pijus Virketis wrote: > So, I would like to ask two questions: how do I grab the output in > terminal Python? And, how do I accomplish the whole task in MacPython? > How come there is this schizophrenic split between the two Pythons? (I > guess that's a third question, we can all fondly remember the Spanish > Inquisition at this point :)). > > Thank you! > > Pijus -- Reggie From charlie@begeistert.org Fri Mar 21 15:28:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Mar 21 15:28:02 2003 Subject: [Tutor] Re: Tutor digest, Vol 1 #2327 - 10 msgs In-Reply-To: <20030321170010.15214.64243.Mailman@mail.python.org> References: <20030321170010.15214.64243.Mailman@mail.python.org> Message-ID: <20030321212836.3172.6@wonderland.1048243135.fake> On 2003-03-21 at 18:00:10 [+0100], tutor-request@python.org wrote: > i am trying to create a script that will make dirs for a part of a > selected file name using string.split but can only make it work for one > file name not many > > import os > import string > > os.chdir("dir") > > list = os.listdirs("dir") > > for name in list > dir_name string.split(name " - ")[1] > > i can only get dir_name to represent on of the file names in directory > but i would like it to be a list of all the names > > how if possible. First of all "list" is a reserved word in Python: use it to turn other objects into lists: $ python Python 2.1.2 (#1, Jan 26 2002, 03:26:04) [GCC 2.9-beos-991026] on beos5 Type "copyright", "credits" or "license" for more information. >>> s = "hi" >>> list(s) ['h', 'i'] >>> You can overwrite this if you want to with Python complaining but it's important to be aware of. "dir" is also a built-in function for inspecting objects and finding out what you can do with them: >>> dir("hi") ['capitalize', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper'] >>> Michael has already pointed out that strings now have methods (these were introduced with Python 1.6 / Python 2.0 at the same time as incremental additional "+=") and the string module will become obsolete as some point so it's probably better to ignore it now. Bearing these things in mind. filenames = os.listdir("my_dir") dir_list = [] for filename in filenames: dir_list.append(filename.split("-")[1]) I'll leave to the gurus to explain the difference between list.append() and "+=" but I think you should in general use append(). Furthermore you might want to study os, and os.path more closely as they have lots of very useful functions. Charlie From ATrautman@perryjudds.com Fri Mar 21 16:47:01 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Fri Mar 21 16:47:01 2003 Subject: [Tutor] How to measure memory usage Message-ID: <06738462136C054B8F8872D69DA140DB010715@corp-exch-1.perryjudds.com> Adam, As far as I can tell unless you are writing you own C++ functions or are using a specific C function that is not normally used a memory leak the lasts a significant amount of time (caused by a delayed garbage collection (could be Java term sneaking in?)) is very difficult. Since you cannot access the heap directly in Python barring the above exceptions any memory watcher will do. The one that comes with all forms of windoze included. There are several for BSD and Linux on source forge. If you wrote you own C/C++ function test with this function only again because Python will use garbage collection on itself. I did a quick check of the bug lists and found nothing in the core libraries that should cause a problem. But you might want to search for specific libraries. Instead I would build a helper application that monitors and counts object instantiation and removal and part of the constructor and destructor of you project you may find your problem that way. HTH, Alan -----Original Message----- From: Adam Groszer [mailto:adamg@mailbox.hu] Sent: Friday, March 21, 2003 7:06 AM To: Tutor@python.org Subject: [Tutor] How to measure memory usage Dear all, I'd like to measure the memory usage of all objects in python. Or better said, I'd like to know 'how big is my application'. I think I have some problems with memory leaks in my app, this I have to solve. any help is appreciated Adam _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From bgailer@alum.rpi.edu Fri Mar 21 17:36:49 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Fri Mar 21 17:36:49 2003 Subject: [Tutor] (no subject) In-Reply-To: Message-ID: <5.2.0.9.0.20030317173215.019f6548@66.28.54.253> --=======412C12B1======= Content-Type: text/plain; x-avg-checked=avg-ok-30CD20FC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 04:49 PM 3/15/2003 +0000, Ian shaw wrote: >I would like a demonstration on computer programming. >Thank you. For a modest fee we could get some activists to march on Redmond, WA. Perhaps flag waving and candle burning, or flag burning and candle waving. Demand that Bill Gates tear down the walls that isolate MS from its dependents. Seriously, could you expand on what you want. If you're looking for Python Tutorials, go to http://www.python.org/doc/Newbies.html and follow the tutorial links. Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======412C12B1======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-30CD20FC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.459 / Virus Database: 258 - Release Date: 2/25/2003 --=======412C12B1=======-- From srobb@insightbb.com Fri Mar 21 17:37:02 2003 From: srobb@insightbb.com (Steve @ Home) Date: Fri Mar 21 17:37:02 2003 Subject: [Tutor] Question on twisted. References: <20030318170008.21106.94487.Mailman@mail.python.org> Message-ID: <000b01c2ed90$b1a2b860$c779dd0c@insightbb.com> I am attempting to look at twisted. So far, it looks good. Very, very, good. I have a problem with it though. I ran the telnet app via the 'twistd' utility successfully. As I read further there was a new example of how to kick off the telnet server from within your preferred Python editor. It reads as follows... CHAPTER 2. THE BASICS 30 Python 1.5.2 (#0, Dec 27 2000, 13:59:38) [GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> import sys >>> sys.path.append('/twisted/Twisted') The text - ( I installed Twisted in /twisted, so the place where my 'twisted' package directory is at is /twisted/Twisted/twisted The text - ( (confusing, I know). For Python to nd the 'twisted' package, it must have the directory containing the package in The text - ( sys.path O which is why I added /twisted/Twisted. >>> from twisted.internet import app, tcp >>> from twisted.protocols import telnet >>> application = app.Application('telnet') >>> ts = telnet.ShellFactory() >>> application.listenTCP(4040, ts) The text - ( The above is basically what mktap telnet does. First we create a new Twisted Application, we create a new The text - ( telnet Shell Factory, and we tell the application to listen on TCP port 4040 with the ShellFactory we've created. The text - ( Now let's start the application. This causes all ports on the application to start listening for incoming connections. The text - ( This step is basically what the 'twistd' utility does. >>> application.run() twisted.protocols.telnet.ShellFactory starting on 4040 The text - ( You now have a functioning telnet server! You can connect with your telnet program and work with it just the The text - ( same as you did before. When you're done using the telnet server, you can switch back to your python console and hit The text - ( ctrl-C. All of this was going along fine. Then from the line ts = telnet.ShellFactory() , I get an error. When I type this line in my interpreter I get the following... ts = telnet.Shell.Factory() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'Shell' Up until then it was running through as documented. I would like to get this working but can't quite figure out what my trouble is. The telnet server worked perfect when I ran it from the utility. Any suggestions or is anyone familiar with twisted? OS Win9x Python 2.2 Pythonwin win32all build 150 Twisted Win binaries (downloaded today) Steve From Lucid Drake Fri Mar 21 17:37:16 2003 From: Lucid Drake (Lucid Drake) Date: Fri Mar 21 17:37:16 2003 Subject: [Tutor] Try/Except, A better way? Message-ID: <129369769875.20030318160244@escex.com> I currently use a few Try/Except clauses in my programming and was hoping to find a better way to do certain things. For instance, if I need to check if someone is in a database, I run a select statement asking for her, if she is there I update, if she isn't there, I insert. Like so... try: # select * from user where id = # update user set ... where id = except: # insert into user ... I've noticed that the try/except clauses cause me problems later on when I'm changing code around and debugging by not logging the errors. Is this a simple matter of declaring the error types in the except clauses, instead of catching all errors? How appropriate is this type of coding? Would it be more appropriate to query for the user and use an if/else statement? (i don't do this now because it's slower) Thanks, --Lucid From BAlmond@russreid.com Fri Mar 21 18:11:10 2003 From: BAlmond@russreid.com (Brian Almond) Date: Fri Mar 21 18:11:10 2003 Subject: [Tutor] Try/Except, A better way? Message-ID: >>> Lucid Drake 03/18/03 04:02PM >>> I currently use a few Try/Except clauses in my programming and was hoping to find a better way to do certain things. [snip] [Disclaimer: I'm by no means an expert at Python exceptions, and welcome any comments on this...] I'd argue that in a database programming context that the additional overhead of an if/else clause or two is insignificant. Additionally, I'd probably wrap up your application's standard DB operations in function calls (and DB stored procedures if supported by your DB). Finally, make the code inside each try: clause as atomic as possible. This should make it easier to identify the source of problems. Note, however, that this will only help if you strive to avoid blanket except clauses. -- Brian Almond From jeff@ccvcorp.com Fri Mar 21 18:32:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Mar 21 18:32:01 2003 Subject: [Tutor] Try/Except, A better way? References: <129369769875.20030318160244@escex.com> Message-ID: <3E7BA136.3020202@ccvcorp.com> Lucid Drake wrote: >I currently use a few Try/Except clauses in my programming and was >hoping to find a better way to do certain things. > >For instance, if I need to check if someone is in a database, I run a >select statement asking for her, if she is there I update, >if she isn't there, I insert. > >Like so... > >try: > # select * from user where id = > > # update user set ... where id = > >except: > # insert into user ... > >I've noticed that the try/except clauses cause me problems later on >when I'm changing code around and debugging by not logging the errors. > >Is this a simple matter of declaring the error types in the except >clauses, instead of catching all errors? > >How appropriate is this type of coding? > Yes, it should be a simple matter of declaring the error types. You can even have different responses to different exceptions: try: [...] except NotFoundError: [....] except DatabaseAccessError: [....] This is perfectly appropriate coding, providing that your code throws appropriate exceptions. One of the Python mantras is "It's easier to ask forgiveness than permission" -- that's exactly what you're doing here. Just remember, when you're catching exceptions, to be as specific as possible so that you're not catching unexpected exceptions with code that's designed to handle only a specific type of error. (I agree with the other respondent that the speed of try/except vs. if/else is very unlikely to be a significant consideration, but I think that a properly specific try/except is a very good way of handling this sort of situation.) Jeff Shannon Technician/Programmer Credit International From bh-wages@swbell.net Fri Mar 21 18:39:04 2003 From: bh-wages@swbell.net (Billie) Date: Fri Mar 21 18:39:04 2003 Subject: [Tutor] New to tutor References: <20030318170008.21106.94487.Mailman@mail.python.org> <000b01c2ed90$b1a2b860$c779dd0c@insightbb.com> Message-ID: <095201c2f003$0c13af60$7840fea9@BillieWages> This is a multi-part message in MIME format. ------=_NextPart_000_094E_01C2EFD0.C09BB0A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hello. I just recently found out about python, and am beginning to get started on learning it. I did BASIC programming waaay back in the 80's, and am really looking forward to learning this language. Are there any lesson plans anywhere? Books? I've been on the list and receiving mail, but haven't actually gotten started yet due to illness. This appears to me to be a very helping group, and I'm sure I'm going to have questions and need help. Billie ------=_NextPart_000_094E_01C2EFD0.C09BB0A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hello.
 
I just recently found out about python, and = am=20 beginning to get started on learning it.  I did BASIC programming = waaay=20 back in the 80's, and am really looking forward to learning this=20 language.
 
Are there any lesson plans anywhere?  = Books? =20 I've been on the list and receiving mail, but haven't actually gotten = started=20 yet due to illness.  This appears to me to be a very helping group, = and I'm=20 sure I'm going to have questions and need help.
 
Billie
------=_NextPart_000_094E_01C2EFD0.C09BB0A0-- From Janssen@rz.uni-frankfurt.de Fri Mar 21 18:47:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Mar 21 18:47:01 2003 Subject: [Tutor] Try/Except, A better way? In-Reply-To: <129369769875.20030318160244@escex.com> Message-ID: On Tue, 18 Mar 2003, Lucid Drake wrote: > try: > # select * from user where id = > > # update user set ... where id = > > except: > # insert into user ... > > I've noticed that the try/except clauses cause me problems later on > when I'm changing code around and debugging by not logging the errors. > > Is this a simple matter of declaring the error types in the except > clauses, instead of catching all errors? strongly recommended. For best result with "try/except" strategie you should narrow the try-statements to smallest necessary: otherwise you might catch an exception that was raised by a part of the code, you doesn't thought of, even if you give an error type. I don't know if database-queries provide a finegraded set of error types. Therefore you probably should avoid "trying" two queries in one step. But I can't determine the reason, why you have first to "select" and than to "update". > How appropriate is this type of coding? > > Would it be more appropriate to query for the user and use an > if/else statement? (i don't do this now because it's slower) Both approaches are valuable. Since try/except could send you into hard to debug "wrong-error-caught-bugs", if/else might be your first try. But sometimes it's "Easier to Ask Forgivenes than Permission": In case the check that next operation is allowed costs time or many typing or readability try/except comes in handy. Also, in many cases it's very easy to make shure, that the try statement(s) can only throw a distinct error. If/else, on the other hand, can be insufficient in some/ many situations. It depends on the details of your code, what's best. Python Cookbook recipe 5.3 tells (a bit) more. On a sidenote: It's not best to choose the algorithem first by runtime than by how stable or just readable it is. Better the other way round: In case you got two stable implementations you can choose by runtime (optimizing runtime against maturity is worth only for throw-away skripts; the programmer always in sight ;-). Michael > > Thanks, > --Lucid > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo@hkn.eecs.berkeley.edu Fri Mar 21 18:50:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 21 18:50:02 2003 Subject: [Tutor] New to tutor In-Reply-To: <095201c2f003$0c13af60$7840fea9@BillieWages> Message-ID: On Fri, 21 Mar 2003, Billie wrote: > I just recently found out about python, and am beginning to get started > on learning it. I did BASIC programming waaay back in the 80's, and am > really looking forward to learning this language. Hi Billie, 10 PRINT "Very cool; I have somewhat fond memories reading introductory" 15 PRINT "BASIC tutorials. I've been told that BASIC is brain-damaging," 20 PRINT "but I think I turned out ok." > Are there any lesson plans anywhere? Books? Yes, there are quite a few that you can browse through. Mark Pilgrim makes his extensive "Dive into Python" tutorial available online: http://www.diveintopython.org/ It's professionally written, and a very good book. If you want to read shorter tutorials, the Python.org web site hosts links to several of them here: http://python.org/doc/Newbies.html And if you're looking for lesson plans, the Livewires educational group has written one for their computer programming camp, and have made their materials available online: http://www.livewires.org.uk/python/ Because Livewires was designed for young readers as its target audience, the Livewires tutorial is very oriented on concrete examples (tic-tac-toe game, designing Spacewar, etc.), and I find it very fun to read. > I've been on the list and receiving mail, but haven't actually gotten > started yet due to illness. This appears to me to be a very helping > group, and I'm sure I'm going to have questions and need help. You are always welcome to ask questions; be prepared, though, for a slew of responses. *grin* We'll do our best of help. Good luck to you! From wolf_binary@hotmail.com Fri Mar 21 19:09:01 2003 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Fri Mar 21 19:09:01 2003 Subject: [Tutor] New to tutor Message-ID: Go to Alan Guald's website or buy his book that is based on his website. I'm not sure what level you're at as a programmer, but I started there and it was a great place to find out about the language from a beginner's stand point. Here is his website book: http://www.freenetpages.co.uk/hp/alan.gauld/ I thought it was pretty help full. Go here for the book lists or go to Amazon and type in Python: http://www.python.org/cgi-bin/moinmoin/PythonBooks HTH, Cameron Stoner >From: "Billie" >To: >Subject: [Tutor] New to tutor >Date: Fri, 21 Mar 2003 17:38:58 -0600 > >Hello. > >I just recently found out about python, and am beginning to get started on >learning it. I did BASIC programming waaay back in the 80's, and am really >looking forward to learning this language. > >Are there any lesson plans anywhere? Books? I've been on the list and >receiving mail, but haven't actually gotten started yet due to illness. >This appears to me to be a very helping group, and I'm sure I'm going to >have questions and need help. > >Billie _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From Bryan.Weingarten@watchguard.com Fri Mar 21 19:33:02 2003 From: Bryan.Weingarten@watchguard.com (Bryan Weingarten) Date: Fri Mar 21 19:33:02 2003 Subject: [Tutor] Defining Python class methods in C Message-ID: can someone please help me with this? there is this cookbook recipe that shows how to make a class type in c. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/54352 what this recipe doesn't show is exactly how to instantiate one of these objects in c (not python) and call the __init__ method. obviously you first call initFoo(), but then what?does anyone know how to do this? =20 thanks, bryan From charlie@begeistert.org Fri Mar 21 19:35:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Mar 21 19:35:02 2003 Subject: [Tutor] Try/Except, A better way? In-Reply-To: <20030321233904.18585.52291.Mailman@mail.python.org> References: <20030321233904.18585.52291.Mailman@mail.python.org> Message-ID: <20030322013611.3996.2@wonderland.1048291771.fake> On 2003-03-22 at 00:39:04 [+0100], tutor-request@python.org wrote: > I currently use a few Try/Except clauses in my programming and was hoping > to find a better way to do certain things. Jeff has already pointed out the importance of defining specific exceptions to raise and check for. I'm surprised he didn't mention dispatching dictionaries at the same time as he's expert at it and dispatching is a good alternative to if/elif/if or try/except. In Python you can use dictionaries to store conditions and function calls. >>> d = {'a': print "a", 'b': print "b"} >>> d = {'a': print_a, 'b': print_b} >>> d['a'] >>> d['a']() Sorry for the over-simplification but others are better at this than I. You can use it like this, however assuming "x" is your condition try d[x](): pass except KeyError: print "forgot about this one" It makes your code shorter and easier to maintain and once easier to understand it, once you've got it. Personally I'm still learning dispatching thanx to this list. Charlie From missive@hotmail.com Fri Mar 21 19:59:01 2003 From: missive@hotmail.com (Lee Harr) Date: Fri Mar 21 19:59:01 2003 Subject: [Tutor] Re: Question on twisted. Message-ID: >All of this was going along fine. Then from the line >ts = telnet.ShellFactory() , I get an error. >When I type this line in my interpreter I get the following... > >ts = telnet.Shell.Factory() Is this what you typed? It is not the same as above... ShallFactory vs Shell.Factory _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From charlie@begeistert.org Fri Mar 21 20:19:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Mar 21 20:19:01 2003 Subject: [Tutor] Re: Tutor digest, Vol 1 #2328 - 13 msgs In-Reply-To: <20030321233904.18585.52291.Mailman@mail.python.org> References: <20030321233904.18585.52291.Mailman@mail.python.org> Message-ID: <20030322022031.4574.3@wonderland.1048291771.fake> On 2003-03-22 at 00:39:04 [+0100], tutor-request@python.org wrote: > I have a program which I have begun writing, > and the code works but is not in appropriate OOP format (or doesn't seem > to be). I am new to writing Python and OOP, having written C programs and > the like for several years. If any of you experienced Python programmers > could take a quick look and advise me on how to get this program into the > appropriate style/format > before it gets so large that it is a major job to > revamp it, I would greatly appreciate it. Hi Vicki, I don't count among "great programmers of our time" and OOP isn't something I'm very good at but I hope the following comments are useful. "input" is a reserved word in Python so it's best not to use it unless you have a good reason. Python won't complain but it might confuse people who read your code later. "src" is shorter anyway ;-) I think this whole thing should be a class or a module. In Python it won't make any difference when you call it but I imagine you might want to pack more of such classes in a single module. You should learn to use """ long strings""" instead of concatenation. I think you should also peruse the suggested syntax rules on Python.org; I find your source somewhat inconsistent re. capitalising or use of "_" to name functions and variables. I also note that you want to "print" lots of variables before you check for them. Why do you "print" rather than "return"? This may well lead to several errors at once making it harder to find them. def SendCommand(command): for command in ('\x09','\x06'): port = serial.Serial(0, 9600, 8, 'N', 2, timeout=2) port.write(command) old=outputbox.getvalue() # where does outputbox come from? new=string.join([old, hex(ord(command))]) outputbox.setvalue(new) # this might cause an error due to scope input=port.read() print input if input: returnedval=hex(ord(input)) if returnedval: print returnedval old=outputbox.getvalue() new=string.join([old, returnedval]) outputbox.setvalue(new) port.close() I don't know what outputbox is but you might get an error doing something to it within a function when you haven't explicitly passed it into that function. I'd be tempted to rewrite this: src = self.port.read() if src: print src val = hex(ord(src)) if val: print val old = outputbox.getvalue() new = "".join([old, val]) outputbox.setvalue(new) self.port.close() Checking twice first for "src" and then for "val" seems wrong to me. I'd favour src = self.port.read() try: val = hex(ord(src)) old = outputbox.getvalue() new = "".join([old, val]) outputbox.setvalue(new) # shouldn't this be returned? return src, val except Error, msg return msg, "something went wrong" self.port.close() Note that I've adjusted your syntax to make it more Pythony. Reviewing the first part of this function/method suggests further improvements are possible, ie. assigning "old", creating "new", assigning outputbox. I see that you define "port" the same in two separate functions. This is a nopey no as it means "copy + paste" to change it. I think this another reason for using a class. This is untested and subject to correction by gurus. class Callback: def port(self): return serial.Serial(0, 9600, 8, 'N', 2, timeout=2) def SendCommand(self, command): for command in ('\x09','\x06'): myport = self.port() def ReadAndClearStatus(self): myport = self.port() I hope this helps. Charlie From j.ezequiel@spitech.com Fri Mar 21 20:38:01 2003 From: j.ezequiel@spitech.com (Ezequiel, Justin) Date: Fri Mar 21 20:38:01 2003 Subject: [Tutor] Automating MSWord (error if run from command line; no error if ru n within PythonWin) Message-ID: <0F757892D113D611BD2E0002559C1FF40301FBE9@email.spitech.com> Thanks lots Danny! ##This did the trick: sFile = os.path.abspath(sFile) What I am now wondering is why the following did not work without that line when the files are all in the same folder X:\>python forPost.py omc00055.doc note that the isfile() check returned true before the call to abspath() ##final code: def process(sFile): if os.path.isfile(sFile): sFile = os.path.abspath(sFile) print "Processing", sFile sRTFFile = GetRTFFile(sFile) print "Saving as RTF..." SaveFile(sFile, sRTFFile, 6) if processRTF(sRTFFile): print "Saving as DOC..." SaveFile(sRTFFile, sFile, 0) print "Made changes to", sFile else: print "No changes made to", sFile os.remove(sRTFFile) else: print "Cannot find", sFile From j.ezequiel@spitech.com Fri Mar 21 20:42:01 2003 From: j.ezequiel@spitech.com (Ezequiel, Justin) Date: Fri Mar 21 20:42:01 2003 Subject: [Tutor] Automating MSWord (error if run from command line; no error if ru n within PythonWin) Message-ID: <0F757892D113D611BD2E0002559C1FF40301FBEF@email.spitech.com> Thanks Bob! >>> doc = win32com.client.GetObject(sOldFile) works for me if I provide the entire path name. Otherwise I get a VARIETY of errors depending on the value. I put a call to os.path.abspath() and everything works just fine! >>>Other interesting things happen with doc: the document opened by GetObject is not visible (Word 2000) For this particular script, I do not want the document visible but it is always good to know these things in case I do. From pytutor" Hi everybody, I am a graphics programmer. I have worked on opengl and have written few experimental graphics programs. i want to do the same using python. can u tell me how python stands vis-a-vis other graphics language like opengl/java/vrml etc etc. one of the graphics has an animated lever experiment for kids that shows the force/fulcrum/load relationships. which python package/library should i use? the library should have 2D/3D objects;animations;text display;maths;linux compatible;portable;free. Thanx, shalabh. Get Your Private, Free E-mail from Indiatimes at http://email.indiatimes.com Buy the best in Movies at http://www.videos.indiatimes.com Bid for for Air Tickets @ Re.1 on Air Sahara Flights. Just log on to http://airsahara.indiatimes.com and Bid Now! From dman@dman.ddts.net Sat Mar 22 00:23:02 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sat Mar 22 00:23:02 2003 Subject: [Tutor] Re: setting EOF symbol In-Reply-To: <465CE444-56B1-11D7-9086-000A9575F08A@virketis.com> References: <465CE444-56B1-11D7-9086-000A9575F08A@virketis.com> Message-ID: <20030322052355.GA31740@dman.ddts.net> --PNTmBPCT7hxwcZjr Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, Mar 14, 2003 at 10:42:22PM -0800, Pijus Virketis wrote: | while lr: | print(lr.readline()) For those who didn't notice, this is a C++-idiom. In C++, an istream will evaluate to false when no more data can be read from it. -D --=20 In my Father's house are many rooms; if it were not so, I would have told you. I am going there to prepare a place for you. And if I go and prepare a place for you, I will come and take you to be with me that you also may be where I am. John 14:2-3 =20 http://dman.ddts.net/~dman/ --PNTmBPCT7hxwcZjr Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj5782sACgkQO8l8XBKTpRRCDACglS82JMyx/ZNraXLkom0TPzXs Z9AAnRLXTffJdxhe/eBD2qSzcS+zVJpw =TqYJ -----END PGP SIGNATURE----- --PNTmBPCT7hxwcZjr-- From pijus@virketis.com Sat Mar 22 00:55:02 2003 From: pijus@virketis.com (Pijus Virketis) Date: Sat Mar 22 00:55:02 2003 Subject: [Tutor] ipconfig on a MacOS X In-Reply-To: <1048270208.1543.11.camel@pika.merfinllc.com> Message-ID: <29F912C9-5C44-11D7-ABC7-000A9575F08A@virketis.com> Reggie, Thank you for your pointer. As it happens, MacPython os module does not seem to have popen() either. But the terminal Python does, and I successfully wrote my script the way you suggested. I would still love to hear from someone wiser in the ways of the Mac OS X what the equivalent approach to executing system calls is from MacPython. -P On Friday, March 21, 2003, at 10:10 AM, Reggie Dugard wrote: > In answer to your first question, you can use os.popen: > >>>> import os >>>> ip = os.popen("ipconfig getifaddr en0").read() >>>> print ip > > os.popen returns a file object which, in this case, I simply read into > ip. This should work in any version of python. As to the "split" you > mention, I know nothing about the Mac, but I do know that David Beazley > noted in his book "Python Essential Reference" (excellent reference > book, by the way) that os.system is only available on UNIX and Windows. > > On Thu, 2003-03-20 at 23:18, Pijus Virketis wrote: > >> So, I would like to ask two questions: how do I grab the output in >> terminal Python? And, how do I accomplish the whole task in MacPython? >> How come there is this schizophrenic split between the two Pythons? (I >> guess that's a third question, we can all fondly remember the Spanish >> Inquisition at this point :)). >> >> Thank you! >> >> Pijus > > -- > Reggie > > From afterimage@gmx.net Sat Mar 22 02:31:02 2003 From: afterimage@gmx.net (Kristian Rink) Date: Sat Mar 22 02:31:02 2003 Subject: [Tutor] rfc822.Message In-Reply-To: <1047913587.25959.6.camel@pika.merfinllc.com> References: <20030315232421.255b9b6a.afterimage@gmx.net> <1047913587.25959.6.camel@pika.merfinllc.com> Message-ID: <20030322082405.64037bc1.afterimage@gmx.net> Hi, Reggie et al,... ..at first, let me say thank you for all the hints / messages I got on this topic; I'm thankful for both having recieved a solution for my initial problem and some interesting things to look at for future tasks which I will be about to do... On 17 Mar 2003 07:06:27 -0800 Reggie Dugard wrote: > I believe the problem you're having is that the rfc822.Message > constructor expects an instance of a file object and not a > filename. If you try something like the following I think you'll > have better luck. >=20 > >>> mailmessage=3Drfc822.Message(open("2")) This is what exactly fixed my problems, so things are working fine now. :) Have a nice weekend wherever you are, Kris --=20 F=FCr Freiheit und die Wahrung demokratischer Grundrechte im=20 Informationszeitalter - gegen Zensur, Manipulation und digitale Entm=FCndigung. Sch=FCtze Deine Rechte - sag _DEINE_ Meinung!=20 --------------- http://www.stop1984.org ---------------------- From afterimage@gmx.net Sat Mar 22 02:34:02 2003 From: afterimage@gmx.net (Kristian Rink) Date: Sat Mar 22 02:34:02 2003 Subject: [Tutor] New to tutor In-Reply-To: <095201c2f003$0c13af60$7840fea9@BillieWages> References: <20030318170008.21106.94487.Mailman@mail.python.org> <000b01c2ed90$b1a2b860$c779dd0c@insightbb.com> <095201c2f003$0c13af60$7840fea9@BillieWages> Message-ID: <20030322082814.43e2cf8d.afterimage@gmx.net> Hi Billie,... On Fri, 21 Mar 2003 17:38:58 -0600 "Billie" wrote: > I just recently found out about python, and am beginning to get > started on learning it. I did BASIC programming waaay back in the > 80's, and am really looking forward to learning this language. Hmmm, remembering pretty well this one on my good old C-64: 10 PRINT "HELLO WORLD" 20 GOTO 10 :] > Are there any lesson plans anywhere? Books? I've been on the > list and receiving mail, but haven't actually gotten started yet A good book I spent quite some time with both reading and playing with the examples IMHO is this one: http://www.ibiblio.org/obp/thinkCSpy/ I dealt with this quite some time earlier trying to get a clue what "object orientation" in languages is about, and this one was pretty helpful. I think it's a good start for both learning programming _and_ Python. :) Cheers, Kris --=20 F=FCr Freiheit und die Wahrung demokratischer Grundrechte im=20 Informationszeitalter - gegen Zensur, Manipulation und digitale Entm=FCndigung. Sch=FCtze Deine Rechte - sag _DEINE_ Meinung!=20 --------------- http://www.stop1984.org ---------------------- From a_abdi406@yahoo.com Sat Mar 22 08:38:01 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Sat Mar 22 08:38:01 2003 Subject: [Tutor] help of Regular expressions Message-ID: <20030322133714.20785.qmail@web14502.mail.yahoo.com> --0-1656330472-1048340234=:20546 Content-Type: text/plain; charset=us-ascii Can anyone help me setting up some regular expressions for the following 1. a conditioned word my intention is to capture the middle tokens(a,conditioned,word) leaving untouched both "", and there more than one pattern of this in the text that I am dealing with I want to capture them all( .........EQN/> ) . what I will do after capturing is to tag token... another words here is what i will do after capturing a conditioned word the inital and the last tag remained unchanged --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1656330472-1048340234=:20546 Content-Type: text/html; charset=us-ascii

Can anyone help me setting up some regular expressions for the following

1. <EQN/> a conditioned word <EQN/>

my intention is to capture the middle tokens(a,conditioned,word) leaving untouched both "<EQN/>", and there more than one pattern of this in the text that I am dealing with I want to capture them all( <EQN/> .........EQN/> ) . what I will do after capturing is to tag <W> token</W>... another words here is what  i will do after capturing

<EQN/> <W>a<W> <W>conditioned</W> <W>word</W><EQN/>

the inital and the last tag remained unchanged



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1656330472-1048340234=:20546-- From antonmuhin at rambler.ru" References: <20030322133714.20785.qmail@web14502.mail.yahoo.com> Message-ID: <712341896.20030322165257@rambler.ru> Hello Abdirizak, Saturday, March 22, 2003, 4:37:14 PM, you wrote: Aa> Can anyone help me setting up some regular expressions for the following Aa> 1. a conditioned word Aa> my intention is to capture the middle tokens(a,conditioned,word) leaving untouched both "", and there more than one pattern of this in the text that I am dealing with I want to capture them Aa> all( .........EQN/> ) . what I will do after capturing is to tag token... another words here is what i will do after capturing Aa> a conditioned word Aa> the inital and the last tag remained unchanged Aa> --------------------------------- Aa> Do you Yahoo!? Aa> Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! Try this: r"(?<=).*?(?=)" or r"(?:)(?P.*?)(?:)" The first matches a little bit more than you might need. The second one seems ok. BTW, if you're parsing HTML, you might better resort to HTML tools, not regexps. -- Best regards, anton mailto:antonmuhin@rambler.ru From highend@malwasandres.de Sat Mar 22 09:49:01 2003 From: highend@malwasandres.de (Stefan Stammberger) Date: Sat Mar 22 09:49:01 2003 Subject: [Tutor] List problem Message-ID: <3E7C7843.2040200@malwasandres.de> Hello, I wrote a little script that reads info from a file and converts it into another (OK at the moment it just reads but everything else will come :P). But I have a little problem. I have two numbers first = 0.697 second = 4.02 first + second = 4.717 when i print out the summ of the two normaly it really prints out 4.717. But when i assign it into a list my sum suddenly changes into 4.7169999999999996. Anybody has a idea? Am I overlooking something here? Thank you! And sorry for my bad english :) From stever@insightbb.com Sat Mar 22 10:02:01 2003 From: stever@insightbb.com (Steve Robb) Date: Sat Mar 22 10:02:01 2003 Subject: [Tutor] Re: Tutor digest, Vol 1 #2329 - 17 msgs In-Reply-To: <20030322133801.5839.36912.Mailman@mail.python.org> References: <20030322133801.5839.36912.Mailman@mail.python.org> Message-ID: <3E7C7AE1.7040209@insightbb.com> > > >Message: 6 >From: "Lee Harr" >To: tutor@python.org >Date: Sat, 22 Mar 2003 00:58:17 +0000 >Subject: [Tutor] Re: Question on twisted. > > > >>All of this was going along fine. Then from the line >>ts = telnet.ShellFactory() , I get an error. >>When I type this line in my interpreter I get the following... >> >>ts = telnet.Shell.Factory() >> >> > >Is this what you typed? It is not the same as above... > >ShallFactory vs Shell.Factory > > >_________________________________________________________________ > > Sorry for the typo. I actually tried it every different way I could think of at one point or another. Here is the documented error listing for both of these possibilities. >>> ts = telnet.ShellFactory() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'ShellFactory' >>> ts = telnet.Shell.Factory() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'Shell' Thanks for replying. Steve From a_abdi406@yahoo.com Sat Mar 22 10:40:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Sat Mar 22 10:40:02 2003 Subject: [Tutor] about regular expression Message-ID: <20030322153912.3519.qmail@web14508.mail.yahoo.com> --0-1009596418-1048347552=:3501 Content-Type: multipart/alternative; boundary="0-2055281175-1048347552=:3501" --0-2055281175-1048347552=:3501 Content-Type: text/plain; charset=us-ascii Hi everyone Thanks anton for your help. I am working on program that incorporates multiple regular expressions: consider that I have tha following : exp_token = re.compile(r""" ([-a-zA-Z0-9_]+| # for charcterset [\"\'.\(),:!\?]| # symbol chracters .*?) """, re.VERBOSE ) the first two work fine for my program, I am having a problem from the third.*?) which I want to parse this pattern Dagan et al. 1993 due to the first two regular expresions the program is tokenising this way REF SELF ' YES ' Daganet al . 1993 REF instead of this Dagan et al. 1993 incase some one wants to help nad have a look my progaram is attached with this e-mail to see what I am trying to achieve. thanks in advance. --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-2055281175-1048347552=:3501 Content-Type: text/html; charset=us-ascii

Hi everyone

Thanks anton for your help.

I am working on program that incorporates multiple regular expressions: consider that I have tha following :

exp_token = re.compile(r"""
               ([-a-zA-Z0-9_]+|   # for charcterset
               [\"\'.\(),:!\?]|    # symbol chracters
              <REF SELF='YES'>.*?</REF>)    
               """, re.VERBOSE )

the first two work fine for my program, I am having a problem from the third<REF SELF='YES'>.*?</REF>)     

which I want to parse this pattern <REF SELF='YES'>Dagan et al. 1993</REF>
due to the first two regular expresions  the program is tokenising this way     

<W>REF</W>
<W>SELF</W>
<W>'</W>
<W>YES</W>
<W>'</W>
<W>Dagan</W
<W>et</W>
<W>al</W>
<W>.</W>
<W>1993</W>
<W>REF</W>

instead of this    <W> <REF SELF='YES'>Dagan et al. 1993</REF> </W> incase some one wants to help nad have a look my progaram is attached with this e-mail to see what I am trying to achieve.

thanks in advance.



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-2055281175-1048347552=:3501-- --0-1009596418-1048347552=:3501 Content-Type: text/plain; name="Ass-01.py" Content-Description: Ass-01.py Content-Disposition: inline; filename="Ass-01.py" import re def markup(line, tag='W'): """ this function tags and to a text """ exp_token = re.compile(r""" ([-a-zA-Z0-9_]+| # for charcterset [\"\'.\(),:!\?]| # symbol chracters (?<=).*?(?=)| #matches < .*?) """, re.VERBOSE ) spacing = " " result = [] #call all the matching regular expression token_list = exp_token.findall(line) for token in token_list: #for testing purposes print '<%s>%s%s' %(tag,token,tag,spacing) result.append('<%s>%s%s' %(tag,token,tag,spacing) ) return result #--------------------------------------------------------------------------- def Process_file(input_file): """ this function takes file input and and process by calling another function called markup() """ token_list = [] #open the file for processing infile = open(input_file) line = infile.readline() #scan and and call markup function to markup while line: token_list += markup(line) line = infile.readline() return token_list #------------------------------------------------------------------------------ #setup a regular expression for pattern matching #first_match = "[a-zA-Z]+" #exp_one = re.compile(r"[a-zA-Z]+") # exp_two = re.compile(r"[a-zA-Z]+\-[a-zA-Z]+") #------------------------------------------------------------------------------ # this function tags every sentence with """ # # get a list of lines removing the leading and trailing lines # lines = text.splitlines(1) # while lines and lines[-1].isspace(): # lines.pop() # while lines and lines[0].isspace(): # lines.pop(0) # # #initialize the line number for display # SenNumb = 0 # #iterate through each sentences and tag it with tags # for i in range(len(lines)): # lines[i] = '<%s%d\'>%s'%(sen_tag,SenNumb,lines[i],theTag) # #increment # SenNumb +=1 # # join the text # text =''.join(lines) # # return text if __name__ == '__main__': import sys for arg in sys.argv[1:]: Process_file(arg) --0-1009596418-1048347552=:3501-- From reavey@nep.net Sat Mar 22 10:44:01 2003 From: reavey@nep.net (reavey) Date: Sat Mar 22 10:44:01 2003 Subject: [Tutor] new to tutor Message-ID: <3E7C83D8.1040208@nep.net> Hi, In response to a question about online tutorials You might take a look at Start Programming for a graphical fun approach. http://www.staff.easthighschool.net/lee/computers/book re-v From selevin@attbi.com Sat Mar 22 11:11:02 2003 From: selevin@attbi.com (selevin) Date: Sat Mar 22 11:11:02 2003 Subject: [Tutor] Remove me please Message-ID: <018a01c2f08d$77d44450$9db3b042@chara> This is a multi-part message in MIME format. ------=_NextPart_000_0187_01C2F063.8EC503E0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable ------=_NextPart_000_0187_01C2F063.8EC503E0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
 
------=_NextPart_000_0187_01C2F063.8EC503E0-- From bgailer@alum.rpi.edu Sat Mar 22 11:42:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Sat Mar 22 11:42:01 2003 Subject: [Tutor] List problem In-Reply-To: <3E7C7843.2040200@malwasandres.de> Message-ID: <5.2.0.9.0.20030322093447.01a00030@66.28.54.253> --=======71D8546======= Content-Type: text/plain; x-avg-checked=avg-ok-1F6F8C2; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:50 PM 3/22/2003 +0100, Stefan Stammberger wrote: >I have two numbers > >first = 0.697 >second = 4.02 >first + second = 4.717 > >when i print out the summ of the two normaly it really prints out 4.717. >But when i assign it into a list my sum suddenly changes into >4.7169999999999996. >Anybody has a idea? Am I overlooking something here? The internal representation of the sum is very close to 4.7169999999999996: >>> first = 0.697;second = 4.02 >>> first + second 4.7169999999999996 Print appears to do a little rounding: >>> print first + second 4.717 Why it behaves differently for the list is a mystery. >And sorry for my bad english :) I enjoy reading your English and appreciate that you are learning it. Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======71D8546======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1F6F8C2 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======71D8546=======-- From bgailer@alum.rpi.edu Sat Mar 22 11:45:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Sat Mar 22 11:45:02 2003 Subject: [Tutor] new to tutor In-Reply-To: <3E7C83D8.1040208@nep.net> Message-ID: <5.2.0.9.0.20030322094406.03747970@66.28.54.253> --=======406710A4======= Content-Type: text/plain; x-avg-checked=avg-ok-1F6F8C2; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 10:40 AM 3/22/2003 -0500, reavey wrote: >Hi, >In response to a question about online tutorials > You might take a look at Start Programming for a graphical fun approach. >http://www.staff.easthighschool.net/lee/computers/book Please note that the link is http://staff.easthighschool.net/lee/computers/book Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======406710A4======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1F6F8C2 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======406710A4=======-- From ahimsa@onetel.net.uk Sat Mar 22 11:58:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Sat Mar 22 11:58:02 2003 Subject: [Tutor] Why error if method __init__ does not return none Message-ID: <200303221653.41190.ahimsa@onetel.net.uk> Hi folks Can someone please give me a quick and dirty sound-byte for why if a=20 constructor (method __init__ ) returns a value other than 'None' it is a= =20 run-time error. What are the mechanics of that method that are so error=20 intolerant? Hope this makes sense as a question. Just haven't come across= =20 anything about this yet. Cheers Andy --=20 "Freedom, Strength, & Quality in Diversity - stop TCPA's hegemony" http://www.againsttcpa.com http://www.againsttcpa.com/tcpa-faq-en.html From bgailer@alum.rpi.edu Sat Mar 22 12:05:05 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Sat Mar 22 12:05:05 2003 Subject: [Tutor] Why error if method __init__ does not return none In-Reply-To: <200303221653.41190.ahimsa@onetel.net.uk> Message-ID: <5.2.0.9.0.20030322095904.0280dab8@66.28.54.253> --=======70C933EA======= Content-Type: text/plain; x-avg-checked=avg-ok-1F6F8C2; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 04:53 PM 3/22/2003 +0000, ahimsa wrote: >why if a constructor (method __init__ ) returns a value other than >'None' it is a >run-time error. class a: def __init__ (self): return None b = a() What is "returned" here is an instance of the class, not what is returned by the __init__ method. I guess that "TypeError: __init__() should return None" is a way of telling you not to return something else with the expectation that it will be available. Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======70C933EA======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1F6F8C2 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======70C933EA=======-- From a_abdi406@yahoo.com Sat Mar 22 13:03:01 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Sat Mar 22 13:03:01 2003 Subject: [Tutor] about regular expression Message-ID: <20030322151009.98346.qmail@web14506.mail.yahoo.com> --0-305104679-1048345809=:96894 Content-Type: multipart/alternative; boundary="0-1779190667-1048345809=:96894" --0-1779190667-1048345809=:96894 Content-Type: text/plain; charset=us-ascii Hi everyone Thanks anton for your help. I am working on program that incorporates multiple regular expressions: consider that I have tha following : exp_token = re.compile(r""" ([-a-zA-Z0-9_]+| # for charcterset [\"\'.\(),:!\?]| # symbol chracters .*?) """, re.VERBOSE ) the first two work fine for my program, I am having a problem from the third.*?) which I want to parse this pattern Dagan et al. 1993 due to the first two regular expresions the program is tokenising this way REF SELF ' YES ' Daganet
al . 1993 REF instead of this Dagan et al. 1993 incase some one wants to help nad have a look my progaram is attached with this e-mail to see what I am trying to achieve. thanks in advance. --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1779190667-1048345809=:96894 Content-Type: text/html; charset=us-ascii

Hi everyone

Thanks anton for your help.

I am working on program that incorporates multiple regular expressions: consider that I have tha following :

exp_token = re.compile(r"""
               ([-a-zA-Z0-9_]+|   # for charcterset
               [\"\'.\(),:!\?]|    # symbol chracters
              <REF SELF='YES'>.*?</REF>)    
               """, re.VERBOSE )

the first two work fine for my program, I am having a problem from the third<REF SELF='YES'>.*?</REF>)     

which I want to parse this pattern <REF SELF='YES'>Dagan et al. 1993</REF>
due to the first two regular expresions  the program is tokenising this way     

<W>REF</W>
<W>SELF</W>
<W>'</W>
<W>YES</W>
<W>'</W>
<W>Dagan</W
<W>et</W>
<W>al</W>
<W>.</W>
<W>1993</W>
<W>REF</W>

instead of this    <W> <REF SELF='YES'>Dagan et al. 1993</REF> </W> incase some one wants to help nad have a look my progaram is attached with this e-mail to see what I am trying to achieve.

thanks in advance.



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1779190667-1048345809=:96894-- --0-305104679-1048345809=:96894 Content-Type: text/plain; name="Ass-01.py" Content-Description: Ass-01.py Content-Disposition: inline; filename="Ass-01.py" import re def markup(line, tag='W'): """ this function tags and to a text """ exp_token = re.compile(r""" ([-a-zA-Z0-9_]+| # for charcterset [\"\'.\(),:!\?]| # symbol chracters .*?) """, re.VERBOSE ) spacing = " " result = [] #call all the matching regular expression token_list = exp_token.findall(line) for token in token_list: #for testing purposes print '<%s>%s%s' %(tag,token,tag,spacing) result.append('<%s>%s%s' %(tag,token,tag,spacing) ) return result #--------------------------------------------------------------------------- def Process_file(input_file): """ this function takes file input and and process by calling another function called markup() """ token_list = [] #open the file for processing infile = open(input_file) line = infile.readline() #scan and and call markup function to markup while line: token_list += markup(line) line = infile.readline() return token_list #------------------------------------------------------------------------------ #setup a regular expression for pattern matching #first_match = "[a-zA-Z]+" #exp_one = re.compile(r"[a-zA-Z]+") # exp_two = re.compile(r"[a-zA-Z]+\-[a-zA-Z]+") #------------------------------------------------------------------------------ # this function tags every sentence with """ # # get a list of lines removing the leading and trailing lines # lines = text.splitlines(1) # while lines and lines[-1].isspace(): # lines.pop() # while lines and lines[0].isspace(): # lines.pop(0) # # #initialize the line number for display # SenNumb = 0 # #iterate through each sentences and tag it with tags # for i in range(len(lines)): # lines[i] = '<%s%d\'>%s'%(sen_tag,SenNumb,lines[i],theTag) # #increment # SenNumb +=1 # # join the text # text =''.join(lines) # # return text if __name__ == '__main__': import sys for arg in sys.argv[1:]: Process_file(arg) --0-305104679-1048345809=:96894-- From antonmuhin at rambler.ru" References: <200303221653.41190.ahimsa@onetel.net.uk> Message-ID: <19224679917.20030322201835@rambler.ru> Hello ahimsa, Saturday, March 22, 2003, 7:53:41 PM, you wrote: a> Hi folks a> Can someone please give me a quick and dirty sound-byte for why if a a> constructor (method __init__ ) returns a value other than 'None' it is a a> run-time error. What are the mechanics of that method that are so error a> intolerant? Hope this makes sense as a question. Just haven't come across a> anything about this yet. a> Cheers a> Andy __init__ as any constructor is rather specific thing. It's not quite a function and shouldn't return any value. Of course, Python might have been more forgiving, butI suppose it'd contradict Zen of Python. -- Best regards, anton mailto:antonmuhin@rambler.ru From bh-wages@swbell.net Sat Mar 22 13:56:03 2003 From: bh-wages@swbell.net (Billie) Date: Sat Mar 22 13:56:03 2003 Subject: [Tutor] new to tutor - thanks References: <5.2.0.9.0.20030322094406.03747970@66.28.54.253> Message-ID: <0a8801c2f0a4$a3e8c900$7840fea9@BillieWages> Thanks for all the support you've given me. I am trying to work learning this in with learning all the new stuff about Paint Shop Pro 8, which utilizes the Python language for writing scripts (same as what was Macros back in the 80's in Word Perfect and LOTUS). Those of you who were "young" in the 80's when the personal computer became easily available to the common person (non-commercial, I guess sounds better :), just do not realize how fortunate you are. I would have given ANYTHING if this had been available to me when I was choosing what to do with my life when I began college in 1960, putting me in my 40's when I got my first taste of the personal computer (already familiar to punch cards in '61). I am an "explorer" by nature, and when I started working for our college in '85 and got to use the computer for the first time, it set me out on an adventure, and the next semester I was taking programming classes - age ---- 42. I took that basic knowledge amd applied it to writing programs in LOTUS for the company I worked for. Then later, I worked as a medical transcriptionist as I approached 50, and programmed macros in Word Perfect, not only for my area in X-ray, but in administration as well. I say all that only to give you an idea of my "forge ahead" mentality that I bring to learning this language, taking it beyond what I need for PSP editing, and teaching users. I'm excited, and am trying to juggle things so I can indulge myself. FWIW, I will be 61 in a few months, and I am disabled and bedridden. I told my doctor last week that I refuse to allow my illnesses clip my wings, though I will have good days and bad days. Again, thanks to all who have responded, and I really look forward to learning and working out the kinks with you all. I've saved all the messages that I've received since I joined to have as a resource. Billie From ahimsa@onetel.net.uk Sat Mar 22 14:14:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Sat Mar 22 14:14:02 2003 Subject: [Tutor] Why error if method __init__ does not return none In-Reply-To: <5.2.0.9.0.20030322095904.0280dab8@66.28.54.253> References: <5.2.0.9.0.20030322095904.0280dab8@66.28.54.253> Message-ID: <200303221913.56977.ahimsa@onetel.net.uk> To explore this a bit and to demonstrate my loss of the plot ... would that mean something like: class 'a' is instantiated and then assign= ed to=20 variable 'b' without 'a' actually calculating/operating on anything, simi= lar=20 to a duplication of a recipe rather than say, the production of a cake wi= th=20 that recipe? If the metaphor isn't stretched too far ... and the return o= f=20 'none' is sort of like a place-holder to not allow that namespace to be b= ound=20 to any other object before an instance of itself is assigned to - here -=20 variable 'b'?=20 Andy On Saturday 22 Mar 2003 5:04 pm, Bob Gailer wrote: > class a: > def __init__ (self): > return None > b =3D a() > > What is "returned" here is an instance of the class, not what is return= ed > by the __init__ method. I guess that "TypeError: __init__() should retu= rn > None" is a way of telling you not to return something else with the > expectation that it will be available. --=20 News from a different perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From Janssen@rz.uni-frankfurt.de Sat Mar 22 14:23:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Mar 22 14:23:02 2003 Subject: [Tutor] about regular expression In-Reply-To: <20030322153912.3519.qmail@web14508.mail.yahoo.com> Message-ID: On Sat, 22 Mar 2003, Abdirizak abdi wrote: > Hi everyone > > Thanks anton for your help. > > I am working on program that incorporates multiple regular expressions: consider that I have tha following : > > exp_token = re.compile(r""" > ([-a-zA-Z0-9_]+| # for charcterset > [\"\'.\(),:!\?]| # symbol chracters > .*?) > """, re.VERBOSE ) this is incorrect: re.VERBOSE *ignores* whitespace (for exceptions compare moduls documentation). ".*?" is getting evaluated and works out. Michael From ahimsa@onetel.net.uk Sat Mar 22 14:24:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Sat Mar 22 14:24:02 2003 Subject: [Tutor] Why error if method __init__ does not return none In-Reply-To: <19224679917.20030322201835@rambler.ru> References: <200303221653.41190.ahimsa@onetel.net.uk> <19224679917.20030322201835@rambler.ru> Message-ID: <200303221927.01560.ahimsa@onetel.net.uk> Hi Anton On Saturday 22 Mar 2003 5:18 pm, antonmuhin at rambler.ru wrote: > Of course, Python might have > been more forgiving, butI suppose it'd contradict Zen of Python. =2E.. as in "Errors should never pass silently"?=20 --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From dyoo@hkn.eecs.berkeley.edu Sat Mar 22 16:06:43 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 22 16:06:43 2003 Subject: [Tutor] Automating MSWord (error if run from command line; no error if ru n within PythonWin) In-Reply-To: <0F757892D113D611BD2E0002559C1FF40301FBE9@email.spitech.com> Message-ID: On Sat, 22 Mar 2003, Ezequiel, Justin wrote: > Thanks lots Danny! > > ##This did the trick: > sFile = os.path.abspath(sFile) > > What I am now wondering is why the following did not work without that > line when the files are all in the same folder Hi Justin, I have to admit complete ignorance on this one. *grin* According to MSDN, GetObject takes in an URL: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/spssdk/html/_getobject_method.asp so perhaps an absolute file name path looks more like an URL than a relative file path. But I feel bad, because I'm just guessing here... *grin* If you have time, can you ask on the Python-win32 list about this one? I'd be interested to hear what the Windows gurus there say about GetObject() and what kind of input it expects to take. Python-win32 can be found here: http://mail.python.org/mailman/listinfo/python-win32 Good luck to you! From dyoo@hkn.eecs.berkeley.edu Sat Mar 22 16:10:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 22 16:10:01 2003 Subject: [Tutor] Remove me please In-Reply-To: <018a01c2f08d$77d44450$9db3b042@chara> Message-ID: On Sat, 22 Mar 2003, selevin wrote: Hi Selevin, You can unsubscribe yourself by visiting that administrative web page that you used to first subscribe to Tutor: http://mail.python.org/mailman/listinfo/tutor If you go down to the bottom of that page, you'll be able to edit your own mailing list options, and this include unsubscription. This system is set up so that you can subscribe and unsubscribe yourself easily. But if you run into problems while unsubscribing, please email us directly at the following address: "tutor-admin@python.org"; that way, the admins can directly attend to you and get things fixed. Good luck to you. From python-list@python.org Sat Mar 22 16:17:58 2003 From: python-list@python.org (Gerrit Holl) Date: Sat Mar 22 16:17:58 2003 Subject: Shouldn't __init__ return self instead of None? (Was: Re: [Tutor] Why error if method __init__ does not return none) In-Reply-To: <5.2.0.9.0.20030322095904.0280dab8@66.28.54.253> References: <200303221653.41190.ahimsa@onetel.net.uk> <5.2.0.9.0.20030322095904.0280dab8@66.28.54.253> Message-ID: <20030322211739.GA3131@nl.linux.org> [FUP: python-list@python.org] Bob Gailer schreef op zaterdag 22 maart om 18:05:29 +0000: > What is "returned" here is an instance of the class, not what is returned > by the __init__ method. I guess that "TypeError: __init__() should return > None" is a way of telling you not to return something else with the > expectation that it will be available. This raises an interesting question. Shouldn't it say: __init__ should return self...? Because _that_ is what it really does... Of course, changing this would break code, but moving towards this might be a good idea...? yours, Gerrit. -- 30. If a chieftain or a man leave his house, garden, and field and hires it out, and some one else takes possession of his house, garden, and field and uses it for three years: if the first owner return and claims his house, garden, and field, it shall not be given to him, but he who has taken possession of it and used it shall continue to use it. -- Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From dyoo@hkn.eecs.berkeley.edu Sat Mar 22 16:22:04 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 22 16:22:04 2003 Subject: [Tutor] graphics in python In-Reply-To: <200303220324.IAA21132@WS0005.indiatimes.com> Message-ID: On Sat, 22 Mar 2003, pytutor wrote: > I am a graphics programmer. I have worked on opengl and have written few > experimental graphics programs. i want to do the same using python. can > u tell me how python stands vis-a-vis other graphics language like > opengl/java/vrml etc etc. Hello! Python and Java are themselves not specialized "graphics" languages --- they're considered general programming languages; they don't have built-in support for anything, but can be extended to many problem domains. OpenGL is a set of functions that can draw graphics, and they're available from a lot of different programming languages --- it's fairly language independent. For example, PyOpenGL compares very favorably to other language bindings for OpenGL: http://pyopengl.sourceforge.net/ But there are other Python programs that try to make 3D programming appealing to new programmers. You may want to look at VPython: http://vpython.org/ > one of the graphics has an animated lever experiment for kids that shows > the force/fulcrum/load relationships. which python package/library > should i use? the library should have 2D/3D objects;animations;text > display;maths;linux compatible;portable;free. Hmmm... ah! Then I highly recommend that you look at VPython! VPython sounds very applicable to your project, and may be what you're looking for. One more project that I'm remember offhand is the Alice project: http://www.alice.org/ which also looks awesome. I wish I had more time to play with these programs! Does anyone have experience with these systems? You may want to ask your question on a general Python forum like the comp.lang.python newsgroup: there are folks there that may be able to give good advice. From dyoo@hkn.eecs.berkeley.edu Sat Mar 22 16:40:10 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 22 16:40:10 2003 Subject: [Tutor] List problem [floating point] In-Reply-To: <5.2.0.9.0.20030322093447.01a00030@66.28.54.253> Message-ID: > At 03:50 PM 3/22/2003 +0100, Stefan Stammberger wrote: > >I have two numbers > > > >first = 0.697 > >second = 4.02 > >first + second = 4.717 > > > >when i print out the summ of the two normaly it really prints out > >4.717. But when i assign it into a list my sum suddenly changes into > >4.7169999999999996. Anybody has a idea? Am I overlooking something > >here? Hi Stefan, Ah! You may want to look at: http://www.python.org/doc/tut/node14.html The official python tutorial explains it better than I ever could. But, as a quick summary: the 'print' statement turns all of its values to strings through the str() function, and str() will fib slightly to be palatable for humans. *grin* It'll do rounding to make the display of numbers easy to read. ### >>> x = 0.1 >>> print x 0.1 >>> print str(x) 0.1 ### On the other hand, if we ask Python to evaluate a value from the interactive prompt, they'll be transformed to a string value using the more accurate repr() function, and repr() is showing us that the system can't represent that floating-point number precisely. ### >>> x 0.10000000000000001 >>> print repr(x) 0.10000000000000001 ### So it actually doesn't have anything to do with lists, except that when we print a list in Python, Python will end up printing the repr()'esentation of each element in the list, and that's why we're seeing so many decimal places. We can make a list of floating-numbers print more nicely by calling str() on each number: ### >>> def printlist(l): ... print map(str, l) ... >>> printlist([x, x+1, x+2]) ['0.1', '1.1', '2.1'] ### This printlist() function might give us slightly more palatable results. If you have more questions, please feel free to ask on Tutor. Good luck! From bgailer@alum.rpi.edu Sat Mar 22 17:45:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Sat Mar 22 17:45:02 2003 Subject: [Tutor] Why error if method __init__ does not return none In-Reply-To: <200303221913.56977.ahimsa@onetel.net.uk> References: <5.2.0.9.0.20030322095904.0280dab8@66.28.54.253> <5.2.0.9.0.20030322095904.0280dab8@66.28.54.253> Message-ID: <5.2.0.9.0.20030322153722.0379ae58@66.28.54.253> --=======174FDF5======= Content-Type: text/plain; x-avg-checked=avg-ok-1F6F8C2; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 07:13 PM 3/22/2003 +0000, ahimsa wrote: >[snips] The init method can contain any Python code you desire; it will execute when you "call the class". It can set instance and class properties, which can be accessed thru the newly created instance. It's just that "Return" in the __init__ method has no place to send to. At 10:17 PM 3/22/2003 +0100, Gerrit Holl wrote: >This raises an interesting question. Shouldn't it say: __init__ should >return self...? Because _that_ is what it really does... Interesting idea. Then it could even return something different, in which case calling the class would be like calling a function. Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======174FDF5======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1F6F8C2 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======174FDF5=======-- From drewp@bigasterisk.com Sat Mar 22 18:36:42 2003 From: drewp@bigasterisk.com (Drew Perttula) Date: Sat Mar 22 18:36:42 2003 Subject: [Tutor] Why error if method __init__ does not return none In-Reply-To: Your message of "Sat, 22 Mar 2003 15:43:57 MST." <5.2.0.9.0.20030322153722.0379ae58@66.28.54.253> Message-ID: <200303222335.h2MNZus01052@bang.houseoflove> > At 10:17 PM 3/22/2003 +0100, Gerrit Holl wrote: > > >This raises an interesting question. Shouldn't it say: __init__ should > >return self...? Because _that_ is what it really does... > > Interesting idea. Then it could even return something different, in which > case calling the class would be like calling a function. > What makes you think __init__ "really" returns self? I'm happy it doesn't, in fact, since the instance is in no way a "product of" __init__. The instance is generated elsewhere, and it's an input to the initializer function. It *could* be an output, but that would be purely for convenience, and I propose that convenience doesn't even help anyone. Another note: class MyClass(Parent1,Parent2): def __init__(self,*args): Parent1.__init__(self,*someargs) Parent2.__init__(self,*otherargs) The latter two calls didn't return anything of interest. They might have returned their self arguments, and I suppose we wouldn't care. (They don't, though.) However, we all know that when I say "m=MyClass()", MyClass returns a new MyClass instance. It is indeed remarkably like calling a function that returns the new instance, although it's not like simply calling the __init__ function. The deliberate function call syntax means that if you wanted to, you could actually swap in a function, and probably no one would notice. -----first version--------------- class LimitedResource: pass lots_of_code_that_uses(LimitedResource) ------next version---------------- class LimitedResource: pass _LimitedResource=LimitedResource # another name for the class- the class's own name is unharmed def LimitedResource(*args): if resources_left(): return _LimitedResource() else: raise "no more resource!" exactly_the_same_code_that_uses(LimitedResource) ----------------------------------- Advanced Python users will remark that the __new__ class method can now be used for these purposes. -Drew From missive@hotmail.com Sat Mar 22 22:13:01 2003 From: missive@hotmail.com (Lee Harr) Date: Sat Mar 22 22:13:01 2003 Subject: [Tutor] Re: Question on twisted. Message-ID: >>>from twisted.internet import app, tcp >>>from twisted.protocols import telnet >>>application = app.Application('telnet') >>>ts = telnet.ShellFactory() >>>application.listenTCP(4040, ts) I tried this and it works just fine. What version of twisted do you have? >>>from twisted.copyright import version >>>version '1.0.1' Maybe just go ahead and install the latest Twisted release with distutils... python setup.py install _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From tony@tcapp.com Sun Mar 23 00:44:02 2003 From: tony@tcapp.com (Tony Cappellini) Date: Sun Mar 23 00:44:02 2003 Subject: [Tutor] problems with pickle Message-ID: <5.1.0.14.0.20030322215226.0491b600@smtp.sbcglobal.net> I keep getting EOFError when I open a file that i saved using pickle. What might cause this problem ? I'm definitely closing the file, after writing it. From a_abdi406@yahoo.com Sun Mar 23 00:59:01 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Sun Mar 23 00:59:01 2003 Subject: [Tutor] about python function +reg expression Message-ID: <20030323055801.44205.qmail@web14505.mail.yahoo.com> --0-1284257744-1048399081=:41886 Content-Type: multipart/alternative; boundary="0-1748435489-1048399081=:41886" --0-1748435489-1048399081=:41886 Content-Type: text/plain; charset=us-ascii hi everyone, I am working on a fucnction that does the following: the function takes a string as follows: what it is in here and first it filters to get the middle part of the string: as follows:--- what it is in here--- and then I want to tag each token as follows: what it is in here and finally it returns: what it is in here My problem: I am filtering a string by using regular expression which below from : what it is in here to : what it is in here Regular expression result: >>> >>> >>> import re >>> test = ' of a conditioned word ' >>> text =re.compile(r"(?<=).*?(?=)") >>> X = text.findall(test) >>> print X [' of a conditioned word '] ---> it extracts what I want that is fine my problem is how can I manipulate this so that I have a list to manipulate such as this [ 'of' ', 'a','conditioned', 'word' ] so that I tag with .... by using a loop as mentioned above: I have also attached the EQNfunc.py with this e-mail for reference X.split() doesn't work simply thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1748435489-1048399081=:41886 Content-Type: text/html; charset=us-ascii

hi everyone,

I am working on a fucnction that does the following:
   the function takes a string as follows:
       <EQN/>what it is in here<EQN/>   and
       first it filters to get the middle part of the string:
      as follows:---  what it is in here--- and then I want to tag each token
      as follows:
      <W>what</W> <W>it</W> <W>is</W> <W>in</W> <W>here</W>
      and finally it returns:
      <EQN/> <W>what</W> <W>it</W> <W>is</W> <W>in</W> <W>here</W> <EQN/>
   My problem:

 I am filtering a string by using regular expression which below

from : <EQN/> what it is in here <EQN/> 
to    :    what it is in here   

Regular expression result:

>>>
>>>
>>> import re
>>> test = '<EQN/> of a conditioned word <EQN/> '
>>> text =re.compile(r"(?<=<EQN/>).*?(?=<EQN/>)")
>>> X = text.findall(test)
>>> print X
[' of a conditioned word '] ---> it extracts what I want that is fine

my problem is how can I manipulate this so that I have a list to manipulate such as this   [ 'of' ', 'a','conditioned', 'word' ] so that I tag with <W>....</W> by using a loop as mentioned above:

I have also attached the EQNfunc.py with this e-mail for reference

X.split()  doesn't work simply

thanks in advance



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1748435489-1048399081=:41886-- --0-1284257744-1048399081=:41886 Content-Type: text/plain; name="EQNfunc.py" Content-Description: EQNfunc.py Content-Disposition: inline; filename="EQNfunc.py" import re def EQNfunc(text1): """ this function takes a string as follows: what it is in here and first it filters to get the middle part of the string: as follows:--- what it is in here--- and then it tags with each token with as follows: what it is in here """ initial_tag = "" spacing = " " tag_W = "W" #print text1 # for test buf = re.compile(r"(?<=).*?(?=)") #temp = buf.findall(text1) #temp = X.split() for i in range(0,len(temp),1): temp = buf.findall(buf) print temp temp[i] = '<%s>%s%s' %(tag_W,temp[i],tag_W,spacing) # join the text #joined_text =''.join(temp) last_result = initial_tag + str(temp) + initial_tag return last_result #------------------------------------------- test = ' of a conditioned word ' # buf = re.compile(r"(?<=).*?(?=)") # X = buf.findall(test) Y = EQNfunc(test) print Y --0-1284257744-1048399081=:41886-- From tony@tcapp.com Sun Mar 23 01:54:01 2003 From: tony@tcapp.com (Tony Cappellini) Date: Sun Mar 23 01:54:01 2003 Subject: [Tutor] problem with pickle using binary mode - re-submission (was problems with pickle) Message-ID: <5.1.0.14.0.20030322230045.0491c4b8@tcapp.com> I keep getting EOFError when I open a file that i saved using pickle. It turns out that if use binary mode when I pickle the file, I get the EOF error when loading it back in. However, if i use text mode, I don' tave this problem. The file is less than 1000 bytes. I'm running Windows 2000, and Python 2.2.2 Is this a known issue with binary mode, or am I doing something wrong ? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From a_abdi406@yahoo.com Sun Mar 23 04:40:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Sun Mar 23 04:40:02 2003 Subject: [Tutor] about python program Message-ID: <20030323093935.20633.qmail@web14509.mail.yahoo.com> --0-1635122931-1048412375=:19279 Content-Type: text/plain; charset=us-ascii Hi everyone, I really need some help, I am working on program that tokinzes a string and the program captures various patterns and I want to process each pattern separatelyby using some other functions to extract some information and format for display, I amusing conditional statement to evaluate the begining of each pattern and then call a function to process and display. I am trying to use a built-in-function startwith()but it is giving me an error message which is like this: File "Ass-002.py", line 65, in markup if token.startswith(""): ttributeError: 'tuple' object has no attribute 'startswith' here is the program: def markup(line, tag='W'): """ this function tags and to a text """ exp_token = re.compile(r""" ([-a-zA-Z0-9_]+| # for charcterset [\"\'.\(),:!\?]| # symbol chracters (?:)(?P.*?)(?:)| #matches < .*?) """, re.VERBOSE ) spacing = " " result = [] #call all the matching regular expression token_list = exp_token.findall(line) for token in token_list: evaluate each token as you go and call the appropriate function if token.startswith(" "): empty_str = empty_string(token) result.append(empty_str) if token.startswith(""): EQN_result = EQNfunc(token) result.append(EQN_result) print result.append(text1) #for testing purposes else: print "error:", token #print '<%s>%s%s' %(tag,token,tag,spacing) #result.append('<%s>%s%s' %(tag,token,tag,spacing) ) thanks in advance return result --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1635122931-1048412375=:19279 Content-Type: text/html; charset=us-ascii

Hi everyone,

I really need some help,  I am working on program that tokinzes a string and the program captures various patterns and I want to process each pattern separatelyby using some other functions to extract some information and format for display, I amusing conditional statement to evaluate the begining of each pattern and then call a function  to process and display. I am trying to use a built-in-function startwith()but it is giving me an error message which is like this:

 File "Ass-002.py", line 65, in markup
 if token.startswith("<EQN/>"):
ttributeError: 'tuple' object has no attribute 'startswith'

here is the program:

def markup(line, tag='W'):
   """ this function tags <w> and </w> to a text """

   exp_token = re.compile(r"""
               ([-a-zA-Z0-9_]+|   # for charcterset
               [\"\'.\(),:!\?]|    # symbol chracters
               (?:<EQN/>)(?P<text>.*?)(?:<EQN/>)| #matches <
              <REF SELF='YES'>.*?</REF>)    
               """, re.VERBOSE )
   spacing = " "
   result  = []

   #call all the matching regular expression

   token_list = exp_token.findall(line)
   for token in token_list:
       evaluate each token as you go and call the appropriate function
       if  token.startswith(" "):
          empty_str = empty_string(token)
          result.append(empty_str)
      
       if token.startswith("<EQN/>"):
           EQN_result = EQNfunc(token)
           result.append(EQN_result)
           print
           result.append(text1)
       #for testing purposes
       else:
           print "error:", token
         
       #print '<%s>%s</%s>%s' %(tag,token,tag,spacing)
       #result.append('<%s>%s</%s>%s' %(tag,token,tag,spacing) )
     

 

thanks in advance
   return result



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1635122931-1048412375=:19279-- From Janssen@rz.uni-frankfurt.de Sun Mar 23 04:50:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sun Mar 23 04:50:02 2003 Subject: [Tutor] problem with pickle using binary mode - re-submission (was problems with pickle) In-Reply-To: <5.1.0.14.0.20030322230045.0491c4b8@tcapp.com> Message-ID: On Sat, 22 Mar 2003, Tony Cappellini wrote: > > > I keep getting EOFError when I open a file that i saved using pickle. > > It turns out that if use binary mode when I pickle the file, I get the EOF > error when loading it back in. > However, if i use text mode, I don' tave this problem. > > The file is less than 1000 bytes. > > I'm running Windows 2000, and Python 2.2.2 on Windows you must open the file in "binary" mode: "rb" and "wb" other wise the OS will turn the newline-or-whatsever into whatsever-else-i-have-forgotten. Socalled "binary" mode for "file/ open" builtin surpresses this implicit newline conversion. Michel > > Is this a known issue with binary mode, or am I doing something wrong ? > > > > > _______________________________________________ > 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 Janssen@rz.uni-frankfurt.de Sun Mar 23 05:08:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sun Mar 23 05:08:02 2003 Subject: [Tutor] about python program In-Reply-To: <20030323093935.20633.qmail@web14509.mail.yahoo.com> Message-ID: On Sun, 23 Mar 2003, Abdirizak abdi wrote: > > Hi everyone, > > I really need some help, I am working on program that tokinzes a you can help yourself, by print all tokens before processen. Python print statement is clever enough to print many kind of data including tuples and you will see which results from your regexp are delivered as tuple ("named group" as an indication :-) compare the Libary for the syntax and meaning of grouping parens "()" ). Michael PS: please make shure, that the traceback is from the same code you send to us. Your code would have triggered that error already in line: if token.startswith(" "): (unless something very strange is going on). Otherwise we lost time while checking if something very strange is going on ;-) > string and the program captures various patterns and I want to process > each pattern separatelyby using some other functions to extract some > information and format for display, I amusing conditional statement to > evaluate the begining of each pattern and then call a function to > process and display. I am trying to use a built-in-function > startwith()but it is giving me an error message which is like this: > > File "Ass-002.py", line 65, in markup > if token.startswith(""): > ttributeError: 'tuple' object has no attribute 'startswith' > > here is the program: > > def markup(line, tag='W'): > """ this function tags and to a text """ > > exp_token = re.compile(r""" > ([-a-zA-Z0-9_]+| # for charcterset > [\"\'.\(),:!\?]| # symbol chracters > (?:)(?P.*?)(?:)| #matches < > .*?) > """, re.VERBOSE ) > spacing = " " > result = [] > > #call all the matching regular expression > > token_list = exp_token.findall(line) > for token in token_list: > evaluate each token as you go and call the appropriate function > if token.startswith(" "): > empty_str = empty_string(token) > result.append(empty_str) > > if token.startswith(""): > EQN_result = EQNfunc(token) > result.append(EQN_result) > print > result.append(text1) > #for testing purposes > else: > print "error:", token > > #print '<%s>%s%s' %(tag,token,tag,spacing) > #result.append('<%s>%s%s' %(tag,token,tag,spacing) ) > > > > > thanks in advance > return result > > > > --------------------------------- > Do you Yahoo!? > Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! From Janssen@rz.uni-frankfurt.de Sun Mar 23 05:33:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sun Mar 23 05:33:01 2003 Subject: [Tutor] about python function +reg expression In-Reply-To: <20030323055801.44205.qmail@web14505.mail.yahoo.com> Message-ID: On Sat, 22 Mar 2003, Abdirizak abdi wrote: > I am working on a fucnction that does the following: > the function takes a string as follows: > what it is in here and > first it filters to get the middle part of the string: > as follows:--- what it is in here--- and then I want to tag each token > as follows: > what it is in here > and finally it returns: > what it is in here your example doesn't say why you split away EQN than split words/ tokens than reattache EQN. Perhaps inbetween are some functions that depends on this behaviour but you will need to boost up my fantasy. Why not split into tokens and conditionally put tags around? > [' of a conditioned word '] ---> it extracts what I want that is fine > > my problem is how can I manipulate this so that I have a list to > manipulate such as this [ 'of' ', 'a','conditioned', 'word' ] so that > I tag with .... by using a loop as mentioned above: > > I have also attached the EQNfunc.py with this e-mail for reference > > X.split() doesn't work simply You're getting empty results, right? One in front and one at the back, right? Due to leading and trailing spaces, isn't it? Check out string.strip . Michael > > thanks in advance > > > > --------------------------------- > Do you Yahoo!? > Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! From op73418@mail.telepac.pt Sun Mar 23 09:21:07 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Mar 23 09:21:07 2003 Subject: Shouldn't __init__ return self instead of None? (Was: Re: [Tutor] Why error if method __init__ does not return none) References: <200303221653.41190.ahimsa@onetel.net.uk> <5.2.0.9.0.20030322095904.0280dab8@66.28.54.253> <20030322211739.GA3131@nl.linux.org> Message-ID: <006f01c2f148$6416f280$d11b0dd5@violante> > [FUP: python-list@python.org] > > Bob Gailer schreef op zaterdag 22 maart om 18:05:29 +0000: > > What is "returned" here is an instance of the class, not what is returned > > by the __init__ method. I guess that "TypeError: __init__() should return > > None" is a way of telling you not to return something else with the > > expectation that it will be available. > > This raises an interesting question. Shouldn't it say: __init__ should > return self...? Because _that_ is what it really does... > > Of course, changing this would break code, but moving towards this might > be a good idea...? > No. __init__ takes the name from initializer: it *initializes* the state of the instance - the instance already exists as a perfectly valid Python object. Returning a *new* instance is for the __new__ magic method (Python >= 2.2) where allocation and such stuff can be taken care of. > yours, > Gerrit. With my best regards, G. Rodrigues From antoneheyward@hotmail.com Sun Mar 23 13:40:08 2003 From: antoneheyward@hotmail.com (antone heyward) Date: Sun Mar 23 13:40:08 2003 Subject: [Tutor] cgi redirection Message-ID: i'm sure this is simple but how can i get my cgi script to rediect to another page? At a certain point i want it to try: whatever then have the exception: redirect to page. This is currently running on IIS but i want it to be able to work on linux also. _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From bobsmith327@hotmail.com Sun Mar 23 16:23:08 2003 From: bobsmith327@hotmail.com (bob smith) Date: Sun Mar 23 16:23:08 2003 Subject: [Tutor] graphics in python Message-ID: Although I'm new to Python myself, I've been looking for ways to do graphics as well. Here are two projects I've found that I'm exploring... A new 3D engine written specifically for use with Python called Soya 3D. It's at: http://oomadness.tuxfamily.org/en/soya/index.html For 2D graphics (and other game related stuff like checking a joystick etc), there's pygame: http://www.pygame.org/ Bob >From: Danny Yoo >To: pytutor >CC: tutor@python.org >Subject: Re: [Tutor] graphics in python >Date: Sat, 22 Mar 2003 13:21:24 -0800 (PST) > > > >On Sat, 22 Mar 2003, pytutor wrote: > > > I am a graphics programmer. I have worked on opengl and have written few > > experimental graphics programs. i want to do the same using python. can > > u tell me how python stands vis-a-vis other graphics language like > > opengl/java/vrml etc etc. > >Hello! > >Python and Java are themselves not specialized "graphics" languages --- >they're considered general programming languages; they don't have built-in >support for anything, but can be extended to many problem domains. > > >OpenGL is a set of functions that can draw graphics, and they're available >from a lot of different programming languages --- it's fairly language >independent. For example, PyOpenGL compares very favorably to other >language bindings for OpenGL: > > http://pyopengl.sourceforge.net/ > > >But there are other Python programs that try to make 3D programming >appealing to new programmers. You may want to look at VPython: > > http://vpython.org/ > > > > one of the graphics has an animated lever experiment for kids that shows > > the force/fulcrum/load relationships. which python package/library > > should i use? the library should have 2D/3D objects;animations;text > > display;maths;linux compatible;portable;free. > >Hmmm... ah! Then I highly recommend that you look at VPython! VPython >sounds very applicable to your project, and may be what you're looking >for. One more project that I'm remember offhand is the Alice project: > > http://www.alice.org/ > >which also looks awesome. I wish I had more time to play with these >programs! Does anyone have experience with these systems? > > >You may want to ask your question on a general Python forum like the >comp.lang.python newsgroup: there are folks there that may be able to give >good advice. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From a_abdi406@yahoo.com Sun Mar 23 20:51:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Sun Mar 23 20:51:02 2003 Subject: [Tutor] about Regular expression Message-ID: <20030324015035.91675.qmail@web14502.mail.yahoo.com> --0-1201731099-1048470635=:91246 Content-Type: text/plain; charset=us-ascii Hi everyone, can anoyone suggest one reg. expression that can match the following tags: Brown et al. 1992 Dagan et al. 1993 is the frequency of and Katz --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1201731099-1048470635=:91246 Content-Type: text/html; charset=us-ascii

Hi everyone,

can anoyone suggest one reg. expression that can match the following

tags:

<REF>Brown et al. 1992</REF>

<REF SELF='YES'>Dagan et al. 1993</REF>

<EQN/> is the frequency of <EQN/>

<CREF/> and <CREF/>

<REFAUTHOR>Katz</REFAUTHOR>



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1201731099-1048470635=:91246-- From j.ezequiel@spitech.com Mon Mar 24 02:20:02 2003 From: j.ezequiel@spitech.com (Ezequiel, Justin) Date: Mon Mar 24 02:20:02 2003 Subject: [Tutor] Automating MSWord (py2exe) Message-ID: <0F757892D113D611BD2E0002559C1FF403053306@email.spitech.com> I hate to be a pain but... I got the program running (thanks to Danny and Bob) on Windows XP with Word XP and also on Windows 98 with Word 97. Had to modify the code a bit though to work on both versions of MS Word. My script works fine when run from the command line on a machine with Python via X:\>Python DelStyles.py myfile.doc However, the script will be used by production people who do not have Python. Our Systems Operations staff would not look too kindly on me if I install Python on production machines. So, I packaged my script as a .EXE file using py2exe (X:\>Python setup.py py2exe). The .EXE file works just fine on my machine on both Windoze versions. However, testing on another machine (Windows NT) without Python got me the following: L:\Util\DelStyles>DelStyles.exe Traceback (most recent call last): File "", line 4, in ? File "imputil.pyc", line 132, in _import_hook File "", line 70, in _finish_import File "imputil.pyc", line 316, in _load_tail File "imputil.pyc", line 271, in _import_one File "", line 128, in _process_result File "win32com\client\__init__.pyc", line 12, in ? File "imputil.pyc", line 93, in _import_hook File "imputil.pyc", line 347, in _do_import File "imputil.pyc", line 271, in _import_one File "", line 128, in _process_result File "win32com\client\dynamic.pyc", line 22, in ? File "imputil.pyc", line 103, in _import_hook File "", line 52, in _import_top_module File "imputil.pyc", line 216, in import_top File "imputil.pyc", line 271, in _import_one File "", line 128, in _process_result File "pythoncom.pyc", line 18, in ? File "pythoncom.pyc", line 10, in __import pywintypes.error: (126, 'LoadLibrary', 'The specified module could not be found. ') code excerpt: import re import sys ##from win32com.client.dynamic import Dispatch import win32com.client.dynamic ## this is line 4! import os usage = """ Usage: python DelStyles.py YourFile.ext """ ## ##body of program not included due to length ## def process(sFile): if os.path.isfile(sFile): sFile = os.path.abspath(sFile) print "Processing", sFile sRTFFile = GetRTFFile(sFile) print "Saving as RTF..." msword = win32com.client.dynamic.Dispatch("Word.Application") SaveFile(msword, sFile, sRTFFile, 6) if processRTF(sRTFFile): print "Saving as DOC..." SaveFile(msword, sRTFFile, sFile, 0) print "Made changes to", sFile else: print "No changes made to", sFile msword.Quit(0) os.remove(sRTFFile) else: print "Cannot find", sFile if __name__ == "__main__": if len(sys.argv) > 1: process(sys.argv[1]) else: print usage BTW, I've used py2exe on another script (that does not use win32com) and have run the created .EXE file on the same test PC (Windows NT) with no problems. That script is actually the 'processRTF(sRTFFile)' part of the above script. From wingnut_nc@hotmail.com Mon Mar 24 10:30:09 2003 From: wingnut_nc@hotmail.com (Pilot Wingnut) Date: Mon Mar 24 10:30:09 2003 Subject: [Tutor] Python book question References: <20030318170008.21106.94487.Mailman@mail.python.org> Message-ID: I've read a review on amazon about a new Python book "The Complete Python Training Course" and it sounds like it covers everything. And I know there are other books out there. Is it even worth it investing in a book ? I'm not much of a book collector or reader, so what you guys suggest ? ***Here's the link to the Amazon site for the above book*** http://www.amazon.com/exec/obidos/tg/detail/-/0130673749/qid=1048519422/sr=1 -1/ref=sr_1_1/102-4716919-1577751?v=glance&s=books >>>>>>Thanks for all your help and TIME >>>>>>>> From ahimsa@onetel.net.uk Mon Mar 24 12:41:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Mon Mar 24 12:41:02 2003 Subject: [Tutor] Question about 'Predicate Methods' Message-ID: <200303241740.56956.ahimsa@onetel.net.uk> Hi all Predicate methods:=20 In Deitel, et al. ("Python: how to program", 2002:233), the concept of=20 'predicate' methods is introduced with reference to access control method= s=20 protecting object's attributes from being 'gotten' at and rendered=20 inconsistent by client code. It is described as a 'read-only' access meth= od=20 that test the validity of a condition. They then go on and discuss 'set' = and=20 'get' (query) methods, and don't mention 'predicate methods' again. I hav= e=20 not been able to find any other references to predicate methods in the=20 Tutorial, aforementioned book, or other tutorials and documents. Could=20 someone point me in the direction of documentation for this method (what = is=20 and how it works), or comment on their own understanding of this term. Thanks Andy --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From ahimsa@onetel.net.uk Mon Mar 24 12:41:57 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Mon Mar 24 12:41:57 2003 Subject: [Tutor] Question about namespace Message-ID: <200303241743.02093.ahimsa@onetel.net.uk> Hi Namespaces:=20 Guido van Rossum defines namespace as a "mapping from names to objects"=20 (Tutorial - Python 2.2.2 :S.9.2 p 54). Would I be correct to think of thi= s as=20 - in Linux-speak - making a symlink that creates a symlink (or=20 'shortcut'/link) between the local reference (the link) and the module or= =20 function itself (the 'target') which 'resides' elsewhere (i.e. has a glob= al=20 scope)? Hence assignment and deletion only add/remove references to that=20 module/function rather than copy/destroy the module/function itself. Does= =20 this similie work? If not, what would be a more appropriate one? Cheers Andy --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From alan.gauld@bt.com Mon Mar 24 12:44:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Mar 24 12:44:02 2003 Subject: [Tutor] Automating MSWord (py2exe) Message-ID: This is not really the answer you are looking for but... > However, the script will be used by production people who do > not have Python. > Our Systems Operations staff would not look too kindly on me > if I install Python on production machines. Have you asked? Do they ban all language engines - eg Perl, VB, Java etc? or is ot just Python? In other words can they be persuaded to install it? > So, I packaged my script as a .EXE file using py2exe While this should work I personally take the approach that if the production platform can't run Python I will use another language which it can run. Could yuou port your code to JScript and run it under WSH for example? JScript is syntactically different but functionally similar to Python IME. (Albeit with more code...) Like I said this doesn't really answer your question just offers some different routes to explore... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From jeff@ccvcorp.com Mon Mar 24 12:50:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Mar 24 12:50:02 2003 Subject: [Tutor] about Regular expression References: <20030324015035.91675.qmail@web14502.mail.yahoo.com> Message-ID: <3E7F4564.7050609@ccvcorp.com> Abdirizak abdi wrote: > Hi everyone, > > can anoyone suggest one reg. expression that can match the following > > tags: > Even if someone is able to come up with a regex that'll match all of those conditions... trying to shoehorn regexes into XML processing is probably not a good idea. Python already comes with some pretty effective HTML/SGML/XML parsers. You'd be better off, in the long run, learning how to use those features, rather than trying to force the issue with regexes, which by their nature are *not* well-suited to XML. (XML is naturally heirarchical, and regexes naturally cannot handle heirarchical data appropriately -- among other things, that requires counting of delimiters, which regexes can't do.) You'll have much better luck if you start off with the right tool for the job. Jeff Shannon Technician/Programmer Credit International From alan.gauld@bt.com Mon Mar 24 12:50:13 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Mar 24 12:50:13 2003 Subject: [Tutor] Python book question Message-ID: > are other books out there. Is it even worth it investing in a book ? > > I'm not much of a book collector or reader, so what you guys suggest ? As an author of one such book I'd say the answer lies in your last comment. If you don't use books much then don't bother. Most of the info you need either comes with Python or is available online. If you are happy reading that way then carry on. My tutor, the official tutor, Dive into Python, the cookbook, the various HowTos and specialist papers etc... Its all there for free, it just needs researching. OTOH If you like the feel of paper and find that easier to read then there are several good books around and a search of the list archives will throw up many suggestions. Whichever you choose remember that reading books is only the first step, try things out, experiment. Its the only way to learn. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From ahimsa@onetel.net.uk Mon Mar 24 13:19:20 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Mon Mar 24 13:19:20 2003 Subject: [Tutor] Python book question In-Reply-To: References: Message-ID: <200303241821.08708.ahimsa@onetel.net.uk> Hi all FWIW, as a Python 'student', I have to agree with Alan's comment (cited=20 below). In the process of trying to learn/teach myself Python, I have fou= nd=20 that I obtain one level of understanding from reading a text and thinking= I=20 understand it, and a fresher, almost more concrete (?) or operational=20 understanding when I then try to (a) put that understanding to the test b= y=20 copying out an example and making it work and (b) taking a basic idea and= =20 playing around with it a bit - include it in a code snippet, or change=20 variables around, or use my own data, etc. It seems until I actually do t= ry=20 the code out my understanding is limited to an abstraction. In short, I c= an=20 vouch for the 'try-it-out-for-yourself' approach: it *does* make a=20 difference. On Monday 24 Mar 2003 5:48 pm, alan.gauld@bt.com wrote: > Whichever you choose remember that reading books is only the first > step, try things out, experiment. Its the only way to learn. --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From dyoo@hkn.eecs.berkeley.edu Mon Mar 24 13:24:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 24 13:24:01 2003 Subject: [Tutor] Question about 'Predicate Methods' In-Reply-To: <200303241740.56956.ahimsa@onetel.net.uk> Message-ID: On Mon, 24 Mar 2003, ahimsa wrote: > In Deitel, et al. ("Python: how to program", 2002:233), the concept of > 'predicate' methods is introduced with reference to access control > methods protecting object's attributes from being 'gotten' at and > rendered inconsistent by client code. It is described as a 'read-only' > access method that test the validity of a condition. A "predicate" is a function that either returns a true or false value, depending on what it's trying to test. Here are some examples of predicates: ### >>> def is_even(x): ... return x % 2 == 0 ... >>> def is_odd(x): ... return not is_even(x) ... >>> is_even(42) 1 >>> is_odd(42) 0 >>> def is_happy(word): ... return word in ('happy', 'blissful', 'bright', 'elysian', ... 'golden', 'halycyon', 'joyful', 'laughing') ... >>> is_happy('me') 0 >>> is_happy('blissful') 1 ### (In the newest versions of Python, the results of the above tests will return the values 'True' and 'False', rather than 1 and 0, so expect to see slightly different displays.) In that sense, a predicate is simply a function that tells us if something is true or not. A predicate method, then, is a method that gives us that true or false value. We often bundle these condition tests into predicates when we want to make the code clearer: we want to often give a concrete name to something that fulfills certain requirements. For example, we might say that a word is "palindromic" if it's spelled forwards and backwards the same: ### # pseudocode, since we haven't really defined is_palindrome() yet... >>> is_palindrome('aba') 1 >>> is_palindrome('rotator') 1 >>> is_palindrome('palindrome') 0 ### So the concept of a predicate --- a boolean function --- isn't really that profound. *grin* Hope this helps! From ahimsa@onetel.net.uk Mon Mar 24 14:43:44 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Mon Mar 24 14:43:44 2003 Subject: [Tutor] Question about 'scopes' Message-ID: <200303241945.24143.ahimsa@onetel.net.uk> Hi (yet again) I'm trying to get my head around certain concepts in Python (and probably= =20 programming more generally), and am finding that I can understand CS=20 terminology when I try and draw a connection between what it refers to an= d my=20 own more familiar frames of reference or conceptual paradigms. Hence, som= e of=20 my recent questions have been about metaphors and similie. Anyway, aside from being verbose, I am also curious as to whether the CS=20 concept of 'scope' can be compared with the biological or cybernetic conc= epts=20 of 'system', or 'domain of reference', in that a scope 'encloses' a=20 particular set of attributes and methods much as a system can be said to=20 'contain' parts. Hence a scope seems quite akin to a 'level' (as in a lev= el=20 of analysis) and comprises namespace references and definitions. Have I got the right end of the stick here? Andy --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From dyoo@hkn.eecs.berkeley.edu Mon Mar 24 14:57:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 24 14:57:01 2003 Subject: [Tutor] Question about 'scopes' In-Reply-To: <200303241945.24143.ahimsa@onetel.net.uk> Message-ID: On Mon, 24 Mar 2003, ahimsa wrote: > Anyway, aside from being verbose, I am also curious as to whether the CS > concept of 'scope' can be compared with the biological or cybernetic > concepts of 'system', or 'domain of reference', in that a scope > 'encloses' a particular set of attributes and methods much as a system > can be said to 'contain' parts. Scope can be thought of as containment. For example, the biological analogy to scope might be to a cell and its membrane. Let's abuse the analogy. Variable names that are local to a function are like enzymes in a cell: the cell membrane localizes the effect of enzymes so that they don't do random things to the whole system, but only within the context of the cell. Likewise, the scope of a function limits the effects of variable names so that we don't effect change globally throughout the system. Some cells do allow controlled input and output through membrane channels, and these channels allow material to flow in and out of the cell in a controlled way. In computer languages, the concept of a return value and input parameters allows us to control the flow of information in and out of a particular function. So it's possible to borrow many of the terms of biology and apply them inappropriately to programming. *grin* Hope this helps! From ATrautman@perryjudds.com Mon Mar 24 15:46:01 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Mon Mar 24 15:46:01 2003 Subject: [Tutor] cgi redirection Message-ID: <06738462136C054B8F8872D69DA140DB010718@corp-exch-1.perryjudds.com> If you are working on IIS and have complete control over the server you can install php which will give you all the redirection commands you would ever need (well as good as the web gets). It also runs quite well on Linux and BSD. Sorry this isn't much help on CGI but I forgot all that as soon as I had mods and active scripting. Good Luck, Alan -----Original Message----- From: antone heyward [mailto:antoneheyward@hotmail.com] Sent: Sunday, March 23, 2003 12:39 PM To: tutor@python.org Subject: [Tutor] cgi redirection i'm sure this is simple but how can i get my cgi script to rediect to another page? At a certain point i want it to try: whatever then have the exception: redirect to page. This is currently running on IIS but i want it to be able to work on linux also. _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Mon Mar 24 17:27:14 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 24 17:27:14 2003 Subject: [Tutor] Question about 'scopes' (fwd) Message-ID: Hi Andy, I will delegate to the main Tutor list --- I'm slightly busy at the moment. It's usually a good idea to do a 'Reply-to-All' so that the main Tutor list is always part of the conversation. This keeps any single person (like me) from being a bottleneck toward your understanding. I'll try to get back to your scope question this evening, but hopefully, someone will get to you before then. *grin* I'm sorry for the nonanswer! ---------- Forwarded message ---------- Date: Mon, 24 Mar 2003 21:00:45 +0000 From: ahimsa To: Danny Yoo Subject: Re: [Tutor] Question about 'scopes' Thanx (once again) Danny So the scope is, in effect, a boundary on what can and cannot be referenced from within a given namespace? On Monday 24 Mar 2003 7:56 pm, Danny Yoo wrote: > Scope can be thought of as containment. For example, the biological > analogy to scope might be to a cell and its membrane. > Let's abuse the analogy. Variable names that are local to a function are > like enzymes in a cell: the cell membrane localizes the effect of enzymes > so that they don't do random things to the whole system, but only within > the context of the cell. Likewise, the scope of a function limits the > effects of variable names so that we don't effect change globally > throughout the system. > Some cells do allow controlled input and output through membrane channels, > and these channels allow material to flow in and out of the cell in a > controlled way. In computer languages, the concept of a return value and > input parameters allows us to control the flow of information in and out > of a particular function. > So it's possible to borrow many of the terms of biology and apply them > inappropriately to programming. *grin* Any little bit of purchase on these concepts is worth having as far as I'm concerned - once I am more comfortable and confident with CS-speak I'll be quite happy to loosen my grip on the more concrete and familiar analogies!!! Thanks Andy -- News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From magnus@thinkware.se Mon Mar 24 20:04:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Mar 24 20:04:02 2003 Subject: [Tutor] Re: cgi redirection In-Reply-To: <20030324170006.11302.25745.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030325015720.034fb6f8@www.thinkware.se> >From: "antone heyward" > >i'm sure this is simple but how can i get my cgi script to rediect to >another page? At a certain point i want it to try: whatever then have the >exception: redirect to page. >This is currently running on IIS but i want it to be able to work on linux >also. I guess something like this would do? url = "web.site.to/redirect/to/" print """Content-Type: text/html If you get stuck on this page, please follow this link """ % (url, url) sys.exit() -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Mon Mar 24 21:10:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Mar 24 21:10:02 2003 Subject: [Tutor] Python book question In-Reply-To: <20030324170006.11302.25745.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030325020515.034f4bb0@www.thinkware.se> At Mon, 24 Mar 2003 10:29:05 -0500, "Pilot Wingnut" wrote: >I've read a review on amazon about a new Python book "The Complete Python >Training Course" and it sounds like it covers everything. And I know there >are other books out there. Is it even worth it investing in a book ? Books are always good investments! Haven't read Deitel though. On a daily basis, I almost exclusively use the standard on-line docs for reference. For learning new fields it might be good to read through a book though. And with a company in a country where taxes are very high, tax deductable books are a cheap way of learning. >I'm not much of a book collector or reader, I am! :) Books are good. Cover your walls with books and you will have better sound and thermal insulation, and you won't have to buy expensive paintings etc. ;) You might also learn something! >so what you guys suggest ? There is no "one size fits all" solution here. People are obviously different. For pure beginners, there are a few options: Learning Python by Lutz & Ascher. ~350 pp. Well liked, but s bit dated? (1999) Covers very little except core python 1.5.2. Any 2nd ed. on the way? Alan Gauld's Learn to Program Using Python. ~270 pp. For complete newbies to programming. Author hangs on this mailing list. There's a lot on his web site. Chris Fehily's "Python Visual Quickstart Guide". ~410 pp. It's also a a beginners book, and it's inexpensive and has a lot of small examples. Also just core language. Finally, there is the paper version of "How to Think Like a Computer Scientist" http://www.ibiblio.org/obp/thinkCSpy/ for a more academic approach. If you want more than just the core language, and have some prior programming skills, some other books are more relevant: A book I just started to read which seems excellent (I already found things I have really missed...) is the Python Cookbook, a very good compilation of the online Python Cookbook at Activestate. Really good! This is much more about learning how to really solve problems with python than about the basics of syntax etc. Besides canned solutions to particular problems it will teach you a lot about how to use Python in a clever way. Hammond & Robinson: Python Programming on Win32 if you want to access Excel etc from python or vice versa. Holden's Python Web Programming (~690) is good if you want something focused on network programming, databases and XML. Harms & McDonald The Quick Python book is also from 1999, but is says more about Jython, GUIs, Windows etc. ~420 pp. I haven't read Wesley Chuns Core Python, but I think it's similar to the Quick Python book. Finally, a more recent book in the same range is Hetland's Practical Python. ~620 pp. I just got it, so I haven't had time to read it yet. It looks good though, and it covers a lot besides the core language: XML, ReportLab, Networking, GUIs etc. I haven't read Alex Martelli's Python in a Nutshell yet, but it's probably good. Some like Lutz: Programming Python, but I don't. I don't have the second edition though, and I'm sure it's better. There's also Brueck & Tanner's Python 2.1 Bible. I got that on CD-ROM with the Zope Bible, but I haven't really read it. It's ~770 pp and covers a wide range. It actually covers some important things I haven't found in other books, like i18n and deployment (distutils, py2exe etc). It also covers interesting things like networking, XML, Extension/Embedding and GUIs with Tkinter and wxPython, but I just browsed it... Beazleys Python Essential Reference is a good book, but it's really very close to the normal Python Module Reference in scope. Personally, I would rather support someone who is active in the Python community, either here at tutor, or at comp.lang.python or in some important Open Source project, than spend my money on an author I don't know. Most of the guys above have useful web sites and contribute to the further development of python and the python community. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From j.ezequiel@spitech.com Tue Mar 25 06:31:44 2003 From: j.ezequiel@spitech.com (Ezequiel, Justin) Date: Tue Mar 25 06:31:44 2003 Subject: [Tutor] Automating MSWord (py2exe) Message-ID: <0F757892D113D611BD2E0002559C1FF403094AE7@email.spitech.com> To: 'alan.gauld@bt.com' Subject: RE: [Tutor] Automating MSWord (py2exe) Thanks for your time. >>Have you asked? Do they ban all language engines >>- eg Perl, VB, Java etc? or is ot just Python? >> >>In other words can they be persuaded to install it? Yes, I've asked and they do not want any language engines installed on production PCs (100+ machines). They are even planning on limiting the applications that can be run on Production PCs (via Group policies I think). >>Could yuou port your code >>to JScript and run it under WSH for example? I have no experience with JScript. I will however have a look at possible alternatives. I am hoping not to have to install anything on the production PCs (except of course the program). From alan.gauld@bt.com Tue Mar 25 06:58:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Mar 25 06:58:02 2003 Subject: [Tutor] Question about 'Predicate Methods' Message-ID: > 'predicate' methods is introduced with reference to access > control methods protecting object's attributes from being > 'gotten' at and rendered inconsistent by client code. That's slightly confusing IMHO. Access control is not directly related to predicate methods. Predicate methods(or even predicate functions!) are really methods which answer a question, they usually return a boolean result. Examples in a graphics library would include methods like: isVisible() overlaps(aShape) contains(aShape) canMove(adistance,aDirection) isShaded() isTransparent() etc... Some of these will be the same as accessor methods in that they return an attribute value, others (more typically) will return the logical combination of several values. > It is described as a 'read-only' access method > that test the validity of a condition. That is correct as the examples above illustrate. They test the state of the object but don't change the state in any way. > someone point me in the direction of documentation for this > method (what is and how it works), Its just a category of method there is no mechanism per se. Its just one way of describing a particular type of method - in the same way that various authors use terms like 'accessor', 'modifier', 'constructor', 'persistor' etc... to categorize the various methods within a class. Personally I prefer to work on the principle that you determine the methods that your clsass needs to have to fulfill its responsibilities and implement them. Don't worry too much about what kind of method it is, just build whats needed. Concentrating on categories can lead you down the road of building in unnecessary methods just because you don't, for example, have any persistence methods defined yet.... Thois is also why I don't like to see a class fuill of getXXX/setXXX methods. If the class's clients don't need to get/set the attributes then don't provide the method - thats what inheritance is for! HTH, Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Tue Mar 25 07:19:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Mar 25 07:19:02 2003 Subject: [Tutor] Automating MSWord (py2exe) Message-ID: > >>In other words can they be persuaded to install it? > > Yes, I've asked and they do not want any language > engines installed on production PCs (100+ machines). Thats not unusual for production use, even though they often break their own rules by using WSH etc - BTW Python can be run under WSH too, but you still need the interpreter. But if the WSH interpreter is allowed, why not Python... Anyway realistically it looks like py2exe is your best bet. > >>Could yuou port your code > >>to JScript and run it under WSH for example? > > I have no experience with JScript. > I will however have a look at possible alternatives. It's only an option if WSH is enabled. Some production boxes don't even have that (quite rightly since it is a security danger). Alan G. From alan.gauld@bt.com Tue Mar 25 07:24:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Mar 25 07:24:01 2003 Subject: [Tutor] Question about 'scopes' Message-ID: > 'contain' parts. Hence a scope seems quite akin to a 'level' > (as in a level of analysis) and comprises namespace references > and definitions. A namespace is a scope. They are synonymous. The best illustration for namespaces that I know is that off an office block. It has lots of teams of people in different offices. Several of the people will have the same first name. Within their own office or team they will be referred to as Joe, Mary etc. But when referring to another team member of the same name we clarify things by saying "Joe from accounts" or Mary from Marketing". Thus the team is a namespace. Similarly in Ptython a namespace is simply a locality within the program within which a given name is valid. Outsider that locality the namespace must be used to prefix the name. Because namespaces work differently in different programming languages it is impossible to give a single definitive description that covers all the options. You might like to take a peek at my namespaces topic in my online tutror too... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From a_abdi406@yahoo.com Tue Mar 25 08:07:01 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Tue Mar 25 08:07:01 2003 Subject: [Tutor] about a function Message-ID: <20030325130652.74205.qmail@web14501.mail.yahoo.com> --0-1491636258-1048597612=:73122 Content-Type: text/plain; charset=us-ascii hi everyone, I am having a proble with a function that takes a string from a list and searches another string and then process and returns a reformatted sring of this form of a conditioned word what happens is that when the function is called at some point in the function it it stops giving me a an error like as follows: File "Ass-002.py", line 30, in EQNfunc reslt = temp.group() AttributeError: 'NoneType' object has no attribute 'group' here is the function and how it gets called, I would appreciate if someone could see the problem so that I can proceed................ I got stuck, I tried with normal string it works but when I try to process from a list is when it gives me the abve error the loop that calls the function: temp_list = [] for i in token_list: #this is a list temp_list + = EQNfunc(i) # the function called here is the function: def EQNfunc(text1): """ this function takes a string as follows: what it is in here and first it filters to get the middle part of the string: as follows:--- what it is in here--- and then it tags with each token with as follows: what it is in here and finally it returns: what it is in here""" # variables for use tag = "" spacing = " " tag_W = "W" # filter the string passed text1 and take the middle section buf = re.compile(r"(?<=).*?(?=)") print buf x = "" temp = buf.search(text1) #take the result of the above step as "string" reslt = temp.group() ----------># here is it is the problem # change the string into a list so the we can manipulate answer = reslt.split() # tag each word in the list with ... for i in range(0,len(answer),1): answer[i] = '<%s>%s%s' %(tag_W,answer[i],tag_W,spacing) #join the text joined_text =''.join(answer) #concatenate the result with ... last_result = tag + " "+ joined_text + tag return last_result --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1491636258-1048597612=:73122 Content-Type: text/html; charset=us-ascii

hi everyone,

I am having a proble with a function that takes a string from a list and searches another string and then process and returns a reformatted sring of this form

<EQN/> <W>of</W> <W>a</W> <W>conditioned</W> <W>word</W> <EQN/>

what happens is that when the function is called at some point in the function it

it stops giving me a an error like as follows:

 File "Ass-002.py", line 30, in EQNfunc
 reslt = temp.group()
AttributeError: 'NoneType' object has no attribute 'group'

here is the function and how it gets called, I would appreciate if someone could see the problem so that  I can  proceed................ I got stuck, I tried with normal string

it works but when I try to process from a list is when it gives me the abve error

the loop that calls the function:

temp_list = []
   for i in token_list:                      #this is a list
        temp_list + = EQNfunc(i)     # the function called

here is the function:

def EQNfunc(text1):
  
   """ this function takes a string as follows:
       <EQN/>what it is in here<EQN/> and
       first it filters to get the middle part of the string:
       as follows:---  what it is in here--- and then it tags
       with each token with as follows:
       <W>what</W> <W>it</W> <W>is</W> <W>in</W> <W>here</W>
       and finally it returns:
       <EQN/> <W>what</W> <W>it</W> <W>is</W> <W>in</W>      <W>here</W><EQN/>"""
  

# variables for use
   tag = "<EQN/>"
   spacing = " "
   tag_W = "W"

   # filter the string passed text1 and take the middle section
   buf = re.compile(r"(?<=<EQN/>).*?(?=<EQN/>)")
   print buf
   x = ""
   temp = buf.search(text1)
   #take the result of the above step as "string"
   reslt = temp.group() ----------># here is it is the problem
   # change the string into a list so the we can manipulate
   answer = reslt.split()

   # tag each word in the list with <W>...</W>
   for i in range(0,len(answer),1):
       answer[i] = '<%s>%s</%s>%s' %(tag_W,answer[i],tag_W,spacing)
       #join the text  
       joined_text =''.join(answer)
   #concatenate the result with  <EQN/>...<EQN/> 
   last_result = tag + " "+ joined_text  + tag
  
   return last_result

 



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1491636258-1048597612=:73122-- From ahimsa@onetel.net.uk Tue Mar 25 08:27:06 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Mar 25 08:27:06 2003 Subject: [Tutor] Question about 'scopes' In-Reply-To: References: Message-ID: <200303251330.36764.ahimsa@onetel.net.uk> Hello Alan It's funny that you chose to respond because I'm actually re-reading your= =20 Chapter 16 on Namespaces, and it is making better sense to me the second-= time=20 around.=20 However, since we're on this topic, on p123 you write that "If you want t= o=20 assign a value to a variable outside the local namespace (which would=20 normally create a new local variable), ... ", could you explain how assig= ning=20 a value to something outside of the local scope creates a new *local*=20 variable - is that because the value was assigned from *within* the local= =20 namespace (i.e. referenced from within the local namespace making it a lo= cal=20 variable), even though the referand (or the object being assigned a value= )=20 'actually' is a global (or non-local) object? Is this on the right track, or have I lost the plot? Cheers Andy --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From ahimsa@onetel.net.uk Tue Mar 25 08:41:44 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Mar 25 08:41:44 2003 Subject: [Tutor] Question about 'Predicate Methods' In-Reply-To: References: Message-ID: <200303251344.24272.ahimsa@onetel.net.uk> On Tuesday 25 Mar 2003 11:56 am, alan.gauld@bt.com wrote: > Predicate methods(or even predicate functions!) are really methods > which answer a question, they usually return a boolean result. Yeah, that's what Danny mentioned also > > Examples in a graphics library would include methods like: > > isVisible() > overlaps(aShape) > contains(aShape) > canMove(adistance,aDirection) > isShaded() > isTransparent() and the method can only return a 1 or a 0 (true or a false): the object e= ither=20 is or is not visible, for eg. > Some of these will be the same as accessor methods in that they > return an attribute value, others (more typically) will return > the logical combination of several values. Could you give a brief eg of an accessor method returning an attribute va= lue?=20 Would this be like an output of a calculation perhaps? > That is correct as the examples above illustrate. > They test the state of the object but don't change the state in any way= =2E I can see that, yes. > Its just a category of method there is no mechanism per se. Its > just one way of describing a particular type of method - in the > same way that various authors use terms like 'accessor', 'modifier', > 'constructor', 'persistor' etc... to categorize the various methods > within a class. And the description is based on the attributes of the method being=20 'read-only', and dichotomous? > Personally I prefer to work on the principle that you determine the > methods that your clsass needs to have to fulfill its responsibilities > and implement them. Don't worry too much about what kind of method it > is, just build whats needed. Concentrating on categories can lead you > down the road of building in unnecessary methods just because you don't= , > for example, have any persistence methods defined yet.... > Thois is also why I don't like to see a class fuill of getXXX/setXXX > methods. If the class's clients don't need to get/set the attributes th= en > don't provide the method - thats what inheritance is for! I heed your advice, and will (hopefully) remember it when it comes time f= or me=20 to have to pay attention to program construction. Right now, I have my ha= nds=20 full trying to bend my brain around these foreign, but fascinating concep= ts.=20 To some extent, this is just like reading philosophy again and trying to = get=20 a sense of what Heidegger (or whomever) was *really* getting at when he s= poke=20 of a certain 'dasein', etc. Thanks to the patience of yourself and other=20 members of this list while I try to learn the ropes. All the best Andy --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From alan.gauld@bt.com Tue Mar 25 08:48:26 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Mar 25 08:48:26 2003 Subject: [Tutor] Question about 'scopes' Message-ID: > assign a value to a variable outside the local namespace (which would > normally create a new local variable), ... ", could you > explain how assigning a value to something outside of the > local scope creates a new *local* variable Its because you are assigning the value to a name. In Python that's how you create a new variable. Thus by the act of assignment you create a new local variable, that's just how Python works, it's the rule. When you want to break the normal mode of operation you have to explicitly tell Python to ignore the usual rule and use the existing global varable. An example: ####### x = 5 # create a global variable by assigning value 5 def f(): # create a new function with its own local scope print x # we don't assign to x so it uses the existing global one def g(): # another new function with its own scope x = 42 # we assign 42 to the name 'x' so python creates a new object print x def h(): # yet another function with its local scope global x # we tell python to use the global one x = 101 # this time assignment is to global x print x print x # --> 5 f() # --> 5, f() uses the global value print x # --> yep, still 5 g() #--> 42, using local x this time print x # still 5, g() didn't change it h() # --> 101, assigned by h() print x # --> 101, h() changed the global value. > is that because the value was assigned from *within* the local > namespace (i.e. referenced from within the local namespace > making it a local variable), Yes > even though the referand (or the object being assigned a value) > 'actually' is a global (or non-local) object? No, its a new object in the local scope created by Pythons normal rule of "assignment generates a new object" > Is this on the right track, or have I lost the plot? Very close. Recall that Python does not require you to declare object up front so it must have some riule for when to create new ones. It just so happens that Guido chose assignment as the trigger. Thus when you want to assign to an existing object which is outside your current scope(either global or in a separate module) we must provide a mechanism to make it clear. In the case of global we use the keyword 'global' and in the case of modules we prefix the name with the module name: sys.exit() for example. HTH, Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From ahimsa@onetel.net.uk Tue Mar 25 09:00:03 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Mar 25 09:00:03 2003 Subject: [Tutor] Question about 'scopes' In-Reply-To: References: Message-ID: <200303251403.46871.ahimsa@onetel.net.uk> On Tuesday 25 Mar 2003 1:47 pm, alan.gauld@bt.com wrote: > Its because you are assigning the value to a name. In Python > that's how you create a new variable. Thus by the act of assignment > you create a new local variable, that's just how Python works, > it's the rule. OK, I'm with you here; one 'declares' an object at the moment of using a=20 variable which is assigned a value, yes? > When you want to break the normal mode of operation you have to > explicitly tell Python to ignore the usual rule and use the > existing global varable. Since this would deviate from 'normal', under what kinds of conditions mi= ght=20 one want to declare a variable as a global variable rather than local? Ar= e=20 there any specific advantages to this? I can understand that there are=20 probably several disadvantages to doing so, such as subtly changing the v= alue=20 of a global variable in the event of a variable name clash, so what might= =20 influence someone to declare a variable globally? Thanks again --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From alan.gauld@bt.com Tue Mar 25 09:01:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Mar 25 09:01:02 2003 Subject: [Tutor] Question about 'Predicate Methods' Message-ID: > > Predicate methods(or even predicate functions!) are really methods > > which answer a question, they usually return a boolean result. ... > > Examples in a graphics library would include methods like: .... > and the method can only return a 1 or a 0 (true or a false): Strictly spreaking a predicate should be boolean however some texts allow things like count values to be classified as predicates. Thus a method like sides() might return 3,4,.... depending on how many sides the shape had. Is that an accessor or a predicate? Technically it's an accessor (even though the number of sides might not really exist as an attribute!), but some folks might call it a predicate because it answers a question... > Could you give a brief eg of an accessor method returning an > attribute value? See the example above. The usual names are things like getSides() [ But I personally hate that style of naming as it implies a breakdown in the data hiding of the class. I just want the object to tell me how many sides, I don;t carte if its an internal stored bvalue or not... ] > Would this be like an output of a calculation perhaps? Yes as discussed above. But the real point is that in any OOP solution the user should neither know nor care whether its calculated or not. > And the description is based on the attributes of the method being > 'read-only', and dichotomous? Just so. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From ahimsa@onetel.net.uk Tue Mar 25 09:03:08 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Mar 25 09:03:08 2003 Subject: [Tutor] Question about 'Predicate Methods' In-Reply-To: References: Message-ID: <200303251407.00146.ahimsa@onetel.net.uk> This was useful to me Alan, thank you. On Tuesday 25 Mar 2003 1:59 pm, alan.gauld@bt.com wrote: > > > Predicate methods(or even predicate functions!) are really methods > > > which answer a question, they usually return a boolean result. > > ... > > > > Examples in a graphics library would include methods like: > > .... > > > and the method can only return a 1 or a 0 (true or a false): > > Strictly spreaking a predicate should be boolean however some texts > allow things like count values to be classified as predicates. > > Thus a method like sides() might return 3,4,.... depending on > how many sides the shape had. Is that an accessor or a predicate? > Technically it's an accessor (even though the number of sides might > not really exist as an attribute!), but some folks might call it > a predicate because it answers a question... > > > Could you give a brief eg of an accessor method returning an > > attribute value? > > See the example above. The usual names are things like > > getSides() > > [ But I personally hate that style of naming as it implies a breakdown > in the data hiding of the class. I just want the object to tell me > how many sides, I don;t carte if its an internal stored bvalue or > not... ] > > > Would this be like an output of a calculation perhaps? > > Yes as discussed above. But the real point is that in any OOP solution > the user should neither know nor care whether its calculated or not. > > > And the description is based on the attributes of the method being > > 'read-only', and dichotomous? > > Just so. > > Alan g. > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld/ --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From alan.gauld@bt.com Tue Mar 25 09:14:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Mar 25 09:14:02 2003 Subject: [Tutor] Question about 'scopes' Message-ID: > Since this would deviate from 'normal', under what kinds of > conditions might one want to declare a variable as a global > variable rather than local? As few as possible. Global variables are generally held to be a bad thing in software engineering. There are very few(none?) cases when you *must* use global variables, but occasionally they help keep the code less cluttered. Use them sparingly is the golden rule... > so what might influence someone to declare a variable globally? If you have a number of values that must be persistent between function calls you might declare them as variables. You can then call the functions and the set value is available to the next function in the chain. However a better way of doing this is to pass the global variables into the functions as parameters and return the new values from the function. Like so: x = 2 y = 8 def f(anX,aY): i = anX**2 j = aY - 1 return i,j def g(): # 'bad' version global x,y x = x**2 y = y - 1 x,y = f(x,y) print x,y #--> 4, 7 g() print x,y #--> 16, 6 Both f() and g() have the same result but f() does it explicitly while g() does it silently via the global statement. Once you start using classes and OOP you will find that these provide an even better way of avoiding globals almost entirely. But I suspect you're not quite ready for OOP just yet. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Tue Mar 25 09:25:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Mar 25 09:25:01 2003 Subject: [Tutor] about a function Message-ID: This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C2F2DA.25C11B80 Content-Type: text/plain; charset="iso-8859-1" > it stops giving me a an error like as follows: File "Ass-002.py", line 30, in EQNfunc reslt = temp.group() AttributeError: 'NoneType' object has no attribute 'group' Have you checked what kind of object temp is? If your search fails it returns None. none does not have a group() attribute, hence the error. You need to either handle the exception (the Pythonic solution) or test to see if its not None: if temp != None: res = temp.group() Thats my guess! :-) Alan G. ------_=_NextPart_001_01C2F2DA.25C11B80 Content-Type: text/html; charset="iso-8859-1"
 >  it stops giving me a an error like as follows:

 File "Ass-002.py", line 30, in EQNfunc
 reslt = temp.group()
AttributeError: 'NoneType' object has no attribute 'group'

Have you checked what kind of object temp is?

If your search fails it returns None. none does not have a group() attribute,
hence the error.

You need to either handle the exception (the Pythonic solution) or test to
see if its not None:

if temp != None: 
   
res = temp.group()

Thats my guess! :-)

Alan G.

------_=_NextPart_001_01C2F2DA.25C11B80-- From ahimsa@onetel.net.uk Tue Mar 25 09:33:13 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Mar 25 09:33:13 2003 Subject: [Tutor] Question about 'scopes' In-Reply-To: References: Message-ID: <200303251435.52354.ahimsa@onetel.net.uk> On Tuesday 25 Mar 2003 2:13 pm, alan.gauld@bt.com wrote: > > Since this would deviate from 'normal', under what kinds of > > conditions might one want to declare a variable as a global > > variable rather than local? > > As few as possible. Global variables are generally held to > be a bad thing in software engineering. There are very few(none?) > cases when you *must* use global variables, but occasionally > they help keep the code less cluttered. Use them sparingly > is the golden rule... I can appreciate that, and since the exception you noted has a viable=20 alternative that doesn't break the golden rule, then I see no need to=20 challenge that.=20 > Once you start using classes and OOP you will find that these > provide an even better way of avoiding globals almost entirely. > But I suspect you're not quite ready for OOP just yet. Damn! What gave me away??? :-D Hopefully soon, though! Thanks a lot A --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From charlie@begeistert.org Tue Mar 25 10:53:04 2003 From: charlie@begeistert.org (Charlie Clark) Date: Tue Mar 25 10:53:04 2003 Subject: [Tutor] cgi redirection In-Reply-To: <20030325113144.23673.58693.Mailman@mail.python.org> References: <20030325113144.23673.58693.Mailman@mail.python.org> Message-ID: <20030325165421.1839.6@wonderland.1048585402.fake> On 2003-03-25 at 12:31:44 [+0100], tutor-request@python.org wrote: > Message: 10 > From: Alan Trautman > To: tutor@python.org > Subject: RE: [Tutor] cgi redirection > Date: Mon, 24 Mar 2003 14:45:44 -0600 > > > If you are working on IIS and have complete control over the server you > can install php which will give you all the redirection commands you > would ever need (well as good as the web gets). It also runs quite well > on Linux and BSD. Sorry this isn't much help on CGI but I forgot all that > as soon as I had mods and active scripting. sorry, but I have to object to this answer here. I much prefer using Python for cgi/web than PHP and you can have mod_python for Apache just like you can have mod_PHP. You can also use Python with ASP instead of Visual Basic if using MS IIS but it's news to me that Microsoft has ported to Unix. But none of that is answer to the initial question! Magnus has provided a good reply based on using HTTP-REFRESH which works with virtually any browser but I initially wasn't sure what the question was. What do you mean by redirection? The problem is that HTTP is stateless and relies on GET requests from browsers. A server can only send a page to a browser when it receives a request from that browser. Redirection can be done in the web server but this usually means that when a page is requested another is returned. When you call a cgi script you can only return one page and that is by essentially by printing it in which case Magnus' answer is the best way. An alternative might be to have the cgi call a page and print it - this is a bit how Google's archive works - but this isn't very common. If you're using IIS and .ASP you should have access to all the functions of the server via Python: http://search.microsoft.com/gomsuri.asp?n=1&c=rp_Results&target=http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B276494 which will also include how to access server-side redirection which happens in the link itself. If you want to move to Unix you may still be able to use .ASP; there is an ASP engine for Linux from Chilisoft I believe. However, IIS + ASP really isn't cross-platform. If you're used to it I'd stick to it as porting the functionality to another language or application server (IIS + ASP is considerably more than a straight webserver) is likely to be labour intensive. If you are looking for a cross-platform solution you might want to look at Zope (www.zope.org). Zope is a an application server written in Python which will run on most platforms with or without an additional web server (IIS or Apache). The API has an explicit redirect() function. Hope that helps but if not please be a little more specific. Charlie From magnus@thinkware.se Tue Mar 25 11:00:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Mar 25 11:00:01 2003 Subject: [Tutor] Question about namespace In-Reply-To: <20030325113144.23673.58693.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030325154540.034eae68@www.thinkware.se> At Mon, 24 Mar 2003 17:43:02 +0000, Andy wrote: >Guido van Rossum defines namespace as a "mapping from names to objects" >(Tutorial - Python 2.2.2 :S.9.2 p 54). Would I be correct to think of this >as - in Linux-speak - making a symlink that creates a symlink (or >'shortcut'/link) between the local reference (the link) and the module or >function itself (the 'target') which 'resides' elsewhere (i.e. has a >global scope)? Almost. It's not a symbolic link (ln -s), it's a *hard* link! $ echo "Graham" > brian # Make a file containing "Graham" and name it brian $ ln brian arthur # Name it arthur as well $ rm brian # Remove the name brian $ cat arthur # But the name arthur still refers to the file Graham $ rm arthur # Let the filesystem use that space for something else now You see? As long as there is one reference to the object, it will remain. This is analogous to: >>> brian = "Graham" # Make a string "Graham" and let brian refer to it >>> arthur = brian # Let arthur refer to the same string as brian >>> del brian # Remove the name brian >>> print arthur # The name arthur still refers to "Graham" though Graham >>> del arthur # We're done, remove the last reference ad let it # be "garbage collected" All variable names refer equally much to the object, and as long as there is at least one remaining reference, the object will live on. If you do "ln -s" instead of "ln", or if you make one of those crippled Windows shortcuts, you add a level of indirection. $ echo "Graham" > brian $ ln -s brian arthur # Let arthur rely on brian to provide something $ rm brian $ cat arthur # Oops, brian's gone, we're lost! :( cat: arthur: No such file or directory With only soft links, there is (as in LeGuin's Earthsea trilogy) one true name for everything. All other names are just aliases for the one true name. With hard links, as in Python, all names are equal. Which name came first is of no relevance. There you are! Python variables and objects aren't like Earthsea! You can't make such nasty things in Python. There is no way (that I know of) you can get a reference to a variable. You always work with references to objects, whether you access them as variables, attributes, members in a collection or whatever. This type of indirection is commonly used in other languages such as C and derivates though, and they cause an enless amount of bugs... A variable in Python is only a named reference to an object. A variable in for instance C is a named location in memory that can house a particular kind of value. For instance, if you do this in C: int a; /* Reserve name in memory for an integer */ a = 5; /* Place the integer value 5 in this place */ a = 7; /* Replace 5 with 7 at that location in memory */ it's not at all the same as in Python: a = 5 # Place integer value 5 on the heap, make a point to it. a = 7 # Place integer value 7 on the heap, make a point to # that instead. If there is no other reference to 5, # it will be cleaned by the GC. The python way is vastly superior. The C way basically breaks down as soon as you try to store something more complex than an integer. You get a mix of directly and indirectly (in one or more steps) refered values, leading to confusing rules about pointers and references and pointers to pointers to pointers. People with many years of experience still have to think very hard to get it right, and need to test such trivialities as accessing a variable in a complex structure very carefully to get it right. Don't laugh, I've been there. It's no fun! (It's always uplifting to get something difficult right in the end, but I'd rather spend my brain cells on hard problems with good tools than on trivial problems with difficult tools. Viva Python!) In Python you need to understand the difference between variables/names and the objects/values the refer to, and you need to understand the difference between mutable and immutable objects. Then the concept works for all kinds of objects, with a single and simple access method. Heck, in "Programming Perl" they spend page after page explaining about all the mistakes you can do in dereferencing variables. That means that if you manage to do the eqivalent to the following code in Perl, you are involved in deep magic. It's a bit like getting a black belt in karate to be able to do such a thing without getting something like ARRAY(0x8101dc0) or just nothing printed at the first three or four attempts. a = 5 b = (a,) c = [b] print c[0][0] 5 If you understand a python dictionary, you should also understand namespaces, since they *are* dictionaries. >>> x = 1 >>> y = "hello" >>> def f(a, b): ... print "locals=",locals() ... print "globals=",globals() ... >>> f(x,y) locals= {'a': 1, 'b': 'hello'} globals= {'y': 'hello', 'x': 1, 'f': , '__builtins__': , '__name__': '__main__', '__doc__': None} You see? They are just dictionaries, and dictionaries are (as other collections) just a heap of references. There is only one object containing 1, and one containing "hello". Nothing is copied, the dicts / namespaces share references. You can verify that with the id() function. >>> y = "hello" >>> id(y) 135614264 >>> def f(object): ... print id(object) ... >>> f(y) 135614264 You see! global 'y' and local 'object' refer to the same string. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From hall@ouhep1.nhn.ou.edu Tue Mar 25 11:08:02 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Tue Mar 25 11:08:02 2003 Subject: [Tutor] general question about memory leaks in python Message-ID: Hi folks. I have fairly broad question that I hope some of you can help me with. I have this program that should be able to run all the time doing some graphical whatnot. (getting a few data-points and displaying the last hours worth on a graph) Anyway, when I run this program, the size just keeps going up and up and up, even after the time where I tell it to throw away old data points. this continues until it crashes or I kill it. anyway, I dont want to get into too much detail, but can anyone explain to me how memory leaks in python occur, and some good practices for keeping the size of the thing down. (or at least to keep it from growing so much) Any help would be hot. Thanks guys. Ike -- From ahimsa@onetel.net.uk Tue Mar 25 11:30:03 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Mar 25 11:30:03 2003 Subject: [Tutor] Question about namespace In-Reply-To: <5.1.0.14.0.20030325154540.034eae68@www.thinkware.se> References: <5.1.0.14.0.20030325154540.034eae68@www.thinkware.se> Message-ID: <200303251633.43828.ahimsa@onetel.net.uk> Wow! Thanks for that Magnus You went to a lot of effort to explain that, thanks.=20 I'm also pleased that you pointed out that namespaces are dictionaries,=20 because it had occurred to me that referencing objects in a given namespa= ce=20 was sort of like the key:value relationship of a dictionary method. I am having a hard enough time getting to grips with Python and all these= =20 terms and concepts. I think that C and Perl are a long way off for me as = of=20 yet - my brain is already taxed and I'm beginning to feel a bit dumb with= all=20 of this. Thanks for your explanation Magnus. Andy --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From abli@freemail.hu Tue Mar 25 16:55:45 2003 From: abli@freemail.hu (Abel Daniel) Date: Tue Mar 25 16:55:45 2003 Subject: [Tutor] general question about memory leaks in python In-Reply-To: References: Message-ID: <20030325215404.GA1644@hooloovoo> Isaac Hall wrote: [ ...snipped description of a memory-eating program... ] Python uses garbage-collecting. Anything which isn't reachable from you program (objects for which you don"t have a reference anywhere, or where the references are only between a set of objects, none of which you can reach, cyclic garbage) gets garbage-collected. This means that the only way of having memory-leaks is having references to objects you no longer need. Some remarks: garbage gets collected as soon as you drop the last reference to it in the C implementation. In Jython (python implemented in Java) Java memory management is used, so garbage may be collected later. Also, for collecting cyclic garbage, a special part of python awakens at a regular interval, looks around for cyclic garbage then breaks those cycles. (So collecting cyclic garbage isn't instanteneus.) You can have old-fashioned memory leaks in for example C extensions. There is nothing python could do about it. To tinkter around with the memory management, check out the gc module. For example, gc.get_objects() is the place I would start to find unneeded references. (Provided you don't use non-python extensions (what do you use for the graphics?), in which case check whether they know of any memory leaks.) Disclaimer: all this gleaned for lurking in comp.lang.python for some months. I never had to debug anything memory-related with python, and all this might be wrong. http://python.org/doc/current/ref/objects.html says: Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether -- it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable. (Implementation note: the current implementation uses a reference-counting scheme with (optional) delayed detection of cyclicly linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the Python Library Reference[link to gc module] for information on controlling the collection of cyclic garbage.) So I can't be that far off.. :) Abel Daniel ps. I saw code which explicitly broke cycles to avoid cyclicc garbage, but that might have been needed before cyclic gc was in the core python. Dont know about that. If all else fails and you have a short snippet of code which shows the problem, or a specific problem, try comp.lang.python (which is also available as a mailing list.) From ATrautman@perryjudds.com Tue Mar 25 17:09:01 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Tue Mar 25 17:09:01 2003 Subject: [Tutor] general question about memory leaks in python Message-ID: <06738462136C054B8F8872D69DA140DB01071B@corp-exch-1.perryjudds.com> All, There was a similar problem based on the method of updating Tkinter ~~6 months ago. I think it was a cycling analog type meter. The screen update information was just building up in memory causing it to visibly slow down. There was a simple fix in the way the screen was updated. I'm hoping somebody who knows more about graphical screen updates may be able to fill in the gaps. In other words it wasn't the data that was being fed to the system but the way the screen was updated that caused the problems. Help, I wish I remembered more. Alan -----Original Message----- From: Isaac Hall [mailto:hall@ouhep1.nhn.ou.edu] Sent: Tuesday, March 25, 2003 10:08 AM To: tutor@python.org Subject: [Tutor] general question about memory leaks in python Hi folks. I have fairly broad question that I hope some of you can help me with. I have this program that should be able to run all the time doing some graphical whatnot. (getting a few data-points and displaying the last hours worth on a graph) Anyway, when I run this program, the size just keeps going up and up and up, even after the time where I tell it to throw away old data points. this continues until it crashes or I kill it. anyway, I dont want to get into too much detail, but can anyone explain to me how memory leaks in python occur, and some good practices for keeping the size of the thing down. (or at least to keep it from growing so much) Any help would be hot. Thanks guys. Ike -- _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jeff@ccvcorp.com Tue Mar 25 18:38:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Mar 25 18:38:02 2003 Subject: [Tutor] general question about memory leaks in python References: <20030325215404.GA1644@hooloovoo> Message-ID: <3E80E87D.9010303@ccvcorp.com> Abel Daniel wrote: >garbage gets collected as soon as you drop the last reference to it in >the C implementation. In Jython (python implemented in Java) Java memory >management is used, so garbage may be collected later. Also, for collecting >cyclic garbage, a special part of python awakens at a regular interval, >looks around for cyclic garbage then breaks those cycles. (So collecting >cyclic garbage isn't instanteneus.) >You can have old-fashioned memory leaks in for example C extensions. >There is nothing python could do about it. > This is how I understand matters as well. Any true memory leaks are extremely likely to be the result of extensions rather than anything within Python -- as a wxPython user I remember discussions about memory leaks caused by references held by C++ objects that never got garbage-collected, though I believe these issues are (mostly) fixed in recent versions, but again it's the extension (and its interface with Python) that cause the problem rather than Python itself. (I have a non-graphical Windows NT service written in Python which is constantly creating and destroying largish strings, which runs for months at a time with no memory problems.) As an additional note, however, keep in mind that every program is ultimately dependent on the platform's virtual memory manager, and sometimes those aren't very smart about returning freed memory. One possible solution to your problem may be to implement some sort of object-caching. Instead of throwing away old data points and creating new ones, you could try to recycle the old data structures to hold new data. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Tue Mar 25 19:06:50 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Mar 25 19:06:50 2003 Subject: [Tutor] about a function References: <20030325130652.74205.qmail@web14501.mail.yahoo.com> Message-ID: <3E80EF2A.6080303@ccvcorp.com> Abdirizak abdi wrote: > hi everyone, > > I am having a proble with a function that takes a string from a list > and searches another string and then process and returns a reformatted > sring of this form > > of a conditioned word > For this specific case, using RE is unnecessarily complex. For the general case, you need an XML parser rather than a RE. Here's how I'd solve your problem: ----test.py----------- def EQNfunc(text): tag1 = "" tag2 = "" tag3 = "" if text.startswith(tag1) and text.endswith(tag1): cut = len(tag1) text = text[cut:-(cut)] # strip off tags result = ["%s%s%s" % (tag2, item, tag3) for item in text.split()] answer = " ".join(result) return "%s%s%s" % (tag1, answer, tag1) else: raise ValueError, "Invalid text: '%s' tags not present" % tag1 ------------------------ >>> import test >>> text = "some text in here" >>> print test.EQNfunc(text) some text in here >>> text2 = "Something without tags" >>> print test.EQNfunc(text2) Traceback (most recent call last): File "", line 1, in ? File "test.py", line 12, in EQNfunc raise ValueError, "Invalid text: '%s' tags not present" % tag1 ValueError: Invalid text: '' tags not present >>> You can easily generalize this a little bit by making the specific tags into parameters, or draw them from some global dictionary, or whatever. But this seems to fulfill all of your specifications without resorting to regular expressions, which are both more powerful than you need and less of a cure-all than you think. Jeff Shannon Technician/Programmer Credit International From j.ezequiel@spitech.com Tue Mar 25 21:03:01 2003 From: j.ezequiel@spitech.com (Ezequiel, Justin) Date: Tue Mar 25 21:03:01 2003 Subject: [Tutor] MSWord (py2exe) Message-ID: <0F757892D113D611BD2E0002559C1FF4030B0247@email.spitech.com> Thanks again for taking the time Alan. >>Anyway realistically it looks like py2exe is your best bet. I did try py2exe. However, when I tried to run the .EXE on a machine without Python I got the following. Traceback (most recent call last): File "", line 4, in ? File "imputil.pyc", line 132, in _import_hook File "", line 70, in _finish_import File "imputil.pyc", line 316, in _load_tail File "imputil.pyc", line 271, in _import_one File "", line 128, in _process_result File "win32com\client\__init__.pyc", line 12, in ? File "imputil.pyc", line 93, in _import_hook File "imputil.pyc", line 347, in _do_import File "imputil.pyc", line 271, in _import_one File "", line 128, in _process_result File "win32com\client\dynamic.pyc", line 22, in ? File "imputil.pyc", line 103, in _import_hook File "", line 52, in _import_top_module File "imputil.pyc", line 216, in import_top File "imputil.pyc", line 271, in _import_one File "", line 128, in _process_result File "pythoncom.pyc", line 18, in ? File "pythoncom.pyc", line 10, in __import pywintypes.error: (126, 'LoadLibrary', 'The specified module could not be found. ') Files in my dist folder: DelStyles.exe win32api.pyd win32trace.pyd python22.dll win32ui.pyd PyWinTypes22.dll _sre.pyd I've used py2exe twice before on scripts that do not use win32com. And have run them successfully on machines without Python. So I'm guessing that I need to include a file or files but I have no idea which. From bobsmith327@hotmail.com Tue Mar 25 22:19:13 2003 From: bobsmith327@hotmail.com (bob smith) Date: Tue Mar 25 22:19:13 2003 Subject: [Tutor] Classes, Object and Encapsulation Message-ID: I'm, fairly new to Python and I understand that by default object attributes are public -- but there's seems to be a lot of different ways to try to enforce encapsulation. You've got: - private variables (which it seems really aren't private, just "name mangling" -- something a determined programmer could get around) - slots - properties - special methods like __getattr__ and __setattr__ - PLUS you could always write you own "get" and "set" methods So, as a Python beginner, what's the best way to protect my object's attributes? Are "get" and "set" methods passé in Python? If you use them, do you write them for every attribute? Or, instead, should you just use properties and let everyone access all of your object's attributes through dot notation? Finally, how do people in the "real" programming world deal with objects and attributes? Do you always go to the trouble of protecting them, or do you just leave them public and assume that they won't be mistreated? I ask because the Python code I've seen seems NOT to take precautions with object attributes and just leaves them public. Many thanks, Bob _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From riex@ligbr.com.br Tue Mar 25 23:13:02 2003 From: riex@ligbr.com.br (riex@ligbr.com.br) Date: Tue Mar 25 23:13:02 2003 Subject: [Tutor] new to prog. question Message-ID: <20030326010854.19497.qmail@ligbr.com.br> Hi tutor. I've a simple question. I create a list containing numbers. list1=[1,2,4,8,16,32,64,128,512] # which is 2**0 ...2**10 If I wanted to find if a given number, 12 for example, is in the list would be easy. But, how about if x+y in the list equals the number (12) ? So, 8 + 4 for example. Maybe I am just going the wrong way here, and there is a easier way to do this. From fredm@smartypantsco.com Tue Mar 25 23:35:02 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Tue Mar 25 23:35:02 2003 Subject: [Tutor] new to prog. question In-Reply-To: <20030326010854.19497.qmail@ligbr.com.br> Message-ID: <5.1.0.14.0.20030326151838.0377a0d0@192.168.1.1> Hi: Your question is not exactly clear. You have created a list of powers of 2, and you want to know if a given number is the sum of numbers in that list. I assume that you know that any number (within the given range) can be expressed as the sum of powers of 2. For example 13 = 8 + 4 + 1 So can you please explain your question better? Do you want to find out if a given number is the sum of only 2 numbers in the list OR do you want to find out which powers of 2 add up to the given number? Alfred Milgrom At 01:08 AM 26/03/03 +0000, riex@ligbr.com.br wrote: >Hi tutor. >I've a simple question. >I create a list containing numbers. list1=[1,2,4,8,16,32,64,128,512] ># which is 2**0 ...2**10 >If I wanted to find if a given number, 12 for example, is >in the list would be easy. But, how about if x+y in the list equals >the number (12) ? >So, 8 + 4 for example. >Maybe I am just going the wrong way here, and there is a easier way to do >this. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > From idiot1@netzero.net Tue Mar 25 23:47:06 2003 From: idiot1@netzero.net (Kirk 'Deliberatus' Bailey) Date: Tue Mar 25 23:47:06 2003 Subject: [Tutor] random file rotation program Message-ID: <3D004217.C8E04701@netzero.net> OK, I have used a program in C to rotate banners and 'fortunbe cookies' for a lonmg time, but I just took a stab at writing one in python to do it for me. Here is my first jab at it. #!/usr/local/bin/python # the previous line MUST be the first line, and MUST point at your server's # python interpeter! # # cookie.py (C)2002 Kirk D Bailey # Released under the GNU GPL. # import os.path, string, sys, random # # targetfile = sys.argv[1] try this later when basic is working. targetfile='cookiejar' # #----v----1---v----2---v---3----v----4----v----5----v----6----v----7----v----8 # # use this next line if you are using ssi with the 'include' tag. # if you use the 'exec' tag, comment out the next line. print "content-type: text/html\n\n" # # invoke in a web page as: # # print '' print '' # def gangstrip(thing): # ok, everybody STRIP! index=0 # This strips out whitespace chars while index < len(thing): # define exit thing[index]=string.strip(thing[index]) index=index+1 # increase the counter return thing # if os.path.exists(targetfile): f1.open(targetfile,'r') cookies=gangstrip(f1.readlines()) f1.close() else cookies = ['ERROR:file "' + targetfile + '" not found or unavailable.'] # print random.choice(cookies) From shalehperry@attbi.com Tue Mar 25 23:56:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue Mar 25 23:56:02 2003 Subject: [Tutor] Classes, Object and Encapsulation In-Reply-To: References: Message-ID: <200303252055.22050.shalehperry@attbi.com> > > Finally, how do people in the "real" programming world deal with objects > and attributes? Do you always go to the trouble of protecting them, or do > you just leave them public and assume that they won't be mistreated? I ask > because the Python code I've seen seems NOT to take precautions with object > attributes and just leaves them public. > if I am writing a module for others to use I try to clamp down as much as possible. For internal classes that are just part of a project I am no where near as rigorous. In the end the level of safety is dictated by the goals of the project at hand. That said, there is an assumption made that people know better than to play with class internals or functions named _foo(). From rob@jam.rr.com Wed Mar 26 00:37:02 2003 From: rob@jam.rr.com (Rob Andrews) Date: Wed Mar 26 00:37:02 2003 Subject: [Tutor] nominees please Message-ID: I'd like to open the floor to nominees for outstanding Tutor List posts. Over time, some absolutely fantastic posts have been made to this list, explaining key concepts in crisp, clear, often entertaining ways. Useless Python 2.0 is in the works, and it would be great to go life with awards for excellent, insightful, or just plain useless posts. Just in case anyone takes me up on this (please!), I don't know if the Illuminati of the Tutor List fnord will want replies to go back to the Tutor List or not. thanks for reading this far down, Rob rob@uselesspython.com From riex@ligbr.com.br Wed Mar 26 00:55:02 2003 From: riex@ligbr.com.br (riex@ligbr.com.br) Date: Wed Mar 26 00:55:02 2003 Subject: [Tutor] new to prog. question (cleared-up) Message-ID: <20030326025232.27996.qmail@ligbr.com.br> Hi Alfred, sorry about that. ======= At 2003-03-26, 15:33:00 you wrote: ======= >Hi: > >Your question is not exactly clear. > >You have created a list of powers of 2, and you want to know if a given >number is the sum of numbers in that list. >I assume that you know that any number (within the given range) can be >expressed as the sum of powers of 2. > >For example 13 = 8 + 4 + 1 > >So can you please explain your question better? >Do you want to find out if a given number is the sum of only 2 numbers in >the list OR do you want to find out which powers of 2 add up to the given >number? > I used powers of 2 because I thought it would be easier. What I was tinking is: in a list containing numbers, which could be randon, how would I go about figuring out if: x in the list is the given number >not the problen or x+x in the list is the given number or even x+x+x in the list is the given number So far just using addition. >Do you want to find out if a given number is the sum of only 2 numbers in >the list I suppose this is part of what I was thinking. To all that go through the time to read this, thanks for responding. I guess this might be simple but I can't figure it out for my self so far. riex@ligbr.com.br 2003-03-26 From a_abdi406@yahoo.com Wed Mar 26 09:00:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed Mar 26 09:00:02 2003 Subject: [Tutor] about regular expression Message-ID: <20030326071329.78623.qmail@web14509.mail.yahoo.com> --0-1589457939-1048662809=:76500 Content-Type: text/plain; charset=us-ascii Hi everyone Can any one suggest a regular expression that can distinguish between two fullstop(e.g : he got married last weeek.) and abbreviated word (e.g Al. Brown), I have tried some but I couldn't get them right. please give an example each of these two. thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1589457939-1048662809=:76500 Content-Type: text/html; charset=us-ascii

Hi everyone

Can any one suggest a regular expression that can distinguish between two fullstop(e.g : he got married last weeek.)  and abbreviated word (e.g Al. Brown), I have tried  some but  I couldn't get them right. please give an example each of these two.

thanks in advance



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1589457939-1048662809=:76500-- From a_abdi406@yahoo.com Wed Mar 26 09:01:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed Mar 26 09:01:02 2003 Subject: [Tutor] about regular expression Message-ID: <20030326110706.26638.qmail@web14506.mail.yahoo.com> --0-1603709283-1048676826=:23968 Content-Type: text/plain; charset=us-ascii Hi everyone Can any one suggest a regular _expression that can distinguish between two fullstop(e.g : he got married last weeek.) and abbreviated word (e.g Al. Brown), I have tried some but I couldn't get them right. please give an example each of these two. thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1603709283-1048676826=:23968 Content-Type: text/html; charset=us-ascii

Hi everyone

Can any one suggest a regular _expression that can distinguish between two fullstop(e.g : he got married last weeek.)  and abbreviated word (e.g Al. Brown), I have tried  some but  I couldn't get them right. please give an example each of these two.

thanks in advance




Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1603709283-1048676826=:23968-- From steegness@hotmail.com Wed Mar 26 09:26:46 2003 From: steegness@hotmail.com (Steegness) Date: Wed Mar 26 09:26:46 2003 Subject: [Tutor] about regular expression References: <20030326140102.15249.53439.Mailman@mail.python.org> Message-ID: In standard well-formed English, a full stop period is usually followed by two spaces, whereas abbreviations are only followed by one. Perhaps this will serve for the purpose for the regex. Sean > Date: Wed, 26 Mar 2003 03:07:06 -0800 (PST) > From: Abdirizak abdi > To: tutor@python.org > Subject: [Tutor] about regular expression > > Hi everyone > > Can any one suggest a regular _expression that can distinguish between two fullstop(e.g : he got married last weeek.) and abbreviated word (e.g Al. Brown), I have tried some but I couldn't get them right. please give an example each of these two. > > thanks in advance From ATrautman@perryjudds.com Wed Mar 26 10:39:02 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Wed Mar 26 10:39:02 2003 Subject: [Tutor] about regular expression Message-ID: <06738462136C054B8F8872D69DA140DB01071C@corp-exch-1.perryjudds.com> Hate to argue but if you are parsing MLA formatted documents there is to be only one space after all periods. Is there a formal style guide for the text you are accepting? The Sean's idea would work well. I also matters which generation of style guide is used. MLA used 2 spaces after sentences until 1998. I think the APA (journalism) may use one space too. Of course people following those standards who are not in formal academic/professional life are rare as unicorns as well. Hate to make it harder but English is hard. Maybe non-capitalized word followed by a period then by spaces(s) and then a capitol letter? I'm sure I might be missing something (You would need a way to catch questions such as "What time is lunch" said Mary?) but maybe it will find more word for you. HTH, Alan -----Original Message----- From: Steegness [mailto:steegness@hotmail.com] Sent: Wednesday, March 26, 2003 8:25 AM To: tutor@python.org Subject: Re: [Tutor] about regular expression In standard well-formed English, a full stop period is usually followed by two spaces, whereas abbreviations are only followed by one. Perhaps this will serve for the purpose for the regex. Sean > Date: Wed, 26 Mar 2003 03:07:06 -0800 (PST) > From: Abdirizak abdi > To: tutor@python.org > Subject: [Tutor] about regular expression > > Hi everyone > > Can any one suggest a regular _expression that can distinguish between two fullstop(e.g : he got married last weeek.) and abbreviated word (e.g Al. Brown), I have tried some but I couldn't get them right. please give an example each of these two. > > thanks in advance _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From am@fx.ro Wed Mar 26 12:06:00 2003 From: am@fx.ro (Adrian Maier) Date: Wed Mar 26 12:06:00 2003 Subject: [Tutor] new to prog. question (cleared-up) In-Reply-To: <20030326025232.27996.qmail@ligbr.com.br>; from riex@ligbr.com.br on Wed, Mar 26, 2003 at 02:52:32AM +0000 References: <20030326025232.27996.qmail@ligbr.com.br> Message-ID: <20030426223312.B417@coto> riex@ligbr.com.br (riex@ligbr.com.br) a scris : > Hi Alfred, sorry about that. > I used powers of 2 because I thought it would be easier. > What I was tinking is: in a list containing numbers, which could be randon, > how would I go about > figuring out if: > x in the list is the given number >not the problen > or x+x in the list is the given number > or even x+x+x in the list is the given number > > So far just using addition. I guess you could use some temporary list: >>> def func(x): return x+x ... >>> a=[1,2,3,5,6] >>> b=map(func,a) >>> b [2, 4, 6, 10, 12] >>> 4 in b 1 >>> 5 in b 0 Or, you could traverse the list yourself and use an 'if' to check the condition: >>> a=[1,2,4,5,12] >>> your_number=10 >>> for i in a: ... if i+i==your_number: ... print i ... 5 -- Adrian Maier (am@fx.ro) From jlohman@cox.net Wed Mar 26 12:06:10 2003 From: jlohman@cox.net (Jeff Lohman) Date: Wed Mar 26 12:06:10 2003 Subject: [Tutor] Opening files? Message-ID: <002d01c2f3b9$b40040d0$fdaa6544@cx826527a> When I want to try and open(import?) and read files, what are the best commands to use? Also, how do I specify the path that python needs to follow to open the file? I am trying to manipuilate text(.txt) files with python 2.2.2. Thanks, -Jeff, first-time poster and new python user... From rob@jam.rr.com Wed Mar 26 12:27:02 2003 From: rob@jam.rr.com (Rob Andrews) Date: Wed Mar 26 12:27:02 2003 Subject: [Tutor] Opening files? In-Reply-To: <002d01c2f3b9$b40040d0$fdaa6544@cx826527a> Message-ID: > When I want to try and open(import?) and read files, what are the > best commands to use? > > Also, how do I specify the path that python needs to follow to > open the file? > > I am trying to manipuilate text(.txt) files with python 2.2.2. Your questions open up a whole interesting subject. Here's an example of opening a .txt file using 2.2.2 on a Windows machine. >>> myLimerick = open("E:/temp/lousyLimerick.txt", 'r') The above line specifies the file to open, and the 'r' says to open it only for reading. The next two lines tell the interpreter to print each line of the file for viewing. >>> for eachLine in myLimerick: ... print eachLine ... There was a programmer in Python whose code (not his rhymes) were all right-on. This limerick blows, Who wrote it? Who knows? For my eyeballs, this limerick's blight on. >>> myLimerick.close() >>> When finished with the file, it is a good idea to explicitly close the file as shown above. I'm sure you've got more specific questions, which we're happy to try and assist with. -Rob From antonmuhin at rambler.ru" References: <3D004217.C8E04701@netzero.net> Message-ID: <1735326326.20030326203312@rambler.ru> Hello Kirk, Friday, June 7, 2002, 8:18:16 AM, you wrote: KDB> OK, I have used a program in C to rotate banners and 'fortunbe cookies' KDB> for a lonmg time, but I just took a stab at writing one in python to do KDB> it for me. Here is my first jab at it. KDB> #!/usr/local/bin/python KDB> # the previous line MUST be the first line, and MUST point at your KDB> server's KDB> # python interpeter! KDB> # KDB> # cookie.py (C)2002 Kirk D Bailey KDB> # Released under the GNU GPL. KDB> # KDB> import os.path, string, sys, random KDB> # KDB> # targetfile = sys.argv[1] try this later when basic is working. KDB> targetfile='cookiejar' KDB> # KDB> #----v----1---v----2---v---3----v----4----v----5----v----6----v----7----v----8 KDB> # KDB> # use this next line if you are using ssi with the 'include' tag. KDB> # if you use the 'exec' tag, comment out the next line. KDB> print "content-type: text/html\n\n" KDB> # KDB> # invoke in a web page as: KDB> # KDB> # KDB> print '' KDB> print '' KDB> # KDB> def gangstrip(thing): # ok, everybody STRIP! KDB> index=0 # This strips out whitespace KDB> chars KDB> while index < len(thing): # define exit KDB> thing[index]=string.strip(thing[index]) KDB> index=index+1 # increase the counter KDB> return thing A little bit unpythonic for me. I'd put it: thing = [s.strip() for s in thing] KDB> # KDB> if os.path.exists(targetfile): KDB> f1.open(targetfile,'r') KDB> cookies=gangstrip(f1.readlines()) KDB> f1.close() KDB> else KDB> cookies = ['ERROR:file "' + targetfile + '" not found or KDB> unavailable.'] It seems (although I didn't check), that it could be written with exceptions: try: f = file(targetfile, 'r') cookies = [line.strip() for line in f] f.close() except: cookies = ['ERROR:file "' + targetfile + '" not found or unavailable.'] Defenitely, it's far from ideal, but for quick'n'dirty script... KDB> # KDB> print random.choice(cookies) -- Best regards, anton mailto:antonmuhin@rambler.ru From antonmuhin at rambler.ru" References: <20030326071329.78623.qmail@web14509.mail.yahoo.com> Message-ID: <15035516680.20030326203623@rambler.ru> Hello Abdirizak, Wednesday, March 26, 2003, 10:13:29 AM, you wrote: Aa> Hi everyone Aa> Can any one suggest a regular expression that can distinguish Aa> between two fullstop(e.g : he got married last weeek.) and Aa> abbreviated word (e.g Al. Brown), I have tried some but I couldn't Aa> get them right. please give an example each of these two. Aa> thanks in advance I don't think it's possible at all. However, you may create a reasonable list of abbreviations. -- Best regards, anton mailto:antonmuhin@rambler.ru From lobow@brturbo.com Wed Mar 26 12:43:02 2003 From: lobow@brturbo.com (Diego Prestes) Date: Wed Mar 26 12:43:02 2003 Subject: [Tutor] Entry in Tkinter Message-ID: <3E81E677.5070005@brturbo.com> Hello, Im trying tu use the Entry widget. I type a word in the Entry and in find1 module it use the entry using the option self.proc.get(), but when I use this, I have this error: AttributeError: 'NoneType' object has no attribute 'get' In a test I try to use the Entry and it works normally, but in my program not. Someone know what I could be doing wrong? self.find1 = Button(frame3, text="Find", command=self.find1).pack(side=LEFT) self.proc = Entry(frame3, background="white").pack(side=LEFT) def find1(self): #count the number of times that the word in the text vpal = count(self.text,self.proc.get()) tkMessageBox.showinfo("Find","%s and %d" % (self.proc.get(),vpal)) Diego PS: If someone dont understand my english ask me and I'll try to explain better. From alan.gauld@bt.com Wed Mar 26 12:43:13 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Mar 26 12:43:13 2003 Subject: [Tutor] Classes, Object and Encapsulation Message-ID: > I'm, fairly new to Python and I understand that by default=20 > object attributes are public=20 Yes. Until C++ came along most OO languages either made all=20 attributes public(Object Pascal, Lisp variants etc) or all=20 private (Smalltalk etc). C++ put the decision in the hands=20 of the programmer and most other languages since have=20 followed suit. Python takes the all public by default line and has gradually=20 added protection mechanisms over time. In practice most Python=20 programmers are happy to let good manners and convention=20 control attribute access. Folks moving to Python from Jaba and C++ seem to get more=20 paranoid about things and want to use the protection mechanisms. [ BTW you can bypass C++ protection fairly easily by doing #define private public #define protected public #include if you really feel mean.... You can also bypass it with some=20 pointer magic by derefencing the VMT and doing pointer=20 arithmetic... Not that you'd ever want to of course!] > - PLUS you could always write you own "get" and "set" methods That doesn't really provide protection unless you've also done=20 at least some of the other stuff you mentioned. > So, as a Python beginner, what's the best way to protect my object's=20 > attributes? As a beginner don't bother. Concentrate on good programming=20 discipline and learning how to use the language including OOP=20 effectively. Leave paranoia to the C++/Java guys. > Are "get" and "set" methods pass=E9 in Python? =20 Nope, they are just a bad thing IMHO. If you can't think of a better name for a method that getXXX then=20 its likely you don't need the method but need to rethink the design. What responbsibility requires one object to know so much about=20 the internal data of another object? Why can't the owning object do=20 whatever you were about to do for you? Its called the Law of = Demeter.... > If you use them, do you write them for every attribute? =20 I usae them very rarely and only write them for attributes that really=20 must be shared between objects. And thats still probably bad OO design=20 at work... > instead, should you just use properties and let everyone access=20 > all of your object's attributes through dot notation? If you are building a component for general distribution and reuse=20 there is a case to be made for using properties. Also if you are using=20 the object in a polymoprphic environment where there is a mix of=20 objects with public access and objects with protected access(for=20 some reason - say you are adding a new object to legacy code) Otherwise I don't see a great deal of advbantage in using=20 properties - a lot of extra work for minimal gain. > Finally, how do people in the "real" programming world deal=20 > with objects and attributes? =20 Depends on the environment. In Lisp or Object Pascal I still tend=20 to leave everything exposed(even though those languages have added=20 protection mechanisms too) I can honestly say I have never yet been=20 burned badly by someone accessing data directly - if the interface=20 is rich enough there should be no need! If it isn't the easier=20 answer is usually to create a subclass which has the missing methods! > because the Python code I've seen seems NOT to take=20 > precautions with object attributes and just leaves them public. Yes, thats the Pythonic norm. Partly for historic reasons, partly=20 cause we're a trusting lot. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Wed Mar 26 12:50:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Mar 26 12:50:02 2003 Subject: [Tutor] new to prog. question Message-ID: > I've a simple question. I love it when they say that... :-) > I create a list containing numbers. list1=[1,2,4,8,16,32,64,128,512] > If I wanted to find if a given number, 12 for example, is > in the list would be easy. But, how about if x+y in the list equals > the number (12) ? Thats not very simple at all. Think how you would do it in your head. Its not trivial, you have to work out every combination of all the numbers in your list. What if you allow multiplications too? There is no way Python can do that for you easily(like a built in function). Instead you will have to write some code(a function) to do it for yourself. This will probably involve two loops nested one inside the other. Something like this: for A in list for B in the remaining numbers if X == A + B: return True else: return False Also do you allow 3 numbers to add together (2+4+8)=14? That is even more complex! > Maybe I am just going the wrong way here, and there is a > easier way to do this. Nope you asked a much harder question than you realised! Alan G. From jlohman@cox.net Wed Mar 26 12:55:11 2003 From: jlohman@cox.net (Jeff Lohman) Date: Wed Mar 26 12:55:11 2003 Subject: [Tutor] Opening files? In-Reply-To: Message-ID: <002e01c2f3c0$a8c3a660$fdaa6544@cx826527a> Ok...I wrote and ran this: >>> myTest = open("C:test.txt", 'r') >>> for eachLine in myTest: ... print eachLine ... >>> myTest.close() >>> No syntax errors...yay! But this was all I got: >>> A carriage return and a prompt... how do I get the text in my file "test.txt" to print? Futhermore, if I do the following: >>> myTest = open("C:test.txt", 'r') >>> print myTest I get this: >>> What is the last bit? An address of sorts? -Jeff > > Your questions open up a whole interesting subject. Here's an > example of > opening a .txt file using 2.2.2 on a Windows machine. > > >>> myLimerick = open("E:/temp/lousyLimerick.txt", 'r') > > The above line specifies the file to open, and the 'r' says > to open it only > for reading. The next two lines tell the interpreter to print > each line of > the file for viewing. > > >>> for eachLine in myLimerick: > ... print eachLine > ... > There was a programmer in Python > > whose code (not his rhymes) were all right-on. > > This limerick blows, > > Who wrote it? Who knows? > > For my eyeballs, this limerick's blight on. > >>> myLimerick.close() > >>> > > When finished with the file, it is a good idea to explicitly > From jeff@ccvcorp.com Wed Mar 26 12:58:11 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Mar 26 12:58:11 2003 Subject: [Tutor] about regular expression References: <20030326110706.26638.qmail@web14506.mail.yahoo.com> Message-ID: <3E81EA50.6060509@ccvcorp.com> Abdirizak abdi wrote: > Hi everyone > > Can any one suggest a regular _expression that can distinguish between > two fullstop(e.g : he got married last weeek.) and abbreviated word > (e.g Al. Brown) > I am sure that this is an impossible problem. Regular expressions work at the character level, and you're trying to determine different syntactic usages of the same character. For that, you'd need full syntactical analysis. There's been a lot of advances in natural language processing over the last few years, but the task is way beyond what regexes alone are capable of -- in the same sense that space flight is beyond what the Wright Brothers' first airplane was capable of. I hate to sound like a broken record here, but regular expressions are *not* the One Solution to all text-processing problems, despite what Perl might lead one to think. "When all you have is a hammer, every problem looks like a nail" seems to apply here.... While a hammer is unarguably an extremely useful (perhaps even necessary) thing to have, there are many jobs that are better solved with other tools. (Yes, you *can* open a computer's case with just a hammer, instead of a screwdriver, but that doesn't mean it's a good idea....) Perhaps you'd be better off if you described your overall goal and requirements, and let us suggest appropriate ways (and appropriate tools) to accomplish that? Jeff Shannon Technician/Programmer Credit International From alan.gauld@bt.com Wed Mar 26 12:58:42 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Mar 26 12:58:42 2003 Subject: [Tutor] random file rotation program Message-ID: > def gangstrip(thing): # ok, everybody STRIP! > index=0 # This strips out > while index < len(thing): # define exit > thing[index]=string.strip(thing[index]) > index=index+1 # increase the counter > return thing > # > if os.path.exists(targetfile): > f1.open(targetfile,'r') > cookies=gangstrip(f1.readlines()) I think this can be replaces by a list comprehension cookies = [line.strip() for line in f1.readlines()] But I seem to recall you are stuck on Python 1.5.1 in which case your gangstrip() function is OK. > print random.choice(cookies) You don;t say if theres a problem. It looks opk to me. Reads in the cookie file, strips off surpluss whitespace then randomly selects one for printing... Its probably faster to randomly select an index and only strip that line - another approach.... cookies = f1.readlines() cookie = random.choice(cookies) print string.strip(cookie) But if you want the cookie cache to be used later preprocessing might be better. Alan g. From rob@jam.rr.com Wed Mar 26 13:00:04 2003 From: rob@jam.rr.com (Rob Andrews) Date: Wed Mar 26 13:00:04 2003 Subject: [Tutor] Opening files? In-Reply-To: <002e01c2f3c0$a8c3a660$fdaa6544@cx826527a> Message-ID: Just at a glance, I'd say you left the / off after the C: in your opening statement. And I believe that last bit is the address of the myTest object. -Rob -- Mississippi Hermetic Connection: http://uselesspython.com/hermetica/hermetica.html > -----Original Message----- > Ok...I wrote and ran this: > > >>> myTest = open("C:test.txt", 'r') > >>> for eachLine in myTest: > ... print eachLine > ... > >>> myTest.close() > >>> > > No syntax errors...yay! But this was all I got: > > >>> > > > A carriage return and a prompt... how do I get the text in my > file "test.txt" to print? > > Futhermore, if I do the following: > > >>> myTest = open("C:test.txt", 'r') > >>> print myTest > > I get this: > > > >>> > > What is the last bit? An address of sorts? > > -Jeff From alan.gauld@bt.com Wed Mar 26 13:03:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Mar 26 13:03:02 2003 Subject: [Tutor] nominees please Message-ID: > I'd like to open the floor to nominees for outstanding Tutor > List posts. I'd nominate Danny Yoo and Magnus Lycka for most everything they post. I wish I had their clarity of thought and inventive knack for examples! Alan g. From alan.gauld@bt.com Wed Mar 26 13:08:06 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Mar 26 13:08:06 2003 Subject: [Tutor] about regular expression Message-ID: This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C2F3C2.5A100700 Content-Type: text/plain; charset="iso-8859-1" > Can any one suggest a regular _expression that can distinguish between two fullstop > (e.g : he got married last weeek.) and abbreviated word (e.g Al. Brown), I have tried > some but I couldn't get them right. please give an example each of these two. Sorry but I don't think that's possible. You are expecting the regex to be able to understand context. You might be able to draw up some rules that work most of the time (sentences must have multiple words in them for example) but there would always be exceptions that fall though. Regular expressions are powerful but they aren't magic. The computer is still stupid. Of course someone might just come up with something that proves me wrong, but I don't think so.... Alan G. ------_=_NextPart_001_01C2F3C2.5A100700 Content-Type: text/html; charset="iso-8859-1"
 >  Can any one suggest a regular _expression that can distinguish between two fullstop 
>  (e.g : he got married last weeek.)  and abbreviated word (e.g Al. Brown), I have tried   
>  some but  I couldn't get them right. please give an example each of these two. 
 
Sorry but I don't think that's possible. You are expecting the regex to be able to understand
context.
 
You might be able to draw up some rules that work most of the time (sentences must have
multiple words in them for example) but there would always be exceptions that fall though.
 
Regular expressions are powerful but they aren't magic. The computer is still stupid.
 
Of course someone might just come up with something that proves me wrong, but I don't
think so....
 
Alan G.
 
------_=_NextPart_001_01C2F3C2.5A100700-- From alan.gauld@bt.com Wed Mar 26 13:10:03 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Mar 26 13:10:03 2003 Subject: [Tutor] about regular expression Message-ID: > In standard well-formed English, a full stop period is > usually followed by two spaces, whereas abbreviations > are only followed by one. Unfortunately that rule of usage is no deprecated. Modern practice is to use single spacing for both. > Perhaps this will serve for the purpose for the regex. In practice it was only observed by touch typists and publishers anyway so probably wouldn't make a lot of difference. I think its too much to ask of a regex... Alan G From alan.gauld@bt.com Wed Mar 26 13:14:08 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Mar 26 13:14:08 2003 Subject: [Tutor] Opening files? Message-ID: > When I want to try and open(import?) and read files, what are > the best commands to use? > Older python versions used open() to open a file, newer versions (2.2.x) use file(). open() worls on both so if backwards compatibility matters use open(). > Also, how do I specify the path that python needs to follow > to open the file? Not sure what you mean here. You specify it in the form that your operating system expects. You can go to town on this and use various OS independant symbols (from the os module?). Normally you just pass the full path to open() or file() > I am trying to manipuilate text(.txt) files with python 2.2.2. You might find the file handling topic in my tutorial useful. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From dyoo@hkn.eecs.berkeley.edu Wed Mar 26 13:16:00 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 26 13:16:00 2003 Subject: [Tutor] Opening files? In-Reply-To: <002e01c2f3c0$a8c3a660$fdaa6544@cx826527a> Message-ID: > Futhermore, if I do the following: > > >>> myTest = open("C:test.txt", 'r') > >>> print myTest > > I get this: > > > >>> > > What is the last bit? An address of sorts? Hi Jeff, What you are seeing is Python's response to printing the file object itself, and Python's default response is to print the address where that object lives. Actually, your program looks ok: what you have in 'myTest' is a "file object" --- it's a thing that will respond to commands like "readline()" or "read()". Try doing: print myTest.read() or print myTest.readline() as your next step, and experiment with these "reading" commands. By the way, if you're interested in details: The reference documentation tells us many of the things we can do with file objects. You can browse through it: http://www.python.org/doc/lib/bltin-file-objects.html Hope this helps! From alan.gauld@bt.com Wed Mar 26 13:20:13 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Mar 26 13:20:13 2003 Subject: [Tutor] Opening files? Message-ID: > >>> myTest = open("C:test.txt", 'r') You probably need to specify the directory as wekll as the drive: myTest = open("C:\\test.txt") # read by default, \\ coz of escaped chars OR myTest = open("C:/test.txt") # read by default, / works in a path > > What is the last bit? An address of sorts? Yes, its where the file object is living in memory.... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From jeff@ccvcorp.com Wed Mar 26 13:23:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Mar 26 13:23:02 2003 Subject: [Tutor] new to prog. question References: Message-ID: <3E81F00B.30903@ccvcorp.com> alan.gauld@bt.com wrote: >>I create a list containing numbers. list1=[1,2,4,8,16,32,64,128,512] >>If I wanted to find if a given number, 12 for example, is >>in the list would be easy. But, how about if x+y in the list equals >>the number (12) ? >> >> > >[...] >Something like this: > >for A in list > for B in the remaining numbers > if X == A + B: return True >else: return False > Alan's right -- there's no way to do this other than adding pairs of numbers and seeing if they match your target. There's one optimization you *can* make, providing that your list is sorted. In that case, as you march through your inner loop, you know that the value of B will only get bigger, so once A + B is greater than X, you know that none of the later values of B can possibly work. At this point, you can skip the rest of the list and move on to the next value of A. Similarly, once the value of A is greater than X, then (assuming no negative values for B) you know that there's nothing that can be added to A that'll sum to X. In fact, since values of B will always be greater than A (because B is "the remaining numbers" in the list), if A + B[0] is greater than X then no further values of A or B can possibly equal X. Jeff Shannon Technician/Programmer Credit International From SWidney@ci.las-vegas.nv.us Wed Mar 26 14:05:02 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Wed Mar 26 14:05:02 2003 Subject: [Tutor] Opening files? Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8471@sovereign.ci.las-vegas.nv.us> > Ok...I wrote and ran this: > > >>> myTest = open("C:test.txt", 'r') > >>> for eachLine in myTest: > ... print eachLine > ... > >>> myTest.close() > >>> > > No syntax errors...yay! But this was all I got: > > >>> > > > A carriage return and a prompt... how do I get the text in my > file "test.txt" to print? Try calling the readlines() method of your open file, like this: >>> myTest = open("C:test.txt", 'r') >>> for eachLine in myTest.readlines(): ... print eachLine ... S From ahimsa@onetel.net.uk Wed Mar 26 14:39:01 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Wed Mar 26 14:39:01 2003 Subject: [Tutor] nominees please In-Reply-To: References: Message-ID: <200303261940.09726.ahimsa@onetel.net.uk> Rob =46rom my limited experience on this list, I would propose that Danny, Ma= gnus,=20 and Alan be considered. Also, Bob would be a close contender too. I submi= t=20 these four because as a newbie to Python and programming, I have consiste= ntly=20 found that their replies to my questions have been informed and informati= ve=20 and really patient, and kudos to them for not only great knowledge, but a= lso=20 for their positive contribution to an online community. Andy On Wednesday 26 Mar 2003 5:36 am, Rob Andrews wrote: > I'd like to open the floor to nominees for outstanding Tutor List posts= =2E > Over time, some absolutely fantastic posts have been made to this list, > explaining key concepts in crisp, clear, often entertaining ways. > > Useless Python 2.0 is in the works, and it would be great to go life wi= th > awards for excellent, insightful, or just plain useless posts. > > Just in case anyone takes me up on this (please!), I don't know if the > Illuminati of the Tutor List fnord will want replies to go back to the > Tutor List or not. > > thanks for reading this far down, > Rob > rob@uselesspython.com > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor --=20 News from a diiferent perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From abli@freemail.hu Wed Mar 26 14:48:02 2003 From: abli@freemail.hu (Abel Daniel) Date: Wed Mar 26 14:48:02 2003 Subject: [Tutor] Entry in Tkinter In-Reply-To: <3E81E677.5070005@brturbo.com> References: <3E81E677.5070005@brturbo.com> Message-ID: <20030326194634.GA5810@hooloovoo> Diego Prestes wrote: > Hello, > Im trying tu use the Entry widget. I type a word in the Entry and in > find1 module it use the entry using the option self.proc.get(), but when > I use this, I have this error: > > AttributeError: 'NoneType' object has no attribute 'get' > > In a test I try to use the Entry and it works normally, but in my > program not. > Someone know what I could be doing wrong? > > self.find1 = Button(frame3, text="Find", command=self.find1).pack(side=LEFT) > self.proc = Entry(frame3, background="white").pack(side=LEFT) > > def find1(self): #count the number of times that the word in the text > vpal = count(self.text,self.proc.get()) > tkMessageBox.showinfo("Find","%s and %d" % (self.proc.get(),vpal)) Your problem is that you store the result of the pack() method instead of the widget instance. pack() returns None, so when you want to call self.proc.get() in your find1 method, you are trying to access an attribute of None giving the AttributeError you saw. Some examples with the interactive interpreter: >>> from Tkinter import * >>> box=Entry() >>> type(box) >>> box >>> p=box.pack() >>> p >>> type(p) >>> box.get() 'asdf' >>> # which was the text I typed in. >>> p.get() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'None' object has no attribute 'get' >>> A second problem will be that in the code you posted you rebind self.find1 when making the Button. Something like this should work: self.find_button = Button(frame3, text="Find", command=self.find1) self.find_button.pack(side=LEFT) self.proc = Entry(frame3, background="white") self.proc.pack(side=LEFT) your find1 method looks ok. -- Abel Daniel From Sean Abrahams Wed Mar 26 14:50:03 2003 From: Sean Abrahams (Sean Abrahams) Date: Wed Mar 26 14:50:03 2003 Subject: [Tutor] Database Connectivity Message-ID: <12325859.20030326115249@sfsu.edu> I'm looking to discuss handling database connections with Python in conjunction with web applications. When to close a connection, persistent connections, etc. I made the following interface for selecting data from a database. """ def dbSelect(db, selectKeys, select, rows=None): """Select information from a database. db = database you want to connect to selectKeys = a list of keys that match up with the table columns select = sql select statement rows = how many rows to fetch """ dbCon = dbConnect(db) dbCursor = dbCon.cursor() dbCursor.execute(select) if rows == 1: dbResults = dbCursor.fetchone() elif rows > 1: dbResults = dbCursor.fetchmany(rows) else: dbResults = dbCursor.fetchall() # If there's only one requested then just throw # it into a standard dictionary, instead of a # list of dictionaries. if rows == 1: i = 0 results = {} for field in selectKeys: try: results[field] = dbResults[i] i = i + 1 except TypeError, e: # Occures when query returns no results pass # If there's more than one row returned, compile # a list of dictionaries else: results = [] for field in dbResults: i = 0 items = {} for item in field: items[selectKeys[i]] = item i = i + 1 results.append(items) return results """ So my first question is when should I explicitly close the database connection? After at the end of this function? If I have 10 selects in one web cgi, isn't that extremely inefficient to connect/disconnect 10 times? Should I take the dbConnect(db) call out of here, put it in the main code, run my 10 selects and explicitly close in the main code? Could I put some code in this function to check for an existing database connection and use that? Then when do I close it? In summation, what's the most efficient way to grab data from a database? I hope to learn much from this. Thank you, --Sean From brian@dungeoncrawl.org Wed Mar 26 15:12:02 2003 From: brian@dungeoncrawl.org (Brian Christopher Robinson) Date: Wed Mar 26 15:12:02 2003 Subject: [Tutor] Some Basic Questions Message-ID: <5.2.0.9.0.20030326151136.024255f0@localhost> I just began writing Python today and have a few basic questions: How can I read a single character from the standard input without consuming any more input? Is there any way to write a boolean function? I wanted to write a simple is_alpha function (which may be in the standard library but I'm leanring), and this is what I came up with: def is_alpha(c) : letters = re.compile("[a-zA-Z]") return letters.match(c) Instead of checking for true or false I check to see if None is returned, but that seems a little kludgy. How can I print to standard out without printing a newline? It seems that the print statement always adds a newline and I haven't found any other outputting functions yet. -- "Words are poison." - Nick on love From Ike Hall Wed Mar 26 15:22:01 2003 From: Ike Hall (Ike Hall) Date: Wed Mar 26 15:22:01 2003 Subject: [Tutor] nominees please References: <200303261940.09726.ahimsa@onetel.net.uk> Message-ID: <000d01c2f3d5$49a021d0$be27e183@chief> I would second this nomination, much on the same grounds. Ike ----- Original Message ----- From: "ahimsa" To: "Rob Andrews" ; "Python Tutor" Sent: Wednesday, March 26, 2003 1:40 PM Subject: Re: [Tutor] nominees please > Rob > >From my limited experience on this list, I would propose that Danny, Magnus, > and Alan be considered. Also, Bob would be a close contender too. I submit > these four because as a newbie to Python and programming, I have consistently > found that their replies to my questions have been informed and informative > and really patient, and kudos to them for not only great knowledge, but also > for their positive contribution to an online community. > > Andy > > On Wednesday 26 Mar 2003 5:36 am, Rob Andrews wrote: > > I'd like to open the floor to nominees for outstanding Tutor List posts. > > Over time, some absolutely fantastic posts have been made to this list, > > explaining key concepts in crisp, clear, often entertaining ways. > > > > Useless Python 2.0 is in the works, and it would be great to go life with > > awards for excellent, insightful, or just plain useless posts. > > > > Just in case anyone takes me up on this (please!), I don't know if the > > Illuminati of the Tutor List fnord will want replies to go back to the > > Tutor List or not. > > > > thanks for reading this far down, > > Rob > > rob@uselesspython.com > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > News from a diiferent perspective: > http://www.scoop.co.nz > http://www.fromthewilderness.com > ____________________________ > Prevent digital monopoly: > http://www.againsttcpa.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From python@jaydorsey.com Wed Mar 26 16:53:02 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Wed Mar 26 16:53:02 2003 Subject: [Tutor] Some Basic Questions In-Reply-To: <5.2.0.9.0.20030326151136.024255f0@localhost> References: <5.2.0.9.0.20030326151136.024255f0@localhost> Message-ID: <3E822091.6050400@jaydorsey.com> Brian Christopher Robinson wrote: > How can I print to standard out without printing a newline? It seems that > the print statement always adds a newline and I haven't found any other > outputting functions yet. To omit the newline after a print statement, add a comma at the end of the print statement. Example: >>> for i in range(1,3): ... print i ... 1 2 >>> for i in range(1,3): ... print i, ... 1 2 hth Jay -- Jay Dorsey python at jay dorsey dot com From R. Alan Monroe" References: <20030326140102.15249.53439.Mailman@mail.python.org> Message-ID: <8174876066.20030326174418@columbus.rr.com> > In standard well-formed English, a full stop period is usually followed by > two spaces, whereas abbreviations are only followed by one. Perhaps this > will serve for the purpose for the regex. Recommendations vary. I was a graphic design major in the late 80s/ early 90s, and most of the typography articles around that time stated that two spaces was becoming deprecated in favor of a single space. Alan From charlie@begeistert.org Wed Mar 26 19:19:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Wed Mar 26 19:19:01 2003 Subject: [Tutor] Re: Natural Language Parsing, was re: Regular Expressions In-Reply-To: <20030326170007.13525.36277.Mailman@mail.python.org> References: <20030326170007.13525.36277.Mailman@mail.python.org> Message-ID: <20030327012125.4593.29@wonderland.1048669968.fake> > > Hate to make it harder but English is hard. Maybe non-capitalized word > followed by a period then by spaces(s) and then a capitol letter? I'm > sure I might be missing something (You would need a way to catch > questions such as "What time is lunch" said Mary?) but maybe it will find > more word for you. "Capital" idea! Regular Expressions is a red herring on this I think. What you need is a natural language parser. Logic and rules is something which Python is weak at, I think, although I ready to be corrected. You need a rules or AI engine which does this for you. Look at Prolog or Alicebot (www.alicebot.org). Systems which can understand questions can easily deal with grammar. Charlie From jeff@ccvcorp.com Wed Mar 26 20:15:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Mar 26 20:15:02 2003 Subject: [Tutor] Some Basic Questions References: <5.2.0.9.0.20030326151136.024255f0@localhost> Message-ID: <3E8250BE.2050000@ccvcorp.com> Brian Christopher Robinson wrote: > I just began writing Python today and have a few basic questions: > > How can I read a single character from the standard input without > consuming > any more input? > > How can I print to standard out without printing a newline? It seems > that > the print statement always adds a newline and I haven't found any other > outputting functions yet. In the sys module there's two special objects, sys.stdin and sys.stdout. They give you file-like access to standard input and output. So you could, perhaps, use sys.stdin.read(1) to read a single character from standard input -- but note that your program will block here if there isn't a character waiting to be read, and I don't know how effective this would be for keyboard input. Good access to the keyboard is platform-specific, and you can look in the curses module (unix) or the msvcrt module (Windows) for help there. Similarly, you can use sys.stdout.write() to send text to standard output without any of the "helpful" formatting that print does. The print statement is designed to be a convenience, rather than to be precise, so if you want byte-by-byte control of your output then sys.stdout.write() is the way to go. > Is there any way to write a boolean function? I wanted to write a simple > is_alpha function (which may be in the standard library but I'm > leanring), > and this is what I came up with: > > def is_alpha(c) : > letters = re.compile("[a-zA-Z]") > return letters.match(c) > > Instead of checking for true or false I check to see if None is returned, > but that seems a little kludgy. Note that, in a boolean context, None evaluates to false so this would work with your function as-is: if is_alpha(mystring): # do something However, the typical method of indicating true or false is to return 1 or 0, though pretty much anything that can conceptually be seen as "empty" will evaluate as false and everything else will evaluate as true. Thus, an empty string '' is false, while a nonempty string 'abc' is true. Recent versions of Python include a boolean type and built-in constants True and False... but those constants are really just prettified 1s and 0s, and True + True = 2. Also, isalpha() *does* already exist as a method of strings, along with isdigit(), isalnum(), and a few others. >>> x = 'abc' >>> x.isalpha() 1 >>> x.isdigit() 0 >>> x.isalnum() 1 >>> Even if I were to write my own is_alpha() function, I'd probably avoid using regular expressions -- I generally avoid them anyhow, actually. Regexes are a lot more heavyweight than is necessary for many problems, and a lot more confusing too. You'd be better off using constants from the string module: >>> string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> >>> def is_alpha(x): ... from string import ascii_letters ... for char in x: ... if char not in ascii_letters: ... return 0 ... return 1 ... >>> is_alpha('spam') 1 >>> is_alpha('123') 0 >>> is_alpha('spam and eggs!') 0 >>> Hope this helps. It's really useful to have some idea of what's in the standard library -- I know it's tedious, but I strongly recommend skimming through the Library Reference docs. Don't worry about understanding everything, just a quick glance to see what kind of stuff is there. Jeff Shannon Technician/Programmer Credit International From jlohman@cox.net Wed Mar 26 20:45:03 2003 From: jlohman@cox.net (jlohman@cox.net) Date: Wed Mar 26 20:45:03 2003 Subject: [Tutor] Opening files? Message-ID: <20030327014236.VWYY1559.fed1mtao05.cox.net@smtp.west.cox.net> Ok...I've taken everyone's advice, and it STILL did not work, though there were no syntax errors...hmmmm... This was the orginal puzzle: >>> myTest = open("C:test.txt", 'r') >>> for eachLine in myTest: ... print eachLine ... >>> myTest.close() >>> things were read, but nothing printed. Now, I decided to break it down. I enter(">>>" is the prompt that the IDLE "Python Shell" gives me): >>> myTest = open("C:/test.txt", 'r') It runs.I get a prompt, so I enter: >>> for eachLine in myTest: print eachLine It goes to the next line, no ">>>" just a blinking cursor, and only when I hit ENTER again, do I get the text from my file. Furthermore, it took me a bit of tweaking and trying just to get the above command to give me what I want. Now, I am a total novice to Python, and advice may have been given making the assumptions that certain basics of syntax were done. They are not. It appears there are levels of indentaion and carriage-returns that are not totally obvious from examples and CERTAINLY do not cut-and-paste well from examples given in the documanetaion I've found. I use notepad to write and then paste that into the IDLE "Python Shell". Is there some basic TAB or SPACE or ... or >>> or anything that i am missing to get these programs to line up right? Is Python always this touchy about whitspace and indentations? Is there soem documentaion somewhere about this, or an editor/compliler that is more forgiving about indentaion s and blocks? -Jeff From jeff@ccvcorp.com Wed Mar 26 21:05:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Mar 26 21:05:02 2003 Subject: [Tutor] Opening files? References: <20030327014236.VWYY1559.fed1mtao05.cox.net@smtp.west.cox.net> Message-ID: <3E825C87.9070509@ccvcorp.com> jlohman@cox.net wrote: >>>>for eachLine in myTest: >>>> >>>> > print eachLine > >It goes to the next line, no ">>>" just a blinking cursor, and only when I hit ENTER again, do I get the text from my file. Furthermore, it took me a bit of tweaking and trying just to get the above command to give me what I want. > Ah, yes. When you're in an indented block, IDLE can't process the block until it's complete. But since the block can be several (many) lines long, how does it know when the block is complete? The answer is that it assumes it's complete when you hit Enter on a blank line. >I use notepad to write and then paste that into the IDLE "Python Shell". Is there some basic TAB or SPACE or ... or >>> or anything that i am missing to get these programs to line up right? Is Python always this touchy about whitspace and indentations? > Pasting multiple lines into a Python shell (whether that be python.exe, IDLE, PythonWin, or whatever) is always pretty dicey. Shells are inherently line-oriented, so dumping a couple lines at a time tends to confuse them. If you paste a line at a time, and hit Enter within the shell yourself, that might work better (though it could be tedious for long code fragments). Another (better) solution is to simply create your code as functions, save it as a file, and then import it as a module from within IDLE. Instead of cutting and pasting, save what you've got in Notepad as, say, test.py. (I recommend putting it somewhere like [python directory]\Lib\site-packages, where it'll be separate from the standard library files but Python can still find it easily.) Then you can switch to IDLE and 'import test', and after that you'll be able to access your functions as 'test.myfunction()'. If you make changes to the code in Notepad, then in order to make the changes show up in IDLE you'll have to save the file again and then type 'reload(test)'. Hope this helps. If you still need a little more, there's an introduction to using IDLE floating around somewhere (I don't happen to have the URL, but maybe someone else will chime in with it). That might be a good thing for you to read through. Good luck! :) Jeff Shannon Technician/Programmer Credit International From a_abdi406@yahoo.com Wed Mar 26 21:08:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed Mar 26 21:08:02 2003 Subject: [Tutor] about reg expression Message-ID: <20030326235958.19801.qmail@web14506.mail.yahoo.com> --0-805182118-1048723198=:18604 Content-Type: text/plain; charset=us-ascii Hi I have a sentence with tokens tagged with ... and I want to split after the fullstop tagged with. so that I can tag the whole sentence with .............. I am having problem setting up with appropriate regular expression can anyone help me set up a Regular Expression for achieving this ? My final string will look like this: ..it is a token . thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-805182118-1048723198=:18604 Content-Type: text/html; charset=us-ascii

Hi

I  have a sentence  with tokens tagged with <W>...</W> and I want to split after the fullstop tagged with<W>.</W>  so that I can tag  the whole sentence with<S ID = 'S-0'> .............<W>.</W> </S>

I am having problem setting up with appropriate regular expression can anyone help me set up a Regular Expression for achieving this ?

My final string will look like this: 
 <S ID = 'S-0'>..<W>it</W> <W> is</W> <W>a</W><W> token</W> <W>.</W></S>

thanks in advance

 



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-805182118-1048723198=:18604-- From fredm@smartypantsco.com Wed Mar 26 21:21:47 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Wed Mar 26 21:21:47 2003 Subject: [Tutor] new to prog. question (cleared-up) In-Reply-To: <20030326025232.27996.qmail@ligbr.com.br> Message-ID: <5.1.0.14.0.20030327131211.03781350@192.168.1.1> At 02:52 AM 26/03/03 +0000, riex@ligbr.com.br wrote: >What I was tinking is: in a list containing numbers, which could be >randon, how would I go about >figuring out if: > x in the list is the given number >not the problen >or x+x in the list is the given number >or even x+x+x in the list is the given number >So far just using addition. I assume you mean x+y in the list If you need to do this comparison a few times, it may be a good idea to construct a new list of numbers which contain the sum of the elements of the original list (plus the original list if you also want to compare against just x) The new list needs to be sorted and duplicates thrown out: set = [1, 2, 3, 5, 6, 9, 11, 15, 17] # just a sample list of random numbers sumset = [(x+y) for x in set for y in set] sumset = sumset + set # include original set if you want to compare against x also sumset.sort() count = 0 newsumset = [] for element in sumset: count = count + 1 if element not in sumset[count:]: newsumset.append(element) >>> print set >>> [1, 2, 3, 5, 6, 9, 11, 15, 17] >>> print sumset >>> [1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 19, 19, 20, 20, 20, 20, 20, 20, 21, 21, 22, 22, 22, 23, 23, 24, 24, 26, 26, 26, 26, 28, 28, 30, 32, 32, 34] >>> print newsumset >>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 34] >>> 24 in newsumset 1 >>> 25 in newsumset 0 This of course may not be practical if your original set is very large, but your original post suggested ten elements or so. HTH, Alfred Milgrom From magnus@thinkware.se Wed Mar 26 21:25:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Mar 26 21:25:03 2003 Subject: [Tutor] about regular expression In-Reply-To: <20030326140102.15249.53439.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030327003631.02cea008@www.thinkware.se> At Wed, 26 Mar 2003 03:07:06 -0800 (PST), Abdirizak abdi wrote: >Can any one suggest a regular _expression that can distinguish between two >fullstop(e.g : he got married last weeek.) and abbreviated word (e.g Al. >Brown), I have tried some but I couldn't get them right. please give an >example each of these two. There's no magic in regular expressions. Would you be able to teach a person who could read latin letters, but didn't understand English at all how to do that? If you can do that in a clear and unambious way, you can do the same with a computer. But I think I'd be able to show you an example that breaks your rule--for any rule you come up with... Even if you knew all possible abbreviations, how would you know whether an abbreviation ended a sentence or not if it's followed by a word that is always capitlized? The spoken languages are full of ambiguities. This can simply not be done in a reliable way. There are probably heuristic approaches that will lead to a big probablility of correct guesses, but there is no way of knowing for sure all the time. Not even if you know the language... We use a lot of context to disambiguate written text, and for spoken language we can't manage without the cues in the voice and in gestures etc. (Just read transcripts of what people have said in different situations. They are usually full of ambiguity.) But since people are intelligent, we can usually figure things out even if the message is ambiguous. Computers aren't clever though. Just look att automatic translators, such as babelfish... Understanding language is too tough for machines... Look at the following cases: a) I really liked Al. Washington is not as nice. b) I really liked Al. Washington in that movie. Case a) is two sentences, and b) is only one. Not that people typically use a full stop when they abbreviate Albert to Al, but that was your suggestion... I'm sure we can make up other cases were it's unclear whther an abbreviation ends a sentence unless we perform some kind of non-trivial grammer analysis. We can't even start sentences with capital letters all the time: "mm is the correct abbreviation for milli metre, Mm on the other hand, means mega metre, or one million metres." "2001 will go to history as a year that changed public attitudes on threats against western countries." Then there are cases where the same word / abbreviation can mean different things. I'm pretty sure words like "as" and "is" are used as abbreviations in some contexts. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Wed Mar 26 21:39:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Mar 26 21:39:01 2003 Subject: [Tutor] nominees please In-Reply-To: <20030327011502.924.16147.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030327030157.02ce4950@www.thinkware.se> At Wed, 26 Mar 2003 19:40:09 +0000, Andy wrote: > From my limited experience on this list, I would propose that Danny, >Magnus, and Alan be considered. Also, Bob would be a close contender >too. Actually, I very often see that Jeff Shannon wrote *exactly* what I was planning to write. (But without getting so longwinded and deviating so much from the subject as I tend to do! ;) If I'm a "nominee" I think he should be. But note that the request was for posts, not for persons. I'm curious to know what posts helped people most, and to what extent people agree on what is helpful and what is not. Regardless of whom they were written by, I'm sure I could learn something from that. The more I work as a software developer, the more I feel that effective and positive communication between humans is one of the most important and often underestimated factors in sotware development, much more important that the choice of programming language and development process etc. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From jlohman@cox.net Wed Mar 26 21:47:02 2003 From: jlohman@cox.net (jlohman@cox.net) Date: Wed Mar 26 21:47:02 2003 Subject: [Tutor] Opening files? Message-ID: <20030327024602.WPZE1559.fed1mtao05.cox.net@smtp.west.cox.net> > > Another (better) solution is to simply create your code as functions, > save it as a file, and then import it as a module from within IDLE. > Instead of cutting and pasting, save what you've got in Notepad as, > say, test.py. (I recommend putting it somewhere like [python > directory]\Lib\site-packages, where it'll be separate from the standard > library files but Python can still find it easily.) Then you can switch > to IDLE and 'import test', and after that you'll be able to access your > functions as 'test.myfunction()'. If you make changes to the code in > Notepad, then in order to make the changes show up in IDLE you'll have > to save the file again and then type 'reload(test)'. Ahah! I downloaded Crimson editor and then found the editor in IDLE...bottom line is now I can write and run not only my own awkward little test programs, but I can use examples and pick them apart...NOW I am programming. This was along the lines of "Where is the "ANY" key?" Now I know where it is, and I can continue... Thanks, Jeff! -Jeff From dyoo@hkn.eecs.berkeley.edu Wed Mar 26 22:16:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 26 22:16:01 2003 Subject: [Tutor] about regular expression [breaking text into sentences] In-Reply-To: <5.1.0.14.0.20030327003631.02cea008@www.thinkware.se> Message-ID: > Computers aren't clever though. Just look att automatic translators, > such as babelfish... Understanding language is too tough for machines... I think Abdirizak is looking for a solution to the common case problem, and that's something we can probably deal with. The TeX text formatter, for example, does use an arbitrary rule for determining the ending of sentences. And for the most part, it works! For the exceptional cases, TeX provides a way to say that a space should be treated as a word separator rather than a sentence separator by using the special tilde spacing character. ("~") Although I can't remember TeX's rules, there's nothing stopping us from defining our own arbitrary rule that isn't always correct, but gets us somewhat close. If we can break a problem down into the common case and the exceptional cases, we've made some progress, even if we can't get it down perfectly. Let's define for the moment that a sentence break as an an ending punctuation mark ('.', '!'), followed by whitespace. ### >>> se_break = re.compile("""[.!?] ## Some ending puncuation ... \s+ ## followed by space. ... """, re.VERBOSE) >>> se_break.split("this is a test. Can you see this? Hello! Goodbye world") ['this is a test', 'Can you see this', 'Hello', 'Goodbye world'] ### This is a good start, and can be improved on: I know this isn't perfect, but it might be enough to play around with teaching a computer to recognize sentence boundaries. > Look at the following cases: > > a) I really liked Al. Washington is not as nice. > > b) I really liked Al. Washington in that movie. > > Case a) is two sentences, and b) is only one. Not that people typically > use a full stop when they abbreviate Albert to Al, but that was your > suggestion... I'm sure we can make up other cases were it's unclear > whther an abbreviation ends a sentence unless we perform some kind of > non-trivial grammer analysis. But I think we can attack this problem trivially by using a non-trivial module. *grin* The Monty Tagger tagging engine will do syntactic markup of a sentence with pretty good accuracy: http://web.media.mit.edu/~hugo/montytagger/ and if we apply it to those sentences, we can see how Monty Tagger interprets those words: ### > I really liked Al. Washington is not as nice. I/PRP really/RB liked/VBD Al/NNP ./. Washington/NNP is/VBZ not/RB as/IN nice/JJ ./. -- monty took 0.05 seconds. -- ### Monty Tagger attaches a semantic 'tag' to each word in our sentence. And now we can probably do something where we look at the stream of word tags, and if a certain sequence of word tags occurs, like ["VBD", "NNP", ".", "NNP", "VBZ"], we can say with some certainty that there's a sentence break in between there, since English doesn't let us have two verbs together like that in a single sentence! Using something like Monty Tagger to do the heavy lifting may give us enough power to make good progress. Hmmm... but I think I'm being handwavy here. *grin* I have not tried this approach yet, so the problem might be hard. I'm positive the Natural Language Processing folks have attacked this problem with vigor, though, and I'm not convinced this is an impossible problem. If I have time, I'll start reading that book I picked up from the college bookstore, http://www-nlp.stanford.edu/fsnlp/promo/ and see what they say about this. From dyoo@hkn.eecs.berkeley.edu Wed Mar 26 22:40:14 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 26 22:40:14 2003 Subject: [Tutor] nominees please In-Reply-To: <000d01c2f3d5$49a021d0$be27e183@chief> Message-ID: > I would second this nomination, much on the same grounds. Hello! I have a problem with this nomination, specifically on the basis of a type mismatch. Rob asked: > > > I'd like to open the floor to nominees for outstanding Tutor List > > > posts. And posts are related to posters, but they are not the same kind of thing. *grin* Seriously though: it might be more worthwhile to nominate outstanding threads, rather than individual posts! Much of the power of Tutor is not in single posts or posters, but in the groups of messages of a thread. I really liked the thread when we were talking about putting the prime numbers in a spiral. http://mail.python.org/pipermail/tutor/2001-April/004862.html ... even though it wasn't really related to Python. *grin* While I was searching for it, I ran into: http://www.hermetic.ch/pns/pns.htm and http://lists.canonical.org/pipermail/kragen-hacks/1998-November/000134.html There's some cool math there! Does anyone want to try writing that Prime Number Spiral program in Tkinter? Best of wishes! From fredm@smartypantsco.com Wed Mar 26 23:05:01 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Wed Mar 26 23:05:01 2003 Subject: [Tutor] nominees please In-Reply-To: References: <000d01c2f3d5$49a021d0$be27e183@chief> Message-ID: <5.1.0.14.0.20030327144839.0378a870@192.168.1.1> OK, you are right that the request was for individual posts rather than posters, but I would tend to agree with the previous posters about the nominations. The outstanding quality of this list is a result of the dedication and effort put in by some brilliant people such as Magnus Lycka, Danny Yoo, and Alan Gauld. To illustrate this point, here are some individual postings which I found helpful and/or insightful and/or amazing: Magnus Lycka for "Re: [Tutor] getting started" on 16/11/2002 Despite the nondescript topic name, this was actually a discussion on the use of while 1: construct Alan Gauld for "RE: [Tutor] getting started" on 17/11/2002 A reply and continuation on the use of while 1: This of course illustrates Danny's point about nominating threads Danny Yoo for "Re: [Tutor] need some help for program!! [More hidden markov models " on 17/11/2002 An eye-opening look at Hidden Markov models Magnus Lycka for "Re: [Tutor] Editors/form builders for GUI and productivity" on 13/12/2002 Encouraging people to think about what can be programmed, such as more automated GUI construction Thanks to all you guys for making this such an interesting list to subscribe to. Fred Milgrom At 07:32 PM 26/03/03 -0800, Danny Yoo wrote: > > I would second this nomination, much on the same grounds. >Hello! > >I have a problem with this nomination, specifically on the basis of a type >mismatch. Rob asked: > > > > > I'd like to open the floor to nominees for outstanding Tutor List > > > > posts. > >And posts are related to posters, but they are not the same kind of thing. >*grin* > > >Seriously though: it might be more worthwhile to nominate outstanding >threads, rather than individual posts! Much of the power of Tutor is not >in single posts or posters, but in the groups of messages of a thread. From tbstep@tampabay.rr.com Wed Mar 26 23:13:02 2003 From: tbstep@tampabay.rr.com (Todd Stephens) Date: Wed Mar 26 23:13:02 2003 Subject: [Tutor] nominees please References: <000d01c2f3d5$49a021d0$be27e183@chief> <5.1.0.14.0.20030327144839.0378a870@192.168.1.1> Message-ID: <016301c2f417$078cfa60$363fa418@tampabay.rr.com> ---- Original Message ---- From: "Alfred Milgrom" To: "Danny Yoo" ; "Python Tutor" Sent: Thursday, March 27, 2003 12:01 AM Subject: Re: [Tutor] nominees please > > Thanks to all you guys for making this such an interesting list to > subscribe to. > Fred Milgrom > I agree. As a consummate lurker, I have found this list to be both informative and entertaining. My one "complaint" is that there are just too many knowledgeable people posting here! I can scarcely keep up with the daily volume from this list! :) Todd Stephens From rob@jam.rr.com Thu Mar 27 02:01:02 2003 From: rob@jam.rr.com (Rob Andrews) Date: Thu Mar 27 02:01:02 2003 Subject: [Tutor] nominees please In-Reply-To: <5.1.0.14.0.20030327030157.02ce4950@www.thinkware.se> Message-ID: > I'm curious to know what posts helped people most, and to what extent > people agree on what is helpful and what is not. Regardless of whom they > were written by, I'm sure I could learn something from that. The more I > work as a software developer, the more I feel that effective and positive > communication between humans is one of the most important and often > underestimated factors in sotware development, much more important that > the choice of programming language and development process etc. This is the sort of thing I had in mind. Picking out particularly helpful posts (although it is good to show some appreciation for those who really lead by example) and spiriting away copies for posterity (and perhaps periodic updates, but that's a different topic). -Rob From am@fx.ro Thu Mar 27 02:51:01 2003 From: am@fx.ro (Adrian Maier) Date: Thu Mar 27 02:51:01 2003 Subject: [Tutor] Tkinter no longer available after compiling Python In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Sat, Mar 22, 2003 at 01:21:24PM -0800 References: <200303220324.IAA21132@WS0005.indiatimes.com> Message-ID: <20030427132224.A2223@coto> Hello all! The operating system that I currently use is Debian Linux 2.2r5. It ships with python 1.5.2 and i thought it would be a good idea to upgrade Python: tar xzvf Python-2.2.2.tar.gz ./configure ; make ; make install Now I have both versions installed ( I didn't uninstall python 1.5.2 because there are some debian packages that depend on it ). The new version is in /usr/local: the binaries in /usr/local/bin and the other files in /usr/local/lib/python2.2. When trying to run programs that use Tkinter i get errors saying that there is no such module Tkinter ( or _tkinter ). I guess that there are 2 possible reasons: 1. the interpreter doesn't use the right modules directory. Maybe i have to set some environment variable? 2. for some reason the configure script thinks that Tk is not available, so that it didn't build the tkinter module. What do you guys think about this? Thanks, Adrian Maier (am@fx.ro) From magnus@thinkware.se Thu Mar 27 04:08:09 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Mar 27 04:08:09 2003 Subject: [Tutor] Pretty-printing Python as pseudocode (using TeX)? Message-ID: <5.1.0.14.0.20030327095752.02d09ea0@www.thinkware.se> I'm fairly certain that I've once stumbled across some python module that would print python programs using a more strict mathematical notation, with assignments looking something like <-, and with proper mathematical symbols for or and and etc. I'm pretty sure it was using TeX. Now I can't find this anywhere. Any pointers? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From wkoorts@mweb.co.za Thu Mar 27 04:12:34 2003 From: wkoorts@mweb.co.za (Wayne Koorts) Date: Thu Mar 27 04:12:34 2003 Subject: [Tutor] Converting to string Message-ID: Hi, I have a counter which increases by one every loop through a for= loop i.e. the for loop runs through the elements of a list and= each time the counter increases. for element in list: =09counter =3D counter + 1 Now I'd like to convert the integer value of counter to a string= every time it completes a loop. The way I understood that to= happen was: for element in list: =09counter =3D counter + 1 =09counterStr =3D str(counter) But when I print counterStr, it's still an integer. What is the proper method of converting integer variables to= strings? Regards, Wayne Koorts wkoorts@mweb.co.za From jerry@j3iss.com Thu Mar 27 05:14:00 2003 From: jerry@j3iss.com (Jerry Jorgenson) Date: Thu Mar 27 05:14:00 2003 Subject: OT: spaces WAS: Re: [Tutor] about regular expression In-Reply-To: <8174876066.20030326174418@columbus.rr.com> References: <20030326140102.15249.53439.Mailman@mail.python.org> <8174876066.20030326174418@columbus.rr.com> Message-ID: <20030327041258.48fc2f27.jerry@j3iss.com> On Wed, 26 Mar 2003 17:44:18 -0500 "R. Alan Monroe" wrote: > Recommendations vary. I was a graphic design major in the late 80s/ > early 90s, and most of the typography articles around that time stated > that two spaces was becoming deprecated in favor of a single space. > > Alan Strictly speaking, it depends on the typeface you use. The "two spaces" were evented because a typewriter has a fixed font and the letters don't have the same space between them, instead each letter takes up the same amount of space (an "i" takes the same space as an "m"), so the extra space was required. When a proportional spaced typeface is used, the space between each letter is the same, so the eye does not need the extra space (and typesetting programs, including most DTP programs, have a spell checker that flags double spacing as an error). Because a lot of text gets loaded into documents that use proportionally spaced typfaces, it's now common to use the single space, even in fixed fonts. The typsetting industry has used a single space for centuries, only the modern invention of the typewriter caused the "double space" convention. Now that there are very few typewriters left, the common practice is now reverting to the proper (or at least traditional) "single space" standard. Jerry -- Jerry Jorgenson jerry@j3iss.com http://www.j3iss.com/ From rob@jam.rr.com Thu Mar 27 08:58:02 2003 From: rob@jam.rr.com (Rob Andrews) Date: Thu Mar 27 08:58:02 2003 Subject: [Tutor] Converting to string In-Reply-To: Message-ID: >>> counter = 0 >>> myList = ["item", "another item", "yet another item"] >>> for element in myList: ... counter = counter + 1 ... >>> counter 3 # Counter is an integer. Notice no quotation marks around 3. >>> for element in myList: ... counter = counter + 1 ... counterStr = str(counter) ... >>> counterStr '6' # You can see by the '' marks that counterStr is a string. >>> counterStr + 1 Traceback (most recent call last): File "", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects >>> Trying to add an integer to counterStr fails, because counterStr is a string, as the Traceback assures us. Hopefully this gives a bit of a frame of reference for your problem. regards, Rob Andrews -- Mississippi Hermetic Connection: http://uselesspython.com/hermetica/hermetica.html > -----Original Message----- > From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of > Wayne Koorts > Sent: Wednesday, March 26, 2003 2:38 PM > To: pyTutor > Subject: [Tutor] Converting to string > > > Hi, > > I have a counter which increases by one every loop through a for > loop i.e. the for loop runs through the elements of a list and > each time the counter increases. > > for element in list: > counter = counter + 1 > > Now I'd like to convert the integer value of counter to a string > every time it completes a loop. The way I understood that to happen was: > > for element in list: > counter = counter + 1 > counterStr = str(counter) > > But when I print counterStr, it's still an integer. > > What is the proper method of converting integer variables to strings? > > Regards, > Wayne Koorts > wkoorts@mweb.co.za > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pan" This is a multi-part message in MIME format. --_b02077e83bf83c187f99289a6d93a0043 Content-Type: text/plain; charset="Big5" Content-Transfer-Encoding: quoted-printable Any eazy way to convert a string of nested-list into a list? An example: target =3D '[[a,b], [[c,d],e]]]' result =3D [ ['a','b'], [['c','d'], 'e'] ] Basically it's a reverse action of repr(). thx in advance. pan =0A=0A=0A=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D ~~~~~ be shapeless ~~~~~ Runsun Pan, PhD Dept. of Ecology & Evolution U. of Chicago, USA =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --_b02077e83bf83c187f99289a6d93a0043 Content-Type: text/html; charset="Big5" Content-Transfer-Encoding: quoted-printable =0A=0A=0A=0A=0AAny eazy way to convert a string of nested-list into a list?=0D
=0A=0D
=0AAn example:=0D
=0A=0D
=0Atarget =3D '[[a,b], [[c,d],e]]]'=0D
=0Aresult =3D [ ['a','b'], [['c','d'], 'e'] ]=0D
=0A=0D
=0ABasically it's a reverse action of repr().=0D
=0A=0D
=0Athx in advance.=0D
=0A=0D
=0Apan=0D
=0A
=0A=0A=0A=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
~~~~~ be shapeless ~~~~~

Runsun Pan, PhD
Dept. of Ecology & Evolution
U. of Chicago, USA
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=0A=0A --_b02077e83bf83c187f99289a6d93a0043-- From nsis5@allstate.com Thu Mar 27 10:08:01 2003 From: nsis5@allstate.com (Sison, Nick) Date: Thu Mar 27 10:08:01 2003 Subject: [Tutor] Configuration? Message-ID: <4DF4786A05BDCA4BA5AC00431981688009C165@a0001-xpo0113-s.hodc.ad.allstate.com> Hello! I just re-installed Python 2.2.2 and applied the Win32all-152 package on my Windows 2000 desktop (SP3). I was wondering if somebody can point out my error in configuring Python. Thanks! My system environment variables are: PATH = %path%;c:\python22 PYTHONPATH = c:\python22\lib; c:\python22\lib\lib-tk TCL_LIBRARY = c:\python22\tcl\tcl8.3 TK_LIBRARY = c:\python22\tcl\tk8.3 When running the GUI test session I get this right after I hit the exit button then python dies: When using IDLE I get this: Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> from Tkinter import * >>> w = Button(text="Hello", command='exit') >>> w.pack() >>> w.mainloop() Traceback (most recent call last): File "", line 1, in ? w.mainloop() File "c:\python22\lib\lib-tk\Tkinter.py", line 937, in mainloop self.tk.mainloop(n) File "c:\python22\lib\lib-tk\Tkinter.py", line 157, in _exit raise SystemExit, code SystemExit: 0 >>> When using PythonWin I get this: PythonWin 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> from Tkinter import * >>> w = Button(text="Hello", command='exit') >>> w.pack() >>> w.mainloop() Firing event 'ProcessEnter' failed. Traceback (most recent call last): File "C:\Python22\lib\site-packages\Pythonwin\pywin\scintilla\bindings.py", line 141, in fire rc = apply(binding.handler, args) File "C:\Python22\lib\site-packages\Pythonwin\pywin\framework\interact.py", line 471, in ProcessEnterEvent if self.interp.runsource(source, ""): # Need more input! File "c:\python22\lib\code.py", line 87, in runsource self.runcode(code) File "C:\Python22\lib\site-packages\Pythonwin\pywin\framework\interact.py", line 257, in runcode exec code in self.globals, self.locals File "", line 1, in ? File "c:\python22\lib\lib-tk\Tkinter.py", line 937, in mainloop self.tk.mainloop(n) File "c:\python22\lib\lib-tk\Tkinter.py", line 157, in _exit raise SystemExit, code SystemExit: 0 From francois.granger@free.fr Thu Mar 27 10:33:02 2003 From: francois.granger@free.fr (Francois Granger) Date: Thu Mar 27 10:33:02 2003 Subject: [Tutor] a string of nested-list to a list? In-Reply-To: <20030327144307.28078.qmail@station172.com> References: <20030327144307.28078.qmail@station172.com> Message-ID: At 14:43 +0000 27/03/2003, in message [Tutor] a string of nested-list to a list?, pan wrote: >Any eazy way to convert a string of nested-list into a list? > >An example: > >target = '[[a,b], [[c,d],e]]]' >result = [ ['a','b'], [['c','d'], 'e'] ] >>> a = "[['a','b'],[['c','d'],'e']]" >>> b = eval(a) >>> b [['a', 'b'], [['c', 'd'], 'e']] >>> b[1] [['c', 'd'], 'e'] >>> -- Hofstadter's Law : It always takes longer than you expect, even when you take into account Hofstadter's Law. From lonetwin@yahoo.com Thu Mar 27 10:57:03 2003 From: lonetwin@yahoo.com (lonetwin) Date: Thu Mar 27 10:57:03 2003 Subject: [Tutor] a string of nested-list to a list? In-Reply-To: References: <20030327144307.28078.qmail@station172.com> Message-ID: <200303272144.36679.lonetwin@yahoo.com> Hi pan, =20 On Thursday 27 March 2003 10:32, Francois Granger wrote: > >>> a =3D "[['a','b'],[['c','d'],'e']]" > >>> b =3D eval(a) > >>> b > > [['a', 'b'], [['c', 'd'], 'e']] > > >>> b[1] > > [['c', 'd'], 'e'] Re: The above code led me to open up my python prompt and try this: >>> import os >>> a =3D '[ "a", "b", ["c", "d"], [ os.system(x) for x in ["/bin/bash",=20 "/bin/ls"] ]]' >>> b =3D eval(a)=20 Scary, ain't it ?? Also , it needn't be 'os.system()' it could be any=20 malicious bit of code. I'd stay away from converting strings repr()s of l= ists=20 if I were pan, unless of course I knew for sure where the repr of my list= is=20 coming from. HTH Peace Steve > At 14:43 +0000 27/03/2003, in message [Tutor] a string of nested-list > > to a list?, pan wrote: > >Any eazy way to convert a string of nested-list into a list? > > > >An example: > > > >target =3D '[[a,b], [[c,d],e]]]' > >result =3D [ ['a','b'], [['c','d'], 'e'] ] > > > >>> a =3D "[['a','b'],[['c','d'],'e']]" > >>> b =3D eval(a) > >>> b > > [['a', 'b'], [['c', 'd'], 'e']] > > >>> b[1] > > [['c', 'd'], 'e'] --=20 # TODO: Think of something witty to put in here. From freemyer@NorcrossGroup.com Thu Mar 27 11:27:34 2003 From: freemyer@NorcrossGroup.com (Greg Freemyer) Date: Thu Mar 27 11:27:34 2003 Subject: [Tutor] Ultra basic question Message-ID: <20030327162018.CPPR21472.imf43bis.bellsouth.net@tiger2> I have some python code I can run in winpython by opening the source file and = clicking run. I need to be able to run it from normal python. I can start python and "import rdiff_backup" but I don't know how to actually = invoke it. I tried simply calling rdiff_backup.Main("--version") but it complains there is = no such attribute. OTOH, help ("modules rdiff_backup") shows Main??? =3D=3D=3D What I tried $ ntpython Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import rdiff_backup >>> rdiff_backup.Main("--version") Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'Main' >>> help ("modules rdiff_backup") Here is a list of matching modules. Enter any module name to get more help. rdiff_backup.FilenameMapping - Coordinate corresponding files with different = nam es rdiff_backup.Globals - Hold a variety of constants usually set at = initialization . rdiff_backup.Hardlink - Preserve and restore hard links rdiff_backup.Main - Start (and end) here - read arguments, set global settings, etc. rdiff_backup.Rdiff - Invoke rdiff utility to make signatures, deltas, or patch rdiff_backup.Security - Functions to make sure remote requests are kosher rdiff_backup.SetConnections - Parse args and setup connections rdiff_backup.TempFile - Manage temp files rdiff_backup.Time - Provide time related exceptions and functions rdiff_backup (package) rdiff_backup.backup - High level functions for mirroring and = mirror+incrementing rdiff_backup.connection - Support code for remote execution and data transfer rdiff_backup.increment - Provides functions and *ITR classes, for writing = increm ent files rdiff_backup.iterfile - Convert an iterator to a file object and vice-versa rdiff_backup.lazy - Define some lazy data structures and functions acting on = the m rdiff_backup.librsync - Provides a high-level interface to some librsync = functio ns rdiff_backup.log - Manage logging, displaying and recording messages with = requir ed verbosity rdiff_backup.manage - list, delete, and otherwise manage increments rdiff_backup.metadata - Store and retrieve metadata in destination directory rdiff_backup.regress - Code for reverting the rdiff-backup directory to prev = sta te rdiff_backup.restore - Read increment files and restore to original rdiff_backup.robust - Catch various exceptions given system call rdiff_backup.rorpiter - Operations on Iterators of Read Only Remote Paths rdiff_backup.rpath - Wrapper class around a real path like "/usr/bin/env" rdiff_backup.selection - Iterate exactly the requested files in a directory rdiff_backup.static - MakeStatic and MakeClass rdiff_backup.statistics - Generate and process aggregated backup information =3D=3D=3D TIA Greg --=20 Greg Freemyer From bh-wages@swbell.net Thu Mar 27 11:47:52 2003 From: bh-wages@swbell.net (Billie) Date: Thu Mar 27 11:47:52 2003 Subject: [Tutor] Another book question References: <20030327144307.28078.qmail@station172.com> <200303272144.36679.lonetwin@yahoo.com> Message-ID: <063801c2f480$558b9f00$7840fea9@BillieWages> This is a multi-part message in MIME format. ------=_NextPart_000_0634_01C2F44E.0A183420 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit I am the newbie recently to whom you gave book suggestions. Could I have some personal feedback to me, privately, on the book(s) "you" personally like, has helped you, and why. The Python books are relatively expensive, though I am a big book collector and am not bound by prices, just want to make sure what I finally choose, will give me what I need for learning Python. Online reading is difficult for me, and this is why I am pushing this book issue. I am very good with reference books; I use an Index very well, and I do not have to be held by the hand for understanding. :) Billie Wages ------=_NextPart_000_0634_01C2F44E.0A183420 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I am the = newbie recently=20 to whom you gave book suggestions.

Could I have some personal = feedback=20 to me, privately, on the book(s) "you" personally like, has helped you, = and=20 why.  The Python books are relatively expensive, though I am a big = book=20 collector and am not bound by prices, just want to make sure what I = finally=20 choose, will give me what I need for learning Python.  Online = reading is=20 difficult for me, and this is why I am pushing this book issue.  I = am very=20 good with reference books; I use an Index very well, and I do not have = to be=20 held by the hand for understanding. :)
Billie = Wages
------=_NextPart_000_0634_01C2F44E.0A183420-- From hall@ouhep1.nhn.ou.edu Thu Mar 27 11:51:01 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Thu Mar 27 11:51:01 2003 Subject: [Tutor] operators Message-ID: Hi list, Im wondering if anyone can tell me how to define an operator to work on multiple types. In my case Im trying to construct a class for matricies and I would like to define matrix multiplication to either multiply 2 matricies or to multiply a matrix by a scalar depending on what is given in the argument. also, if someone can correct me if I am wrong, to redifine multiplication in a class, I must use: def __*__(self,a): blah right? anyway, any help would be hot thanks Ike -- From dyoo@hkn.eecs.berkeley.edu Thu Mar 27 12:31:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 27 12:31:02 2003 Subject: [Tutor] a string of nested-list to a list? In-Reply-To: <200303272144.36679.lonetwin@yahoo.com> Message-ID: On Thu, 27 Mar 2003, lonetwin wrote: > > >>> a = "[['a','b'],[['c','d'],'e']]" > > >>> b = eval(a) > > >>> b > > > > [['a', 'b'], [['c', 'd'], 'e']] > > > > >>> b[1] > > > > [['c', 'd'], 'e'] > > Re: The above code led me to open up my python prompt and try this: > >>> import os > >>> a = '[ "a", "b", ["c", "d"], [ os.system(x) for x in ["/bin/bash", > "/bin/ls"] ]]' > >>> b = eval(a) > > Scary, ain't it ?? Also , it needn't be 'os.system()' it could be any > malicious bit of code. I'd stay away from converting strings repr()s of > lists if I were pan, unless of course I knew for sure where the repr of > my list is coming from. Hello! eval() can be dangerous, but there's some things that we can do to restrict what things can be evaluated, to make it partially safer. For example: ### >>> def restricted_eval(s): ... """Calls eval, but sets the __builtins__ dictionary to be ... empty when we do the evalutation.""" ... empty_builtin_dict = {'__builtins__': {}} ... return eval(s, empty_builtin_dict) ... >>> import os >>> a = '[ "a", "b", ["c", "d"], os.popen("ls").read()]' >>> c = restricted_eval(a) Traceback (most recent call last): File "", line 1, in ? File "", line 5, in restricted_eval File "", line 0, in ? NameError: name 'os' is not defined ### The idea is to empty out the environment where the evaluation runs, so that it only knows how to do simple stuff like string and list evaluation: ### >>> l = '[ "a", "b", ["c", "d"]]' >>> restricted_eval(l) ['a', 'b', ['c', 'd']] ### Hope this helps! From amd@atlas.ucpel.tche.br Thu Mar 27 12:32:02 2003 From: amd@atlas.ucpel.tche.br (Aurelio Magalhaes Dias) Date: Thu Mar 27 12:32:02 2003 Subject: [Tutor] operators In-Reply-To: References: Message-ID: On Thu, 27 Mar 2003, Isaac Hall wrote: > Hi list, > Hi Isaac, > Im wondering if anyone can tell me how to define an operator to work on > multiple types. In my case Im trying to construct a class for matricies > and I would like to define matrix multiplication to either multiply 2 > matricies or to multiply a matrix by a scalar depending on what is given > in the argument. also, if someone can correct me if I am wrong, to > redifine multiplication in a class, I must use: > def __*__(self,a): > =09blah > > right? > no, you should use def __mult__(self,a): =09blah > anyway, any help would be hot > > thanks > Hope this helps !!! Aur=E9lio. From dyoo@hkn.eecs.berkeley.edu Thu Mar 27 12:47:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 27 12:47:02 2003 Subject: [Tutor] operators In-Reply-To: Message-ID: On Thu, 27 Mar 2003, Aurelio Magalhaes Dias wrote: > > Im wondering if anyone can tell me how to define an operator to work > > on multiple types. In my case Im trying to construct a class for > > matricies and I would like to define matrix multiplication to either > > multiply 2 matricies or to multiply a matrix by a scalar depending on > > what is given in the argument. Hi Issac, Would it be ok to make two separate methods, one to do scalar multiplication, and one to do matrix multiplication? It sounds like you want to do the "polymorphism" that languages like C++ and Java support. Python doesn't automatically support "polymorphic" functions, but we can simulate it by doing a runtime check on the arguments to __mul__. For example: ### >>> class MulTest: ... def __mul__(self, other): ... if isinstance(other, MulTest): ... return MulTest() ... else: ... return other ... >>> x = MulTest() >>> y = MulTest() >>> z = "mulberry" >>> x*y <__main__.MulTest instance at 0x810f0a4> >>> x*z 'mulberry' >>> y*z 'mulberry' ### Here, we make a decision based on what isinstance() tells us about the 'other' argument. In your matrix code, you can check to see if the argument is a "scalar" or another matrix, and then branch from there. Note that doing 'z*x' isn't automatically supported! ### >>> z*x Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for *: 'str' and 'instance' ### But we can fix that. To make it work, we need to also define an __rmul__() method that tells Python what to do when our instance is on the right hand side of the multiplication. See: http://python.org/doc/current/ref/numeric-types.html for more details on writing overloaded operators. I hope this helps! From jeff@ccvcorp.com Thu Mar 27 13:19:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Mar 27 13:19:02 2003 Subject: [Tutor] Configuration? References: <4DF4786A05BDCA4BA5AC00431981688009C165@a0001-xpo0113-s.hodc.ad.allstate.com> Message-ID: <3E8340C1.5060201@ccvcorp.com> Sison, Nick wrote: >When running the GUI test session I get this right after I hit the exit >button then python dies: > >When using IDLE I get this: [...] > >When using PythonWin I get this: [...] > > I believe this problem isn't anything that you've done wrong. As it turns out, both IDLE and PythonWin have a similar weakness -- they both run scripts in the same process that they're running in, using the same Python interpreter. This means that certain memory structures are shared between the IDE and any scripts that you're running in them. Normally this is not a problem, but it does tend to cause issues when the scripts you're running use a GUI. Different GUI toolkits tend to clash in ugly ways (thus PythonWin won't cooperate with Tkinter), and even with the same GUI toolkit (IDLE uses Tkinter as well) only one mainloop() is allowed per process, so trying to start a second mainloop() from within IDLE causes problems. There's several ways around this problem. The quickest is to simply launch your GUI app from a command prompt. Open a command prompt window (and run DOSKey if you're using Win9x!), cd to the directory that your script is saved in, and run 'python myscript.py' -- your GUI should work much better. You can make changes to the open window in IDLE/PythonWin, save the changes, and just hit the up-arrow and return in your command window to restart your script. The other solution is to switch to a different IDE. Sourceforge has a project called IDLEFork, which is an updated and upgraded version of IDLE. (I think I've heard that IDLEFork will replace mainstream IDLE in the Python 2.3 distribution, but I'm not certain about that.) One of the improvements in IDLEFork is that it runs scripts in their own process -- this means that you won't have the mainloop() clashes, and your GUI script should work just fine. There's also a number of commercial IDEs (such as WingIDE and, I think, Komodo) that run Python scripts in a separate process, if you want to (and can afford to) go that route. Hope this helps! Jeff Shannon Technician/Programmer Credit International From alan.gauld@bt.com Thu Mar 27 13:40:08 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Mar 27 13:40:08 2003 Subject: [Tutor] operators Message-ID: > and I would like to define matrix multiplication to either multiply 2 > matricies or to multiply a matrix by a scalar depending on > what is given You can check the type of the argument within the operator method. > in the argument. also, if someone can correct me if I am wrong, to > redifine multiplication in a class, I must use: > def __*__(self,a): > blah I believe its actually def __mul__(self,a): pass There may even be an __rmul__() etc for doing things like: x *= 7 Alan g. From alan.gauld@bt.com Thu Mar 27 13:42:03 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Mar 27 13:42:03 2003 Subject: [Tutor] Ultra basic question Message-ID: > I have some python code I can run in winpython by opening the > source file and clicking run. > > I need to be able to run it from normal python. C:\> python yourscript.py > I can start python and "import rdiff_backup" but I don't > know how to actually invoke it. Depends how you've defined it. If you created a main() function then you also need the magic incantation: if __name__ == "__main__": main() If the driver code is not in a main() functin but inline then just importing the module will execute it as will doing it from the OS prompt as shown above. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From dmandini@inet.hr Thu Mar 27 14:48:02 2003 From: dmandini@inet.hr (djuro m.) Date: Thu Mar 27 14:48:02 2003 Subject: [Tutor] msvcrt or else? Message-ID: <001501c2f4e5$208a0700$a542cad5@k5a9l2> Hello! For instance: def hello(): n = raw_input('your name?>>') if n == 'q': sys.exit() print 'hello ' + n hello() How to replace "if" conditional with single press on "Esc" key? Would it be the same solution in unix? Thank you Djuro From jeff@ccvcorp.com Thu Mar 27 15:08:05 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Mar 27 15:08:05 2003 Subject: [Tutor] msvcrt or else? References: <001501c2f4e5$208a0700$a542cad5@k5a9l2> Message-ID: <3E835A4D.5080407@ccvcorp.com> djuro m. wrote: >Hello! > >For instance: > >def hello(): > n = raw_input('your name?>>') > if n == 'q': > sys.exit() > print 'hello ' + n > hello() > >How to replace "if" conditional with single press on "Esc" key? >Would it be the same solution in unix? > > AFAIK, on Windows you would indeed need to use the msvcrt module, and on Unix you'd need the curses module. Low-level keypresses is one area where cross-platform compatibility just isn't really possible. (What about platforms, such as PDAs and cellphones, that don't have a keyboard as such?) You have to make do with whatever specialized input methods are available for your platform, which (unfortunately) means writing platform-specific (or at very least platform-aware) code. Jeff Shannon Technician/Programmer Credit International From vicki@stanfield.net Thu Mar 27 15:28:02 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Thu Mar 27 15:28:02 2003 Subject: [Tutor] Python question Message-ID: <20030327122719.28385.h003.c000.wm@mail.stanfield.net.criticalpath.net> I'm getting better at this Python stuff, but I still have a question. If creating a class with several methods in it, is it typical to create the widgets themselves in that same class? For example, I am creating an entry box like this: --------------------Class itself----------------- class EntryClass: import Pmw EntryWidget = Pmw.EntryField(Frame2, label_text='Enter command:', labelpos='w') def Callback(self): value=self.getvalue() print value if value: SendCommand(value) ------------------main code---------------------- entry=EntryClass() callback=SimpleCallback(entry.Callback) entry.EntryWidget.configure(command=callback) entry.EntryWidget.pack(pady=25) ------------------- This all looks okay to me, but how is the Frame2 which I want to be the parent of the EntryWidget accessed from outside the function? Do I have to create a class for it too? From ahimsa@onetel.net.uk Thu Mar 27 16:16:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Thu Mar 27 16:16:02 2003 Subject: [Tutor] nominees please In-Reply-To: <016301c2f417$078cfa60$363fa418@tampabay.rr.com> References: <000d01c2f3d5$49a021d0$be27e183@chief> <5.1.0.14.0.20030327144839.0378a870@192.168.1.1> <016301c2f417$078cfa60$363fa418@tampabay.rr.com> Message-ID: <200303271733.32520.ahimsa@onetel.net.uk> Ditto THAT!! :-]) A On Thursday 27 Mar 2003 4:12 am, Todd Stephens wrote: > ---- Original Message ---- > From: "Alfred Milgrom" > To: "Danny Yoo" ; "Python Tutor" > Sent: Thursday, March 27, 2003 12:01 AM > Subject: Re: [Tutor] nominees please > > > Thanks to all you guys for making this such an interesting list to > > subscribe to. > > Fred Milgrom > > I agree. As a consummate lurker, I have found this list to be both > informative and entertaining. My one "complaint" is that there are jus= t > too many knowledgeable people posting here! I can scarcely keep up wit= h > the daily volume from this list! :) > > Todd Stephens > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor --=20 News from a different perspective: http://www.scoop.co.nz http://www.fromthewilderness.com ____________________________ Prevent digital monopoly: http://www.againsttcpa.com From dyoo@hkn.eecs.berkeley.edu Thu Mar 27 18:18:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 27 18:18:01 2003 Subject: [Tutor] msvcrt or else? In-Reply-To: <3E835A4D.5080407@ccvcorp.com> Message-ID: > >def hello(): > > n = raw_input('your name?>>') > > if n == 'q': > > sys.exit() > > print 'hello ' + n > > hello() > > > >How to replace "if" conditional with single press on "Esc" key? > >Would it be the same solution in unix? > > You have to make do with whatever specialized input methods are > available for your platform, which (unfortunately) means writing > platform-specific (or at very least platform-aware) code. Here you go: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 I believe that the escape character is the same on Windows and Unix systems ('\x1b'), but, unfortunately, I don't have a Windows machine to test this on. Hope this helps! From missive@hotmail.com Thu Mar 27 23:13:01 2003 From: missive@hotmail.com (Lee Harr) Date: Thu Mar 27 23:13:01 2003 Subject: [Tutor] Re: Python question Message-ID: I am not too familiar with this, but I think my code might look more like this: import Pmw class EntryClass: def __init__(self, Frame2): self.EntryWidget = Pmw.EntryField(Frame2, label_text='Enter command:', labelpos='w') callback = SimpleCallback(self.callback) self.EntryWidget.configure(command=callback) self.EntryWidget.pack(pady=25) def callback(self): value = self.getvalue() print value if value: SendCommand(value) # not sure where you get Frame2 entry = EntryClass(Frame2) _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From maillist@kuwest.de Fri Mar 28 07:03:01 2003 From: maillist@kuwest.de (Jens Kubieziel) Date: Fri Mar 28 07:03:01 2003 Subject: [Tutor] help() fails Message-ID: <20030328112524.GA6310@kubieziel.de> Hi, within this group it is often suggested to type help() to get specific help. I tried this within IDLE and Python prompt and got the following error: >>> help() Traceback (most recent call last): File "", line 1, in ? NameError: name 'help' is not defined kubi@QBI050102:~$ python Python 2.1.3 (#1, Jul 29 2002, 22:34:51) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> IDLE is in version 0.8. What I am missing here? TIA -- Jens Kubieziel http://www.kubieziel.de How sharper than a serpent's tooth is a sister's "See?" -- Linus Van Pelt From charlie@begeistert.org Fri Mar 28 08:48:09 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Mar 28 08:48:09 2003 Subject: [Tutor] Cgi redirection Message-ID: <20030328144857.3982.13@wonderland.1048841014.fake> Hi list, there was a question on the list the other week about URL redirection. At the time I with others said this wasn't possible but I have to stand corrected. It turns out you can easily set the "Location:" header with a redirect. There is a good recipe for this in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52287 An example def redirect(url = None): host = os.environ.get('HTTP_HOST', '') if not host: host = os.environ.get('SERVER_NAME', 'localhost') port = os.environ.get('SERVER_PORT', '80') result = "%s://%s" %('http', host) result += url return result form = cgi.FieldStorage() if form.getvalue('page') == "1": print "Location:", redirect("/page1.html") elif form.getvalue('page') == "2": print "Location:", redirect("/page2.html") Easy, huh? Charlie From vicki@stanfield.net Fri Mar 28 10:46:53 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Fri Mar 28 10:46:53 2003 Subject: [Tutor] multiple classes in same file Message-ID: <20030328074504.16934.h003.c000.wm@mail.stanfield.net.criticalpath.net> I have an app with multiple classes defined in the same file (at least for now). It seems to have no problem with the first two, but on the third I get an error: Traceback (most recent call last): File "C:\file.py", line 51 in ? class EntryClass: File "C:\file.py", line 58 in EntryClass EntryWidget=Pmw.EntryField(self.parent, NameError: name 'self' is not defined I assume that this indicates a problem with declaring the EntryClass, but the format looks identical to the second class declaration which it has no problem with. And obviously I don't yet get the "self" always passed thing. The code looks like this: -----class class EntryClass: import Pmw def __init__(self, parent): self.__parent = parent EntryWidget = Pmw.EntryField(self.parent, label_text='Enter command:', labelpos='w') def parent(self,parent): self.parent=parent def Callback(self): value=self.getvalue() print value if value: SendCommand(value) -------------main code entry=EntryClass() entry.parent(frame2) callback=SimpleCallback(entry.Callback) entry.EntryWidget.configure(command=callback) entry.EntryWidget.pack(pady=25) ------------------------ Any clues would be appreciated. --vicki From brian@dungeoncrawl.org Fri Mar 28 11:40:01 2003 From: brian@dungeoncrawl.org (Brian Christopher Robinson) Date: Fri Mar 28 11:40:01 2003 Subject: [Tutor] Colons Message-ID: <5.2.0.9.0.20030328113719.00ade3d8@localhost> Can someone explain the design philosophy behind certain statements, namely function definitions and control statements, requiring colons? I like that indentation controls scope in Python, removing the need for semicolons, but the inclusion of colons seems a step backwards in that regard. All the statements I'd have to terminate in Java I don't in Python, and vice versa. -- "Words are poison." - Nick on love From alan.gauld@bt.com Fri Mar 28 12:58:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Mar 28 12:58:02 2003 Subject: [Tutor] msvcrt or else? Message-ID: > def hello(): > n = raw_input('your name?>>') > if n == 'q': > sys.exit() > How to replace "if" conditional with single press on "Esc" key? > Would it be the same solution in unix? You can use the msvcrt.getchar() function in a loop to read characters until you get an ESC. You need to append the chars you read to the input string and take account of empty input buffers etc so its not trivial but ultimately does make for a more dynamic UI. You might find my event-driven programming topic useful (especially if you have the paper book version coz it actually uses msvcrt!). Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Fri Mar 28 13:01:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Mar 28 13:01:01 2003 Subject: [Tutor] operators Message-ID: > It sounds like you want to do the "polymorphism" that > languages like C++ and Java support. Python doesn't > automatically support "polymorphic" functions, I hate to nit pick but Puython doies support polymorphic functions very well, what it doesn't directly support is function *overloading*, where the same function name can be defined to take different type arguments. This is non sensical in Python since the arguments are just untyped names, hence we need to use dynamic type checks if the types are important. Sorry, but I get these picky days... Alan g. From hall@ouhep1.nhn.ou.edu Fri Mar 28 13:05:14 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Fri Mar 28 13:05:14 2003 Subject: [Tutor] operators In-Reply-To: Message-ID: Hi Alan, This was exactly they type of explanation I was looking for. I *thought* that this would be the case, but was unsure as lately Ive been having to muck around with somebody elses C++ code, and its confusing me all to heck. So just to re_iterate, if I want a function (class method) to do different things based on what is given to it, I need to check the type of the objects within the fuction. correct? Thanks, Ike On Fri, 28 Mar 2003 alan.gauld@bt.com wrote: > > It sounds like you want to do the "polymorphism" that > > languages like C++ and Java support. Python doesn't > > automatically support "polymorphic" functions, > > I hate to nit pick but Puython doies support polymorphic > functions very well, what it doesn't directly support > is function *overloading*, where the same function name > can be defined to take different type arguments. > > This is non sensical in Python since the arguments are > just untyped names, hence we need to use dynamic type > checks if the types are important. > > Sorry, but I get these picky days... > > Alan g. > -- From alan.gauld@bt.com Fri Mar 28 13:10:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Mar 28 13:10:01 2003 Subject: [Tutor] Python question Message-ID: Caveat: I never use PMW so there might be a flaw in my reasoning! > --------------------Class itself----------------- > class EntryClass: > EntryWidget = Pmw.EntryField(Frame2, ... > def Callback(self): ... Id define the class as a subclass oif the EntryWidget, like so: class EntryClass(pmw.EntryWidget): def __init__(self, parent=0): pmw.EntryWidget.__init__(self,parent) def CallBack(self): ...as before... Now you pass the parent in the constructoir as usual: entry = EntryClass(frame2) and dont need to access the internal member to configure: entry.conmfigure(command = callback) entry.pack(pady=25) This is the power of inheritance. Also means you can create multiple independant entries whereas with your design they all share the same EntryWidget! In fact you could even define the __init__ to take args* and pass the command parameter at creation: entry = EntryClass(frame2, command=foo) This But using the Command class technique you seem to prefer that tends to get messy. HTH, Alan G. From alan.gauld@bt.com Fri Mar 28 13:11:00 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Mar 28 13:11:00 2003 Subject: [Tutor] help() fails Message-ID: > >>> help() > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'help' is not defined What Python version - look in the interactive window. If its before 2.2.2 I believe you had to import help from somewhere - help maybe? Alan G. From alan.gauld@bt.com Fri Mar 28 13:13:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Mar 28 13:13:02 2003 Subject: [Tutor] multiple classes in same file Message-ID: > class EntryClass: > def __init__(self, parent): > self.__parent = parent > > EntryWidget = Pmw.EntryField(self.parent, > label_text='Enter command:', > labelpos='w') Python will try to execute the abiove line during the class definition. But self does not exist at that time so you can't dereference it. Try moving the instantiation into the __init__: def __init__(self, parent): self.__parent = parent self.EntryWidget = Pmw.EntryField(self.parent, label_text='Enter command:', labelpos='w') Alan G. From alan.gauld@bt.com Fri Mar 28 13:21:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Mar 28 13:21:01 2003 Subject: [Tutor] operators Message-ID: > muck around with somebody elses C++ code, and its confusing C++ is always confusing, but if its someone elses then doubly so! :-) > heck. So just to re_iterate, if I want a function (class > method) to do different things based on what is given to > it, I need to check the type of the objects within the fuction. There are two possibilities. One is to ensure that all possible types being passed in support the same interface and only have one function - the ideal solution. The other one is to heck type on entry. The first approach is best but not always practical, the second messy but works - beware of sequence issues, eg: def f(a,b): if type(a) == type(1): return a elif type(a) == type(b): return b else: return 42 print f(12,'foo') # -> 12 print f('see','far') # -> 'far' print f('foo',12) # -> 42! print f(12,15) # -> 12, but is that what we wanted? It depends on if/elif order in the typecheck Alan G From vicki@stanfield.net Fri Mar 28 13:21:12 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Fri Mar 28 13:21:12 2003 Subject: [Tutor] Python question Message-ID: <20030328102037.14097.h014.c000.wm@mail.stanfield.net.criticalpath.net> Does defining the class as a subclass of the widget itself mean that I don't actually call the command that creates the widget? (the Pmw.EntryField command)? --vicki From alan.gauld@bt.com Fri Mar 28 13:27:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Mar 28 13:27:01 2003 Subject: [Tutor] Colons Message-ID: > Can someone explain the design philosophy behind certain > statements, namely function definitions and control statements, > requiring colons? I agree, it's strange on first sighting. I certainly didn't understand it when I started. Basically the colon tells Python that what follows is the block of code to be executed as the function or control structure. The idea is it looks like the use of a colon in English grammar. Apparently its something that comes from Pythons ABC heritage where some research showed that absolute beginning students found the colon helpful in comprehending the code Its useful IMHO for single line statements like: if foo != bar: print bar But if you always use an indented newline like if foo != bar: print bar then it's not so useful IMHO. Alan G From alan.gauld@bt.com Fri Mar 28 13:30:30 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Mar 28 13:30:30 2003 Subject: [Tutor] Python question Message-ID: > Does defining the class as a subclass of the widget > itself mean that I don't actually call the command that > creates the widget? (the Pmw.EntryField command)? Thats right, because your widget is itself an instance of the EntryWidget class. That's how inheritance works. You simply extend the behaviour of the parent class and when you crate an instance youi get all of the inherited methods/attributes for free plus the methods that you have added. Thats what makes inheritance so powerful. Have a look at my OOP topic in my tutor, check out the BankAccount classes to see how the derived classes have all the features of the original Account. Same applies when you inherit from a GUI class... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From am@fx.ro Fri Mar 28 13:51:02 2003 From: am@fx.ro (Adrian Maier) Date: Fri Mar 28 13:51:02 2003 Subject: [Tutor] Tkinter no longer available after compiling Python In-Reply-To: <20030427132224.A2223@coto>; from am@fx.ro on Sun, Apr 27, 2003 at 01:22:24PM +0300 References: <200303220324.IAA21132@WS0005.indiatimes.com> <20030427132224.A2223@coto> Message-ID: <20030428120528.A286@coto> I figured out what was that problem: it needed the development packages for tk and tcl to be installed. Cheers! Adrian Maier (am@fx.ro) a scris : > Hello all! > > The operating system that I currently use is Debian Linux 2.2r5. > It ships with python 1.5.2 and i thought it would be a good idea > to upgrade Python: > > tar xzvf Python-2.2.2.tar.gz > ./configure ; make ; make install > > Now I have both versions installed ( I didn't uninstall python 1.5.2 > because there are some debian packages that depend on it ). The > new version is in /usr/local: the binaries in /usr/local/bin > and the other files in /usr/local/lib/python2.2. > > When trying to run programs that use Tkinter i get errors saying > that there is no such module Tkinter ( or _tkinter ). -- Adrian Maier (am@fx.ro, 0723.002.097) From jeff@ccvcorp.com Fri Mar 28 13:52:05 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Mar 28 13:52:05 2003 Subject: [Tutor] help() fails References: <20030328112524.GA6310@kubieziel.de> Message-ID: <3E849A0D.5060203@ccvcorp.com> Jens Kubieziel wrote: >>>>help() >>>> >>>> >Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'help' is not defined > >kubi@QBI050102:~$ python >Python 2.1.3 (#1, Jul 29 2002, 22:34:51) >[GCC 2.95.4 20011002 (Debian prerelease)] on linux2 >Type "copyright", "credits" or "license" for more information.' > I believe that the help() builtin was added in Python 2.2. While it's not nearly as convenient, you can often acheive much the same effect by using 'print somemodule.__doc__' or 'print function.__doc__' -- the help() facility just shows docstrings for the module and any classes and functions within it. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Fri Mar 28 13:56:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Mar 28 13:56:02 2003 Subject: [Tutor] multiple classes in same file References: <20030328074504.16934.h003.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <3E849AE3.3080509@ccvcorp.com> vicki@stanfield.net wrote: >-----class >class EntryClass: > > import Pmw > > def __init__(self, parent): > self.__parent = parent > > EntryWidget = Pmw.EntryField(self.parent, > label_text='Enter command:', > labelpos='w') > Here you're defining EntryWidget as a *class* attribute, rather than an instance attribute -- it's outside of (and at the same level as) the __init__() method. Since you're outside of that method, and outside of anything related to a particular instance, 'self' has no meaning in that context. I believe that you want to move this inside __init__(), which is a simple case of moving it in one indentation stop, so that it matches with the 'self.__parent = parent' line above it. Jeff Shannon Technician/Programmer Credit International From vicki@stanfield.net Fri Mar 28 14:04:09 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Fri Mar 28 14:04:09 2003 Subject: [Tutor] Python question Message-ID: <20030328110341.29831.h011.c000.wm@mail.stanfield.net.criticalpath.net> Okay, I am getting it, but now I have a similar problem. I have a callback defined as part of a class, but the callback command is in another class. I show both classes below... ---------------------- class EntryClass(Pmw.EntryField): def __init__(self, parent=0): Pmw.EntryField.__init__(self, parent) # EntryWidget = Pmw.EntryField(parent, # label_text='Enter command:', # labelpos='w') def Callback(self): value=self.getvalue() print value if value: MainWindow.SendCommand(value) class MainWindow: def SendCommand() ----------------------Main code MainWin=MainWindow() entry=EntryClass(Frame2) callback=SimpleCallback(entry.Callback) entry.configure(command=callback) entry.pack(pady=25) ---------------------- Obviously I cannot use the class name as I do above because that is not instantiated. I realize that a quick fix would be to include the SendCommand function in the Widget class, but I call it from other functions too. Do I pass the value out to the main and deal with it there? How is that done in a Callback like this? I see that I am making some progress in understanding this, but the use of the SimpleCallback class confuses me. Can I buy a clue? --vicki From jeff@ccvcorp.com Fri Mar 28 14:56:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Mar 28 14:56:02 2003 Subject: [Tutor] operators References: Message-ID: <3E84A8EF.7070306@ccvcorp.com> Isaac Hall wrote: >So just to re_iterate, if I want a function (class method) to do >different things based on what is given to it, I need to check the type of >the objects within the fuction. correct? > For some definition of "check the type of the objects" -- you don't necessarily need to use an explicit type() check. Often, the best way to do "typechecking" is to simply try an operation, and if that fails then use a backup -- "It's easier to ask forgiveness than permission". def itemcount(object): try: result = len(object) # get the length of a sequence except TypeError: result = 1 # if it's not a sequence, then there's only one object return result This has the advantage that it will work for *any* sequence (or class) that supports len() -- including types that you know nothing about, and even types that haven't been written yet. An explicit type() call will let you catch lists, tuples, and strings, but what about array.arrays? Or numeric arrays? Or some other specialized sequence object that you haven't thought of? Thus, by simply trying something and seeing if it works (and catching the exception if it doesn't), you're creating code that's much more polymorphic than straightforward typechecking allows. Jeff Shannon Technician/Programmer Credit International From amd@atlas.ucpel.tche.br Fri Mar 28 14:57:03 2003 From: amd@atlas.ucpel.tche.br (Aurelio Magalhaes Dias) Date: Fri Mar 28 14:57:03 2003 Subject: [Tutor] help() fails In-Reply-To: <3E849A0D.5060203@ccvcorp.com> References: <20030328112524.GA6310@kubieziel.de> <3E849A0D.5060203@ccvcorp.com> Message-ID: On Fri, 28 Mar 2003, Jeff Shannon wrote: > Jens Kubieziel wrote: > > >>>>help() > >>>> > >>>> > >Traceback (most recent call last): > > File "", line 1, in ? > > NameError: name 'help' is not defined > > > >kubi@QBI050102:~$ python > >Python 2.1.3 (#1, Jul 29 2002, 22:34:51) > >[GCC 2.95.4 20011002 (Debian prerelease)] on linux2 > >Type "copyright", "credits" or "license" for more information.' > > > > I believe that the help() builtin was added in Python 2.2. While it's > not nearly as convenient, you can often acheive much the same effect by > using 'print somemodule.__doc__' or 'print function.__doc__' -- the > help() facility just shows docstrings for the module and any classes and > functions within it. > > Jeff Shannon > Technician/Programmer > Credit International > That's right, it was added in Python 2.2. Aur=E9lio. ----------------------------------------- Aur=E9lio Magalh=E3es Dias Ci=EAncia da Computa=E7=E3o UCPel - RS - Brasil ----------------------------------------- From bh-wages@swbell.net Fri Mar 28 15:44:02 2003 From: bh-wages@swbell.net (Billie) Date: Fri Mar 28 15:44:02 2003 Subject: [Tutor] Another book question References: <20030327144307.28078.qmail@station172.com> <200303272144.36679.lonetwin@yahoo.com> <063801c2f480$558b9f00$7840fea9@BillieWages> Message-ID: <005001c2f56a$61cc1b60$7840fea9@BillieWages> This is a multi-part message in MIME format. ------=_NextPart_000_004C_01C2F538.163A04F0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit I must, for now give a collective thank you to replies I have received. Due to my physical condition today, I am unable to send personal emails as I'd wish to. You have been a big help, and I'll go shopping now :) and hope to broaden my knowledge of Python (which I learned about through Paint Shop Pro Scripts). In answer to a query or two posed to me, I do have programming knowledge from being a BASIC programmer in the 80's. It's interesting just how much that has helped me learn html, and other internet/web languages. Not to the extent I can call myself a programmer, but as one person put it, I'm not afraid of programming languages. LOL Hardly. I like control of my computer, and the more I know about how it operates, the better I feel, plus I have this unrelenting urge to know how everything works. To most people I look like a 60 y/o "about to be great grandmother" but my scientific/mathematical sense is still very strong. I envy those of you who have or are coming to age during this communications revolution. Appreciate it if you like it! Just wish it had been available to me in 1960; I surely would have followed this vein of education rather than the female's expected one of that era. However, I thank God for it now, because I am bedridden and the computer has gained me access to people and ideas I never would have imagined, even after following my husband around the world during his military career in the 60's and 70's. Just an interesting tidbit: When I was in high school in the 50's, I was one of only three girls taking Chemistry in the 11th grade (not the first three), and, in my senior year, one of the very first two girls EVER to take Physics, in the history of our school. I was also the first girl to run for President of the Student Council in my Junior year; this encompassed running a campaign not unlike any politician - only HONEST! Now, I'm hoping to add Python, XML, and Java Script to my knowledge base. I'm in bed because of pain, and my legs fail me due to several illnesses, but that doesn't mean I must put my brain to rest! Billie............. headed to go book shopping now! ----- Original Message ----- From: Billie To: tutor@python.org Sent: Thursday, March 27, 2003 10:45 AM Subject: [Tutor] Another book question I am the newbie recently to whom you gave book suggestions. Could I have some personal feedback to me, privately, on the book(s) "you" personally like, has helped you, and why. The Python books are relatively expensive, though I am a big book collector and am not bound by prices, just want to make sure what I finally choose, will give me what I need for learning Python. Online reading is difficult for me, and this is why I am pushing this book issue. I am very good with reference books; I use an Index very well, and I do not have to be held by the hand for understanding. :) Billie Wages ------=_NextPart_000_004C_01C2F538.163A04F0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I must, for now give a collective thank you = to replies=20 I have received.  Due to my physical condition today, I am unable = to send=20 personal emails as I'd wish to.  You have been a big help, and I'll = go=20 shopping now :) and hope to broaden my knowledge of Python (which I = learned=20 about through Paint Shop Pro Scripts).  In answer to a query or two = posed=20 to me, I do have programming knowledge from being a BASIC programmer in = the=20 80's.  It's interesting just how much that has helped me learn = html, and=20 other internet/web languages.  Not to the extent I can call myself = a=20 programmer, but as one person put it, I'm not afraid of programming=20 languages.  LOL  Hardly.  I like control of my computer, = and the=20 more I know about how it operates, the better I feel, plus I have this=20 unrelenting urge to know how everything works.  To most people I = look like=20 a 60 y/o "about to be great grandmother" but my scientific/mathematical = sense is=20 still very strong.  I envy those of you who have or are coming = to age=20 during this communications revolution.  Appreciate it if you like = it!=20  Just wish it had been available to me in 1960; I surely would have = followed this vein of education rather than the female's expected one of = that=20 era.  However, I thank God for it now, because I am bedridden and = the=20 computer has gained me access to people and ideas I never would have = imagined,=20 even after following my husband around the world during his military = career in=20 the 60's and 70's.
 
Just an interesting tidbit:  When I was = in high=20 school in the 50's, I was one of only three girls taking Chemistry in = the 11th=20 grade (not the first three), and, in my senior year, one of the = very first=20 two girls EVER to take Physics, in the history of our=20 school.  I was also the first girl to run for President of the = Student=20 Council in my Junior year; this encompassed running a campaign not = unlike=20 any politician - only HONEST!  Now, I'm hoping to add Python, = XML, and=20 Java Script to my knowledge base.  I'm in bed because of pain, = and my legs fail me due to several illnesses, but that doesn't mean = I must=20 put my brain to rest! 
 
Billie............. headed to go book = shopping=20 now!
 
----- Original Message -----=20
From: Billie
Sent: Thursday, March 27, 2003 10:45 AM
Subject: [Tutor] Another book question

I am the newbie recently to whom = you gave=20 book suggestions.

Could I have some personal feedback to me, = privately,=20 on the book(s) "you" personally like, has helped you, and why.  The = Python=20 books are relatively expensive, though I am a big book collector and am = not=20 bound by prices, just want to make sure what I finally choose, will give = me what=20 I need for learning Python.  Online reading is difficult for me, = and this=20 is why I am pushing this book issue.  I am very good with reference = books;=20 I use an Index very well, and I do not have to be held by the hand for=20 understanding. :)
Billie=20 Wages
------=_NextPart_000_004C_01C2F538.163A04F0-- From hsteiger@comcast.net Fri Mar 28 21:29:01 2003 From: hsteiger@comcast.net (Henry Steigerwaldt) Date: Fri Mar 28 21:29:01 2003 Subject: [Tutor] Placement of text on a canvas Message-ID: <000501c2e41f$9caf79e0$0201a8c0@eagle> To All: I am puzzled how the placement of text occurs on a canvas widget of Tkinter. For example, say the following line of numbers is plotted using a certain x,y value for text placement: 30/40/80/90 Now say I add two more numbers to the line and use the same x,y value for text placement. What happens is that the beginning or left edge of the text shifts to the left as shown immediately below, rather than starting at the same x,y location and extending from there TO THE RIGHT: 30/40/80/90/10/100 I would think that as additional numbers are added to the line, the text would extend further to the right, NOT TO THE LEFT. This makes it impossible to keep the start of the text anchored at the same location. The "justify" option will only matter if the text is displayed as multiple lines. I just have one line of text so that's out. Also the "anchor" option does not anchor the left side of the text when additional numbers are added to the line. Below is the line of code I am using: canvas.create_text(100,342, text='P ' + '10/20/40/40', fill='red', font=('verdana', 8, 'bold')) The "P" stands for the Probability of Precipitation, and the numbers are the probabilities for different periods of time. They can vary from single digits (2, 5 etc.) to 100, hence the varying line length, even when no additional numbers are added to the line. What can I do to keep the left side (start of numbers) AT THE SAME X,Y LOCATION from changing? Is there an option that would work? Thanks. Henry Steigerwaldt Hermitage, TN Email: hsteiger@comcast.net From rick@niof.net Fri Mar 28 22:01:02 2003 From: rick@niof.net (Rick Pasotto) Date: Fri Mar 28 22:01:02 2003 Subject: [Tutor] Placement of text on a canvas In-Reply-To: <000501c2e41f$9caf79e0$0201a8c0@eagle> References: <000501c2e41f$9caf79e0$0201a8c0@eagle> Message-ID: <20030329030019.GA32668@tc.niof.net> On Thu, Mar 06, 2003 at 02:33:13PM -0600, Henry Steigerwaldt wrote: > To All: > > I am puzzled how the placement of text occurs on a canvas widget of > Tkinter. > > For example, say the following line of numbers is plotted using a > certain x,y value for text placement: > > 30/40/80/90 > > Now say I add two more numbers to the line and use the same x,y value > for text placement. What happens is that the beginning or left edge of > the text shifts to the left as shown immediately below, rather than > starting at the same x,y location and extending from there TO THE > RIGHT: > > 30/40/80/90/10/100 > > > I would think that as additional numbers are added to the line, the > text would extend further to the right, NOT TO THE LEFT. This makes it > impossible to keep the start of the text anchored at the same > location. > > The "justify" option will only matter if the text is displayed as > multiple lines. I just have one line of text so that's out. Also the > "anchor" option does not anchor the left side of the text when > additional numbers are added to the line. > > Below is the line of code I am using: > > canvas.create_text(100,342, text='P ' + '10/20/40/40', fill='red', > font=('verdana', 8, 'bold')) > > The "P" stands for the Probability of Precipitation, and the numbers > are the probabilities for different periods of time. They can vary > from single digits (2, 5 etc.) to 100, hence the varying line length, > even when no additional numbers are added to the line. > > What can I do to keep the left side (start of numbers) AT THE SAME X,Y > LOCATION from changing? Is there an option that would work? You need to add the option 'anchor=W'. Thus: canvas.create_text(30,30,text="whatever",fill='red',anchor=W) You are deleting the first text item aren't you? -- "The secret wealth of commerce & the precarious profits of art & labor are susceptible only of a discretionary value, which is seldom disadvantageous to the interest of the treasury... the payment of the imposition, which in the case of a land tax may be obtained by seizure of property, can rarely be extorted by any other means than those of corporal punishments." -- Edward Gibbon 1788 _The Decline & Fall of the Roman Empire_ (quoted in Charles Adams 1993 _For Good & Evil: The Impact of Taxes on the Course of Civilization_) Rick Pasotto rick@niof.net http://www.niof.net From rick@niof.net Fri Mar 28 22:11:01 2003 From: rick@niof.net (Rick Pasotto) Date: Fri Mar 28 22:11:01 2003 Subject: [Tutor] silly auto-responder Message-ID: <20030329031032.GB32668@tc.niof.net> Why do I keep getting that silly auto-responder telling me to check the FAQ? I'm *answering* a question, not asking one. -- "Television: chewing gum for the eyes." -- Frank Lloyd Wright Rick Pasotto rick@niof.net http://www.niof.net From pijus@virketis.com Fri Mar 28 23:00:02 2003 From: pijus@virketis.com (Pijus Virketis) Date: Fri Mar 28 23:00:02 2003 Subject: [Tutor] how to send an email via Microsoft Outlook? Message-ID: <511F0484-61B4-11D7-AE7B-000A9575F08A@virketis.com> Dear all, First of all, let me reassure you that I am not asking about this because I plan to send spam. :) In fact, I want to send emails to myself when some system events happen. I have figured out how to use the win32com module to create an instance of Outlook.Application, and move around mailboxes. Now, I need to create an instance of MailItem, Outlook-speak for an email. I think it should look like this: >>> message = outlook.CreateItem("MailItem") Except that "MailItem" is not it ... Does anyone know what I should be passing to the CreateItem() method? Thank you! Pijus From stusmith@rogers.com Fri Mar 28 23:39:04 2003 From: stusmith@rogers.com (Stuart Smith) Date: Fri Mar 28 23:39:04 2003 Subject: [Tutor] how to send an email via Microsoft Outlook? In-Reply-To: <511F0484-61B4-11D7-AE7B-000A9575F08A@virketis.com> Message-ID: <000001c2f5ac$e977ae70$6501a8c0@Gandalf> The CreateItem method takes a numeric value. In VBA these numbers are given names such as 'olMailItem' or 'olContactItem'. The one you want is olMailItem, the value of which is 0, so... >>> message = outlook.CreateItem(0) Should do what you are looking to accomplish. For your reference, other items you can create: olMailItem = 0 olAppointmentItem = 1 olContactItem = 2 olTaskItem = 3 olJournalItem = 4 olNoteItem = 5 olPostItem = 6 olDistributionListItem = 7 BTW, opening an instance of Outlook just to send out an email seems a bit of an overkill - have you considered using one of the modules that comes with Python? If it's just simple notifications you're looking to send, I'd be tempted to use smtplib. -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org] On Behalf Of Pijus Virketis Sent: March 29, 2003 02:02 To: tutor@python.org Subject: [Tutor] how to send an email via Microsoft Outlook? Dear all, First of all, let me reassure you that I am not asking about this because I plan to send spam. :) In fact, I want to send emails to myself when some system events happen. I have figured out how to use the win32com module to create an instance of Outlook.Application, and move around mailboxes. Now, I need to create an instance of MailItem, Outlook-speak for an email. I think it should look like this: >>> message = outlook.CreateItem("MailItem") Except that "MailItem" is not it ... Does anyone know what I should be passing to the CreateItem() method? Thank you! Pijus From adamg@mailbox.hu Sat Mar 29 13:30:01 2003 From: adamg@mailbox.hu (=?iso-8859-2?B?IkcgwWThbSIg?=) Date: Sat Mar 29 13:30:01 2003 Subject: [Tutor] implementing relationship between objects Message-ID: <20030329182921.11336.qmail@arnold.mailbox.hu> Dear All, How would you implement in python a 'relational' 1:1, 1:N, N:N relationship between objects? Of course both 'sides' should know about the other and changing one 'side' of the relation should affect the other side (kind of referetial integrity). any ideas are welcome Adam _______________________________________________________________________ http://mailbox.hu - WAP-on is olvashatod From dyoo@hkn.eecs.berkeley.edu Sat Mar 29 14:36:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 29 14:36:02 2003 Subject: [Tutor] operators In-Reply-To: Message-ID: On Fri, 28 Mar 2003 alan.gauld@bt.com wrote: > > It sounds like you want to do the "polymorphism" that languages like > > C++ and Java support. Python doesn't automatically support > > "polymorphic" functions, > > I hate to nit pick but Puython doies support polymorphic functions very > well, what it doesn't directly support is function *overloading*, where > the same function name can be defined to take different type arguments. Ah, thanks for the correction! I must have mistakenly thought about "overloading" vs "overriding" vs "polymorphism", and munged up my terminology in the process. From rick@niof.net Sat Mar 29 16:01:01 2003 From: rick@niof.net (Rick Pasotto) Date: Sat Mar 29 16:01:01 2003 Subject: [Tutor] Placement of text on a canvas In-Reply-To: <20030329030019.GA32668@tc.niof.net> References: <000501c2e41f$9caf79e0$0201a8c0@eagle> <20030329030019.GA32668@tc.niof.net> Message-ID: <20030329210024.GA3168@tc.niof.net> On Fri, Mar 28, 2003 at 10:00:19PM -0500, Rick Pasotto wrote: > On Thu, Mar 06, 2003 at 02:33:13PM -0600, Henry Steigerwaldt wrote: > > > > Below is the line of code I am using: > > > > canvas.create_text(100,342, text='P ' + '10/20/40/40', fill='red', > > font=('verdana', 8, 'bold')) > > > > The "P" stands for the Probability of Precipitation, and the numbers > > are the probabilities for different periods of time. They can vary > > from single digits (2, 5 etc.) to 100, hence the varying line length, > > even when no additional numbers are added to the line. > > > > What can I do to keep the left side (start of numbers) AT THE SAME X,Y > > LOCATION from changing? Is there an option that would work? > > You need to add the option 'anchor=W'. Thus: > > canvas.create_text(30,30,text="whatever",fill='red',anchor=W) > > You are deleting the first text item aren't you? Investigating a little more I've learned better how this works. Turns out that the x,y coordinates supplied to create_text refer to the anchor point and the anchor point defaults to 'center'. You can test this by creating a default canvas and adding a line with known coords and then using those coords to add text using different anchors. cv = Canvas(background='white') cv.pack() cv.create_line(100,50,300,50) cv.create_text(100,50,anchor=CENTER,fill='red', text='this is a line of text') cv.create_text(100,50,anchor=NW,fill='blue', text='this is a line of text') cv.create_text(100,50,anchor=SW,fill='green', text='this is a line of text') The blue text will be below the line and the green will be above the line but both will line up on the left with the endpoint of the line. The center of the red text will be the left endpoint of the line and the line will go through the center of the text. -- "As empty vessels make the loudest sound, so they that have the least wit are the greatest blabbers." -- Plato Rick Pasotto rick@niof.net http://www.niof.net From bds@waywood.co.uk Sat Mar 29 16:25:02 2003 From: bds@waywood.co.uk (Barnaby Scott) Date: Sat Mar 29 16:25:02 2003 Subject: [Tutor] Newbie - Simple mailing list archiver Message-ID: <000501c2f639$293800a0$1200a8c0@StudyDell> First off, I have to confess to being a complete novice - apart from a 'Hello World' type of thing and a bit of reading, I am trying to write my first ever Python script. However, the only way I have ever found of learning anything is to jump in the deep end and try to do something that I actually need to do, rather than half-heartedly wading through excercises (which I'm sure would be good for the soul)! I manage a mailing list and want to archive it, in a very basic form, to a website - which happens to consist of a wiki (the engine for which is PikiePikie - which I'm very impressed by and which is itself written in Python). The great thing about this excercise is that the wiki uses only text files, and the HTML is generated on the fly, so my archive will be all plain text. Below I have sketched out a skeleton for what the archiver needs to do, as I see it. It would be a bit cheeky just to come here and ask someone to fill in all the Python code for me! However, I would be extremely grateful for 2 things: 1: Any comments about the strategic 'skeleton' I have laid out 2: As much or as little of the code as anyone feels able/inclined to fill in. It's not that I'm lazy, it's just that when you are starting literally from scratch, it is really hard to know if you are getting EVERYTHING completely wrong, and wasting time disappearing up blind alleys. Even incredibly simple-sounding things sometimes take weeks to discover unless you are shown the way! As I say, ANY amount of guidance would be gratefully received. Here's my skeleton... #Read mail message from STDIN #Get these header values: # From # Subject (or specify 'no subject') # Message-ID # Date (in a short, consistent format) # In-Reply-To, or failing that the last value in References, if either exist # Content-Type #If Content-Type is multipart/*, get only the body section that is text/plain #Else if Content-Type is text/plain, get the body text #Else give up now! #Open my 'messageIDs' file (a lookup file which stores, from previous messages, the value pairs: An integer messageID, original Message-ID) #Find there the highest existing integer messageID and generate a new one by adding 1 #Append to the 'messageIDs' file: # Our newly generated integer messageID, this message's Message-ID #Open my 'ArchiveIndex' file (a wiki page which lists all messages in threads, with a specific method of indenting) #If there is an In-Reply-To or References value # Look in the 'messageIDs' file for this Message-ID and return that message's corresponding integer messageID # Look in the 'ArchiveIndex' file to find this integer at the beginning of a line (save for preceding spaces and '*') # Add a new line immediately after this line we have found # Pad it with one more leading space than the preceding line had and... #Else # Add a new line at beginning of file # Pad it with 1 leading space and... #...now write on that line: # '*' integer messageID + ': ' + Subject + ' ' + From + ' ' + Date + ' ['ArchivedMessage' + integer messageID + ' ' + 'View]' #Close the 'ArchiveIndex' and 'messageIDs' files #Create and open a new file called 'ArchivedMessage' + integer messageID #Write to this file: # From # Subject # Date # plain text body #Close the 'ArchivedMessage?' file From missive@hotmail.com Sat Mar 29 21:09:01 2003 From: missive@hotmail.com (Lee Harr) Date: Sat Mar 29 21:09:01 2003 Subject: [Tutor] Re: implementing relationship between objects Message-ID: >How would you implement in python a 'relational' 1:1, 1:N, N:N >relationship between objects? > >Of course both 'sides' should know about the other and changing one >'side' of the relation should affect the other side (kind of >referetial >integrity). > One thing you might use is a mutable builtin object, like a list. Two objects might share the same list for instance: class Rel: members = [] def __init__(self): if len(self.members) > 1: raise TypeError, "Two members maximum" else: if self.members: self.other = self.members[0] self.other.other = self self.members.append(self) I bet you could extend this to the other cases also. I do not know if this is the best way, or even really a good way. I guess it depends on what your goal is. _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From GREENDAY31087@aol.com Sun Mar 30 01:58:01 2003 From: GREENDAY31087@aol.com (GREENDAY31087@aol.com) Date: Sun Mar 30 01:58:01 2003 Subject: [Tutor] py2exe problem Message-ID: <166.1e11643e.2bb7ef2c@aol.com> --part1_166.1e11643e.2bb7ef2c_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Well, I went to the py2exe site and downloaded it, looked at the example( http://starship.python.net/crew/theller/py2exe/)and I just don't get it. I have python2.2.2 so... I think I have the 'distutils' thing but I don't know what to do with the text in the bluish boxes under 'using py2exe.' Could someone please tell me what I need to do? I have no clue. --part1_166.1e11643e.2bb7ef2c_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable Well, I went to the py2exe site and downloaded it, loo= ked at the example(http://starship.python.net/crew/theller/py2exe/)and I just don't g= et it. I have python2.2.2 so... I think I have the 'distutils' thing but= I don't know what to do with the text in the bluish boxes under 'using py2e= xe.' Could someone please tell me what I need to do? I have no clue.<= /HTML> --part1_166.1e11643e.2bb7ef2c_boundary-- From dmandini@inet.hr Sun Mar 30 07:12:02 2003 From: dmandini@inet.hr (djuro m.) Date: Sun Mar 30 07:12:02 2003 Subject: [Tutor] msvcrt or else? References: <001501c2f4e5$208a0700$a542cad5@k5a9l2> <3E835A4D.5080407@ccvcorp.com> Message-ID: <002001c2f700$d2007060$2b43cad5@k5a9l2> Thanx everyone for help. Djuro ----- Original Message ----- From: "Jeff Shannon" To: Cc: "djuro m." Sent: Thursday, March 27, 2003 12:08 PM Subject: Re: [Tutor] msvcrt or else? > djuro m. wrote: > > >Hello! > > > >For instance: > > > >def hello(): > > n = raw_input('your name?>>') > > if n == 'q': > > sys.exit() > > print 'hello ' + n > > hello() > > > >How to replace "if" conditional with single press on "Esc" key? > >Would it be the same solution in unix? > > > > > > AFAIK, on Windows you would indeed need to use the msvcrt module, and on > Unix you'd need the curses module. Low-level keypresses is one area > where cross-platform compatibility just isn't really possible. (What > about platforms, such as PDAs and cellphones, that don't have a keyboard > as such?) You have to make do with whatever specialized input methods > are available for your platform, which (unfortunately) means writing > platform-specific (or at very least platform-aware) code. > > Jeff Shannon > Technician/Programmer > Credit International > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rob@jam.rr.com Sun Mar 30 08:18:01 2003 From: rob@jam.rr.com (Rob Andrews) Date: Sun Mar 30 08:18:01 2003 Subject: [Tutor] py2exe problem In-Reply-To: <166.1e11643e.2bb7ef2c@aol.com> Message-ID: Hopefully this will help. I recently did a fresh download/install of py2exe and created a simple stand-alone application, recording the steps in the process in ridiculous detail: http://www.uselesspython.com/newsite/py2exeHOWTO.txt I haven't made the document all pretty yet, but the info is current. -Rob -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of GREENDAY31087@aol.com Sent: Sunday, March 30, 2003 12:57 AM To: tutor@python.org Subject: [Tutor] py2exe problem Well, I went to the py2exe site and downloaded it, looked at the example(http://starship.python.net/crew/theller/py2exe/)and I just don't get it. I have python2.2.2 so... I think I have the 'distutils' thing but I don't know what to do with the text in the bluish boxes under 'using py2exe.' Could someone please tell me what I need to do? I have no clue. From GREENDAY31087@aol.com Sun Mar 30 11:37:02 2003 From: GREENDAY31087@aol.com (GREENDAY31087@aol.com) Date: Sun Mar 30 11:37:02 2003 Subject: [Tutor] still need help Message-ID: <1c8.78892bc.2bb876d3@aol.com> --part1_1c8.78892bc.2bb876d3_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Concerning py2exe: I think I'm doing this right but it still wont work for me. I have the setup file and the script file. here they are: # setup.py from distutils.core import setup import py2exe setup(name="test", scripts=["test.py"], ) #test.py print "THIS IS A TEST" And When I start the setup program, it says: usage: test.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: test.py --help [cmd1 cmd2 ...] or: test.py --help-commands or: test.py cmd --help error: no commands supplied Am I missing something that's completely obvious? I apologize for being kinda thick but I'm trying to get it to work. Thanks --part1_1c8.78892bc.2bb876d3_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable Concerning py2exe: I think I'm doing this right but it= still wont work for me. I have the setup file and the script file.
here they are:

# setup.py
from distutils.core import setup
import py2exe

setup(name=3D"test",
      scripts=3D["test.py"],
)


#test.py
print "THIS IS A TEST"


And When I start the setup program,  it says:

usage: test.py [global_opts]= cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]   
    or: test.py --help [cmd1 cmd2 ...]   
    or: test.py --help-commands   
    or: test.py cmd --help
error: no commands supplied

Am I missing something that'= s completely obvious? I apologize for being kinda thick but I'm trying to ge= t it to work.
Thanks
--part1_1c8.78892bc.2bb876d3_boundary-- From bh-wages@swbell.net Sun Mar 30 12:12:01 2003 From: bh-wages@swbell.net (Billie) Date: Sun Mar 30 12:12:01 2003 Subject: [Tutor] Creating a database Message-ID: <0f0c01c2f6df$4dae3e80$7840fea9@BillieWages> This is a multi-part message in MIME format. ------=_NextPart_000_0F09_01C2F6AD.0237C660 Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: 7bit Well, I'm off on a project, and want to know if Python will do the trick. I'm wanting to create a web page that lists names, addresses and phone numbers, and I want it to be storable. Being new, first I'm sure it's possible, second, is it very difficult (I shouldn't think so, but am still asking). I remember making sorted lists in BASIC, but I want this where the user clicks and chooses their preference. Am I taking on more than I'm ready for? I like challenges, but must have a bit of reality in check, also. Billie ------=_NextPart_000_0F09_01C2F6AD.0237C660 Content-Type: text/x-vcard; name=" Billie.vcf" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename=" Billie.vcf" BEGIN:VCARD VERSION:2.1 N:;Billie FN: Billie EMAIL;PREF;INTERNET:bwages@BWages.net REV:20030330T171044Z END:VCARD ------=_NextPart_000_0F09_01C2F6AD.0237C660-- From bgailer@alum.rpi.edu Sun Mar 30 12:42:03 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Sun Mar 30 12:42:03 2003 Subject: [Tutor] Newbie - Simple mailing list archiver In-Reply-To: <000501c2f639$293800a0$1200a8c0@StudyDell> Message-ID: <5.2.0.9.0.20030330101827.031b4998@66.28.54.253> --=======49B341D0======= Content-Type: text/plain; x-avg-checked=avg-ok-50C2466; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 09:21 PM 3/29/2003 +0000, Barnaby Scott wrote: >I manage a mailing list and want to archive it, in a very basic form, to a >website - which happens to consist of a wiki (the engine for which is >PikiePikie - which I'm very impressed by and which is itself written in >Python). The great thing about this excercise is that the wiki uses only >text files, and the HTML is generated on the fly, so my archive will be all >plain text. > >Below I have sketched out a skeleton for what the archiver needs to do, as I >see it. It would be a bit cheeky just to come here and ask someone to fill >in all the Python code for me! However, I would be extremely grateful for 2 >things: >1: Any comments about the strategic 'skeleton' I have laid out >2: As much or as little of the code as anyone feels able/inclined to fill >in. It's not that I'm lazy, it's just that when you are starting literally >from scratch, it is really hard to know if you are getting EVERYTHING >completely wrong, and wasting time disappearing up blind alleys. Even >incredibly simple-sounding things sometimes take weeks to discover unless >you are shown the way! > >As I say, ANY amount of guidance would be gratefully received. Here's my >skeleton... > >#Read mail message from STDIN > >#Get these header values: ># From ># Subject (or specify 'no subject') ># Message-ID ># Date (in a short, consistent format) ># In-Reply-To, or failing that the last value in References, if either >exist ># Content-Type > >#If Content-Type is multipart/*, get only the body section that is >#text/plain >#Else if Content-Type is text/plain, get the body text >#Else give up now! # Perhaps several of us will help in various areas. My contribution, at this # point is to suggest you consider using the SQLite database for your # messageIDs "file". SQLite is free, as well the Python interface pySQLite. # See www.sqlite.org/ and pysqlite.sourceforge.net/. import sqlite connection = sqlite.connect('messageids', 077) # messageids is the database file path cursor = connection.cursor() >#Open my 'messageIDs' file (a lookup file which stores, from previous >messages, the value pairs: An integer messageID, original Message-ID) # you'll need to create a table. Do this just once: cursor.execute("create table messageids (messageid int, originalid int)") >#Find there the highest existing integer messageID and generate a new one by >#adding 1 cursor.execute("select max(messageid) from messageids") newid = int(cursor.fetchone()[0]) + 1 >#Append to the 'messageIDs' file: ># Our newly generated integer messageID, this message's Message-ID cursor.execute("insert into messageids values(newid, messageid)") # this may seem like overkill, but as you expand you may find that having # a database will be very useful >#Open my 'ArchiveIndex' file (a wiki page which lists all messages in >#threads, with a specific method of indenting) > >#If there is an In-Reply-To or References value ># Look in the 'messageIDs' file for this Message-ID and return that >message's corresponding integer messageID ># Look in the 'ArchiveIndex' file to find this integer at the beginning >of a line (save for preceding spaces and '*') ># Add a new line immediately after this line we have found ># Pad it with one more leading space than the preceding line had and... >#Else ># Add a new line at beginning of file ># Pad it with 1 leading space and... > >#...now write on that line: ># '*' integer messageID + ': ' + Subject + ' ' + From + ' ' + Date + ' >['ArchivedMessage' + integer messageID + ' ' + 'View]' > >#Close the 'ArchiveIndex' and 'messageIDs' files > >#Create and open a new file called 'ArchivedMessage' + integer messageID > >#Write to this file: ># From ># Subject ># Date ># plain text body > >#Close the 'ArchivedMessage?' file > > >_______________________________________________ >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.463 / Virus Database: 262 - Release Date: 3/17/2003 Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======49B341D0======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-50C2466 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======49B341D0=======-- From bgailer@alum.rpi.edu Sun Mar 30 12:58:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Sun Mar 30 12:58:01 2003 Subject: [Tutor] Re: implementing relationship between objects In-Reply-To: Message-ID: <5.2.0.9.0.20030330105527.0314da98@66.28.54.253> --=======75EC6BBB======= Content-Type: text/plain; x-avg-checked=avg-ok-50C2466; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 02:08 AM 3/30/2003 +0000, Lee Harr wrote: >>How would you implement in python a 'relational' 1:1, 1:N, N:N >>relationship between objects? >> >>Of course both 'sides' should know about the other and changing one >>'side' of the relation should affect the other side (kind of >referetial >>integrity). [snip] >I guess it depends on what your goal is. My question too: tell us a bit more about what you want to accomplish. And consider, based on what you've told us so far, using a database to manage these relationships, as that's what (inter alia) they're good at. Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======75EC6BBB======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-50C2466 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======75EC6BBB=======-- From bgailer@alum.rpi.edu Sun Mar 30 13:01:51 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Sun Mar 30 13:01:51 2003 Subject: [Tutor] Creating a database In-Reply-To: <0f0c01c2f6df$4dae3e80$7840fea9@BillieWages> Message-ID: <5.2.0.9.0.20030330105904.03166a90@66.28.54.253> --=======3726192C======= Content-Type: text/plain; x-avg-checked=avg-ok-50C2466; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:10 AM 3/30/2003 -0600, Billie wrote: >I'm wanting to create a web page that lists names, addresses and phone >numbers, and I want it to be storable. [snip] For the storage aspect, see my comments about the SQLite data base in my response to [Tutor] Newbie - Simple mailing list archiver Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======3726192C======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-50C2466 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======3726192C=======-- From Janssen@rz.uni-frankfurt.de Sun Mar 30 13:16:52 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sun Mar 30 13:16:52 2003 Subject: [Tutor] Creating a database In-Reply-To: <0f0c01c2f6df$4dae3e80$7840fea9@BillieWages> Message-ID: On Sun, 30 Mar 2003, Billie wrote: > Well, I'm off on a project, and want to know if Python will do the trick. > > I'm wanting to create a web page that lists names, addresses and phone > numbers, and I want it to be storable. Being new, first I'm sure it's > possible, second, is it very difficult (I shouldn't think so, but am still > asking). I remember making sorted lists in BASIC, but I want this where the > user clicks and chooses their preference. Easiest thing would be to generate a static webpage from a text-file containing all addresses in a proper format (comma separated value, eg) and rerun the script with every change you make to the database. But you want the user to sort (and search?) the webpage on the fly, right? The "database" can remain a simple text-file, that's enough for many needs (otherwise a SQL-Database-System comes in handy. Bob Gailer had already written this part :-). But you must use some technology, that allows you to interact between webpage and script. cgi is such a thing: You're webpage gets some html-form-code and this way the user can send informations to your cgi-script. E.g. sort-order. Now the script can parse the address-file and sort its internal data before putting it into on-the-fly htmlcode (In case it is not clear: you can't sort the content on the user side [unless you make much java/javascript]). Consult your favorite html-reference for forms and Python's Library Reference for the cgi-modul (It comes with some explanations). Ask tutor, of course. > > Am I taking on more than I'm ready for? don't know ;-) In case you stumble against reality you could fall back to a static webpage, which is rather simple to write (and you can reuse code when you make your next try with an on-the-fly website). Michael I like challenges, but must have a > bit of reality in check, also. > > Billie > > > > From python@jaydorsey.com Sun Mar 30 13:55:01 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Sun Mar 30 13:55:01 2003 Subject: [Tutor] Script Optimization (PIL) Message-ID: <3E873D54.4080305@jaydorsey.com> I have a thumbnail script I wrote, which is running as a CGI script. The script receives an image name, a height and width, and uses the Python Imaging Library to thumbnail the image. This script could potentially be called ~300 times a minute to thumbnail images so I want it to be as fast as possible. I'm not sure if multi-threading is an option -- what I've read on threading in Python is confusing so I'm not sure if its possible, or if it will work in this situation. The script creates the images dynamically, and doesn't save the thumbnail at all. The source images are all available locally. Currently I benchmark the script by calling a PHP page which loops through 200 image names and does a GET to retrieve and display the thumbnails. This is similar to how the actual service will work when it is finished. I have the script broken up into two files: The first, thumb.py, imports some functions I created in the second file, thumblib.py. I found that by putting the functions into thumblib.py and importing them, the script ran much quicker. thumb.py ----------begin file---------- #!/usr/local/bin/python from thumblib import createThumb, sendImage, getqs sendImage(createThumb(getqs())) ----------end file---------- thumblib.py ----------begin file---------- #!/usr/local/bin/python import Image # Borrowed the following two lines from Fredrik Lundh's # contribution on pythonware.com. This imports only the modules # that I need; in this case, the Jpeg plugin import JpegImagePlugin Image._initialized = 1 # import this for temporary file storage from cStringIO import StringIO # used to get the querystring from cgi import FieldStorage def getqs(): """ Reads in a querystring and assigns the querystring vars to variables """ form = FieldStorage() i, w, h = form.getvalue('i'), int(form.getvalue('w')), \ int(form.getvalue('h')) return i, w, h def createThumb(vars): """ Does the actual thumbnail """ image, width, height = vars # my image file object thumb = StringIO() im = Image.open("".join(["/usr/local/xitami/webpages/images/", image])) im.thumbnail((int(width), int(height))) # saving the image as progressive speeds up the script im.save(thumb, "JPEG", progressive=1) thumb.seek(0) return thumb.getvalue() def sendImage(image): """ Produces the proper HTTP headers and the resultant thumbnails """ print "Content-type: image/jpeg\nContent-length: %s\n\n%s" % (len(image) , image) ----------end file---------- I've found a few little tricks, such as instead of saying: x = 1 y = 2 use: x, y = 1, 2 I've also used py_compile to compile both the thumb.py and thumblib.py files. Currently, I can thumbnail 200 640x480 JPEG images in about 35 seconds, which meets my requirements of 300 in a minute, but I'm running on a local box and I know once I add some network overhead on it the speed is going to go down some. Any tips/tricks/ideas would be appreciated, code examples will get you a beer next time I'm in town;). I want this to run as a web service (multiple servers will be hitting it), but I'm not sure whats the best way to do this? I've thought about writing the JPEG to a tmp directory, as a form of "caching", but if I can make this work fast enough without having to resort to such trickery ;) I would rather not. Would I be able to make this script into some sort of daemon/service to cut down on python load time? Thanks again, -- Jay Dorsey python at jay dorsey dot com From bds@waywood.co.uk Sun Mar 30 21:13:01 2003 From: bds@waywood.co.uk (Barnaby Scott) Date: Sun Mar 30 21:13:01 2003 Subject: [Tutor] Newbie - Simple mailing list archiver References: <000501c2f639$293800a0$1200a8c0@StudyDell> Message-ID: <002c01c2f721$870aab40$1200a8c0@StudyDell> I have to apologise - since I posted my first message I have be wrestling solidly with this problem, and have managed to write my script. I suspect it contains mistakes - some of which will probably appear incredibly stupid! May I therefore change my request to asking for comments on what I have done, and pointers to things which are wrong. One thing to bear in mind - I am going to have to run this on a machine which only has version 1.5.2 (until I can persuade them to upgrade), so I have taken that version's documentation as my guide. Thanks in advance for any pointers - please be kind though, it's my first effort. import sys, string, rfc822, mimetools, multifile #paths pathtolookupfile = '/I/Will/Fill/This/In Later/' pathtowikifiles = '/Assuming/I/Remeber/' #Read mail message from STDIN msg = rfc822.Message(sys.stdin) #Get these header values: #From fromtuple = msg.getaddr('From') from = fromtuple[0] #Subject (or specify 'no subject') subject = msg.getheader('Subject', 'no subject') #Message-ID messageid = msg.getheader('Message-ID') #Date (in a short, consistent format) datetuple = msg.getdate('Date') if datetuple == None: datetuple = time.localtime() date = `datetuple[2]` + '/' + `datetuple[1]` + '/' + `datetuple[0]` #In-Reply-To, or failing that the last value in References, if either exist if msg.has_key('In-Reply-To'): parentmailid = msg.getheader('In-Reply-To') elif msg.has_key('References'): references = msg.getheader('References') refsl = string.split(references) parentmailid = refsl.pop() else: parentmailid = None #Content-Type contenttype = msg.getheader('Content-Type', 'text/plain') #If Content-Type is multipart/*, get only the body section that is text/plain if contenttype[:10] == "multipart/": mimemsg = mimetools.Message(sys.__stdin__) boundary = mimemsg.getparam('boundary') mf = multifile.MultiFile(sys.__stdin__) mf.push(boundary) while mf.next(): msgpart = mimetools.Message(mf) if msgpart.gettype() == 'text/plain': bodytext = msgpart.fp.read() break #Else if Content-Type is text/plain, get the body text elif contenttype[:10] == "text/plain": bodytext = msg.fp.read() else: bodytext = 'no body text suitable for archive' #Open my 'messageIDs' file (a lookup file which stores, from previous messages, the value pairs: Original Message-ID, An integer messageID) msgids = {} f1 = open(pathtolookupfile + "messageIDs", 'w') msgids = pickle.load(f1) #Find there the highest existing integer messageID and generate a new one by adding 1 l1 = msgids.values() newintid = max(l1) + 1 #Append to the 'messageIDs' file: # This message's Message-ID, Our newly generated integer messageID msgids.append(messageid: newintid) pickle.dump(msgids, f1) f1.close() #Open my 'ArchiveIndex' file (a wiki page which lists all messages in threads, with a specific method of indenting) f2 = open("ArchiveIndex", 'w') #If there is an In-Reply-To or References value if parentmailid != None: # Look in the 'messageIDs' dictionary for this Message-ID and return that message's corresponding integer messageID parentintid = msgids[parentmailid] # Look in the 'ArchiveIndex' file to find this integer at the beginning of a line (save for preceding spaces and '*') f2 = open("pathtowikifiles/ArchiveIndex", 'w') l2 = f2.readlines() for s in l2: p = string.find('*' + `parentintid` + ':') if p != -1: indentspaces = len(s) - len(string.lstrip(s)) + 1 insertpos = l2.index(s) + 1 break else: indentspaces = 1 insertpos = 0 #Else else: indentspaces = 1 insertpos = 0 #write new line to wiki page ArchiveIndex newarchiveentry = ' ' * indentspaces + '*' + `newintid` + ': ' + subject + ' ' + from + ' ' + date + ' [ArchivedMessage' + `newintid` + ' ' + 'View]\n\n' l2.insert(insertpos, newarchiveentry) f2.write(l2) f2.close() #Create and open a new file called 'ArchivedMessage' + integer messageID f3 = open("pathtowikifiles/ArchivedMessage" + `newintid`, 'w') #Write to this file: # From # Subject # Date # plain text body f3.write(senderemail + '/n/n' + subject + '/n/n' + date + '/n/n' + bodytext) #Close the 'ArchivedMessage?' file f3.close() From sudhirchauhan1@yahoo.co.in Mon Mar 31 11:12:30 2003 From: sudhirchauhan1@yahoo.co.in (=?iso-8859-1?q?sudhir=20chauhan?=) Date: Mon Mar 31 11:12:30 2003 Subject: [Tutor] Problem in open function Message-ID: <20030331161123.41833.qmail@web8203.mail.in.yahoo.com> Dear all, how i can use built in open() functions when i have imported os module which also have open() system call. the code allows me to use one only why? what i should do to to use os module fucntions as well builin open()function. regards, sudhir ________________________________________________________________________ Missed your favourite TV serial last night? Try the new, Yahoo! TV. visit http://in.tv.yahoo.com From vicki@stanfield.net Mon Mar 31 11:13:01 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Mon Mar 31 11:13:01 2003 Subject: [Tutor] If not global, how? Message-ID: <20030331081208.26747.h015.c000.wm@mail.stanfield.net.criticalpath.net> In the app that I am developing, I have some callbacks that need data from other methods. I am trying to figure out how to make that data available without making it global. Here is an example: This class is instantiated. class EntryClass(Pmw.EntryField): def __init__(self, parent=0): Pmw.EntryField.__init__(self, parent) def SendCommand(command): for command in ('\x09','\x06'): port = serial.Serial(0, 9600, 8, 'N', 2, timeout=2) port.write(command) old=outputbox.getvalue() new=string.join([old, hex(ord(command))]) outputbox.setvalue(new) input=port.read() print input if input: returnedval=hex(ord(input)) if returnedval: print returnedval old=outputbox.getvalue() new=string.join([old, returnedval]) outputbox.setvalue(new) port.close() def Callback(self): value=self.getvalue() print value if value SendCommand(value) ------------------------------------ As you can see, I need to call SendCommand from the callback. Since it is not an instance within the class, I can't use EntryClass.SendCommand. If I move the call to SendCommand into the main code, I don't think I can be sure that it was just called and has a value that I actually want to send out. I realize that I am probably making this much harder than it is, but I am stuck. Can someone help me fix this one? --vicki From antonmuhin at rambler.ru" References: <20030331161123.41833.qmail@web8203.mail.in.yahoo.com> Message-ID: <9022577524.20030331215127@rambler.ru> Hello sudhir, Monday, March 31, 2003, 8:11:23 PM, you wrote: sc> Dear all, sc> how i can use built in open() functions when i have sc> imported os module which also have open() system call. sc> the code allows me to use one only why? sc> what i should do to to use os module fucntions as well sc> builin open()function. sc> regards, sc> sudhir sc> ________________________________________________________________________ sc> Missed your favourite TV serial last night? Try the new, Yahoo! TV. sc> visit http://in.tv.yahoo.com 1. Use file instead (open even seems to be depricated now). 2. If you import with 'import os', then os.open should work, but it seems that you imorted it with 'from os import open'. In this case you migth want to save the old functiuon: old_open = open from os import open old_open(...) # standard open open(...) # os.open -- Best regards, anton mailto:antonmuhin@rambler.ru From antonmuhin at rambler.ru" References: <20030331081208.26747.h015.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <122744574.20030331215414@rambler.ru> Hello vicki, Monday, March 31, 2003, 8:12:08 PM, you wrote: vsn> In the app that I am developing, I have some callbacks vsn> that need data from other methods. I am trying to vsn> figure out how to make that data available without vsn> making it global. Here is an example: vsn> This class is instantiated. vsn> class EntryClass(Pmw.EntryField): vsn> def __init__(self, parent=0): vsn> Pmw.EntryField.__init__(self, parent) vsn> def SendCommand(command): vsn> for command in ('\x09','\x06'): vsn> port = serial.Serial(0, 9600, 8, 'N', 2, timeout=2) vsn> port.write(command) vsn> old=outputbox.getvalue() vsn> new=string.join([old, hex(ord(command))]) vsn> outputbox.setvalue(new) vsn> input=port.read() vsn> print input vsn> if input: vsn> returnedval=hex(ord(input)) vsn> if returnedval: vsn> print returnedval vsn> old=outputbox.getvalue() vsn> new=string.join([old, returnedval]) vsn> outputbox.setvalue(new) vsn> port.close() vsn> def Callback(self): vsn> value=self.getvalue() vsn> print value vsn> if value vsn> SendCommand(value) vsn> ------------------------------------ vsn> As you can see, I need to call SendCommand from the vsn> callback. Since it is not an instance within the class, vsn> I can't use EntryClass.SendCommand. If I move the call vsn> to SendCommand into the main code, I don't think I can vsn> be sure that it was just called and has a value that I vsn> actually want to send out. I realize that I am probably vsn> making this much harder than it is, but I am stuck. Can vsn> someone help me fix this one? vsn> --vicki There are several options. One in style of Magnus: use class and define __call__ method. Another is to use closures (if I use the term correctly): def f(x, y): return x + y def bind2nd(f, value2): def inner_f(x): return f(x, value2) my_func = bind2nd(f, 1) my_func(3) # should be the same to f(3, 1) Warning: I didn't test it. -- Best regards, anton mailto:antonmuhin@rambler.ru From antonmuhin at rambler.ru" Hello vicki, I forgot one really important line: def bind2nd(f, value2): def inner_f(x): return f(x, value2) return inner_f # HERE IT IS I beg your pardon -- Best regards, anton mailto:antonmuhin@rambler.ru From vicki@stanfield.net Mon Mar 31 13:09:14 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Mon Mar 31 13:09:14 2003 Subject: [Tutor] If not global, how? Message-ID: <20030331100856.8578.h016.c000.wm@mail.stanfield.net.criticalpath.net> I am pretty sure that __call__ is what I need, but I am still unclear how to implement it in my case. Is there some documentation that you can point me to? --vicki From abli@freemail.hu Mon Mar 31 13:31:02 2003 From: abli@freemail.hu (Abel Daniel) Date: Mon Mar 31 13:31:02 2003 Subject: [Tutor] If not global, how? In-Reply-To: <20030331081208.26747.h015.c000.wm@mail.stanfield.net.criticalpath.net> References: <20030331081208.26747.h015.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <20030331183022.GA449@hooloovoo> vicki@stanfield.net wrote: Ok. You have two widgets, and you want to read from one of them, do something in the background and then write to the second one. In the code you posted, SendCommand looks like being the method of one of the widgets, which is imho not what you want. (Does it belong to the entryfiled or to the outputbox? Or none of them ? I would think none of them) Instead, create an object which has two widgets and a SendCommand method. I would do it like this: class PortDebugger(Pmw.MegaWidget): def __init__(self, parent=None, **kw): self.defineoptions(kw, ()) Pmw.MegaWidget.__init__(self, parent) entry_box=self.createcomponent('entry', (), 'entry', Tkinter.Entry, (self.interior(),), ) entry_box.grid(row = 0, column=0, sticky="ew") result_box=self.createcomponent('result_box', (), 'label', Tkinter.Label, (self.interior(),), ) result_box.grid(row = 1, column=0,sticky="ew") self.initialiseoptions(PortDebugger) def Callback(self): # the same as your code, but calls self.SendCommand() # instead of SendCommand() # and instead of # value=self.getvalue() # uses # value=self.component('entry_box').getvalue() def SendCommand(self, command): # note that it is a method of PortDebugger now # same code as you posted, but instead of # outputbox.setvalue(new) # uses "self.component('result_box')['text']=new" # and instead of # old=outputbox.getvalue() # uses "old = self.component('result_box')['text']" I inherit from MegaWidget, as i think this wouldn't be an entrybox with extra methods, but a collection of different widgets, with some extra functionality thrown in. Also, I use the full "infractructure" of pmw in the __init__ method (thats why it got more complex), leaving even a single line out of that would cause wierd breakage. (See the pmw docs.) Oh, yes and don't copy-paste the above as I not only didn't test it, but didn't prove it correct, either. : ) Abel Daniel p.s. are you sure that the line for command in ('\x09','\x06'): is correct? Don't you want if command in ('\x09','\x06'): instead? From lobow@brturbo.com Mon Mar 31 14:03:00 2003 From: lobow@brturbo.com (Diego Prestes) Date: Mon Mar 31 14:03:00 2003 Subject: [Tutor] Events in tkinter Message-ID: <3E8890A8.1010604@brturbo.com> How can I create the following event using classes? I want to type "control o", for example, and it call this function. def open(self): a = tkFileDialog.askopenfilename(title="Open", initialdir="/") self.text = open(a).read() self.text1.delete(0.0,END) self.text1.insert(END, self.text) Diego From abli@freemail.hu Mon Mar 31 14:43:02 2003 From: abli@freemail.hu (Abel Daniel) Date: Mon Mar 31 14:43:02 2003 Subject: [Tutor] Events in tkinter In-Reply-To: <3E8890A8.1010604@brturbo.com> References: <3E8890A8.1010604@brturbo.com> Message-ID: <20030331194214.GA923@hooloovoo> Diego Prestes wrote: > How can I create the following event using classes? > > I want to type "control o", for example, and it call this function. The event sequence you need is . I guess you already have some widgets, so do a widget.bind_all('', open) at the same place where you create the widget. (Where widget is any Tkinter widget you created.) This will bind the event to all the widgets, so it will work whichever widget has the focus. I guess thats what you want for a general short-cut like this. You can also bind to a specifc widget with widget.bind( ) or to all instance of a class with widget.bind_class( ). The callback (in your case open) will get an event instance as an argument, so it should accept it: def open(self, event): > a = tkFileDialog.askopenfilename(title="Open", initialdir="/") > self.text = open(a).read() > self.text1.delete(0.0,END) > self.text1.insert(END, self.text) Abel Daniel p.s. looks like also works instead of (I don't think there is a difference). "Tkinter reference: a GUI for Python" (84 pp.) is a pretty extensive reference. You can get it from http://www.nmt.edu/tcc/help/lang/python/tkinter.html (look for it in the 'Local Links' section). At the end it has 8 pages about events in Tkinter. From dyoo@hkn.eecs.berkeley.edu Mon Mar 31 17:18:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 31 17:18:02 2003 Subject: [Tutor] Problem in open function In-Reply-To: <9022577524.20030331215127@rambler.ru> Message-ID: On Mon, 31 Mar 2003, antonmuhin at rambler.ru wrote: > sc> how i can use built in open() functions when i have > sc> imported os module which also have open() system call. > > sc> the code allows me to use one only why? > 1. Use file instead (open even seems to be depricated now). > 2. If you import with 'import os', then os.open should work, but it > seems that you imorted it with 'from os import open'. In this case you > migth want to save the old functiuon: > > old_open = open > from os import open > old_open(...) # standard open > open(...) # os.open Even so, it's probably a good idea to avoid using 'from os import open', as lots of folks probably expect open() to stand for the standard "builtin" open function. Sudhir, it does sounds like you're using something like 'from os import *'. The 'from' statement's meant to plunk the contents of a module directly into the global namespace for convenience sake, but is problematic since it plunks the contents of a module directly into the global namespace. *grin* Doing something like 'from os import *' ends up overwriting some important builtin functions like open() so that they're not easily accessible anymore. Can you check to see if you can find that 'from os import *' in your code? The Python Tutorial does have a section on 'Importing * From a a Package'; it might be useful for you: http://www.python.org/doc/tut/node8.html#SECTION008410000000000000000 Good luck! From GREENDAY31087@aol.com Mon Mar 31 21:47:02 2003 From: GREENDAY31087@aol.com (GREENDAY31087@aol.com) Date: Mon Mar 31 21:47:02 2003 Subject: [Tutor] please help Message-ID: <20.df5196c.2bba575e@aol.com> --part1_20.df5196c.2bba575e_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Concerning py2exe: I think I'm doing this right but it still wont work for me. I have the setup file and the script file. here they are: # setup.py from distutils.core import setup import py2exe setup(name="test", scripts=["test.py"], ) #test.py print "THIS IS A TEST" And When I start the setup program, it says: usage: test.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: test.py --help [cmd1 cmd2 ...] or: test.py --help-commands or: test.py cmd --help error: no commands supplied Am I missing something that's completely obvious? I apologize for being kinda thick but I'm trying to get it to work. Thanks --part1_20.df5196c.2bba575e_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable Concerning py2exe: I think I'm doing this right but it= still wont work for me. I have the setup file and the script file.
here they are:

# setup.py
from distutils.core import setup
import py2exe

setup(name=3D"test",
      scripts=3D["test.py"],
)


#test.py
print "THIS IS A TEST"


And When I start the setup program,  it says:

usage: test.py [global_opts]= cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]   
    or: test.py --help [cmd1 cmd2 ...]   
    or: test.py --help-commands   
    or: test.py cmd --help
error: no commands supplied

Am I missing something that'= s completely obvious? I apologize for being kinda thick but I'm trying to ge= t it to work.
Thanks
--part1_20.df5196c.2bba575e_boundary--