From kent37 at tds.net Mon Jun 1 03:58:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 31 May 2009 21:58:05 -0400 Subject: [Tutor] Challenge supporting custom deepcopy with inheritance In-Reply-To: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local> References: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local> Message-ID: <1c2a2c590905311858x4fa7ec79t5a876c45b78ad6a1@mail.gmail.com> On Sun, May 31, 2009 at 5:35 PM, Michael H. Goldwasser wrote: > > Yesterday, I posted a question to python-list involving custom > deepcopies in an inheritance hierarchy. ?I haven't received any > responses, so I thought I'd cross-post to see if anyone on tutor > has any thoughts. > > To avoid splitting the thread, I'll simply reference the original post at > http://mail.python.org/pipermail/python-list/2009-May/714866.html > and ask for responses to be sent there. Sorry, splitting the thread for you... ISTM that in general B.__deepcopy__() should call A.__deepcopy__() to do the "A" part of the work. In your example, this won't work because A.__deepcopy__() assumes that subclasses have a one-argument constructor. So, I would say that B is not fulfilling the contract assumed by A. What if you give B a one-arg constructor by making the bTag argument optional? Then I think B.__deepcopy__() can call A.__deepcopy__(), then do the "B" part of the copy on the result. Kent From allen.fowler at yahoo.com Mon Jun 1 05:40:53 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Sun, 31 May 2009 20:40:53 -0700 (PDT) Subject: [Tutor] Sample python file/module templates? Message-ID: <933869.57157.qm@web45611.mail.sp1.yahoo.com> Hello, In terms of in-code documentation of function / section headers, change logs, etc. Are there well-done sample files I can use as inspiration? Thank you, :) From alan.gauld at btinternet.com Mon Jun 1 09:13:03 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Jun 2009 08:13:03 +0100 Subject: [Tutor] Sample python file/module templates? References: <933869.57157.qm@web45611.mail.sp1.yahoo.com> Message-ID: "Allen Fowler" wrote > In terms of in-code documentation of function / section headers, > change logs, etc. Are there well-done sample files I can use > as inspiration? The standard library. Much of it is written in Python and the documentation is designed to play well with Pythons help() function. Change logs are mostly kept in the version control tool, but you can access the svn repository onthe web site to see the history etc. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jun 1 09:27:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Jun 2009 08:27:00 +0100 Subject: [Tutor] Challenge supporting custom deepcopy with inheritance References: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local> <1c2a2c590905311858x4fa7ec79t5a876c45b78ad6a1@mail.gmail.com> Message-ID: "Kent Johnson" wrote > > Yesterday, I posted a question to python-list involving custom > > deepcopies in an inheritance hierarchy. I haven't received any > > ISTM that in general B.__deepcopy__() should call > A.__deepcopy__() to do the "A" part of the work. In your example, > this won't work because A.__deepcopy__() assumes that > subclasses have a one-argument constructor. So, I would > say that B is not fulfilling the contract assumed by A. I've been trying to think of a clear way to reply to this but kept getting sucked into discussions of the Liskoff Substitution Principle and Law of Demeter and such. Kent's explanation is much clearer! But this example highlights a real problem (IMHO) with dynamic OOP languages like Python. You can write classes that examine themselves at runtime and manipulate attributes that were actually provided by subclasses (or even by the application writer!). This makes any attempt at things like deepcopy fraught with difficulty because the clear separation of concerns between parent and subclass has been broken. It is very important for good OO design that classes only operate on their own data. But when you can dynamically add attributes to instances after theit creation, as you can in Python, it's almost impossible to distinguish between attributes of the parent class and the subclass. It's one of the penalties of Python's dynamic nature and there is no easy solution to the general case. In the specific case you need to read the code of both parent and subclass and the application(s) using them! > What if you give B a one-arg constructor by making the > bTag argument optional? Then I think B.__deepcopy__() > can call A.__deepcopy__(), then do the "B" part of the > copy on the result. As a minimum subclasses should adhere to the parent interface. Unfortunately because Python only allows a single constructor that can be a limiting factor :-( ( Multiple constructors (or factory methods) is one feature I would like to see added to Python! ) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From srilyk at gmail.com Mon Jun 1 12:27:52 2009 From: srilyk at gmail.com (W W) Date: Mon, 1 Jun 2009 05:27:52 -0500 Subject: [Tutor] Challenge supporting custom deepcopy with inheritance In-Reply-To: References: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local> <1c2a2c590905311858x4fa7ec79t5a876c45b78ad6a1@mail.gmail.com> Message-ID: <333efb450906010327p47c9b56bo9b2c0099246c19f6@mail.gmail.com> On Mon, Jun 1, 2009 at 2:27 AM, Alan Gauld wrote: > > "Kent Johnson" wrote > >> > Yesterday, I posted a question to python-list involving custom >> > deepcopies in an inheritance hierarchy. I haven't received any >> >> ISTM that in general B.__deepcopy__() should call A.__deepcopy__() to do >> the "A" part of the work. In your example, this won't work because >> A.__deepcopy__() assumes that subclasses have a one-argument constructor. >> So, I would say that B is not fulfilling the contract assumed by A. >> > > I've been trying to think of a clear way to reply to this but kept getting > sucked into discussions of the Liskoff Substitution Principle and Law of > Demeter and such. Kent's explanation is much clearer! > > But this example highlights a real problem (IMHO) with dynamic OOP > languages like Python. You can write classes that examine themselves at > runtime and manipulate attributes that were actually > provided by subclasses (or even by the application writer!). This makes any > attempt at things like deepcopy fraught with difficulty because the clear > separation of concerns between parent and subclass has been broken. > > It is very important for good OO design that classes only operate on their > own data. But when you can dynamically add attributes to instances after > theit creation, as you can in Python, it's almost impossible to distinguish > between attributes of the parent class and the subclass. It's one of the > penalties of Python's dynamic nature and there is no easy solution to the > general case. In the specific case you need to read the code of both parent > and subclass and the application(s) using them! > > What if you give B a one-arg constructor by making the bTag argument >> optional? Then I think B.__deepcopy__() can call A.__deepcopy__(), then do >> the "B" part of the copy on the result. >> > > As a minimum subclasses should adhere to the parent interface. > Unfortunately because Python only allows a single constructor that can be a > limiting factor :-( > ( Multiple constructors (or factory methods) is one feature I would like > to see added to Python! ) > Wouldn't it be possible to create sort of a... bastardization? i.e. def __init__(self, *args): if len(args) == 0: #do something if len(args) == 1: #do something else etc.? Or would that create more problems than is worth it? -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 1 15:59:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Jun 2009 14:59:11 +0100 Subject: [Tutor] Challenge supporting custom deepcopy with inheritance References: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local> <1c2a2c590905311858x4fa7ec79t5a876c45b78ad6a1@mail.gmail.com> <333efb450906010327p47c9b56bo9b2c0099246c19f6@mail.gmail.com> Message-ID: "W W" wrote >> ( Multiple constructors (or factory methods) is one feature I would >> like >> to see added to Python! ) > > Wouldn't it be possible to create sort of a... bastardization? i.e. > > def __init__(self, *args): > if len(args) == 0: > #do something > if len(args) == 1: > #do something else > > Or would that create more problems than is worth it? Thats the standard workaround but its not clean and certainly not self documenting. Its also not reliable becaause thre is nothing to stop someone calling it with the first argument of the 2 arg case (a filename maybe?) and then it gets treated as a single arg case ( a tuple of values say?) Oops! Whereas in C++/Java style you could say class C: @constructor def C(fname, count);... @constructor def C(valueTuple):.... etc. Or in Delphi style: class C: @constructor def LoadFromFile(fname, count): ... @constructor def Create(valueTuple):... Personally I prefer the Delphi style sincve it makes the constructor call explicit and adds to the documentation. Alan G From goldwamh at slu.edu Mon Jun 1 19:19:19 2009 From: goldwamh at slu.edu (Michael H. Goldwasser) Date: Mon, 1 Jun 2009 12:19:19 -0500 Subject: [Tutor] Challenge supporting custom deepcopy with inheritance In-Reply-To: References: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local> <1c2a2c590905311858x4fa7ec79t5a876c45b78ad6a1@mail.gmail.com> <18978.5438.755496.633709@Michael-Goldwassers-Computer.local> <18979.19148.208649.805972@Michael-Goldwassers-Computer.local> <18978.63514.319199.287551@Michael-Goldwassers-Computer.local> Message-ID: <18980.3479.234994.204687@Michael-Goldwassers-Computer.local> Chris, Thanks for your well-written reply. Your analogy to the complexities of other special methods is well noted. I'll accept the "small price for flexibility" that you note, if necessary. However, I still desire a cleaner solution. I can examine the inherited slots to see which special methods are there, and to implement my own __deepcopy__ accordingly. But to do so well seems to essentially require reimplementing the complicated logic of the copy.deepcopy function. That is, if my new class is the first to be implementing an explicit __deepcopy__ function, I seem to have no easy way to invoke the inherited version of "deepcopy(self)". I wonder if the logic inherent in the copy.deepcopy function could instead be implemented directly within object.__deepcopy__ (rather than the current model in which object does not have __deepcopy__). Then I would always have a means for simulating a call to deepcopy(self) based upon the super.__deepcopy__ logic. I wouldn't be surprised if I'm overlooking some undesirable consequence of such a major change in the model, but I don't see one upon first thought. Michael On Monday June 1, 2009, Gabriel Genellina wrote: > In general, you have to know whether A implements __deepcopy__ or not. > This is a small price for the flexibility (or anarchy) in the copy/pickle > interfases: there are several ways to implement the same thing, and you > have to know which one your base class has chosen in order to extend it. > > The following is a possible implementation that doesn't use __init__ at > all, so their different signature is not an issue: > > # class A: > def __deepcopy__(self, memo={}): > dup = type(self).__new__(type(self)) > dup.__aTag = self.__aTag > dup.__aList = copy.deepcopy(self.__aList, memo) > dup.__aList.reverse() > return dup > > # class B: > def __deepcopy__(self, memo={}): > dup = A.__deepcopy__(self, memo) > dup.__bTag = self.__bTag > dup.__bList = copy.deepcopy(self.__bList, memo) > return dup > > Note that A.__deepcopy__ does two things: a) create a new, empty, > instance; and b) transfer state. B.__deepcopy__ handles *its* portion of > state only. This can be written in a more generic way, relying on > __getstate__/__setstate__ (the methods that should return the current > state of the object): > > # class A: > def __deepcopy__(self, memo={}): > dup = type(self).__new__(type(self)) > if hasattr(self, '__getstate__'): state = self.__getstate__() > else: state = self.__dict__ > state = copy.deepcopy(state, memo) > if hasattr(dup, '__setstate__'): dup.__setstate__(state) > else: dup.__dict__.update(state) > dup.__aList.reverse() > return dup > > # remove __deepcopy__ definition from class B > > Now, B (and any other subclass) is concerned only with __getstate__ / > __setstate__, and only when the default implementation isn't appropriate. > > > As another basic puzzle, consider a class definition for B where B has > > a registry list that it doesn't want cloned for the new instance (but > > it does want pickled when serialized). This would seem to require > > that B implement its own __deepcopy__. We want to somehow rely on > > the class definition for A to enact the cloning fo the state defined > > by A. But without knowing about how A supports the deepcopy > > semantics, I don't see how to accomplish this goal. > > I don't understand such bizarre requirement, but anyway, you can override > __deepcopy__ (make B fix only the part that the default implementation > doesn't implement well) > > # A.__deepcopy__ as above > > # class B: > def __deepcopy__(self, memo={}): > dup = A.__deepcopy__(self, memo) > dup.__registry = self.__registry > return dup > > This [the need to know how certain feature is implemented in the base > class] is not special or peculiar to pickle/copy, although the multiple > (and confusing) ways in which a class can implement pickling doesn't help > to understand the issue very well. > > Consider the + operator: when some subclass wants to implement addition, > it must know which of the several special methods involved (__add__, > __iadd__, __radd__) are implemented in the base class, in order to > extend/override them. Same for __cmp__/__eq__/__hash__: you can't just > ignore what your base class implements. All of this applies to other > languages too, but in Python, there is an additional consideration: the > mere *existence* of some methods/attributes can have consequences on how > the object behaves. In short, you can't blindly write __special__ methods. > > -- > Gabriel Genellina From srilyk at gmail.com Mon Jun 1 22:18:37 2009 From: srilyk at gmail.com (W W) Date: Mon, 1 Jun 2009 15:18:37 -0500 Subject: [Tutor] Challenge supporting custom deepcopy with inheritance In-Reply-To: References: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local> <1c2a2c590905311858x4fa7ec79t5a876c45b78ad6a1@mail.gmail.com> <333efb450906010327p47c9b56bo9b2c0099246c19f6@mail.gmail.com> Message-ID: <333efb450906011318t5ac6c9c4l402d9b02d71994e7@mail.gmail.com> On Mon, Jun 1, 2009 at 8:59 AM, Alan Gauld wrote: > > "W W" wrote > > ( Multiple constructors (or factory methods) is one feature I would like >>> to see added to Python! ) >>> >> >> Wouldn't it be possible to create sort of a... bastardization? i.e. >> >> def __init__(self, *args): >> if len(args) == 0: >> #do something >> if len(args) == 1: >> #do something else >> >> Or would that create more problems than is worth it? >> > > Thats the standard workaround but its not clean and certainly > not self documenting. Its also not reliable becaause thre is nothing > to stop someone calling it with the first argument of the 2 arg case > (a filename maybe?) and then it gets treated as a single arg case > ( a tuple of values say?) Oops! > > Whereas in C++/Java style you could say > > class C: > @constructor > def C(fname, count);... > > @constructor > def C(valueTuple):.... > > etc. > > Or in Delphi style: > > class C: > @constructor > def LoadFromFile(fname, count): ... > @constructor > def Create(valueTuple):... > > Personally I prefer the Delphi style sincve it makes the constructor > call explicit and adds to the documentation. > > Alan G > That does make it problematic... although I suppose checking the type would be a workaround - still, not simple or beautiful. Has this been introduced as a PEP? -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 1 22:55:38 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Jun 2009 21:55:38 +0100 Subject: [Tutor] Challenge supporting custom deepcopy with inheritance References: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local> <1c2a2c590905311858x4fa7ec79t5a876c45b78ad6a1@mail.gmail.com> <333efb450906010327p47c9b56bo9b2c0099246c19f6@mail.gmail.com> <333efb450906011318t5ac6c9c4l402d9b02d71994e7@mail.gmail.com> Message-ID: "W W" wrote >> class C: >> @constructor >> def LoadFromFile(fname, count): ... >> @constructor >> def Create(valueTuple):... >> >> Personally I prefer the Delphi style sincve it makes the constructor >> call explicit and adds to the documentation. >> >> Alan G >> > > That does make it problematic... although I suppose checking the type > would > be a workaround - still, not simple or beautiful. Has this been > introduced > as a PEP? Type checking is the problem. Until Python can distinguish methods based on types (which introduces other issues) thisi is difficult with the C/Java style. We can fake the Delphi style by using a default constructor and then just calling the "constructors" after initialisation: class C: def __init__(): pass @constructor def LoadFromFile(fname, count): ... @constructor def Create(valueTuple):... c = C() c.LoadFromFile(fn, cnt) But its two lines not one... :-( And so far as I know it has not been PEPd although I'm sure it has been discussed. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Mon Jun 1 23:35:12 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 1 Jun 2009 17:35:12 -0400 Subject: [Tutor] Challenge supporting custom deepcopy with inheritance In-Reply-To: References: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local> <1c2a2c590905311858x4fa7ec79t5a876c45b78ad6a1@mail.gmail.com> <333efb450906010327p47c9b56bo9b2c0099246c19f6@mail.gmail.com> <333efb450906011318t5ac6c9c4l402d9b02d71994e7@mail.gmail.com> Message-ID: <1c2a2c590906011435t3f2bcee7ta2124bcecd5fdd4@mail.gmail.com> On Mon, Jun 1, 2009 at 4:55 PM, Alan Gauld wrote: > We can fake the Delphi style by using a default constructor and then just > calling the "constructors" after initialisation: > > class C: > ? ? ? ?def __init__(): pass > ? ? ? @constructor > ? ? ? def LoadFromFile(fname, count): ... > ? ? ?@constructor > ? ? ?def Create(valueTuple):... > > c = C() > c.LoadFromFile(fn, cnt) > > But its two lines not one... :-( Why not this? class C: def __init__(self): pass @staticmethod def LoadFromFile(fname, count): c = C() # init c from the file return c and similar for Create(). Client code is one line: c = C.LoadFromFile(fn, cnt) Kent From srilyk at gmail.com Mon Jun 1 23:50:05 2009 From: srilyk at gmail.com (W W) Date: Mon, 1 Jun 2009 16:50:05 -0500 Subject: [Tutor] Challenge supporting custom deepcopy with inheritance In-Reply-To: References: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local> <1c2a2c590905311858x4fa7ec79t5a876c45b78ad6a1@mail.gmail.com> <333efb450906010327p47c9b56bo9b2c0099246c19f6@mail.gmail.com> <333efb450906011318t5ac6c9c4l402d9b02d71994e7@mail.gmail.com> Message-ID: <333efb450906011450t4b01edabica4c8fb28f52f0cb@mail.gmail.com> On Mon, Jun 1, 2009 at 3:55 PM, Alan Gauld wrote: > > "W W" wrote > >> class C: >>> @constructor >>> def LoadFromFile(fname, count): ... >>> @constructor >>> def Create(valueTuple):... >>> >>> Personally I prefer the Delphi style sincve it makes the constructor >>> call explicit and adds to the documentation. >>> >>> Alan G >>> >>> >> That does make it problematic... although I suppose checking the type >> would >> be a workaround - still, not simple or beautiful. Has this been introduced >> as a PEP? >> > > Type checking is the problem. Until Python can distinguish methods based > on types (which introduces other issues) thisi is difficult with the > C/Java style. > > We can fake the Delphi style by using a default constructor and then just > calling the "constructors" after initialisation: > > class C: > def __init__(): pass > @constructor > def LoadFromFile(fname, count): ... > @constructor > def Create(valueTuple):... > > c = C() > c.LoadFromFile(fn, cnt) > > But its two lines not one... :-( > > And so far as I know it has not been PEPd although I'm sure it has > been discussed. I'm not sure how types are implemented in the underlying C, but it seems that it should be a somewhat trivial addition. I mean, type checking is already built-in to python, i.e. type('a') o/p: , so just building a handler specific to the __init__ method, or modifying it if it's already unique, should be able to take care of it. I guess one way you could try to parse it on your own is build a list of types: f1 = [type(''), type(1), type(())], f2 = [type([]), type(1)]] and compare the types of arguments provided from *args. I suppose really, one could go so far as to build a dict of lists with the lengths: spam = {1:[[type(''))],], 2:[[type([]), type(())], [type(1), type(1.0)] then compare then lengths of args first. That's a lot of work, though :P -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From allen.fowler at yahoo.com Tue Jun 2 00:27:20 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Mon, 1 Jun 2009 15:27:20 -0700 (PDT) Subject: [Tutor] Spell checking source code? Message-ID: <806934.5719.qm@web45603.mail.sp1.yahoo.com> Hello, Are there any utilities to help "spell check" source code? (Docstrings, etc) Thank you, :) From alan.gauld at btinternet.com Tue Jun 2 01:45:30 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Jun 2009 00:45:30 +0100 Subject: [Tutor] Challenge supporting custom deepcopy with inheritance References: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local><1c2a2c590905311858x4fa7ec79t5a876c45b78ad6a1@mail.gmail.com><333efb450906010327p47c9b56bo9b2c0099246c19f6@mail.gmail.com><333efb450906011318t5ac6c9c4l402d9b02d71994e7@mail.gmail.com> <1c2a2c590906011435t3f2bcee7ta2124bcecd5fdd4@mail.gmail.com> Message-ID: "Kent Johnson" wrote > But its two lines not one... :-( Why not this? class C: def __init__(self): pass @staticmethod def LoadFromFile(fname, count): c = C() # init c from the file return c and similar for Create(). Client code is one line: c = C.LoadFromFile(fn, cnt) Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Tue Jun 2 01:48:10 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Jun 2009 00:48:10 +0100 Subject: [Tutor] Challenge supporting custom deepcopy with inheritance References: <18978.63514.319199.287551@Michael-Goldwassers-Computer.local><1c2a2c590905311858x4fa7ec79t5a876c45b78ad6a1@mail.gmail.com><333efb450906010327p47c9b56bo9b2c0099246c19f6@mail.gmail.com><333efb450906011318t5ac6c9c4l402d9b02d71994e7@mail.gmail.com> <1c2a2c590906011435t3f2bcee7ta2124bcecd5fdd4@mail.gmail.com> Message-ID: "Kent Johnson" wrote > > We can fake the Delphi style by using a default constructor and then > > just > > calling the "constructors" after initialisation: > > But its two lines not one... :-( > > Why not this? > > class C: > def __init__(self): pass > > @staticmethod > def LoadFromFile(fname, count): > c = C() > # init c from the file > return c > > and similar for Create(). Client code is one line: > c = C.LoadFromFile(fn, cnt) Why not indeed?! I must remember that pattern for future reference. Wish I'd thought of it a few months ago when I was wrestling with a problem that could have used multiple constructors! Alan G. From alan.gauld at btinternet.com Tue Jun 2 01:50:44 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Jun 2009 00:50:44 +0100 Subject: [Tutor] Spell checking source code? References: <806934.5719.qm@web45603.mail.sp1.yahoo.com> Message-ID: "Allen Fowler" wrote > Are there any utilities to help "spell check" source code? (Docstrings, > etc) I used to have an emacvs script that could do it for C/C++ using the vanilla Unix spell program. Unfiortunately I can't remember its name but a hunt around the e,macs web sites might throw up an updated version. But only useful if you use emacs! (Which I don't any more) Alan G. From xboxmuncher at gmail.com Tue Jun 2 06:41:15 2009 From: xboxmuncher at gmail.com (xbmuncher) Date: Tue, 2 Jun 2009 00:41:15 -0400 Subject: [Tutor] Spell checking source code? In-Reply-To: References: <806934.5719.qm@web45603.mail.sp1.yahoo.com> Message-ID: if you're on windows, notepad++ has a spell check feature in it using aspell On Mon, Jun 1, 2009 at 7:50 PM, Alan Gauld wrote: > > "Allen Fowler" wrote > > Are there any utilities to help "spell check" source code? (Docstrings, >> etc) >> > > I used to have an emacvs script that could do it for C/C++ using > the vanilla Unix spell program. Unfiortunately I can't remember its name > but a hunt around the e,macs web sites might throw up an updated version. > > But only useful if you use emacs! > (Which I don't any more) > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Jun 2 08:19:04 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 02 Jun 2009 08:19:04 +0200 Subject: [Tutor] Spell checking source code? In-Reply-To: References: <806934.5719.qm@web45603.mail.sp1.yahoo.com> Message-ID: Alan Gauld wrote: > > "Allen Fowler" wrote > >> Are there any utilities to help "spell check" source code? >> (Docstrings, etc) > > I used to have an emacvs script that could do it for C/C++ using > the vanilla Unix spell program. Unfiortunately I can't remember its name > but a hunt around the e,macs web sites might throw up an updated version. There's a flyspell minor mode for this purpose. Stefan From alan.gauld at btinternet.com Tue Jun 2 10:15:45 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 2 Jun 2009 08:15:45 +0000 (GMT) Subject: [Tutor] Spell checking source code? In-Reply-To: <2117728667-1243901219-cardhu_decombobulator_blackberry.rim.net-493569101-@bxe1119.bisx.prod.on.blackberry> References: <806934.5719.qm@web45603.mail.sp1.yahoo.com> <2117728667-1243901219-cardhu_decombobulator_blackberry.rim.net-493569101-@bxe1119.bisx.prod.on.blackberry> Message-ID: <83142.24910.qm@web86702.mail.ird.yahoo.com> > From: "worminater at gmail.com" > To: Alan Gauld > Sent: Tuesday, 2 June, 2009 1:09:39 AM > Subject: Re: [Tutor] Spell checking source code? > > In vim, > > :set spell > :set nospell > :help spell But that will check the whole file. The OP only wanted to spell check the comments. Unless I'm missing something? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ From prasadaraon50 at gmail.com Tue Jun 2 12:02:03 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Tue, 2 Jun 2009 15:32:03 +0530 Subject: [Tutor] Text.index() Message-ID: <9e3fac840906020302i17fdd889v2efee28f99eaa838@mail.gmail.com> Hello I created a gui app.I am finding it impossible to use Text.insert().please some one give an example of using it. def fshow(): x=entry1.get() try: value1,value2=x.split(',') text.insert(len(myfiles(value1,value2)),myfiles(value1,value2)) except: text.insert(len(myfiles(value1,value2)),myfiles(x)) >>> import example4 Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "C:\Python26\example4.py", line 37, in fshow text.insert(len(myfiles(value1,value2)),myfiles(x)) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3001, in insert self.tk.call((self._w, 'insert', index, chars) + args) TclError: bad text index "178" import example4 Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "C:\Python26\example4.py", line 37, in fshow text.insert(None,myfiles(x)) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3001, in insert self.tk.call((self._w, 'insert', index, chars) + args) TclError: wrong # args: should be ".18428952.18430232 insert index chars ?tagList chars tagList ...?" I cant understand what these error messages are telling. Thanking you Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From cheesman at titan.physx.u-szeged.hu Tue Jun 2 12:47:31 2009 From: cheesman at titan.physx.u-szeged.hu (Andy Cheesman) Date: Tue, 2 Jun 2009 12:47:31 +0200 (CEST) Subject: [Tutor] delphi, pascal and Python In-Reply-To: References: <34895.160.114.38.31.1242827642.squirrel@titan.physx.u-szeged.hu> <40af687b0905201916p3d09e7c6je672f7c7fb07ee3@mail.gmail.com> Message-ID: <48766.87.97.16.29.1243939651.squirrel@titan.physx.u-szeged.hu> After Much Looking and pointers from the author, There is this most excellent post by the same author at http://wiki.lazarus.freepascal.org/Developing_Python_Modules_with_Pascal This nearly works but I have issue with the linking of the new module. The error is Linking PyMinMod.so /usr/bin/ld: Python: No such file: No such file or directory I've no clue what the issue is and I don't understand what should be going on. I'm running 64bit ubuntu. I know this might be a bit off topic, but if someone could point me in the right direction, I would be rather grateful Thanks Andy > > "Marc Tompkins" wrote > >>> Is there a Method for wrapping delphi and/or pascal code into python >>> like >>>> SWIG? >>> http://membres.lycos.fr/marat/delphi/python.htm >> >> That's a package to let you embed Python in Delphi; the OP wants to go >> the >> other direction. > > So it is, I didn't read the OP question closely enough. > > On Windows you could create a DLL and use ctypes to access it, > but thats not the same as creating an importable module as could > be done with SWIG > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From lie.1296 at gmail.com Tue Jun 2 12:48:07 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 02 Jun 2009 20:48:07 +1000 Subject: [Tutor] Text.index() In-Reply-To: <9e3fac840906020302i17fdd889v2efee28f99eaa838@mail.gmail.com> References: <9e3fac840906020302i17fdd889v2efee28f99eaa838@mail.gmail.com> Message-ID: prasad rao wrote: > Hello > I created a gui app.I am finding it impossible to > use Text.insert().please some one give an example of using it. > In Tkinter.Text, insert's argument is a string of the form "line.collumn" instead of a number. >>> tb.insert("2.6", 'abc') you usually use %-formatting to create such string. From srilyk at gmail.com Tue Jun 2 13:10:36 2009 From: srilyk at gmail.com (W W) Date: Tue, 2 Jun 2009 06:10:36 -0500 Subject: [Tutor] Spell checking source code? In-Reply-To: <83142.24910.qm@web86702.mail.ird.yahoo.com> References: <806934.5719.qm@web45603.mail.sp1.yahoo.com> <2117728667-1243901219-cardhu_decombobulator_blackberry.rim.net-493569101-@bxe1119.bisx.prod.on.blackberry> <83142.24910.qm@web86702.mail.ird.yahoo.com> Message-ID: <333efb450906020410p7a835213u3012bcef943170cc@mail.gmail.com> On Tue, Jun 2, 2009 at 3:15 AM, ALAN GAULD wrote: > > > From: "worminater at gmail.com" > > To: Alan Gauld > > Sent: Tuesday, 2 June, 2009 1:09:39 AM > > Subject: Re: [Tutor] Spell checking source code? > > > > In vim, > > > > :set spell > > :set nospell > > :help spell > > > But that will check the whole file. The OP only wanted to spell > check the comments. Unless I'm missing something? Shouldn't be too difficult to write a vim script to check only # to EOL, ' to ', " to ", ''' to ''' and "" to """. I think that's the only non-code available? -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 2 16:55:43 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Jun 2009 15:55:43 +0100 Subject: [Tutor] Text.index() References: <9e3fac840906020302i17fdd889v2efee28f99eaa838@mail.gmail.com> Message-ID: "prasad rao" wrote > I created a gui app.I am finding it impossible to > use Text.insert().please some one give an example of using it. Look in my tutorial at event driven programming and the Case study. Both use the Text widget. For more detailed info try this introduction: http://www.linuxjournal.com/article/7357 Or for more detailed info: http://www.pythonware.com/library/tkinter/introduction/x7883-concepts.htm > text.insert(len(myfiles(value1,value2)),myfiles(value1,value2)) I'm not sure what you expected this to do but it looks like you are trying to locate the cursor at the positionn defined by the lengths of your myfiles? But then you don't actually provide any data to insert! Did you read the Tkinter tutorial on the Text widget? > self.tk.call((self._w, 'insert', index, chars) + args) > TclError: bad text index "178" > > File "C:\Python26\example4.py", line 37, in fshow > text.insert(None,myfiles(x)) > File "C:\Python26\lib\lib-tk\Tkinter.py", line 3001, in insert > self.tk.call((self._w, 'insert', index, chars) + args) > TclError: wrong # args: should be ".18428952.18430232 insert index chars > ?tagList chars tagList ...?" > I cant understand what these error messages are telling. They are both telling you that you are passing the wrong information to Text. It expects an index (in the form of a decimal as dwescribed in the links above) and some text, plus optionally some flags. Please read the documentation then ask some specific questions about what you don't understand. The Text widget is immensley powerful so you need to spend some time studying it to get the best out of it. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From roberto03 at gmail.com Tue Jun 2 17:29:41 2009 From: roberto03 at gmail.com (roberto) Date: Tue, 2 Jun 2009 17:29:41 +0200 Subject: [Tutor] serious problem with graphics module In-Reply-To: <4A1B1B8F.5060504@aon.at> References: <4bcde3e10905241403t3356c053m31b5964365860f0f@mail.gmail.com> <4A1B1B8F.5060504@aon.at> Message-ID: <4bcde3e10906020829p75a05cc6m97789dfd4fd92a47@mail.gmail.com> On Tue, May 26, 2009 at 12:28 AM, Gregor Lingl wrote: > > > roberto schrieb: > Do you use Python from the command line (terminal) or do you use IDLE? > I ask this, because these two show different behaviour. i use IDLE, in Python 3.0 >> >> i have a problem with python 3.0 graphics module: >> >> no problem while importing the module >> >>>>> >>>>> import turtle >>>>> >> >> but when i issue any command like: >> >>>>> >>>>> t = turtle.pen() >>>>> > > After performing this command you should be able to observe > a blank window with a tiny black arrow - it's the turtle yes, i can see it but each time i try to get into that window, the mouse pointer switch to the hourglass look and i cannot do anything over the windwow; moreover, if i try to click or move it, WS Xp tells me the program pythonw.exe is not responding > > pen() is a function in the module turtle. It returns a dictionary > of the attributes of the turtle's pen. Have a look at it: > >>>> print(t) > {'pensize': 1, 'resizemode': 'noresize', 'pendown': True, 'fillcolor': > 'black', > 'speed': 3, 'shown': True, 'outline': 1, 'tilt': 0.0, 'pencolor': 'black', > 'stretchfactor': (1.0, 1.0), 'shearfactor': 0.0} >>>> yes, i get a very similar answer > >>>>> t = turtle.forward(60) >>>>> >> >> nothing appears on the screen, only a blank window, with nothing inside; >> may you give me some hint ? >> > > > What happens if you do this? > >>>> from turtle import * >>>> for i in range(4): > ? ? ? forward(100) > ? ? ? left(90) > as i wrote before, i can see the arrow inside the graphic window but i cannot do anything inside it, i mean i cannot move or resize the window etc. anyway, yes i can see the arrow moving and drawing the square correctly ps: i'll answer to your other mails also, thank you very much Gregor -- roberto From roberto03 at gmail.com Tue Jun 2 17:48:58 2009 From: roberto03 at gmail.com (roberto) Date: Tue, 2 Jun 2009 17:48:58 +0200 Subject: [Tutor] serious problem with graphics module In-Reply-To: <4A1B1F78.9070603@aon.at> References: <4bcde3e10905241403t3356c053m31b5964365860f0f@mail.gmail.com> <4A1B1F78.9070603@aon.at> Message-ID: <4bcde3e10906020848m28827aefu5034f60b642c9b41@mail.gmail.com> On Tue, May 26, 2009 at 12:45 AM, Gregor Lingl wrote: > I know one situation in which can happen what you describe: > > If you use IDLE, issue the above commands and your Idle-shell-window > covers the graphics window - then you have to move the shell window in order > to see what's on the graphics window. Alas, in this situation the graphics > window may get nonresponsive (to the Windows-event-queue) and may not > be refreshed. So it remains apparentl empty. You may also experience > problems when trying to close the window (because of the same reasons). right ! > > *Remedy*: if you use the turtle module interactively, you have to use Idle > with the -n flag, which prevents it from using subprocesses for executing > scripts. > > I recommend to prepare a special shortcut on your desktop, something > like this: > > C:\Python30\pythonw.exe C:\Python30\Lib\idlelib\idle.pyw -n > > When you fire up Idle with this link you will get the text: > > ==== No Subprocess ==== > > above your first input prompt. > Now you can enter your commands and everything should work fine. > ok, it works all right now the minor issue is that i could not create the shortcut with the -n flag as you pointed out, that's why i issued both commands: C:\Python30\pythonw.exe C:\Python30\Lib\idlelib\idle.pyw -n via the C: prompt and the graphic window finally worked correctly thank you again -- roberto From roberto03 at gmail.com Tue Jun 2 17:54:09 2009 From: roberto03 at gmail.com (roberto) Date: Tue, 2 Jun 2009 17:54:09 +0200 Subject: [Tutor] python workspace Message-ID: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> hello, i'd like to ask if there is anything in python which helps to see what variables have been defined and their type and their dimension etc; if any of you has ever used Matlab, i mean something really similar to its workspace, where all the user created variables are stored and constantly updated thank you -- roberto From gokhansever at gmail.com Tue Jun 2 18:07:44 2009 From: gokhansever at gmail.com (=?UTF-8?Q?G=C3=B6khan_SEVER?=) Date: Tue, 2 Jun 2009 11:07:44 -0500 Subject: [Tutor] python workspace In-Reply-To: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> References: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> Message-ID: <49d6b3500906020907o4f71c7cbt2c0360de5c45f0e@mail.gmail.com> Hi, Have you tried Ipython? https://launchpad.net/ipython And also there is and on-going work called pydee ( http://code.google.com/p/pydee/) which they plan to integrate Ipython into a GUI very similar to the one in Matlab. G?khan On Tue, Jun 2, 2009 at 10:54 AM, roberto wrote: > hello, > i'd like to ask if there is anything in python which helps to see what > variables have been defined and their type and their dimension etc; > > if any of you has ever used Matlab, i mean something really similar to > its workspace, where all the user created variables are stored and > constantly updated > > thank you > -- > roberto > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Jun 2 18:13:00 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 03 Jun 2009 02:13:00 +1000 Subject: [Tutor] serious problem with graphics module In-Reply-To: <4bcde3e10906020848m28827aefu5034f60b642c9b41@mail.gmail.com> References: <4bcde3e10905241403t3356c053m31b5964365860f0f@mail.gmail.com> <4A1B1F78.9070603@aon.at> <4bcde3e10906020848m28827aefu5034f60b642c9b41@mail.gmail.com> Message-ID: roberto wrote: > On Tue, May 26, 2009 at 12:45 AM, Gregor Lingl wrote: >> I know one situation in which can happen what you describe: >> >> If you use IDLE, issue the above commands and your Idle-shell-window >> covers the graphics window - then you have to move the shell window in order >> to see what's on the graphics window. Alas, in this situation the graphics >> window may get nonresponsive (to the Windows-event-queue) and may not >> be refreshed. So it remains apparentl empty. You may also experience >> problems when trying to close the window (because of the same reasons). > right ! > >> *Remedy*: if you use the turtle module interactively, you have to use Idle >> with the -n flag, which prevents it from using subprocesses for executing >> scripts. >> >> I recommend to prepare a special shortcut on your desktop, something >> like this: >> >> C:\Python30\pythonw.exe C:\Python30\Lib\idlelib\idle.pyw -n >> >> When you fire up Idle with this link you will get the text: >> >> ==== No Subprocess ==== >> >> above your first input prompt. >> Now you can enter your commands and everything should work fine. >> > ok, it works all right now > > the minor issue is that i could not create the shortcut with the -n > flag as you pointed out, that's why i issued both commands: > C:\Python30\pythonw.exe > C:\Python30\Lib\idlelib\idle.pyw -n > > via the C: prompt > > and the graphic window finally worked correctly > > thank you again > Be aware though that using IDLE without subprocess also has its own problems such as leaked variables from previous execution. Although IDLE tries to clear itself up sometimes there are things that still leaves various odd effects here and there especially with Tkinter itself. The real solution would be to give up IDLE and use python from cmd.exe From lie.1296 at gmail.com Tue Jun 2 18:48:50 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 03 Jun 2009 02:48:50 +1000 Subject: [Tutor] python workspace In-Reply-To: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> References: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> Message-ID: roberto wrote: > hello, > i'd like to ask if there is anything in python which helps to see what > variables have been defined and their type and their dimension etc; > > if any of you has ever used Matlab, i mean something really similar to > its workspace, where all the user created variables are stored and > constantly updated > > thank you You can use pdb (python debugger) module; and if you're using IDLE the Debugger Window will keep track and show variables. Personally, I usually simply sprawl print here and there. From roberto03 at gmail.com Tue Jun 2 19:14:10 2009 From: roberto03 at gmail.com (roberto) Date: Tue, 2 Jun 2009 19:14:10 +0200 Subject: [Tutor] python workspace In-Reply-To: <49d6b3500906020907o4f71c7cbt2c0360de5c45f0e@mail.gmail.com> References: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> <49d6b3500906020907o4f71c7cbt2c0360de5c45f0e@mail.gmail.com> Message-ID: <4bcde3e10906021014s6f346b0dm6eb6236be0bf65ef@mail.gmail.com> On Tue, Jun 2, 2009 at 6:07 PM, G?khan SEVER wrote: > Hi, > > Have you tried Ipython? > > https://launchpad.net/ipython not yet > > And also there is and on-going work called pydee > (http://code.google.com/p/pydee/) which they plan to integrate Ipython into > a GUI very similar to the one in Matlab. great ! that is probably what i was looking for but it still runs on python 2.x, isn't it ? i do not hope so :) > > G?khan > > > On Tue, Jun 2, 2009 at 10:54 AM, roberto wrote: >> >> hello, >> i'd like to ask if there is anything in python which helps to see what >> variables have been defined and their type and their dimension etc; >> >> if any of you has ever used Matlab, i mean something really similar to >> its workspace, where all the user created variables are stored and >> constantly updated >> >> thank you >> -- >> roberto >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > -- roberto From emile at fenx.com Tue Jun 2 19:47:38 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 02 Jun 2009 10:47:38 -0700 Subject: [Tutor] python workspace In-Reply-To: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> References: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> Message-ID: On 6/2/2009 8:54 AM roberto said... > hello, > i'd like to ask if there is anything in python which helps to see what > variables have been defined and their type and their dimension etc; In appropriate contexts, you may be able to use a variant of: from pprint import pprint pprint (locals()) HTH, Emile > > if any of you has ever used Matlab, i mean something really similar to > its workspace, where all the user created variables are stored and > constantly updated > > thank you From jyotsna.guleria at gmail.com Tue Jun 2 19:42:51 2009 From: jyotsna.guleria at gmail.com (jyotsna guleria) Date: Tue, 2 Jun 2009 12:42:51 -0500 Subject: [Tutor] How o convert spaces into tabs?? Message-ID: <7c04b9780906021042u162d76c4v664ec3bd8d1e4c2e@mail.gmail.com> Hello every one, I am trying to parse a file: I want to convert all the spaces in between the characters to single tab. e.g: my file has contents like: 1G5 79011 1 0 2 0 0 0 0 0 0 0 5Ht-2 60459 1 1 0 0 0 0 0 0 0 0 I want them to be separated by a single tab not with spaces.. It should look like: 1G5 79011 1 0 2 0 0 0 0 0 0 0 5Ht-2 60459 1 1 0 0 0 0 0 0 0 0 each separated by Tab... It is a text file containing such a data .. Thanks -- Jyotsna Guleria -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Jun 2 20:22:15 2009 From: srilyk at gmail.com (W W) Date: Tue, 2 Jun 2009 13:22:15 -0500 Subject: [Tutor] How o convert spaces into tabs?? In-Reply-To: <7c04b9780906021042u162d76c4v664ec3bd8d1e4c2e@mail.gmail.com> References: <7c04b9780906021042u162d76c4v664ec3bd8d1e4c2e@mail.gmail.com> Message-ID: <333efb450906021122m125c9a3at8ab03689c7508249@mail.gmail.com> On Tue, Jun 2, 2009 at 12:42 PM, jyotsna guleria wrote: > > Hello every one, > > I am trying to parse a file: > > I want to convert all the spaces in between the characters to single tab. > > e.g: my file has contents like: > > 1G5 79011 1 0 2 0 0 0 > 0 0 0 0 > 5Ht-2 60459 1 1 0 0 0 0 > 0 0 0 0 > > > I want them to be separated by a single tab not with spaces.. > > It should look like: > > 1G5 79011 1 0 2 0 0 0 0 0 0 0 > 5Ht-2 60459 1 1 0 0 0 0 0 0 0 0 > > each separated by Tab... > > It is a text file containing such a data .. > Easiest way I know of goes something like this: for line in myfile: newline = '\t'.join(line.split()) Consider: In [16]: x = 'the quick brown fox ate some spam and eggs' In [17]: x.split() Out[17]: ['the', 'quick', 'brown', 'fox', 'ate', 'some', 'spam', 'and', 'eggs'] In [18]: '\t'.join(x.split()) Out[18]: 'the\tquick\tbrown\tfox\tate\tsome\tspam\tand\teggs' In [19]: print '\t'.join(x.split()) the quick brown fox ate some spam and eggs HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Jun 2 20:30:29 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 02 Jun 2009 14:30:29 -0400 Subject: [Tutor] python workspace In-Reply-To: References: Message-ID: <4A256FC5.60601@ieee.org> roberto wrote: > On Tue, Jun 2, 2009 at 10:54 AM, roberto wrote: > >> >> >> >> hello, >> >> i'd like to ask if there is anything in python which helps to see what >> >> variables have been defined and their type and their dimension etc; >> >> >> >> if any of you has ever used Matlab, i mean something really similar to >> >> its workspace, where all the user created variables are stored and >> >> constantly updated >> >> >> >> thank you >> >> -- >> >> roberto > You could use the commercial Komodo IDE. It's got a debugger that runs the Python code as a separate process, so it can be used for GUI debugging as well as console work. I use it with wxPython, and Python 2.6.2 http://www.activestate.com/komodo/ From vinces1979 at gmail.com Tue Jun 2 20:34:27 2009 From: vinces1979 at gmail.com (vince spicer) Date: Tue, 2 Jun 2009 12:34:27 -0600 Subject: [Tutor] How o convert spaces into tabs?? In-Reply-To: <7c04b9780906021042u162d76c4v664ec3bd8d1e4c2e@mail.gmail.com> References: <7c04b9780906021042u162d76c4v664ec3bd8d1e4c2e@mail.gmail.com> Message-ID: <1e53c510906021134wc2a33d1pd7d89576965afb55@mail.gmail.com> regex will do it import re line = re.sub(r"\s+", "\t", line) print line Vince On Tue, Jun 2, 2009 at 11:42 AM, jyotsna guleria wrote: > > Hello every one, > > I am trying to parse a file: > > I want to convert all the spaces in between the characters to single tab. > > e.g: my file has contents like: > > 1G5 79011 1 0 2 0 0 0 > 0 0 0 0 > 5Ht-2 60459 1 1 0 0 0 0 > 0 0 0 0 > > > I want them to be separated by a single tab not with spaces.. > > It should look like: > > 1G5 79011 1 0 2 0 0 0 0 0 0 0 > 5Ht-2 60459 1 1 0 0 0 0 0 0 0 0 > > each separated by Tab... > > It is a text file containing such a data .. > > > Thanks > -- > Jyotsna Guleria > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gokhansever at gmail.com Tue Jun 2 20:34:32 2009 From: gokhansever at gmail.com (=?UTF-8?Q?G=C3=B6khan_SEVER?=) Date: Tue, 2 Jun 2009 13:34:32 -0500 Subject: [Tutor] python workspace In-Reply-To: References: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> Message-ID: <49d6b3500906021134qfce3f2fq9b06972dd7d73490@mail.gmail.com> In Ipython If you just type local() you get a pretty printed out without a need for an explicit pprint call. Secondly, Ipython works only for 2.4-5-6 as of now. Here what the documentation says: "We have not begun to test IPython on Python 2.6 or 3.0, but we expect it will work with some minor changes." G?khan On Tue, Jun 2, 2009 at 12:47 PM, Emile van Sebille wrote: > On 6/2/2009 8:54 AM roberto said... > >> hello, >> i'd like to ask if there is anything in python which helps to see what >> variables have been defined and their type and their dimension etc; >> > > In appropriate contexts, you may be able to use a variant of: > > from pprint import pprint > pprint (locals()) > > HTH, > > Emile > > > >> if any of you has ever used Matlab, i mean something really similar to >> its workspace, where all the user created variables are stored and >> constantly updated >> >> thank you >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From shantanoo at gmail.com Tue Jun 2 20:15:47 2009 From: shantanoo at gmail.com (=?UTF-8?B?IiDgpLbgpILgpKTgpKjgpYIgKFNoYW50YW5vbyki?=) Date: Tue, 02 Jun 2009 23:45:47 +0530 Subject: [Tutor] How o convert spaces into tabs?? In-Reply-To: <7c04b9780906021042u162d76c4v664ec3bd8d1e4c2e@mail.gmail.com> References: <7c04b9780906021042u162d76c4v664ec3bd8d1e4c2e@mail.gmail.com> Message-ID: <4A256C53.9040703@gmail.com> jyotsna guleria wrote: > Hello every one, > > I am trying to parse a file: > > I want to convert all the spaces in between the characters to single tab. > > e.g: my file has contents like: > > 1G5 79011 1 0 2 0 0 > 0 0 0 0 0 > 5Ht-2 60459 1 1 0 0 0 > 0 0 0 0 0 > > > I want them to be separated by a single tab not with spaces.. > > It should look like: > > 1G5 79011 1 0 2 0 0 0 0 0 0 0 > 5Ht-2 60459 1 1 0 0 0 0 0 0 0 0 > > each separated by Tab... > > It is a text file containing such a data .. > You can try re module. More info at: http://docs.python.org/library/re.html http://www.regular-expressions.info/python.html -- From jyotsna.guleria at gmail.com Tue Jun 2 20:34:50 2009 From: jyotsna.guleria at gmail.com (jyotsna guleria) Date: Tue, 2 Jun 2009 13:34:50 -0500 Subject: [Tutor] How o convert spaces into tabs?? In-Reply-To: <333efb450906021122m125c9a3at8ab03689c7508249@mail.gmail.com> References: <7c04b9780906021042u162d76c4v664ec3bd8d1e4c2e@mail.gmail.com> <333efb450906021122m125c9a3at8ab03689c7508249@mail.gmail.com> Message-ID: <7c04b9780906021134q17709b81pfff8bd789c73fd1a@mail.gmail.com> Thank you very much..:) On Tue, Jun 2, 2009 at 1:22 PM, W W wrote: > On Tue, Jun 2, 2009 at 12:42 PM, jyotsna guleria < > jyotsna.guleria at gmail.com> wrote: > >> >> Hello every one, >> >> I am trying to parse a file: >> >> I want to convert all the spaces in between the characters to single tab. >> >> e.g: my file has contents like: >> >> 1G5 79011 1 0 2 0 0 0 >> 0 0 0 0 >> 5Ht-2 60459 1 1 0 0 0 0 >> 0 0 0 0 >> >> >> I want them to be separated by a single tab not with spaces.. >> >> It should look like: >> >> 1G5 79011 1 0 2 0 0 0 0 0 0 0 >> 5Ht-2 60459 1 1 0 0 0 0 0 0 0 0 >> >> each separated by Tab... >> >> It is a text file containing such a data .. >> > > Easiest way I know of goes something like this: > > for line in myfile: > newline = '\t'.join(line.split()) > > Consider: > > In [16]: x = 'the quick brown fox ate some spam and eggs' > > In [17]: x.split() > Out[17]: ['the', 'quick', 'brown', 'fox', 'ate', 'some', 'spam', 'and', > 'eggs'] > > In [18]: '\t'.join(x.split()) > Out[18]: 'the\tquick\tbrown\tfox\tate\tsome\tspam\tand\teggs' > > In [19]: print '\t'.join(x.split()) > the quick brown fox ate some spam and eggs > > > HTH, > Wayne > -- Jyotsna Guleria -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Jun 2 20:57:47 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 02 Jun 2009 11:57:47 -0700 Subject: [Tutor] python workspace In-Reply-To: <49d6b3500906021134qfce3f2fq9b06972dd7d73490@mail.gmail.com> References: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> <49d6b3500906021134qfce3f2fq9b06972dd7d73490@mail.gmail.com> Message-ID: On 6/2/2009 11:34 AM G?khan SEVER said... > In Ipython Good for IPYTHON -- I wasn't presuming that. Emile From mwalsh at mwalsh.org Tue Jun 2 21:53:36 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 02 Jun 2009 14:53:36 -0500 Subject: [Tutor] How o convert spaces into tabs?? In-Reply-To: <1e53c510906021134wc2a33d1pd7d89576965afb55@mail.gmail.com> References: <7c04b9780906021042u162d76c4v664ec3bd8d1e4c2e@mail.gmail.com> <1e53c510906021134wc2a33d1pd7d89576965afb55@mail.gmail.com> Message-ID: <4A258340.10709@mwalsh.org> vince spicer wrote: > > regex will do it > > > import re > > line = re.sub(r"\s+", "\t", line) > > print line The above replaces the newline, which reminds me that even seemingly trivial uses of 're' can become not-so-trivial in a hurry. In [1]: import re In [2]: line = '1 2 3 4 5\n' In [3]: re.sub('\s+', '\t', line) Out[3]: '1\t2\t3\t4\t5\t' Maybe this is closer to your intent, but I refuse to guarantee it ;) Better to stick with str methods whenever possible. In [4]: re.sub('[ ]+', '\t', line) Out[4]: '1\t2\t3\t4\t5\n' HTH, Marty From david at abbottdavid.com Tue Jun 2 22:07:17 2009 From: david at abbottdavid.com (David) Date: Tue, 02 Jun 2009 16:07:17 -0400 Subject: [Tutor] Spell checking source code? In-Reply-To: <83142.24910.qm@web86702.mail.ird.yahoo.com> References: <806934.5719.qm@web45603.mail.sp1.yahoo.com> <2117728667-1243901219-cardhu_decombobulator_blackberry.rim.net-493569101-@bxe1119.bisx.prod.on.blackberry> <83142.24910.qm@web86702.mail.ird.yahoo.com> Message-ID: <4A258675.9050108@abbottdavid.com> ALAN GAULD wrote: > But that will check the whole file. The OP only wanted to spell > check the comments. Unless I'm missing something? > "Allen Fowler" wrote > Are there any utilities to help "spell check" source code? (Docstrings, etc) > I came up with this; [sample file] #!/usr/bin/python def doc_test(): """Do notheing, but document it. No, really, it doesn't do anything. """ pass [test program] #!/usr/bin/python from doc_function_test import doc_test from enchant.checker import SpellChecker doc_string = doc_test.__doc__ doc_string = str(doc_string) chkr = SpellChecker("en_US") chkr.set_text(doc_string) for err in chkr: print "Error:", err.word [results] python spell_check_doc.py Error: notheing -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From srilyk at gmail.com Tue Jun 2 23:40:43 2009 From: srilyk at gmail.com (W W) Date: Tue, 2 Jun 2009 16:40:43 -0500 Subject: [Tutor] python workspace In-Reply-To: <4A256FC5.60601@ieee.org> References: <4A256FC5.60601@ieee.org> Message-ID: <333efb450906021440j43472538i5c555d5027ca7c26@mail.gmail.com> On Tue, Jun 2, 2009 at 1:30 PM, Dave Angel wrote: > roberto wrote: > > On Tue, Jun 2, 2009 at 10:54 AM, roberto wrote: >> >> >>> >> >>> >> hello, >>> >> i'd like to ask if there is anything in python which helps to see what >>> >> variables have been defined and their type and their dimension etc; >>> >> >>> >> if any of you has ever used Matlab, i mean something really similar to >>> >> its workspace, where all the user created variables are stored and >>> >> constantly updated >>> >> >>> >> thank you >>> >> -- >>> >> roberto >>> >> >> > You could use the commercial Komodo IDE. It's got a debugger that runs the > Python code as a separate process, so it can be used for GUI debugging as > well as console work. I use it with wxPython, and Python 2.6.2 > > http://www.activestate.com/komodo/ Wingware also has a commercial IDE, and most of the functionality is included in the free student/personal use version. They were also generous enough to donate I think it was 4 or 8 commercial licensees to our PyArkansas un-conference. I played around with it a bit and it seemed like quite a solid IDE. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From allen.fowler at yahoo.com Wed Jun 3 00:06:46 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Tue, 2 Jun 2009 15:06:46 -0700 (PDT) Subject: [Tutor] Suggested source code folder layout Message-ID: <616626.98865.qm@web45616.mail.sp1.yahoo.com> Hello, I'm looking for some suggestions as to the filesystem source code layout for a new project. Here is what I am thinking so far: root_folder/ - app/ -- Code for our pylons/django/TG/etc web app - web/ -- Public static web files (and wsgi / fastCGI connector files) - db/ -- SQlite DB - scripts/ -- Various custom programs that will also interact with the DB / app. (Some cron, some interactive.) However, I am still wondering about a couple of items: 1) Where to create the virtualpython installation that will be used by both the app and the scripts. 2) Where to put our in-house created python modules that will be imported by both the app and scripts. Thank you, :) From alan.gauld at btinternet.com Wed Jun 3 00:44:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Jun 2009 23:44:00 +0100 Subject: [Tutor] python workspace References: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> Message-ID: "roberto" wrote > i'd like to ask if there is anything in python which helps to see what > variables have been defined and their type and their dimension etc; Bear in mind that Python variables are simply names so they have no type or dimension information. That belongs to the objects to which they refer. > if any of you has ever used Matlab, i mean something really similar to > its workspace, where all the user created variables are stored and > constantly updated That having been said most debugger envioronments will show you the current variables in scope and their values. Certainly IDLE, Pythonwin and Eclipse/PyDev can all do that. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From gregor.lingl at aon.at Wed Jun 3 02:12:04 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 03 Jun 2009 02:12:04 +0200 Subject: [Tutor] serious problem with graphics module In-Reply-To: References: <4bcde3e10905241403t3356c053m31b5964365860f0f@mail.gmail.com> <4A1B1F78.9070603@aon.at> <4bcde3e10906020848m28827aefu5034f60b642c9b41@mail.gmail.com> Message-ID: <4A25BFD4.1050701@aon.at> Lie Ryan schrieb: > roberto wrote: > >> On Tue, May 26, 2009 at 12:45 AM, Gregor Lingl wrote: >> >>> I know one situation in which can happen what you describe: >>> ... >> ok, it works all right now >> >> the minor issue is that i could not create the shortcut with the -n >> flag as you pointed out, that's why i issued both commands: >> C:\Python30\pythonw.exe >> C:\Python30\Lib\idlelib\idle.pyw -n >> >> via the C: prompt >> >> and the graphic window finally worked correctly >> >> thank you again >> > > Be aware though that using IDLE without subprocess also has its own > problems such as leaked variables from previous execution. That's certainly true, and it was the reason for introducing Idle's feature to execute scripts in their own subprocesses with Python 2.3 Despite of this I like to use Idle when working interactively with the turtle module and also when developing small programs as it is much more comfortable than a cmd-shell window. But I reglularly run them (during development) from the 'normal' Idle (or from a cmd-shell) to assure that effects like those you mention below are not present. Does anyone have experience with using IPython with Tkinter? Regards, Gregor > Although IDLE > tries to clear itself up sometimes there are things that still leaves > various odd effects here and there especially with Tkinter itself. The > real solution would be to give up IDLE and use python from cmd.exe > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From srilyk at gmail.com Wed Jun 3 07:07:58 2009 From: srilyk at gmail.com (W W) Date: Wed, 3 Jun 2009 00:07:58 -0500 Subject: [Tutor] serious problem with graphics module In-Reply-To: <4A25BFD4.1050701@aon.at> References: <4bcde3e10905241403t3356c053m31b5964365860f0f@mail.gmail.com> <4A1B1F78.9070603@aon.at> <4bcde3e10906020848m28827aefu5034f60b642c9b41@mail.gmail.com> <4A25BFD4.1050701@aon.at> Message-ID: <333efb450906022207u46e7a05fw8a950be2bc227298@mail.gmail.com> On Tue, Jun 2, 2009 at 7:12 PM, Gregor Lingl wrote: > > Does anyone have experience with using IPython with Tkinter? Plenty, and it works wonderfully. I've never had any errors (that I know of) that weren't of my own making ;) My personal development environment consists of ipython for trying out snippets, vim for writing my main blocks of code, and bazaar for version control. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Wed Jun 3 09:50:38 2009 From: denis.spir at free.fr (spir) Date: Wed, 3 Jun 2009 09:50:38 +0200 Subject: [Tutor] python workspace -- vars() vs locals() In-Reply-To: References: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> Message-ID: <20090603095038.31eaba42@o> Le Tue, 02 Jun 2009 10:47:38 -0700, Emile van Sebille s'exprima ainsi: > On 6/2/2009 8:54 AM roberto said... > > hello, > > i'd like to ask if there is anything in python which helps to see what > > variables have been defined and their type and their dimension etc; > > In appropriate contexts, you may be able to use a variant of: > > from pprint import pprint > pprint (locals()) By the way, it take the opportunity to ask about the difference between vars() & locals(). Denis ------ la vita e estrany From prasadaraon50 at gmail.com Wed Jun 3 10:47:36 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Wed, 3 Jun 2009 14:17:36 +0530 Subject: [Tutor] Text.insert() Message-ID: <9e3fac840906030147j79cb67c6we51676e003d30e9e@mail.gmail.com> Hello >> I created a gui app.I am finding it impossible to >> use Text.insert().please some one give an example of using it. >Look in my tutorial at event driven programming and the Case >study. Both use the Text widget. >For more detailed info try this introduction: >http://www.linuxjournal.com/article/7357 >Or for more detailed info: >http://www.pythonware.com/library/tkinter/introduction/x7883->concepts.htm Thank you,I got it right.I am reading your tutor for the 3rd time. The web sights you pointed above are of good help. Thank you Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Jun 3 15:21:43 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 03 Jun 2009 06:21:43 -0700 Subject: [Tutor] python workspace -- vars() vs locals() In-Reply-To: <20090603095038.31eaba42@o> References: <4bcde3e10906020854w1d640364obc520c43fa9dab3b@mail.gmail.com> <20090603095038.31eaba42@o> Message-ID: On 6/3/2009 12:50 AM spir said... > Le Tue, 02 Jun 2009 10:47:38 -0700, > Emile van Sebille s'exprima ainsi: > >> On 6/2/2009 8:54 AM roberto said... >>> hello, >>> i'd like to ask if there is anything in python which helps to see what >>> variables have been defined and their type and their dimension etc; >> In appropriate contexts, you may be able to use a variant of: >> >> from pprint import pprint >> pprint (locals()) > > > By the way, it take the opportunity to ask about the difference between vars() & locals(). Well, start in the interpreter... -------------- >>> help (vars) Help on built-in function vars in module __builtin__: vars(...) vars([object]) -> dictionary Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__. >>> help (locals) Help on built-in function locals in module __builtin__: locals(...) locals() -> dictionary Update and return a dictionary containing the current scope's local variables. -------------- So, vars() is locals(), while vars(localvar) returns information about localvar. In practice, you might do: (taken from a zope project I did a few years back) --------------registrant.py-------------- """A Registrant type that has an editable schema""" __author__ = 'Aaron VanDerlip aaron at netcorps.org' __docformat__ = 'plaintext' import pdb;pdb.set_trace() from AccessControl import ClassSecurityInfo --------------snip balance-------------- Then when run: -------------- > c:\...\registrant.py(8)?() -> from AccessControl import ClassSecurityInfo (Pdb) import pprint (Pdb) pprint.pprint(vars()) {'__author__': 'Aaron VanDerlip aaron at netcorps.org', '__builtins__': , '__doc__': 'A Registrant type that has an editable schema', '__docformat__': 'plaintext', '__file__': 'C:\\...\\registrant.py', '__name__': '__main__', 'pdb': , 'pprint': } (Pdb) pprint.pprint(locals()) {'__author__': 'Aaron VanDerlip aaron at netcorps.org', '__builtins__': , '__doc__': 'A Registrant type that has an editable schema', '__docformat__': 'plaintext', '__file__': 'C:\\...\\registrant.py', '__name__': '__main__', 'pdb': , 'pprint': } -------------- So, vars() and local() are the same. Now a look at vars(pdb) -------------- (Pdb) pprint.pprint(vars(pdb)) {'Pdb': , 'Repr': , 'TESTCMD': 'import x; x.main()', '__all__': ['run', 'pm', 'Pdb', 'runeval', 'runctx', 'runcall', 'set_trace', 'post_mortem', 'help'], Emile > > Denis > ------ > la vita e estrany > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cheesman at titan.physx.u-szeged.hu Wed Jun 3 15:22:53 2009 From: cheesman at titan.physx.u-szeged.hu (Andy Cheesman) Date: Wed, 3 Jun 2009 15:22:53 +0200 (CEST) Subject: [Tutor] delphi, pascal and Python In-Reply-To: <48766.87.97.16.29.1243939651.squirrel@titan.physx.u-szeged.hu> References: <34895.160.114.38.31.1242827642.squirrel@titan.physx.u-szeged.hu> <40af687b0905201916p3d09e7c6je672f7c7fb07ee3@mail.gmail.com> <48766.87.97.16.29.1243939651.squirrel@titan.physx.u-szeged.hu> Message-ID: <42065.160.114.38.31.1244035373.squirrel@titan.physx.u-szeged.hu> By the way, the error was generated by following the tutorial and compiling in lazarus > After Much Looking and pointers from the author, There is this most > excellent post by the same author at > > http://wiki.lazarus.freepascal.org/Developing_Python_Modules_with_Pascal > > This nearly works but I have issue with the linking of the new module. The > error is > > Linking PyMinMod.so > /usr/bin/ld: Python: No such file: No such file or directory > > I've no clue what the issue is and I don't understand what should be going > on. I'm running 64bit ubuntu. I know this might be a bit off topic, but if > someone could point me in the right direction, I would be rather grateful > > Thanks > Andy > > > >> >> "Marc Tompkins" wrote >> >>>> Is there a Method for wrapping delphi and/or pascal code into python >>>> like >>>>> SWIG? >>>> http://membres.lycos.fr/marat/delphi/python.htm >>> >>> That's a package to let you embed Python in Delphi; the OP wants to go >>> the >>> other direction. >> >> So it is, I didn't read the OP question closely enough. >> >> On Windows you could create a DLL and use ctypes to access it, >> but thats not the same as creating an importable module as could >> be done with SWIG >> >> Alan G. >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From prasadaraon50 at gmail.com Wed Jun 3 17:10:02 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Wed, 3 Jun 2009 20:40:02 +0530 Subject: [Tutor] my first gui Message-ID: <9e3fac840906030810g277fab89o5bb344dcce8f74cc@mail.gmail.com> Hello. I made my first mager gui program.I need your openions suggestions and improvements. #! usr\\bin\\env python from Tkinter import * def myfiles (n='',m=''): import os mf=[os.path.join(x,i)for x,y,z in os.walk(n) for i in z if i.endswith(m)] return mf def fshow(): tclear() x=entry1.get() try: value1,value2=x.split(',') mf=myfiles(value1,value2) text.insert(END,('Total files in %s are %d \n'%(entry1.get(),len(mf)))+ mystring(mf)) except: mf=myfiles(x) text.insert(END,('Total files in %s are %d \n'%(entry1.get(),len(mf)))+ mystring(mf)) def atime(x): import time import os atime=time.strftime("%c",time.localtime(os.path.getatime(x))) return atime def mtime(x): import time import os mtime=time.strftime("%c",time.localtime(os.path.getmtime(x))) return mtime def ctime(x): import time import os ctime=time.strftime("%c",time.localtime(os.path.getctime(x))) return ctime def mystring(x): q='' for n,m in enumerate(x,start=1): o=str(n)+'.'+str(m) q+=(o+'\n') return q+'\n' def info(): tclear() import glob,os mf='' md='' mfl,mdl=[],[] mdd=glob.glob(entry1.get()+os.sep+'*') for x in mdd: if os.path.isfile(x)==True: mfl.append(x) else:mdl.append(x) mf+=mystring(mfl) md+=mystring(mdl) mf=("Total files in %s are %d \n\n"%(entry1.get(),len(mfl)))+mf md=('Total directories in %s are %d \n\n'%(entry1.get(),len(mdl)))+md mf+='\n\n' text.insert(END,mf+md) def destroy(): root.destroy() def eclear(): entry1.delete(0,END) entry2.delete(0,END) entry3.delete(0,END) entry4.delete(0,END) def tclear(): text.delete(1.0,END) def ashow(): x=entry1.get() try: n,m=x.split(',') value=atime(n) except:value=atime(x) entry2.insert(0,value) def mshow(): x=entry1.get() try: n,m=x.split(',') value=mtime(n) except:value=mtime(x) entry3.insert(0,value) def cshow(): x=entry1.get() try: n,m=x.split(',') value=ctime(n) except:value=ctime(x) entry4.insert(0,value) root = Tk() frame1=Frame(root,relief='sunken',border=1) frame1.pack(side='top',expand="true") frame2=Frame(root,relief='sunken',border=1) frame2.pack(side='top',expand="true") frame3=Frame(root,relief='sunken',border=1) frame3.pack(side='top',expand="true") frame4=Frame(root,relief='sunken',border=1,) frame4.pack(side='top',expand="true") frame5=Frame(root,relief='sunken',border=1) frame5.pack(side='top',expand="true") label5=Label(frame1,text="Enter file path to get information about the file \ or enter directory(or directory,fileextension) to get files init ",border=1) label5.pack(side='top',fill='both') b1=Button(frame2,text='quit',command=destroy,border=1) b1.pack(side='left',padx=5,pady=5) b2=Button(frame2,text='clear',command=eclear,border=1) b2.pack(side='left',padx=5,pady=5) b3=Button(frame2,text='accessed',command=ashow,border=1) b3.pack(side='left',padx=5,pady=5) b4=Button(frame2,text='modified',command=mshow,border=1) b4.pack(side='left',padx=5,pady=5) b5=Button(frame2,text='created',command=cshow,border=1) b5.pack(side='left',padx=5,pady=5) b5=Button(frame2,text='files',command=fshow,border=1) b5.pack(side='left',padx=5,pady=5) b6=Button(frame2,text='deltxt',command=tclear,border=1) b6.pack(side='left',padx=5,pady=5) b7=Button(frame2,text='files+dirs',command=info,border=1) b7.pack(side='left',padx=5,pady=5) label4=Label(frame3,text="Enter full path",border=1) label4.pack(side='left',fill='both') entry1=Entry(frame3,relief='sunken',border=1) entry1.pack(side='left',fill='both') lable1=Label(frame3,text='access time',border=1) lable1.pack(side='left',fill='both') entry2=Entry(frame3,relief='sunken',border=1) entry2.pack(side='left',fill='both') lable2=Label(frame3,text='modifide time',border=1) lable2.pack(side='left',fill='both') entry3=Entry(frame3,relief='sunken',border=1) entry3.pack(side='left',fill='both') lable3=Label(frame3,text='created time',border=1) lable3.pack(side='left',fill='both') entry4=Entry(frame3,relief='sunken',border=1) entry4.pack(side='left',fill='both') text=Text(frame4,relief='sunken',border=1,width=130,height=40,padx=5,pady=5) text.pack(side='top') text.xview(SCROLL,30,UNITS) text.yview(SCROLL,30,UNITS) root.title("info of file") root.mainloop() == Thank you Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jun 3 18:06:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 3 Jun 2009 17:06:28 +0100 Subject: [Tutor] my first gui References: <9e3fac840906030810g277fab89o5bb344dcce8f74cc@mail.gmail.com> Message-ID: "prasad rao" wrote > I made my first mager gui program.I need your openions suggestions and > improvements. OK, Here goes... > def myfiles (n='',m=''): > import os > mf=[os.path.join(x,i)for x,y,z in os.walk(n) for i in z if > i.endswith(m)] > return mf The parameters could use more descriptive names. It's not clear what n and m represent? > def fshow(): > tclear() > x=entry1.get() > > try: > value1,value2=x.split(',') > mf=myfiles(value1,value2) again, value1, value2 is not very descriptive of what the values represent. > text.insert(END,('Total files in %s are %d > \n'%(entry1.get(),len(mf)))+ mystring(mf)) > except: > mf=myfiles(x) > text.insert(END,('Total files in %s are %d > \n'%(entry1.get(),len(mf)))+ mystring(mf)) > > def atime(x): > > import time > import os > atime=time.strftime("%c",time.localtime(os.path.getatime(x))) > return atime You only need one time function. They are identical apart from the name so just use a single function. > def mystring(x): > q='' > for n,m in enumerate(x,start=1): > > o=str(n)+'.'+str(m) > q+=(o+'\n') > return q+'\n' > > def info(): > tclear() > import glob,os > mf='' > md='' > mfl,mdl=[],[] > mdd=glob.glob(entry1.get()+os.sep+'*') > for x in mdd: > if os.path.isfile(x)==True: > mfl.append(x) > else:mdl.append(x) > > mf+=mystring(mfl) > md+=mystring(mdl) > mf=("Total files in %s are %d \n\n"%(entry1.get(),len(mfl)))+mf You could use a bit more whitespace to clarify whats going on: mf="Total files in %s are %d \n\n" % (entry1.get(), len(mfl)) + mf > md=('Total directories in %s are %d > \n\n'%(entry1.get(),len(mdl)))+md > mf+='\n\n' > text.insert(END,mf+md) > def destroy(): > root.destroy() > def eclear(): > entry1.delete(0,END) > entry2.delete(0,END) > entry3.delete(0,END) > entry4.delete(0,END) > def tclear(): > text.delete(1.0,END) > def ashow(): > x=entry1.get() > try: > n,m=x.split(',') > > value=atime(n) > except:value=atime(x) > entry2.insert(0,value) The only real difference in these show funxctions is the enytry widget used at the end, so why not have a single function which takes an entry wisget as a parameter? Any time you find yourself writing nearly identical functions look to see if you could parameterise them. This is the DRY principle - Don't Repeat Yourself > root = Tk() > > frame1=Frame(root,relief='sunken',border=1) > frame1.pack(side='top',expand="true") > > frame2=Frame(root,relief='sunken',border=1) > frame2.pack(side='top',expand="true") > > frame3=Frame(root,relief='sunken',border=1) > frame3.pack(side='top',expand="true") > > frame4=Frame(root,relief='sunken',border=1,) > frame4.pack(side='top',expand="true") > > frame5=Frame(root,relief='sunken',border=1) > frame5.pack(side='top',expand="true") > > label5=Label(frame1,text="Enter file path to get information about the > file > \ > or enter directory(or directory,fileextension) to get files init > ",border=1) > label5.pack(side='top',fill='both') > > b1=Button(frame2,text='quit',command=destroy,border=1) > b1.pack(side='left',padx=5,pady=5) > > b2=Button(frame2,text='clear',command=eclear,border=1) > b2.pack(side='left',padx=5,pady=5) > > b3=Button(frame2,text='accessed',command=ashow,border=1) > b3.pack(side='left',padx=5,pady=5) Here you can asign your parameterised show function by using lambda: b3=Button(frame2,text='accessed',command=lambda : show(entry2) ,border=1) > b4=Button(frame2,text='modified',command=mshow,border=1) > b4.pack(side='left',padx=5,pady=5) > > b5=Button(frame2,text='created',command=cshow,border=1) > b5.pack(side='left',padx=5,pady=5) > > b5=Button(frame2,text='files',command=fshow,border=1) > b5.pack(side='left',padx=5,pady=5) > > b6=Button(frame2,text='deltxt',command=tclear,border=1) > b6.pack(side='left',padx=5,pady=5) > > b7=Button(frame2,text='files+dirs',command=info,border=1) > b7.pack(side='left',padx=5,pady=5) > > label4=Label(frame3,text="Enter full path",border=1) > label4.pack(side='left',fill='both') > > entry1=Entry(frame3,relief='sunken',border=1) > entry1.pack(side='left',fill='both') > > lable1=Label(frame3,text='access time',border=1) > lable1.pack(side='left',fill='both') > > entry2=Entry(frame3,relief='sunken',border=1) > entry2.pack(side='left',fill='both') > > lable2=Label(frame3,text='modifide time',border=1) > lable2.pack(side='left',fill='both') > > entry3=Entry(frame3,relief='sunken',border=1) > entry3.pack(side='left',fill='both') > > lable3=Label(frame3,text='created time',border=1) > lable3.pack(side='left',fill='both') > > entry4=Entry(frame3,relief='sunken',border=1) > entry4.pack(side='left',fill='both') > > text=Text(frame4,relief='sunken',border=1,width=130,height=40,padx=5,pady=5) > text.pack(side='top') > text.xview(SCROLL,30,UNITS) > text.yview(SCROLL,30,UNITS) > > root.title("info of file") > > root.mainloop() But well done for getting it all to work. You could look at using classes next time, that could tidy things up quite a bit. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lie.1296 at gmail.com Wed Jun 3 18:20:20 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 04 Jun 2009 02:20:20 +1000 Subject: [Tutor] my first gui In-Reply-To: <9e3fac840906030810g277fab89o5bb344dcce8f74cc@mail.gmail.com> References: <9e3fac840906030810g277fab89o5bb344dcce8f74cc@mail.gmail.com> Message-ID: prasad rao wrote: > Hello. > I made my first mager gui program.I need your openions suggestions and > improvements. > > > #! usr\\bin\\env python Why is the shebang like that? > from Tkinter import * importing * is considered namespace pollution since you cannot control what name would be introduced to the global namespace. Better to use the regular "import Tkinter" (Tips: typing Tkinter for every control is often distracting, I usually do "import Tkinter as Tk" to shorten it, much better than import *) > def myfiles (n='',m=''): > import os > mf=[os.path.join(x,i)for x,y,z in os.walk(n) for i in z if > i.endswith(m)] > > return mf > > def fshow(): > tclear() > x=entry1.get() > > try: > value1,value2=x.split(',') > mf=myfiles(value1,value2) > > text.insert(END,('Total files in %s are %d > \n'%(entry1.get(),len(mf)))+ mystring(mf)) > except: > mf=myfiles(x) > text.insert(END,('Total files in %s are %d > \n'%(entry1.get(),len(mf)))+ mystring(mf)) > def atime(x): > > import time > import os > atime=time.strftime("%c",time.localtime(os.path.getatime(x))) > return atime The way you're doing right now will import time and os every function call. Although python interpreter is smart enough to not reiimport a module twice, for various reasons it is usually better to place all imports on the top of the module. > def mtime(x): > > import time > import os > mtime=time.strftime("%c",time.localtime(os.path.getmtime(x))) > return mtime > > def ctime(x): > import time > import os > ctime=time.strftime("%c",time.localtime(os.path.getctime(x))) > return ctime > def mystring(x): > q='' > for n,m in enumerate(x,start=1): > > o=str(n)+'.'+str(m) you could use %=formatting there o = '%s.%s' % (n, m) > q+=(o+'\n') > return q+'\n' > > def info(): > tclear() > import glob,os > mf='' > md='' > mfl,mdl=[],[] > mdd=glob.glob(entry1.get()+os.sep+'*') > for x in mdd: > if os.path.isfile(x)==True: in python, you usually don't test against True in an if statement (though it won't really matter) if os.path.isfile(x): pass > mfl.append(x) I assume this line should appear more indented, probably the mail client is playing some tricks... > else:mdl.append(x) > > mf+=mystring(mfl) > md+=mystring(mdl) > mf=("Total files in %s are %d \n\n"%(entry1.get(),len(mfl)))+mf > md=('Total directories in %s are %d > \n\n'%(entry1.get(),len(mdl)))+md > mf+='\n\n' > text.insert(END,mf+md) What's wrong with the indentation? Is this the mail client messing things up or you should use consistent indentation. PEP 8 (http://www.python.org/dev/peps/pep-0008/ ) recommends 4 spaces. Now we're talking about PEP 8; I should also mention that the recommended way to style your code is like this: def func(a, b, c=2, d=3): e = a + b r = calling(a, s='John') you can read the details in the PEP 8 link. Basically space after commas, and space on both side of operators; whitespace on assignment = except on function argument assignment. > def destroy(): > root.destroy() > def eclear(): > entry1.delete(0,END) > entry2.delete(0,END) > entry3.delete(0,END) > entry4.delete(0,END) > def tclear(): > text.delete(1.0,END) > def ashow(): > x=entry1.get() > try: > n,m=x.split(',') > > value=atime(n) > except:value=atime(x) don't use bare except; catch only the specific exception you want to catch. > entry2.insert(0,value) > def mshow(): > > x=entry1.get() > try: > n,m=x.split(',') > > value=mtime(n) > except:value=mtime(x) > > entry3.insert(0,value) > def cshow(): > > x=entry1.get() > try: > n,m=x.split(',') > > value=ctime(n) > except:value=ctime(x) > entry4.insert(0,value) You could use an if __name__ == '__main__': here > root = Tk() > > frame1=Frame(root,relief='sunken',border=1) > frame1..pack(side='top',expand="true") > > frame2=Frame(root,relief='sunken',border=1) > frame2.pack(side='top',expand="true") > > frame3=Frame(root,relief='sunken',border=1) > frame3.pack(side='top',expand="true") > > frame4=Frame(root,relief='sunken',border=1,) > frame4.pack(side='top',expand="true") > > frame5=Frame(root,relief='sunken',border=1) > frame5.pack(side='top',expand="true") > > label5=Label(frame1,text="Enter file path to get information about the > file \ > or enter directory(or directory,fileextension) to get files init ",border=1) > label5.pack(side='top',fill='both') > > b1=Button(frame2,text='quit',command=destroy,border=1) > b1.pack(side='left',padx=5,pady=5) > > b2=Button(frame2,text='clear',command=eclear,border=1) > b2.pack(side='left',padx=5,pady=5) > > b3=Button(frame2,text='accessed',command=ashow,border=1) > b3.pack(side='left',padx=5,pady=5) > > b4=Button(frame2,text='modified',command=mshow,border=1) > b4.pack(side='left',padx=5,pady=5) > > b5=Button(frame2,text='created',command=cshow,border=1) > b5.pack(side='left',padx=5,pady=5) > > b5=Button(frame2,text='files',command=fshow,border=1) > b5.pack(side='left',padx=5,pady=5) > > b6=Button(frame2,text='deltxt',command=tclear,border=1) > b6.pack(side='left',padx=5,pady=5) > > b7=Button(frame2,text='files+dirs',command=info,border=1) > b7.pack(side='left',padx=5,pady=5) > > label4=Label(frame3,text="Enter full path",border=1) > label4.pack(side='left',fill='both') > > entry1=Entry(frame3,relief='sunken',border=1) > entry1.pack(side='left',fill='both') > > lable1=Label(frame3,text='access time',border=1) > lable1..pack(side='left',fill='both') > > entry2=Entry(frame3,relief='sunken',border=1) > entry2.pack(side='left',fill='both') > > lable2=Label(frame3,text='modifide time',border=1) > lable2.pack(side='left',fill='both') > > entry3=Entry(frame3,relief='sunken',border=1) > entry3.pack(side='left',fill='both') > > lable3=Label(frame3,text='created time',border=1) > lable3.pack(side='left',fill='both') > > entry4=Entry(frame3,relief='sunken',border=1) > entry4.pack(side='left',fill='both') Instead of names like entry1, entry2, entry3, and entry4 you should use a more descriptive name like path, accesstime, modtime, createdtime. I usually use a plain name (e.g. path) for the most significant GUI element and a plain name++ (e.g. path_label) for GUI element that describes the main elements. > text=Text(frame4,relief='sunken',border=1,width=130,height=40,padx=5,pady=5) > text.pack(side='top') > text.xview(SCROLL,30,UNITS) > text.yview(SCROLL,30,UNITS) > > root.title("info of file") > > root.mainloop() > > == > > Thank you > > Prasad > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From david at abbottdavid.com Wed Jun 3 19:55:59 2009 From: david at abbottdavid.com (David) Date: Wed, 03 Jun 2009 13:55:59 -0400 Subject: [Tutor] my first gui] Message-ID: <4A26B92F.8030304@abbottdavid.com> -- powered by Gentoo/GNU Linux http://linuxcrazy.com -------------- next part -------------- An embedded message was scrubbed... From: David Subject: Re: [Tutor] my first gui Date: Wed, 03 Jun 2009 12:48:29 -0400 Size: 1219 URL: From david at abbottdavid.com Wed Jun 3 20:09:17 2009 From: david at abbottdavid.com (David) Date: Wed, 03 Jun 2009 14:09:17 -0400 Subject: [Tutor] my first gui] In-Reply-To: <4A26B92F.8030304@abbottdavid.com> References: <4A26B92F.8030304@abbottdavid.com> Message-ID: <4A26BC4D.1000603@abbottdavid.com> David wrote: > > prasad rao wrote: > >> Hello. >> I made my first mager gui program.I need your openions suggestions and >> improvements. >> >> > Hi Prasad, > I get this error, I am using 2.5 on Linux; > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1403, in __call__ > return self.func(*args) > File "prasad_gui.py", line 20, in fshow > text.insert(END,('Total files in %s are %d > \n'%(entry1.get(),len(mf)))+ mystring(mf)) > File "prasad_gui.py", line 36, in mystring > for n,m in enumerate(x,start=1): > TypeError: 'start' is an invalid keyword argument for this function > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Ok this works, def mystring(x): q='' for n,m in enumerate(x): n + 1 o=str(n)+'.'+str(m) q+=(o+'\n') return q+'\n' I took the liberty of editing the format; #! usr\bin\python from Tkinter import * import os import time import glob def myfiles (n='',m=''): mf=[os.path.join(x,i)for x,y,z in os.walk(n) for i in z if i.endswith(m)] return mf def fshow(): tclear() x=entry1.get() try: value1,value2=x.split(',') mf=myfiles(value1,value2) text.insert(END,('Total files in %s are %d \n'%(entry1.get(),len(mf)))+ mystring(mf)) except: mf=myfiles(x) text.insert(END,('Total files in %s are %d \n'%(entry1.get(),len(mf)))+ mystring(mf)) def atime(x): atime=time.strftime("%c",time.localtime(os.path.getatime(x))) return atime def mtime(x): mtime=time.strftime("%c",time.localtime(os.path.getmtime(x))) return mtime def ctime(x): ctime=time.strftime("%c",time.localtime(os.path.getctime(x))) return ctime def mystring(x): q='' for n,m in enumerate(x): n + 1 o=str(n)+'.'+str(m) q+=(o+'\n') return q+'\n' def info(): tclear() import glob,os mf='' md='' mfl,mdl=[],[] mdd=glob.glob(entry1.get()+os.sep+'*') for x in mdd: if os.path.isfile(x)==True: mfl.append(x) else:mdl.append(x) mf+=mystring(mfl) md+=mystring(mdl) mf=("Total files in %s are %d \n\n"%(entry1.get(),len(mfl)))+mf md=('Total directories in %s are %d \n\n'%(entry1.get(),len(mdl)))+md mf+='\n\n' text.insert(END,mf+md) def destroy(): root.destroy() def eclear(): entry1.delete(0,END) entry2.delete(0,END) entry3.delete(0,END) entry4.delete(0,END) def tclear(): text.delete(1.0,END) def ashow(): x=entry1.get() try: n,m=x.split(',') value=atime(n) except: value=atime(x) entry2.insert(0,value) def mshow(): x=entry1.get() try: n,m=x.split(',') value=mtime(n) except: value=mtime(x) entry3.insert(0,value) def cshow(): x=entry1.get() try: n,m=x.split(',') value=ctime(n) except: value=ctime(x) entry4.insert(0,value) root = Tk() frame1=Frame(root,relief='sunken',border=1) frame1.pack(side='top',expand="true") frame2=Frame(root,relief='sunken',border=1) frame2.pack(side='top',expand="true") frame3=Frame(root,relief='sunken',border=1) frame3.pack(side='top',expand="true") frame4=Frame(root,relief='sunken',border=1,) frame4.pack(side='top',expand="true") frame5=Frame(root,relief='sunken',border=1) frame5.pack(side='top',expand="true") label5=Label(frame1,text="Enter file path to get information about the file \ or enter directory(or directory,fileextension) to get files init ",border=1) label5.pack(side='top',fill='both') b1=Button(frame2,text='quit',command=destroy,border=1) b1.pack(side='left',padx=5,pady=5) b2=Button(frame2,text='clear',command=eclear,border=1) b2.pack(side='left',padx=5,pady=5) b3=Button(frame2,text='accessed',command=ashow,border=1) b3.pack(side='left',padx=5,pady=5) b4=Button(frame2,text='modified',command=mshow,border=1) b4.pack(side='left',padx=5,pady=5) b5=Button(frame2,text='created',command=cshow,border=1) b5.pack(side='left',padx=5,pady=5) b5=Button(frame2,text='files',command=fshow,border=1) b5.pack(side='left',padx=5,pady=5) b6=Button(frame2,text='deltxt',command=tclear,border=1) b6.pack(side='left',padx=5,pady=5) b7=Button(frame2,text='files+dirs',command=info,border=1) b7.pack(side='left',padx=5,pady=5) label4=Label(frame3,text="Enter full path",border=1) label4.pack(side='left',fill='both') entry1=Entry(frame3,relief='sunken',border=1) entry1.pack(side='left',fill='both') lable1=Label(frame3,text='access time',border=1) lable1.pack(side='left',fill='both') entry2=Entry(frame3,relief='sunken',border=1) entry2.pack(side='left',fill='both') lable2=Label(frame3,text='modifide time',border=1) lable2.pack(side='left',fill='both') entry3=Entry(frame3,relief='sunken',border=1) entry3.pack(side='left',fill='both') lable3=Label(frame3,text='created time',border=1) lable3.pack(side='left',fill='both') entry4=Entry(frame3,relief='sunken',border=1) entry4.pack(side='left',fill='both') text=Text(frame4,relief='sunken',border=1,width=130,height=40,padx=5,pady=5) text.pack(side='top') text.xview(SCROLL,30,UNITS) text.yview(SCROLL,30,UNITS) root.title("info of file") root.mainloop() -- powered by Gentoo/GNU Linux http://linuxcrazy.com From srilyk at gmail.com Wed Jun 3 23:51:41 2009 From: srilyk at gmail.com (W W) Date: Wed, 3 Jun 2009 16:51:41 -0500 Subject: [Tutor] serious problem with graphics module In-Reply-To: <4A26E13D.3070600@aon.at> References: <4bcde3e10905241403t3356c053m31b5964365860f0f@mail.gmail.com> <4A1B1F78.9070603@aon.at> <4bcde3e10906020848m28827aefu5034f60b642c9b41@mail.gmail.com> <4A25BFD4.1050701@aon.at> <333efb450906022207u46e7a05fw8a950be2bc227298@mail.gmail.com> <4A26E13D.3070600@aon.at> Message-ID: <333efb450906031451l3b74549by5c9900935aee0ace@mail.gmail.com> Forwarding on to the list... ---------- Forwarded message ---------- From: Gregor Lingl Date: Wed, Jun 3, 2009 at 3:46 PM Subject: Re: [Tutor] serious problem with graphics module To: W W W W schrieb: > On Tue, Jun 2, 2009 at 7:12 PM, Gregor Lingl gregor.lingl at aon.at>> wrote: > > > Does anyone have experience with using IPython with Tkinter? > > > Plenty, and it works wonderfully. I've never had any errors (that I know > of) that weren't of my own making ;) > Do you (or sombody else) know how to get ipython working with Python 2.6 (you know, the Python release, which has that new turtle module ;-) ) doesn't install on my Windows box... other than that I've got no experience with it -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jun 4 02:20:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Jun 2009 01:20:04 +0100 Subject: [Tutor] serious problem with graphics module References: <4bcde3e10905241403t3356c053m31b5964365860f0f@mail.gmail.com> <4A1B1F78.9070603@aon.at><4bcde3e10906020848m28827aefu5034f60b642c9b41@mail.gmail.com> <4A25BFD4.1050701@aon.at><333efb450906022207u46e7a05fw8a950be2bc227298@mail.gmail.com> <4A26E13D.3070600@aon.at> <333efb450906031451l3b74549by5c9900935aee0ace@mail.gmail.com> Message-ID: "W W" wrote > Do you (or sombody else) know how to get ipython working with Python 2.6 > (you know, the Python release, which has that new turtle module ;-) ) > > doesn't install on my Windows box... other than that I've got no > experience > with it I thought the new turtle module could be made to work on 2.5 as well as 2.6? And IPython plays with 2.5 OK. So if its only the turtle module thats needed it should work? Or am I mistaken in the 2.5 turtle compatibility? Alan G. From ntb1088 at gmail.com Thu Jun 4 02:48:11 2009 From: ntb1088 at gmail.com (NTB) Date: Wed, 3 Jun 2009 17:48:11 -0700 Subject: [Tutor] array manipulations Message-ID: <33335eec0906031748m7f7c35e4yeafe81a4ca36cc9@mail.gmail.com> Hello, I'm an R user, who just started with numpy. I'm planning on setting up a large nutrient database. Here's my question: I'm trying to reshape? or manipulate? the following array: array [['Food 1', 'Nutrient 1', 0.9], ['Food 1', 'Nutrient 2', 0.2], ['Food 2', 'Nutrient 1', 0.55], ['Food 2', 'Nutrient 2', 0.11]] into a new array that looks like this: array [['Food 1', 0.9, 0.2], ['Food 2', 0.55, 0.11]] or more simply: array [[0.9, 0.2], [0.55, 0.11]] In other words, the data and shape that I need in the first array is the 3rd column, where the row names are the 1st column and the column names are the 2nd column. I am thinking that I need to use .flat(), maybe with some kind of list comprehension? I really don't know, and would really appreciate some help. Thanks! -NT -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Jun 4 06:35:54 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 04 Jun 2009 14:35:54 +1000 Subject: [Tutor] array manipulations In-Reply-To: <33335eec0906031748m7f7c35e4yeafe81a4ca36cc9@mail.gmail.com> References: <33335eec0906031748m7f7c35e4yeafe81a4ca36cc9@mail.gmail.com> Message-ID: NTB wrote: > Hello, > I'm an R user, who just started with numpy. I'm planning on setting up > a large nutrient database. Here's my question: > > I'm trying to reshape? or manipulate? the following array: > > array [['Food 1', 'Nutrient 1', 0.9], > ['Food 1', 'Nutrient 2', 0.2], > ['Food 2', 'Nutrient 1', 0.55], > ['Food 2', 'Nutrient 2', 0.11]] > > into a new array that looks like this: > > array [['Food 1', 0.9, 0.2], > ['Food 2', 0.55, 0.11]] > > or more simply: > > array [[0.9, 0.2], > [0.55, 0.11]] > > In other words, the data and shape that I need in the first array is the > 3rd column, where the row names are the 1st column and the column names > are the 2nd column. > > I am thinking that I need to use .flat(), maybe with some kind of list > comprehension? I really don't know, and would really appreciate some help. > Use itertools.groupby() from the itertools module >>> arr = [['Food 1', 'Nutrient 1', 0.9], ... ['Food 1', 'Nutrient 2', 0.2], ... ['Food 2', 'Nutrient 1', 0.55], ... ['Food 2', 'Nutrient 2', 0.11], ... ] >>> grouped = itertools.groupby(arr, lambda x: x[0]) >>> for name, food in grouped: ... print name ... print [nutrient[2] for nutrient in food] ... Food 1 [0.90000000000000002, 0.20000000000000001] Food 2 [0.55000000000000004, 0.11] you may need to sort the array first since groupby only group adjacent enties. The sorted() and list.sort() function accept a key= argument that would be a function/lambda that generates the key to sort with sorted(arr, key=labmda x: x[0]) or arr.sort(key=lambda x: x[0]) From prasadaraon50 at gmail.com Thu Jun 4 06:48:25 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Thu, 4 Jun 2009 10:18:25 +0530 Subject: [Tutor] my first gui Message-ID: <9e3fac840906032148n6a3f7fefq6acb5d5634619ac5@mail.gmail.com> Hello Thanks I will implement your suggestions. True .Names and parameters are not descriptive. There are no comments(docstrings) in the program . There is scope to reduce number of functions. Thank you Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From dextrous85 at gmail.com Thu Jun 4 09:23:09 2009 From: dextrous85 at gmail.com (vishwajeet singh) Date: Thu, 4 Jun 2009 12:53:09 +0530 Subject: [Tutor] Generating Hetmaps Message-ID: <5487b3060906040023o1c7f1a03u6f8093e9052920e8@mail.gmail.com> Hi, I have a small query is there any standard module available for generating heatmap from given set of data. -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jun 4 10:22:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Jun 2009 09:22:51 +0100 Subject: [Tutor] array manipulations References: <33335eec0906031748m7f7c35e4yeafe81a4ca36cc9@mail.gmail.com> Message-ID: "NTB" wrote > array [['Food 1', 'Nutrient 1', 0.9], > ['Food 1', 'Nutrient 2', 0.2], > ['Food 2', 'Nutrient 1', 0.55], > ['Food 2', 'Nutrient 2', 0.11]] > > into a new array that looks like this: > > array [['Food 1', 0.9, 0.2], > ['Food 2', 0.55, 0.11]] > I'd probably use an intermediate dictionary: >>> a = [['F1','ggh',0.9],['F1','gh',0.5],['f2','dsd',0.7]] >>> d = {} >>> for r in a: ... if r[0] in d: d[r[0]].append(r[2]) ... else: d[r[0]] = [r[0],r[2]] ... >>> new = [v for k,v in d.items()] >>> new [['F1', 0.9, 0.5], ['f2', 0.6999]] >>> There may be a more elegant way to handle the if/else but its too early to think of one :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From norman at khine.net Thu Jun 4 15:29:16 2009 From: norman at khine.net (Norman Khine) Date: Thu, 4 Jun 2009 15:29:16 +0200 Subject: [Tutor] advise on this loop Message-ID: <9c2c8ffb0906040629r6ef372did4ecfec6c3442540@mail.gmail.com> Hello, I have the following code, which searches through a directory structure such as: $ tree -L 2 companies companies |-- aberdeen-airport-ltd | |-- aberdeen-airport-dyce-grampian | `-- aberdeen-airport-dyce-grampian.metadata |-- aberdeen-airport-ltd.metadata |-- aberdeen-motor-company-ltd | |-- mugiemoss-road-grampian | `-- mugiemoss-road-grampian.metadata the code can be seen at: http://paste.lisp.org/display/81348 I basically have a form, where the user makes a search for 'Company' name, than the code searches for all the items that do not contain 'hotel' in the metadata This works for the first level, i.e. when searching in the companies directory. Now I want to extend this to search for the '/companies/company/ but to only search the addresses that are in the found = [] list from the previous search. Thanks Norman From dineshbvadhia at hotmail.com Thu Jun 4 15:47:50 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 4 Jun 2009 06:47:50 -0700 Subject: [Tutor] unicode, utf-8 problem again Message-ID: Hi! I'm processing a large number of xml files that are all declared as utf-8 encoded in the header ie. My Python environment has been set for 'utf-8' through site.py. Additionally, the top of each program/module has the declaration: # -*- coding: utf-8 -*- But, I still get this error: Traceback (most recent call last): ... UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 76: ordinal not in range(128) What am I missing? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Thu Jun 4 15:48:12 2009 From: srilyk at gmail.com (W W) Date: Thu, 4 Jun 2009 08:48:12 -0500 Subject: [Tutor] advise on this loop In-Reply-To: <9c2c8ffb0906040629r6ef372did4ecfec6c3442540@mail.gmail.com> References: <9c2c8ffb0906040629r6ef372did4ecfec6c3442540@mail.gmail.com> Message-ID: <333efb450906040648t16affcb2v25d67698f45300ed@mail.gmail.com> On Thu, Jun 4, 2009 at 8:29 AM, Norman Khine wrote: > Hello, > I have the following code, which searches through a directory structure > such as: > > $ tree -L 2 companies > companies > |-- aberdeen-airport-ltd > | |-- aberdeen-airport-dyce-grampian > | `-- aberdeen-airport-dyce-grampian.metadata > |-- aberdeen-airport-ltd.metadata > |-- aberdeen-motor-company-ltd > | |-- mugiemoss-road-grampian > | `-- mugiemoss-road-grampian.metadata > > > the code can be seen at: > > http://paste.lisp.org/display/81348 > > I basically have a form, where the user makes a search for 'Company' > name, than the code searches for all the items that do not contain > 'hotel' in the metadata > > This works for the first level, i.e. when searching in the companies > directory. > > Now I want to extend this to search for the '/companies/company/ but > to only search the addresses that are in the found = [] list from the > previous search. I haven't looked at your code, but I presume your "search" is a function? I certainly hope so anyway! Also I presume you return the found list? If so, it should be trivial. If not, you should probably adjust your code to do such things. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Thu Jun 4 15:55:06 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 4 Jun 2009 06:55:06 -0700 Subject: [Tutor] Fw: unicode, utf-8 problem again Message-ID: I forgot to add that I'm using elementtree to process the xml files and don't (usually) have any problems with that. Plus, the workaround that works is to encode each elementtree output ie.: thisxmlline = thisxmlline.encode('utf8') But, this seems odd to me as isn't it already being processed as utf-8? Dinesh From: Dinesh B Vadhia Sent: Thursday, June 04, 2009 6:47 AM To: tutor at python.org Subject: unicode, utf-8 problem again Hi! I'm processing a large number of xml files that are all declared as utf-8 encoded in the header ie. My Python environment has been set for 'utf-8' through site.py. Additionally, the top of each program/module has the declaration: # -*- coding: utf-8 -*- But, I still get this error: Traceback (most recent call last): ... UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 76: ordinal not in range(128) What am I missing? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Jun 4 16:05:03 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 04 Jun 2009 16:05:03 +0200 Subject: [Tutor] unicode, utf-8 problem again In-Reply-To: References: Message-ID: <4A27D48F.2030700@compuscan.co.za> Dinesh B Vadhia wrote: > Hi! I'm processing a large number of xml files that are all declared > as utf-8 encoded in the header ie. > > > > My Python environment has been set for 'utf-8' through site.py. > Additionally, the top of each program/module has the declaration: > > # -*- coding: utf-8 -*- > > But, I still get this error: > > Traceback (most recent call last): > ... > UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in > position 76: ordinal not in range(128) > > What am I missing? > > Dinesh > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi, Take a read through http://evanjones.ca/python-utf8.html which will give you insight as to how you should be reading and processing your files. As for the encoding line "# -*- coding: utf-8 -*-", that is actually to declare the character encoding of your script and not of potential data it will be working with. -- Kind Regards, Christian Witts From norman at khine.net Thu Jun 4 17:59:22 2009 From: norman at khine.net (Norman Khine) Date: Thu, 4 Jun 2009 17:59:22 +0200 Subject: [Tutor] advise on this loop In-Reply-To: <333efb450906040648t16affcb2v25d67698f45300ed@mail.gmail.com> References: <9c2c8ffb0906040629r6ef372did4ecfec6c3442540@mail.gmail.com> <333efb450906040648t16affcb2v25d67698f45300ed@mail.gmail.com> Message-ID: <9c2c8ffb0906040859q182cb1cdw3de9697102876a6@mail.gmail.com> On Thu, Jun 4, 2009 at 3:48 PM, W W wrote: > On Thu, Jun 4, 2009 at 8:29 AM, Norman Khine wrote: >> >> Hello, >> I have the following code, which searches through a directory structure >> such as: >> >> $ tree -L 2 companies >> companies >> |-- aberdeen-airport-ltd >> | ? |-- aberdeen-airport-dyce-grampian >> | ? `-- aberdeen-airport-dyce-grampian.metadata >> |-- aberdeen-airport-ltd.metadata >> |-- aberdeen-motor-company-ltd >> | ? |-- mugiemoss-road-grampian >> | ? `-- mugiemoss-road-grampian.metadata >> >> >> the code can be seen at: >> >> http://paste.lisp.org/display/81348 >> >> I basically have a form, where the user makes a search for 'Company' >> name, than the code searches for all the items that do not contain >> 'hotel' in the metadata >> >> This works for the first level, i.e. when searching in the companies >> directory. >> >> Now I want to extend this to search for the '/companies/company/ but >> to only search the addresses that are in the found = [] list from the >> previous search. > > I haven't looked at your code, but I presume your "search" is a function? I > certainly hope so anyway! Also I presume you return the found list? If so, > it should be trivial. If not, you should probably adjust your code to do > such things. Hi, thanks for the reply. It was simpler than I thought. > HTH, > Wayne From dineshbvadhia at hotmail.com Thu Jun 4 18:29:29 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 4 Jun 2009 09:29:29 -0700 Subject: [Tutor] unicode, utf-8 problem again In-Reply-To: <4A27D48F.2030700@compuscan.co.za> References: <4A27D48F.2030700@compuscan.co.za> Message-ID: Okay, I get it now ... reading/writing files with the codecs module and the 'utf-8' option fixes it. Thanks! From: Christian Witts Sent: Thursday, June 04, 2009 7:05 AM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] unicode, utf-8 problem again Dinesh B Vadhia wrote: > Hi! I'm processing a large number of xml files that are all declared > as utf-8 encoded in the header ie. > > > > My Python environment has been set for 'utf-8' through site.py. > Additionally, the top of each program/module has the declaration: > > # -*- coding: utf-8 -*- > > But, I still get this error: > > Traceback (most recent call last): > ... > UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in > position 76: ordinal not in range(128) > > What am I missing? > > Dinesh > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi, Take a read through http://evanjones.ca/python-utf8.html which will give you insight as to how you should be reading and processing your files. As for the encoding line "# -*- coding: utf-8 -*-", that is actually to declare the character encoding of your script and not of potential data it will be working with. -- Kind Regards, Christian Witts -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Thu Jun 4 19:25:20 2009 From: norman at khine.net (Norman Khine) Date: Thu, 4 Jun 2009 19:25:20 +0200 Subject: [Tutor] improvement of if - else code Message-ID: <9c2c8ffb0906041025l699f3fd3rad290e7b49d8101e@mail.gmail.com> Hello, Is there a better way to write this: @staticmethod def get_form(address=None, postcode=None, town=None, phone=None, fax=None, freephone=None, address_country=None, address_region=None, address_county=None, hotel=None): context = get_context() root = context.root # List authorized countries if hotel is True: countries = [ {'name': y, 'title': x, 'selected': y == address_country} for x, y in root.get_active_countries(context) ] else: countries = [ {'name': y, 'title': x, 'selected': y == address_country} for x, y in root.get_authorized_countries(context) ] Thanks From vinces1979 at gmail.com Thu Jun 4 19:34:34 2009 From: vinces1979 at gmail.com (vince spicer) Date: Thu, 4 Jun 2009 11:34:34 -0600 Subject: [Tutor] improvement of if - else code In-Reply-To: <9c2c8ffb0906041025l699f3fd3rad290e7b49d8101e@mail.gmail.com> References: <9c2c8ffb0906041025l699f3fd3rad290e7b49d8101e@mail.gmail.com> Message-ID: <1e53c510906041034w2d818014ue4d31d288c2be79f@mail.gmail.com> you could assign loop variable @staticmethod def get_form(address=None, postcode=None, town=None, phone=None, fax=None, freephone=None, address_country=None, address_region=None, address_county=None, hotel=None): context = get_context() root = context.root # List authorized countries loopvar = root.get_active_countries(context) if hotel else root.get_authorized_countries(context) countries = [ {'name': y, 'title': x, 'selected': y == address_country} for x, y in loopvar ] On Thu, Jun 4, 2009 at 11:25 AM, Norman Khine wrote: > Hello, > Is there a better way to write this: > > @staticmethod > def get_form(address=None, postcode=None, town=None, phone=None, > fax=None, > freephone=None, address_country=None, address_region=None, > address_county=None, hotel=None): > context = get_context() > root = context.root > # List authorized countries > if hotel is True: > countries = [ > {'name': y, 'title': x, 'selected': y == address_country} > for x, y in root.get_active_countries(context) ] > else: > countries = [ > {'name': y, 'title': x, 'selected': y == address_country} > for x, y in root.get_authorized_countries(context) ] > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Thu Jun 4 19:36:34 2009 From: norman at khine.net (Norman Khine) Date: Thu, 4 Jun 2009 19:36:34 +0200 Subject: [Tutor] improvement of if - else code In-Reply-To: <1e53c510906041034w2d818014ue4d31d288c2be79f@mail.gmail.com> References: <9c2c8ffb0906041025l699f3fd3rad290e7b49d8101e@mail.gmail.com> <1e53c510906041034w2d818014ue4d31d288c2be79f@mail.gmail.com> Message-ID: <9c2c8ffb0906041036j6169de72w5c3fdcffbe858106@mail.gmail.com> Thanks On Thu, Jun 4, 2009 at 7:34 PM, vince spicer wrote: > you could assign loop variable > > ?? @staticmethod > ? ?def get_form(address=None, postcode=None, town=None, phone=None, > fax=None, > ? ? ? ? ? ? ? ? freephone=None, address_country=None, address_region=None, > ? ? ? ? ? ? ? ? address_county=None, hotel=None): > ? ? ? ?context = get_context() > ? ? ? ?root = context.root > ? ? ? ?# List authorized countries > > ?????? loopvar = root.get_active_countries(context) if hotel else > root.get_authorized_countries(context) > > ? ? ?? countries = [ {'name': y, 'title': x, 'selected': y == > address_country} for x, y in loopvar ] > > > > > On Thu, Jun 4, 2009 at 11:25 AM, Norman Khine wrote: >> >> Hello, >> Is there a better way to write this: >> >> ? ?@staticmethod >> ? ?def get_form(address=None, postcode=None, town=None, phone=None, >> fax=None, >> ? ? ? ? ? ? ? ? freephone=None, address_country=None, address_region=None, >> ? ? ? ? ? ? ? ? address_county=None, hotel=None): >> ? ? ? ?context = get_context() >> ? ? ? ?root = context.root >> ? ? ? ?# List authorized countries >> ? ? ? ?if hotel is True: >> ? ? ? ? ? ?countries = [ >> ? ? ? ? ? ? ? ?{'name': y, 'title': x, 'selected': y == address_country} >> ? ? ? ? ? ? ? ?for x, y in root.get_active_countries(context) ] >> ? ? ? ?else: >> ? ? ? ? ? ?countries = [ >> ? ? ? ? ? ? ? ?{'name': y, 'title': x, 'selected': y == address_country} >> ? ? ? ? ? ? ? ?for x, y in root.get_authorized_countries(context) ] >> >> Thanks >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > From steve at alchemy.com Thu Jun 4 19:36:05 2009 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 4 Jun 2009 10:36:05 -0700 Subject: [Tutor] improvement of if - else code In-Reply-To: <9c2c8ffb0906041025l699f3fd3rad290e7b49d8101e@mail.gmail.com> References: <9c2c8ffb0906041025l699f3fd3rad290e7b49d8101e@mail.gmail.com> Message-ID: <20090604173605.GB70048@dragon.alchemy.com> On Thu, Jun 04, 2009 at 07:25:20PM +0200, Norman Khine wrote: > Hello, > Is there a better way to write this: Depends on what's cleaner and clearer for what you're doing, especially as the complexity of this code grows. For example, if the only difference is which method to call, one approach might be to call one method which figures out which set of countries to return: context = get_context() root = context.root countries = [{...} for x, y in root.get_countries(context, hotel)] Alternatively, you can put some logic up front which determines which method to call later, removing the if/else and repetition of code: context = get_context() root = context.root method = root.get_active_countries if hotel else root.get_authorized_countries countries = [{...} for x, y in method(context)] > > @staticmethod > def get_form(address=None, postcode=None, town=None, phone=None, fax=None, > freephone=None, address_country=None, address_region=None, > address_county=None, hotel=None): > context = get_context() > root = context.root > # List authorized countries > if hotel is True: > countries = [ > {'name': y, 'title': x, 'selected': y == address_country} > for x, y in root.get_active_countries(context) ] > else: > countries = [ > {'name': y, 'title': x, 'selected': y == address_country} > for x, y in root.get_authorized_countries(context) ] > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From wescpy at gmail.com Thu Jun 4 19:45:42 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 4 Jun 2009 10:45:42 -0700 Subject: [Tutor] unicode, utf-8 problem again In-Reply-To: <4A27D48F.2030700@compuscan.co.za> References: <4A27D48F.2030700@compuscan.co.za> Message-ID: <78b3a9580906041045v44b4a64du4c35fbf2ed6dea1@mail.gmail.com> >> ?But, I still get this error: >> ?Traceback (most recent call last): >> ... >> UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in >> position 76: ordinal not in range(128) >> ?What am I missing? > > Take a read through http://evanjones.ca/python-utf8.html which will give you > insight as to how you should be reading and processing your files. in a similar vein, i wrote a shorter blog post awhile ago that focuses specifically on string processing: http://wesc.livejournal.com/1743.html ... in it, i also describe the correct way of thinking about strings in these contexts... the difference between a string that represents data vs. a "string" which is made up of various bytes, as in binary files. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dineshbvadhia at hotmail.com Thu Jun 4 20:36:56 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 4 Jun 2009 11:36:56 -0700 Subject: [Tutor] unicode, utf-8 problem again In-Reply-To: <78b3a9580906041045v44b4a64du4c35fbf2ed6dea1@mail.gmail.com> References: <4A27D48F.2030700@compuscan.co.za> <78b3a9580906041045v44b4a64du4c35fbf2ed6dea1@mail.gmail.com> Message-ID: That was very useful - thanks! Hopefully, I'm "all Unicode" now. From: wesley chun Sent: Thursday, June 04, 2009 10:45 AM To: Dinesh B Vadhia ; tutor at python.org Subject: Re: [Tutor] unicode, utf-8 problem again >> But, I still get this error: >> Traceback (most recent call last): >> ... >> UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in >> position 76: ordinal not in range(128) >> What am I missing? > > Take a read through http://evanjones.ca/python-utf8.html which will give you > insight as to how you should be reading and processing your files. in a similar vein, i wrote a shorter blog post awhile ago that focuses specifically on string processing: http://wesc.livejournal.com/1743.html ... in it, i also describe the correct way of thinking about strings in these contexts... the difference between a string that represents data vs. a "string" which is made up of various bytes, as in binary files. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Thu Jun 4 21:04:43 2009 From: norman at khine.net (Norman Khine) Date: Thu, 4 Jun 2009 21:04:43 +0200 Subject: [Tutor] stripping 0's from 01's - 09's Message-ID: <9c2c8ffb0906041204l26b32079pee36b07c40e2ba11@mail.gmail.com> Hello, Simple, I guess, but I am trying to do a formated date function, which I have working but for a small annoyance in that: >>> from datetime import date >>> def format_date(day): ... if day > 3 and day < 14: ... return '%b %dth %Y' ... indicator = day % 10 ... if indicator == 1: ... return '%b %dst %Y' ... elif indicator == 2: ... return '%b %dnd %Y' ... elif indicator == 3: ... return '%b %drd %Y' ... else: ... return '%b %dth %Y' ... >>> today = '2009-06-04' >>> year, month, day = today.split('-') >>> date_object = date(int(year), int(month), int(day)) >>> format = format_date(date_object.day) >>> formated_date = date_object.strftime(format) >>> formated_date 'Jun 04th 2009' It will be much better to have: 'Jun 4th 2009' How would you go about in doing this? Thanks From emile at fenx.com Thu Jun 4 21:39:16 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 04 Jun 2009 12:39:16 -0700 Subject: [Tutor] stripping 0's from 01's - 09's In-Reply-To: <9c2c8ffb0906041204l26b32079pee36b07c40e2ba11@mail.gmail.com> References: <9c2c8ffb0906041204l26b32079pee36b07c40e2ba11@mail.gmail.com> Message-ID: On 6/4/2009 12:04 PM Norman Khine said... > Hello, > Simple, I guess, but I am trying to do a formated date function, which > I have working but for a small annoyance in that: > >>>> from datetime import date >>>> def format_date(day): > ... if day > 3 and day < 14: > ... return '%b %dth %Y' > ... indicator = day % 10 > ... if indicator == 1: > ... return '%b %dst %Y' > ... elif indicator == 2: > ... return '%b %dnd %Y' > ... elif indicator == 3: > ... return '%b %drd %Y' > ... else: > ... return '%b %dth %Y' > ... >>>> today = '2009-06-04' >>>> year, month, day = today.split('-') >>>> date_object = date(int(year), int(month), int(day)) >>>> format = format_date(date_object.day) >>>> formated_date = date_object.strftime(format) >>>> formated_date > 'Jun 04th 2009' > > It will be much better to have: > > 'Jun 4th 2009' > > How would you go about in doing this? Without reading the docs, you could just strip it out: formated_date = date_object.strftime(format).replace(" 0"," ") Emile > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From worminater at gmail.com Thu Jun 4 22:49:02 2009 From: worminater at gmail.com (Chris Mueller) Date: Thu, 4 Jun 2009 16:49:02 -0400 Subject: [Tutor] Python 2.2... os.exec catch stdout Message-ID: <940dc7890906041349n1dd2673dgbe75979062e8767d@mail.gmail.com> *Hello. I am relegated to running python 2.2; so I do not have access to subprocess. In my script; at one point, I need to run a program; interact with the program; exit the program; and parse the output printed to stdout. This would be simple; if I did not need to interact with my sub-program. I currently have.. import os program = "vim" arguments = ["myFile"] pid = os.fork() if not pid: os.execvp(program, (program,) + tuple(arguments)) os.wait()[0] This works fine; lets me interact with "vim" fine; and return to the python script when I am done; but I do not seem to be able to execute read stdout; and all examples I have found on the net do not allow me to interact with the called program. Any pokes int he right direction? Thanks, Chris * -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Jun 4 23:02:20 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 04 Jun 2009 14:02:20 -0700 Subject: [Tutor] Python 2.2... os.exec catch stdout In-Reply-To: <940dc7890906041349n1dd2673dgbe75979062e8767d@mail.gmail.com> References: <940dc7890906041349n1dd2673dgbe75979062e8767d@mail.gmail.com> Message-ID: On 6/4/2009 1:49 PM Chris Mueller said... > /Hello. > > I am relegated to running python 2.2; so I do not have access to subprocess. > > In my script; at one point, I need to run a program; interact with the > program; exit the program; and parse the output printed to stdout. > > This would be simple; if I did not need to interact with my > sub-program. I currently have.. > > import os > program = "vim" > arguments = ["myFile"] > pid = os.fork() > if not pid: > os.execvp(program, (program,) + tuple(arguments)) > os.wait()[0] > > This works fine; lets me interact with "vim" fine; and return to the > python script when I am done; but I do not seem to be able to execute > read stdout; and all examples I have found on the net do not allow me to > interact with the called program. > > Any pokes int he right direction? What OS? Emile > > Thanks, > Chris > / > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From gregor.lingl at aon.at Fri Jun 5 00:07:55 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 05 Jun 2009 00:07:55 +0200 Subject: [Tutor] serious problem with graphics module In-Reply-To: References: <4bcde3e10905241403t3356c053m31b5964365860f0f@mail.gmail.com> <4A1B1F78.9070603@aon.at><4bcde3e10906020848m28827aefu5034f60b642c9b41@mail.gmail.com> <4A25BFD4.1050701@aon.at><333efb450906022207u46e7a05fw8a950be2bc227298@mail.gmail.com> <4A26E13D.3070600@aon.at> <333efb450906031451l3b74549by5c9900935aee0ace@mail.gmail.com> Message-ID: <4A2845BB.9070403@aon.at> Alan Gauld schrieb: > > "W W" wrote > >> Do you (or sombody else) know how to get ipython working with Python 2.6 >> (you know, the Python release, which has that new turtle module ;-) ) >> >> doesn't install on my Windows box... other than that I've got no >> experience >> with it > > I thought the new turtle module could be made to work on 2.5 > as well as 2.6? And IPython plays with 2.5 OK. So if its only the turtle > module thats needed it should work? > > Or am I mistaken in the 2.5 turtle compatibility? Not at all. But possibly I'mgoing to give a tutorial on turtle.py at EuroPython (depending on the number of attendees). There I'd like to use Python 2.6 (as it is the most recent release of the 2.x branch and contains turtle.py already). That's why I asked. (There are some postings in some forums on using IPython with Python 2.6 but the advice to install it I found there didn't work for me) And, Alan, some months ago you complained not to come to Pycon. Will you attend EuroPython? Would be nice to meet you there. Regards, Gregor > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Fri Jun 5 02:47:04 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Jun 2009 20:47:04 -0400 Subject: [Tutor] serious problem with graphics module In-Reply-To: <333efb450906031451l3b74549by5c9900935aee0ace@mail.gmail.com> References: <4bcde3e10905241403t3356c053m31b5964365860f0f@mail.gmail.com> <4A1B1F78.9070603@aon.at> <4bcde3e10906020848m28827aefu5034f60b642c9b41@mail.gmail.com> <4A25BFD4.1050701@aon.at> <333efb450906022207u46e7a05fw8a950be2bc227298@mail.gmail.com> <4A26E13D.3070600@aon.at> <333efb450906031451l3b74549by5c9900935aee0ace@mail.gmail.com> Message-ID: <1c2a2c590906041747m56c2d7f3q8e278f0852711b51@mail.gmail.com> On Wed, Jun 3, 2009 at 5:51 PM, W W wrote: > Do you (or sombody else) know how to get ipython working with Python 2.6 > (you know, > the Python release, which has that new turtle module ;-) ? ) > > doesn't install on my Windows box... other than that I've got no experience > with it What trouble did you have? I use IPython with Python 2.6 on Windows. Not sure how I installed it though. Kent From srilyk at gmail.com Fri Jun 5 04:25:07 2009 From: srilyk at gmail.com (W W) Date: Thu, 4 Jun 2009 21:25:07 -0500 Subject: [Tutor] serious problem with graphics module In-Reply-To: <1c2a2c590906041747m56c2d7f3q8e278f0852711b51@mail.gmail.com> References: <4bcde3e10905241403t3356c053m31b5964365860f0f@mail.gmail.com> <4A1B1F78.9070603@aon.at> <4bcde3e10906020848m28827aefu5034f60b642c9b41@mail.gmail.com> <4A25BFD4.1050701@aon.at> <333efb450906022207u46e7a05fw8a950be2bc227298@mail.gmail.com> <4A26E13D.3070600@aon.at> <333efb450906031451l3b74549by5c9900935aee0ace@mail.gmail.com> <1c2a2c590906041747m56c2d7f3q8e278f0852711b51@mail.gmail.com> Message-ID: <333efb450906041925k9d70620gddf2214aa7f480d1@mail.gmail.com> On Thu, Jun 4, 2009 at 7:47 PM, Kent Johnson wrote: > On Wed, Jun 3, 2009 at 5:51 PM, W W wrote: > > > Do you (or sombody else) know how to get ipython working with Python 2.6 > > (you know, > > the Python release, which has that new turtle module ;-) ) > > > > doesn't install on my Windows box... other than that I've got no > experience > > with it > > What trouble did you have? I use IPython with Python 2.6 on Windows. > Not sure how I installed it though. After install it gave me this: *** run_installscript: internal error 0xFFFFFFFF *** same error I get trying to install pyreadline. No shortcuts on the desktop/start menu/etc show up. All the files are in the site-packages directory, it seems. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Fri Jun 5 06:45:48 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Thu, 4 Jun 2009 21:45:48 -0700 Subject: [Tutor] unicode, utf-8 problem again References: Message-ID: "Dinesh B Vadhia" wrote in message news:COL103-DS25BB23A18E216061C32EB1A34B0 at phx.gbl... > Hi! I'm processing a large number of xml files that are all declared as > utf-8 encoded in the header ie. > > My Python environment has been set for 'utf-8' through site.py. It's a bad idea to change the encoding through site.py. Your script won't work on any other system. -Mark From stefan_ml at behnel.de Fri Jun 5 07:08:08 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 05 Jun 2009 07:08:08 +0200 Subject: [Tutor] Fw: unicode, utf-8 problem again In-Reply-To: References: Message-ID: Dinesh B Vadhia wrote: > Hi! I'm processing a large number of xml files that are all declared as utf-8 encoded in the header ie. > > > > I'm using elementtree to process the xml files and > don't (usually) have any problems with that. Plus, the workaround that > works is to encode each elementtree output ie.: > > thisxmlline = thisxmlline.encode('utf8') This doesn't make any sense. If you want to serialise XML encoded as UTF-8, pass encoding="UTF-8" to tostring() or ET.write(). http://effbot.org/zone/pythondoc-elementtree-ElementTree.htm#elementtree.ElementTree.tostring-function Stefan From lie.1296 at gmail.com Fri Jun 5 08:11:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 05 Jun 2009 16:11:28 +1000 Subject: [Tutor] stripping 0's from 01's - 09's In-Reply-To: <9c2c8ffb0906041204l26b32079pee36b07c40e2ba11@mail.gmail.com> References: <9c2c8ffb0906041204l26b32079pee36b07c40e2ba11@mail.gmail.com> Message-ID: Norman Khine wrote: > Hello, > Simple, I guess, but I am trying to do a formated date function, which > I have working but for a small annoyance in that: > >>>> from datetime import date >>>> def format_date(day): > .... if day > 3 and day < 14: > .... return '%b %dth %Y' > .... indicator = day % 10 > .... if indicator == 1: > .... return '%b %dst %Y' > .... elif indicator == 2: > .... return '%b %dnd %Y' > .... elif indicator == 3: > .... return '%b %drd %Y' > .... else: > .... return '%b %dth %Y' > .... >>>> today = '2009-06-04' >>>> year, month, day = today.split('-') >>>> date_object = date(int(year), int(month), int(day)) >>>> format = format_date(date_object.day) >>>> formated_date = date_object.strftime(format) >>>> formated_date > 'Jun 04th 2009' > > It will be much better to have: > > 'Jun 4th 2009' > > How would you go about in doing this? > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > instead of using '%d' use '%e' >>> import datetime >>> from string import letters >>> letters = ['%%%s' % let for let in letters] >>> letters ['%a', '%b', '%c', '%d', '%e', '%f', '%g', '%h', '%i', '%j', '%k', '%l', '%m', '%n', '%o', '%p', '%q', '%r', '%s', '%t', '%u', '%v', '%w', '%x', '%y', '%z', '%A', '%B', '%C', '%D', '%E', '%F', '%G', '%H', '%I', '%J', '%K', '%L', '%M', '%N', '%O', '%P', '%Q', '%R', '%S', '%T', '%U', '%V', '%W', '%X', '%Y', '%Z'] >>> d = datetime.date(*map(int, '2009-06-05'.split('-'))) >>> formats = ['%s: %s' % (let, d.strftime(let)) for let in letters] >>> for x in formats: print x ... %a: Fri %b: Jun %c: Fri Jun 5 00:00:00 2009 %d: 05 %e: 5 %f: %f %g: 09 %h: Jun %i: %i %j: 156 %k: 0 %l: 12 %m: 06 %n: %o: %o %p: AM %q: %q %r: 12:00:00 AM %s: 1244124000 %t: %u: 5 %v: %v %w: 5 %x: 06/05/09 %y: 09 %z: %A: Friday %B: June %C: 20 %D: 06/05/09 %E: %E %F: 2009-06-05 %G: 2009 %H: 00 %I: 12 %J: %J %K: %K %L: %L %M: 00 %N: %N %O: %O %P: am %Q: %Q %R: 00:00 %S: 00 %T: 00:00:00 %U: 22 %V: 23 %W: 22 %X: 00:00:00 %Y: 2009 %Z: I don't know why %e is not in the docs though, can anyone confirm whether this is a doc bug or an undocumented (and therefore unreliable) feature leaked from the underlying C library? And anyone know what's wrong with %n since it seems it produces a "\n" (newline) character. Note: %z and %Z are for timezone data (e.g. +0500 or EST). Since my sample data does not account for timezone it is now empty (as documented) From lie.1296 at gmail.com Fri Jun 5 08:19:16 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 05 Jun 2009 16:19:16 +1000 Subject: [Tutor] Python 2.2... os.exec catch stdout In-Reply-To: <940dc7890906041349n1dd2673dgbe75979062e8767d@mail.gmail.com> References: <940dc7890906041349n1dd2673dgbe75979062e8767d@mail.gmail.com> Message-ID: Chris Mueller wrote: > /Hello. > > I am relegated to running python 2.2; so I do not have access to subprocess. > > In my script; at one point, I need to run a program; interact with the > program; exit the program; and parse the output printed to stdout. > > This would be simple; if I did not need to interact with my > sub-program.. I currently have.. > > import os > program = "vim" > arguments = ["myFile"] > pid = os.fork() > if not pid: > os.execvp(program, (program,) + tuple(arguments)) > os.wait()[0] > > This works fine; lets me interact with "vim" fine; and return to the > python script when I am done; but I do not seem to be able to execute > read stdout; and all examples I have found on the net do not allow me to > interact with the called program. > > Any pokes int he right direction? > > Thanks, > Chris Use the subprocess module. The os.execvp terminates your program and replace it with the new process; you can't catch the stdout from a terminated process From mobiledreamers at gmail.com Fri Jun 5 09:16:42 2009 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Fri, 5 Jun 2009 00:16:42 -0700 Subject: [Tutor] unified way or cookbook to access cheetah from other frameworks django/webpy/pylons Message-ID: can you or tavis or one of the cheetah masters please show us how to use cheetah from webpy the only useful thing webpy cheetah.py does is replace the #include with the content of the files Can you share a simple snippet/cookbook example on how to hook up cheetah from other frameworks such as django/webpy/pylons, if there is a unified way to access the cheetah template then the problems will be easier to fix? Thanks a lot... for trying to help... -- Bidegg worlds best auction site http://bidegg.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 5 10:43:12 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Jun 2009 09:43:12 +0100 Subject: [Tutor] Python 2.2... os.exec catch stdout References: <940dc7890906041349n1dd2673dgbe75979062e8767d@mail.gmail.com> Message-ID: "Chris Mueller" wrote > This would be simple; if I did not need to interact with my sub-program. > I > currently have.. > > pid = os.fork() > if not pid: > os.execvp(program, (program,) + tuple(arguments)) > os.wait()[0] > > This works fine; lets me interact with "vim" fine; and return to the > python > script when I am done; but I do not seem to be able to execute read > stdout; If its actually vim you want to use, and by stdout you mean the text on the screen while editing, then you have a problem in that vim does not write to stdout! It uses curses (I think) to address the screen directly, it does not write onto the stdout stream. (I think if you switch to ex mode it does use stdout - but I may be wrong about that!) If vim is just an unfortunate example then it might be possible but I think we need to know a bit more about what exactly you are trying to do. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From norman at khine.net Fri Jun 5 13:18:18 2009 From: norman at khine.net (Norman Khine) Date: Fri, 5 Jun 2009 13:18:18 +0200 Subject: [Tutor] split or replace Message-ID: <9c2c8ffb0906050418x3bf5c70doe88f62305c573352@mail.gmail.com> Hello, What is the way to group each value so that I get a list, from a string like: dir = '/expert/forum/expert/expert' list = ['/expert', '/forum', '/expert', '/expert'] I've tried: >>> dir = '/expert/forum' >>> dir.split('/') ['', 'expert', 'forum'] >>> dir.replace("/expert","") '/forum' >>> dir = '/expert/forum/expert' >>> dir.replace("/expert","") '/forum' Thanks From srilyk at gmail.com Fri Jun 5 13:32:17 2009 From: srilyk at gmail.com (W W) Date: Fri, 5 Jun 2009 06:32:17 -0500 Subject: [Tutor] split or replace In-Reply-To: <9c2c8ffb0906050418x3bf5c70doe88f62305c573352@mail.gmail.com> References: <9c2c8ffb0906050418x3bf5c70doe88f62305c573352@mail.gmail.com> Message-ID: <333efb450906050432v61a0e548qf48ee9ade4c2603b@mail.gmail.com> On Fri, Jun 5, 2009 at 6:18 AM, Norman Khine wrote: > Hello, > What is the way to group each value so that I get a list, from a string > like: > > dir = '/expert/forum/expert/expert' > list = ['/expert', '/forum', '/expert', '/expert'] > > I've tried: > >>> dir = '/expert/forum' > >>> dir.split('/') > ['', 'expert', 'forum'] > >>> dir.replace("/expert","") > '/forum' > >>> dir = '/expert/forum/expert' > >>> dir.replace("/expert","") > '/forum' will it always begin with /? and is there any reason you want to retain the /? because this gets them without the / >>> dir.split('/')[1:] ['expert', 'forum', 'expert', 'expert'] I think you might be able to use a list comprehension. Otherwise you could do this: >>> dir.replace('/',' /').split() ['/expert', '/forum', '/expert', '/expert'] HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jun 5 13:47:53 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 5 Jun 2009 07:47:53 -0400 Subject: [Tutor] split or replace In-Reply-To: <9c2c8ffb0906050418x3bf5c70doe88f62305c573352@mail.gmail.com> References: <9c2c8ffb0906050418x3bf5c70doe88f62305c573352@mail.gmail.com> Message-ID: <1c2a2c590906050447q45eb8785ya3798faf03807e25@mail.gmail.com> On Fri, Jun 5, 2009 at 7:18 AM, Norman Khine wrote: > Hello, > What is the way to group each value so that I get a list, from a string like: > > dir = '/expert/forum/expert/expert' > list = ['/expert', '/forum', '/expert', '/expert'] Here is one way using re.split(): In [28]: import re In [29]: [ x for x in re.split(r'(/[^/]+)', dir) if x ] Out[29]: ['/expert', '/forum', '/expert', '/expert'] Kent From cfuller084 at thinkingplanet.net Fri Jun 5 14:01:58 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 5 Jun 2009 07:01:58 -0500 Subject: [Tutor] split or replace In-Reply-To: <9c2c8ffb0906050418x3bf5c70doe88f62305c573352@mail.gmail.com> References: <9c2c8ffb0906050418x3bf5c70doe88f62305c573352@mail.gmail.com> Message-ID: <200906050701.58990.cfuller084@thinkingplanet.net> On Friday 05 June 2009 06:18, Norman Khine wrote: > Hello, > What is the way to group each value so that I get a list, from a string > like: > > dir = '/expert/forum/expert/expert' > list = ['/expert', '/forum', '/expert', '/expert'] > > I've tried: > >>> dir = '/expert/forum' > >>> dir.split('/') > > ['', 'expert', 'forum'] > > >>> dir.replace("/expert","") > > '/forum' > > >>> dir = '/expert/forum/expert' > >>> dir.replace("/expert","") > > '/forum' > > Thanks Your code will be more portable if you use the os.path module. I'd do something like this: import os.path as osp import os path = '/bear/duck/gecko/toad' l = [] b = True a = path sep = os.sep while b: a,b = osp.split(a) l.append(osp.join(sep,b)) l.pop() l.reverse() print l ['/bear', '/duck', '/gecko', '/toad'] If you wanted something more consice, you could use a list comprehension: ['/'+i for i in path.split('/')] Cheers From walker.hale.iv at gmail.com Fri Jun 5 14:52:59 2009 From: walker.hale.iv at gmail.com (Walker Hale IV) Date: Fri, 5 Jun 2009 07:52:59 -0500 Subject: [Tutor] Mapping to an equivalent / similar object? In-Reply-To: <916298.49448.qm@web45608.mail.sp1.yahoo.com> References: <916298.49448.qm@web45608.mail.sp1.yahoo.com> Message-ID: <312f43620906050552t70d3fa55i8c90495f09471d83@mail.gmail.com> On Thu, May 28, 2009 at 5:41 PM, Allen Fowler wrote: > How should the mapping between the CanonicalFlavor('Vanilla') object and ManufAFlavor('Vanilla') / ManufBFlavor('Vanilla') objects be handled. Create a dict. The keys are either CannonicalFlavor objects or just strings containing the canonical names. The values of the dict are either sets or lists. Inside one of those sets or lists, you have the manufactured flavor objects. If there is a natural ordering to the manufactured flavor objects, such as preferring to get vanilla from Manufacturer A but chocolate from Manufacturer B, then use lists. Otherwise use sets. Example code: flavor_sources = dict() flavor_sources['vanilla'] = [ManufAFlavor('Vanilla'), ManufBFlavor('Vanilla')] flavor_sources['chocolate'] = [ManufBFlavor('Chocolate'), ManufAFlavor('Chocolate')] If needed you can customize this in two ways: using objects for the keyes and using sets for the values. Note that if you want to use objects for keys, then your class needs to implement __hash__() and __cmp__(). See http://www.python.org/doc/2.5.4/ref/customization.html -- Walker Hale From alan.gauld at btinternet.com Sat Jun 6 00:28:47 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 5 Jun 2009 22:28:47 +0000 (GMT) Subject: [Tutor] Python 2.2... os.exec catch stdout In-Reply-To: <940dc7890906050534h709bc40cxe96b899c7ad16476@mail.gmail.com> References: <940dc7890906041349n1dd2673dgbe75979062e8767d@mail.gmail.com> <940dc7890906050534h709bc40cxe96b899c7ad16476@mail.gmail.com> Message-ID: <652885.8973.qm@web86707.mail.ird.yahoo.com> If vim is just an unfortunate example then it might be possible but I think we need to know a bit more about what exactly you are trying to do. > It's actually a stand alone program; which opens up a $EDITOR; an > then prints to stdout the results of some db munging. ... > what I'm wanting to grab is the output printed to stdout after execution. In that case use one of subprocesses predecessors, either os.popen or the command module. Either of these will start a subprocess and return stdout as a file like object. If you need to send input to the process via stdin you can use popen2 and if you also need access to stderr you can use popen3 - you can see why they wanted to rationalise this with subprocess! HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Sat Jun 6 11:04:35 2009 From: norman at khine.net (Norman Khine) Date: Sat, 6 Jun 2009 11:04:35 +0200 Subject: [Tutor] class design Message-ID: <9c2c8ffb0906060204y566eee20x13a1364b632808da@mail.gmail.com> Hello, I would like help to design the following: In my application I have 3 folders each containing images, something like: $ tree -L 3 /database/companies/company/ |-- product | |-- itinerary | | |-- img1.gif | | |-- img1.gif.metadata | | |-- day1 | | | |-- img2.gif | | | `-- img2.gif.metadata | | |-- day1.metadata | | |-- day2 | | | |-- Alon.jpg | | | `-- Alon.jpg.metadata | | |-- day2.metadata | | |-- nc.jpg | | `-- nc.jpg.metadata | |-- itinerary.metadata | |-- pyre.jpg | `-- pyre.jpg.metadata `-- product.metadata where I have the Product, Itinerary and Day folders, each containing images and other files. Here is what I have so far that works, but I am looking for better solution. http://paste.lisp.org/display/81448 Thanks Norman From kent37 at tds.net Sat Jun 6 13:02:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 6 Jun 2009 07:02:05 -0400 Subject: [Tutor] class design In-Reply-To: <9c2c8ffb0906060204y566eee20x13a1364b632808da@mail.gmail.com> References: <9c2c8ffb0906060204y566eee20x13a1364b632808da@mail.gmail.com> Message-ID: <1c2a2c590906060402v19dad63cg67c46c45fc184431@mail.gmail.com> On Sat, Jun 6, 2009 at 5:04 AM, Norman Khine wrote: > Hello, > I would like help to design the following: > http://paste.lisp.org/display/81448 Product.get_days() may have a bug, it only returns the first container it finds. You probably don't want the view code in the same class with the data. It's generally a good idea to separate the model - the representation of data - from the view - the display of the data. The get_images() methods are all very similar. If each class had a get_children() method then you could combine the get_images(). For example class Product(Folder): ... def get_children(self): children = [ self ] children.extend(self.get_itinerary()) children.extend(self.get_days()) class Folder(object): def get_images(self): images = [] for child in self.get_children(): images.extend(child.search_handlers(handler_class=File)) return images You might be able to do something similar with get_days(). I wonder why you are not using a database to store all this? I can't help wondering what the code would look like in Django. Kent From norman at khine.net Sat Jun 6 14:26:32 2009 From: norman at khine.net (Norman Khine) Date: Sat, 6 Jun 2009 14:26:32 +0200 Subject: [Tutor] class design In-Reply-To: <1c2a2c590906060402v19dad63cg67c46c45fc184431@mail.gmail.com> References: <9c2c8ffb0906060204y566eee20x13a1364b632808da@mail.gmail.com> <1c2a2c590906060402v19dad63cg67c46c45fc184431@mail.gmail.com> Message-ID: <9c2c8ffb0906060526m41788b47mde484e66f063c72b@mail.gmail.com> Thanks for the reply. I am using the iTools python library from http://hforge.org (http://git.hforge.org/) and the data is stored as XML files. On Sat, Jun 6, 2009 at 1:02 PM, Kent Johnson wrote: > On Sat, Jun 6, 2009 at 5:04 AM, Norman Khine wrote: >> Hello, >> I would like help to design the following: >> http://paste.lisp.org/display/81448 > > Product.get_days() may have a bug, it only returns the first container it finds. It was an error when I simplified the code for posting on the list. > > You probably don't want the view code in the same class with the data. > It's generally a good idea to separate the model - the representation > of data - from the view - the display of the data. In iTools, each class has a view, edit, state etc... functions depending on the class. > > The get_images() methods are all very similar. If each class had a > get_children() method then you could combine the get_images(). For > example Here is what I wanted to improve on, I will try to combine this as suggested. > > class Product(Folder): > ?... > ?def get_children(self): > ? ?children = [ self ] > ? ?children.extend(self.get_itinerary()) > ? ?children.extend(self.get_days()) > > class Folder(object): > ?def get_images(self): > ? ?images = [] > ? ?for child in self.get_children(): > ? ? ?images.extend(child.search_handlers(handler_class=File)) > ? ?return images > > You might be able to do something similar with get_days(). > > I wonder why you are not using a database to store all this? I can't > help wondering what the code would look like in Django. > > Kent > Thank you for your feedback Norman From alan.gauld at btinternet.com Sat Jun 6 14:38:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Jun 2009 13:38:40 +0100 Subject: [Tutor] class design References: <9c2c8ffb0906060204y566eee20x13a1364b632808da@mail.gmail.com> Message-ID: "Norman Khine" wrote > In my application I have 3 folders each containing images, something > like: > > $ tree -L 3 /database/companies/company/ > |-- product > | |-- itinerary > | | |-- img1.gif > | | |-- img1.gif.metadata > | | |-- day1 > | | | |-- img2.gif > | | | `-- img2.gif.metadata > | | |-- day1.metadata > > where I have the Product, Itinerary and Day folders, each containing > images and other files. > > Here is what I have so far that works, but I am looking for better > solution. When you say it "works" I'm not sure what it is you are trying to do? It seems that kmostly the classes are just containers representing the file structure and mostly you could accomplish the same, more simply, with os.walk? Do the classes actually do anything? What exactly do you do with a Product object? What is it for? Can you fill in a (virtual) CRC card for each class? Until we know what the cklasses are for its hard to know what you want improved... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From norman at khine.net Sat Jun 6 14:55:15 2009 From: norman at khine.net (Norman Khine) Date: Sat, 6 Jun 2009 14:55:15 +0200 Subject: [Tutor] class design In-Reply-To: References: <9c2c8ffb0906060204y566eee20x13a1364b632808da@mail.gmail.com> Message-ID: <9c2c8ffb0906060555s67ff91fs22c857d27ad3b05c@mail.gmail.com> Hi On Sat, Jun 6, 2009 at 2:38 PM, Alan Gauld wrote: > > "Norman Khine" wrote > >> In my application I have 3 folders each containing images, something like: >> >> $ tree -L 3 /database/companies/company/ >> |-- product >> | ? |-- itinerary >> | ? | ? |-- img1.gif >> | ? | ? |-- img1.gif.metadata >> | ? | ? |-- day1 >> | ? | ? | ? |-- img2.gif >> | ? | ? | ? `-- img2.gif.metadata >> | ? | ? |-- day1.metadata >> >> where I have the Product, Itinerary and Day folders, each containing >> images and other files. >> >> Here is what I have so far that works, but I am looking for better >> solution. > > When you say it "works" I'm not sure what it is you are trying to do? > It seems that kmostly the classes are just containers representing > the file structure and mostly you could accomplish the same, more > simply, with os.walk? > > Do the classes actually do anything? What exactly do you do with > a Product object? What is it for? Can you fill in a (virtual) CRC card > for each class? I will do this and see if I can improve the design. > > Until we know what the cklasses are for its hard to know what you > want improved... Each class is an object containing elements from generated from data based on the current .metadata file, it's contents plus any data which is within the 'folder' In simple terms I was trying to create a 'folder with a view' which displays all the data it contains on one page, rather than having to view each node individually. Thanks > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sat Jun 6 15:24:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 6 Jun 2009 09:24:08 -0400 Subject: [Tutor] class design In-Reply-To: <9c2c8ffb0906060526m41788b47mde484e66f063c72b@mail.gmail.com> References: <9c2c8ffb0906060204y566eee20x13a1364b632808da@mail.gmail.com> <1c2a2c590906060402v19dad63cg67c46c45fc184431@mail.gmail.com> <9c2c8ffb0906060526m41788b47mde484e66f063c72b@mail.gmail.com> Message-ID: <1c2a2c590906060624l58ca8452g2dc91394bf4fb7d2@mail.gmail.com> On Sat, Jun 6, 2009 at 8:26 AM, Norman Khine wrote: >> You probably don't want the view code in the same class with the data. >> It's generally a good idea to separate the model - the representation >> of data - from the view - the display of the data. > > In iTools, each class has a view, edit, state etc... functions > depending on the class. Can you point to an example in the itools docs? I don't see this usage. There are a some of disadvantages to this design. - it ties the data model to a specific view technology, whether text, Tkinter, HTML, or whatever - it makes it more difficult to have multiple views, for example summary and detail views, or admin edit vs user edit I only couple a model class to a representation of the model when they are very tightly linked, for example in serialization. User views should be decoupled from the model. Kent From norman at khine.net Sat Jun 6 16:43:01 2009 From: norman at khine.net (Norman Khine) Date: Sat, 6 Jun 2009 16:43:01 +0200 Subject: [Tutor] class design In-Reply-To: <1c2a2c590906060624l58ca8452g2dc91394bf4fb7d2@mail.gmail.com> References: <9c2c8ffb0906060204y566eee20x13a1364b632808da@mail.gmail.com> <1c2a2c590906060402v19dad63cg67c46c45fc184431@mail.gmail.com> <9c2c8ffb0906060526m41788b47mde484e66f063c72b@mail.gmail.com> <1c2a2c590906060624l58ca8452g2dc91394bf4fb7d2@mail.gmail.com> Message-ID: <9c2c8ffb0906060743j2b9821aev392d64b43cacec0b@mail.gmail.com> http://docs.hforge.org/itools/web.html although this is for the newer version, in my case i am maintaining an older version. On Sat, Jun 6, 2009 at 3:24 PM, Kent Johnson wrote: > On Sat, Jun 6, 2009 at 8:26 AM, Norman Khine wrote: > >>> You probably don't want the view code in the same class with the data. >>> It's generally a good idea to separate the model - the representation >>> of data - from the view - the display of the data. >> >> In iTools, each class has a view, edit, state etc... functions >> depending on the class. > > Can you point to an example in the itools docs? I don't see this > usage. There are a some of disadvantages to this design. > - it ties the data model to a specific view technology, whether text, > Tkinter, HTML, or whatever > - it makes it more difficult to have multiple views, for example > summary and detail views, or admin edit vs user edit > > I only couple a model class to a representation of the model when they > are very tightly linked, for example in serialization. User views > should be decoupled from the model. > > Kent > From kent37 at tds.net Sat Jun 6 17:55:49 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 6 Jun 2009 11:55:49 -0400 Subject: [Tutor] class design In-Reply-To: <9c2c8ffb0906060743j2b9821aev392d64b43cacec0b@mail.gmail.com> References: <9c2c8ffb0906060204y566eee20x13a1364b632808da@mail.gmail.com> <1c2a2c590906060402v19dad63cg67c46c45fc184431@mail.gmail.com> <9c2c8ffb0906060526m41788b47mde484e66f063c72b@mail.gmail.com> <1c2a2c590906060624l58ca8452g2dc91394bf4fb7d2@mail.gmail.com> <9c2c8ffb0906060743j2b9821aev392d64b43cacec0b@mail.gmail.com> Message-ID: <1c2a2c590906060855k5436d459ld40cf0e263ad78b9@mail.gmail.com> On Sat, Jun 6, 2009 at 10:43 AM, Norman Khine wrote: > http://docs.hforge.org/itools/web.html although this is for the newer > version, in my case i am maintaining an older version. >From that page it seems that itools does as I suggest. They claim to follow the Model-View-Controller pattern which separates the model and view. The View classes are responsible for display of data but not for the contents. It's not clear from the examples where the model fits in but it is distinct from the view. Kent > On Sat, Jun 6, 2009 at 3:24 PM, Kent Johnson wrote: >> On Sat, Jun 6, 2009 at 8:26 AM, Norman Khine wrote: >> >>>> You probably don't want the view code in the same class with the data. >>>> It's generally a good idea to separate the model - the representation >>>> of data - from the view - the display of the data. >>> >>> In iTools, each class has a view, edit, state etc... functions >>> depending on the class. >> >> Can you point to an example in the itools docs? From walker.hale.iv at gmail.com Sat Jun 6 19:02:41 2009 From: walker.hale.iv at gmail.com (Walker Hale IV) Date: Sat, 6 Jun 2009 12:02:41 -0500 Subject: [Tutor] Suggested source code folder layout In-Reply-To: <616626.98865.qm@web45616.mail.sp1.yahoo.com> References: <616626.98865.qm@web45616.mail.sp1.yahoo.com> Message-ID: <312f43620906061002i22bf826cm350c4b210a1c1055@mail.gmail.com> On Tue, Jun 2, 2009 at 5:06 PM, Allen Fowler wrote: > > Hello, > > I'm looking for some suggestions as to the filesystem source code layout for a new project. > > Here is what I am thinking so far: > > root_folder/ > - app/ -- Code for our pylons/django/TG/etc web app > - web/ -- Public static web files (and wsgi / fastCGI connector files) > - db/ -- SQlite DB > - scripts/ -- Various custom programs that will also interact with the DB / app. (Some cron, some interactive.) > > However, I am still wondering about a couple of items: > > 1) Where to create the virtualpython installation that will be used by both the app and the scripts. > > 2) Where to put our in-house created python modules that will be imported by both the app and scripts. > > Thank you, > :) My 2 cents... 1) Since you are describing your source code layout, any virtual environment should be outside. A virtual environment (virtualenv) is part of deployment and not part of source. If you need to make a reproducible deployment environment, then you need a deployment system such as zc.buildout. You would store just the recipe for the environment in source, but not the resulting buildout. Your build recipe will typically go in the top of your source tree. http://pypi.python.org/pypi/zc.buildout/ 2) Common library code shared by both app and scripts belongs in a directory named lib. During buildout, the lib directory would be copied to the site-packages of some python environment. Alternatively, you could add the lib directory to the search path of your running Python instances. When running either your app or scripts directly from your source directory, just add the lib directory to your PYTHONPATH environment variable. -- Walker Hale From alan.gauld at btinternet.com Sat Jun 6 19:30:12 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 6 Jun 2009 17:30:12 +0000 (GMT) Subject: [Tutor] class design In-Reply-To: <9c2c8ffb0906060555s67ff91fs22c857d27ad3b05c@mail.gmail.com> References: <9c2c8ffb0906060204y566eee20x13a1364b632808da@mail.gmail.com> <9c2c8ffb0906060555s67ff91fs22c857d27ad3b05c@mail.gmail.com> Message-ID: <807549.85900.qm@web86708.mail.ird.yahoo.com> > In simple terms I was trying to create a 'folder with a view' which > displays all the data it contains on one page, rather than having to > view each node individually. In that case I'd probably create a FolderView class with a show or display method. If you want to do something with the contents then I'd have a Folder object and associate each FolderView with its Folder -0 which is what Kent recommended in another post. But I'd expect the Folder to be doing more than simply returning the items in the Folder, I'd expect you to be doing something with it - moving it, copying it, deleting it etc. ie Actually manipulating the Folder itself in some way. Otherwise the View can fetch and display the contents itself using standard OS functions. HTH, Alan G. http://www.alan-g.me.uk/ From eduardo.susan at gmail.com Sat Jun 6 19:44:05 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Sat, 6 Jun 2009 11:44:05 -0600 Subject: [Tutor] Need better understanding of **kwargs Message-ID: <9356b9f30906061044i4ded250fif3b387e64a11700d@mail.gmail.com> Hello, I thought I understood **kwargs until I stumbled with this function: def changeflexion(myword, mytag, **dicty): global er_verbs global ar_verbs global ir_verbs # global dicty for item in dicty: if myword in item and mytag in item[1]: if dicty[item].endswith('ar'): ending = item[0].replace(dicty[item][:-2], "") try: return dicty[item][:-2] + ar_verbs[ending] except KeyError: return item[0] elif dicty[item].endswith('er'): ending = item[0].replace(dicty[item][:-2], "") try: return dicty[item][:-2] + er_verbs[ending] except KeyError: return item[0] elif dicty[item].endswith('ir'): ending = item[0].replace(dicty[item][:-2], "") try: return dicty[item][:-2] + ir_verbs[ending] except KeyError: return item[0] else: return item[0] but when I import the module and call: a = conjugate.changeflexion('estaban', 'VLFin', conjugate.mydict) I get this error: TypeError: changeflexion() takes exactly 2 arguments (3 given) Isn't the 3rd argument supposed to be a dictionary? Thanks for all the help this list has provided me as a novice From bgailer at gmail.com Sat Jun 6 20:24:53 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 06 Jun 2009 14:24:53 -0400 Subject: [Tutor] Need better understanding of **kwargs In-Reply-To: <9356b9f30906061044i4ded250fif3b387e64a11700d@mail.gmail.com> References: <9356b9f30906061044i4ded250fif3b387e64a11700d@mail.gmail.com> Message-ID: <4A2AB475.7090902@gmail.com> Eduardo Vieira wrote: > Hello, I thought I understood **kwargs until I stumbled with this function: > > def changeflexion(myword, mytag, **dicty): > global er_verbs > global ar_verbs > global ir_verbs > # global dicty > for item in dicty: > if myword in item and mytag in item[1]: > if dicty[item].endswith('ar'): > ending = item[0].replace(dicty[item][:-2], "") > try: > return dicty[item][:-2] + ar_verbs[ending] > except KeyError: > return item[0] > elif dicty[item].endswith('er'): > ending = item[0].replace(dicty[item][:-2], "") > try: > return dicty[item][:-2] + er_verbs[ending] > except KeyError: > return item[0] > elif dicty[item].endswith('ir'): > ending = item[0].replace(dicty[item][:-2], "") > try: > return dicty[item][:-2] + ir_verbs[ending] > except KeyError: > return item[0] > else: > return item[0] > > but when I import the module and call: > a = conjugate.changeflexion('estaban', 'VLFin', conjugate.mydict) > I get this error: > TypeError: changeflexion() takes exactly 2 arguments (3 given) > **dicty accumulates any name=value pairs in the call into a dictionary. > Isn't the 3rd argument supposed to be a dictionary? > If you want that remove the ** from dicty. -- Bob Gailer Chapel Hill NC 919-636-4239 From metolone+gmane at gmail.com Sat Jun 6 20:25:27 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 6 Jun 2009 11:25:27 -0700 Subject: [Tutor] Need better understanding of **kwargs References: <9356b9f30906061044i4ded250fif3b387e64a11700d@mail.gmail.com> Message-ID: "Eduardo Vieira" wrote in message news:9356b9f30906061044i4ded250fif3b387e64a11700d at mail.gmail.com... > Hello, I thought I understood **kwargs until I stumbled with this > function: > > def changeflexion(myword, mytag, **dicty): > global er_verbs > global ar_verbs > global ir_verbs > # global dicty > for item in dicty: > if myword in item and mytag in item[1]: > if dicty[item].endswith('ar'): > ending = item[0].replace(dicty[item][:-2], "") > try: > return dicty[item][:-2] + ar_verbs[ending] > except KeyError: > return item[0] > elif dicty[item].endswith('er'): > ending = item[0].replace(dicty[item][:-2], "") > try: > return dicty[item][:-2] + er_verbs[ending] > except KeyError: > return item[0] > elif dicty[item].endswith('ir'): > ending = item[0].replace(dicty[item][:-2], "") > try: > return dicty[item][:-2] + ir_verbs[ending] > except KeyError: > return item[0] > else: > return item[0] > > but when I import the module and call: > a = conjugate.changeflexion('estaban', 'VLFin', conjugate.mydict) > I get this error: > TypeError: changeflexion() takes exactly 2 arguments (3 given) > Isn't the 3rd argument supposed to be a dictionary? No, **dicty means the function takes zero or more keyword parameters: >>> def f(a,b,**k): ... print a,b,k ... >>> f(1,2) # no keyword parameters 1 2 {} >>> f(1,2,c=3) # one keyword parameter 1 2 {'c': 3} >>> f(1,2,{'c':3}) # a dictionary Traceback (most recent call last): File "", line 1, in TypeError: f() takes exactly 2 arguments (3 given) But there is a syntax to pass keyword arguments as a dictionary: >>> f(1,2,**{'c':3}) 1 2 {'c': 3} -Mark From burgess.nick at gmail.com Sat Jun 6 21:19:11 2009 From: burgess.nick at gmail.com (Nick Burgess) Date: Sat, 6 Jun 2009 15:19:11 -0400 Subject: [Tutor] converting xls to csv In-Reply-To: References: <3a13c8e50905302151k41e5221bj7d3d4287a1df1da@mail.gmail.com> <3a13c8e50905310209h2c2ff914g3b216b3f57e2d1@mail.gmail.com> <3a13c8e50905310248p50027487l51ac7fe2c8c5061d@mail.gmail.com> Message-ID: <3a13c8e50906061219o3b9d6d0fh54401775d754b730@mail.gmail.com> Thank you. The data is pretty much random throughout the csv's so I think I it would have to iterate over the entire rows . I need to search all .csv files in the current directory. I can get glob to return a list of files. How could I get csv.reader to open all the files in the list? My loop logic must be bad.. I am using ActivePython 2.6.1.1. Any clues would be appreciated. pattern = re.compile(r'10\.191\.239\.0') files = glob.glob("*.csv") csv.reader(open (files), delimiter=' ', quotechar='|') for f in files: for row in f: for cell in row: if pattern.search(cell): print ', '.join(row) Traceback (most recent call last): File "Q:\FILES\COMPUTER_NETWORKING\Python\CVSs\ipSrch-v1.0.py", l csv.reader(open (files), delimiter=' ', quotechar='|') TypeError: coercing to Unicode: need string or buffer, list found On Sun, May 31, 2009 at 12:45 PM, Richard Lovely wrote: > 2009/5/31 Nick Burgess : >> Got it. >> >> the row is not a string or buffer but the cell is.. >> >> for row in spamReader: >> ? ?for cell in row: >> ? ? ? ?if pattern.search(cell): >> ? ? ? ? ? ?print ', '.join(row) >> >> > Alternatively, if you know that the string you want to search for only > appears in a single cell from the row, you could use > > for row in spamReader: > ? if pattern.search(cell[coll_number_here]): > ? ? ? print ', '.join(row) > > If there is a range of adjacent cells that could contain the text, you > could try something like > ? ?if pattern.search('|'.join(row[3:5]) > > For non-adjacent cells, try something like > > targetCells = [1,3,5] > for row in spamReader: > ? if pattern.search('|'.join(row[i] for i in targetCells)) > > Both of these solutions will be faster than iterating over th entire > row, unless tht is specifically what you want. > -- > Richard "Roadie Rich" Lovely, part of the JNP|UK Famile > www.theJNP.com > From gonzillaaa at gmail.com Sat Jun 6 21:31:04 2009 From: gonzillaaa at gmail.com (Gonzalo Garcia-Perate) Date: Sat, 6 Jun 2009 20:31:04 +0100 Subject: [Tutor] creating a range above & below a given number Message-ID: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> Hello tutor, What's the simplest way of creating a list with a range of numbers above and below a given number? see the function below: def within_range( self, number, median, threshold=5 ): # build a list of (threshold) numbers above and below median range_list = range( median - threshold, median ) range_list.extend( range( median, median + ( threshold + 1 ) ) ) if __debug__: print "number %s, median %s, within range %s, list %s, list length %s" % ( number, median, number in range_list, range_list, len( range_list ) ) if number not in range_list: return False return True this works fine, but is there a simpler way of doing it? a one liner? :) Thanks, From emile at fenx.com Sat Jun 6 21:33:27 2009 From: emile at fenx.com (Emile van Sebille) Date: Sat, 06 Jun 2009 12:33:27 -0700 Subject: [Tutor] converting xls to csv In-Reply-To: <3a13c8e50906061219o3b9d6d0fh54401775d754b730@mail.gmail.com> References: <3a13c8e50905302151k41e5221bj7d3d4287a1df1da@mail.gmail.com> <3a13c8e50905310209h2c2ff914g3b216b3f57e2d1@mail.gmail.com> <3a13c8e50905310248p50027487l51ac7fe2c8c5061d@mail.gmail.com> <3a13c8e50906061219o3b9d6d0fh54401775d754b730@mail.gmail.com> Message-ID: On 6/6/2009 12:19 PM Nick Burgess said... > Thank you. The data is pretty much random throughout the csv's so I > think I it would have to iterate over the entire rows . I need to > search all .csv files in the current directory. I can get glob to > return a list of files. How could I get csv.reader to open all the > files in the list? Open the files from within your loop. > My loop logic must be bad.. I am using > ActivePython 2.6.1.1. Any clues would be appreciated. > > > > pattern = re.compile(r'10\.191\.239\.0') > files = glob.glob("*.csv") > > csv.reader(open (files), delimiter=' ', quotechar='|') > for f in files: do the open here > for row in f: > for cell in row: > if pattern.search(cell): > print ', '.join(row) > Emile From burgess.nick at gmail.com Sat Jun 6 22:07:31 2009 From: burgess.nick at gmail.com (Nick Burgess) Date: Sat, 6 Jun 2009 16:07:31 -0400 Subject: [Tutor] converting xls to csv In-Reply-To: References: <3a13c8e50905302151k41e5221bj7d3d4287a1df1da@mail.gmail.com> <3a13c8e50905310209h2c2ff914g3b216b3f57e2d1@mail.gmail.com> <3a13c8e50905310248p50027487l51ac7fe2c8c5061d@mail.gmail.com> <3a13c8e50906061219o3b9d6d0fh54401775d754b730@mail.gmail.com> Message-ID: <3a13c8e50906061307n26de74c2m2efac94b09d4cfd@mail.gmail.com> f seems to be a string containing the file names, so csv.reader isnt actually opening them.. maybe i will play with os.walk..? files = glob.glob("*.csv") for f in files: print f csv.reader(open (f), delimiter=' ', quotechar='|') for row in f: for cell in row: if pattern.search(cell): print ', '.join(row) XLS.xls.org1.csv XLS.xls.org2.csv XLS.xls.org3.csv On Sat, Jun 6, 2009 at 3:33 PM, Emile van Sebille wrote: > On 6/6/2009 12:19 PM Nick Burgess said... >> >> Thank you. The data is pretty much random throughout the csv's so I >> think I it would have to iterate over the entire rows . ?I need to >> search all .csv files in the current directory. ? I can get glob to >> return a list of files. ?How could I get csv.reader to open all the >> files in the list? > > Open the files from within your loop. > >> My loop logic must be bad.. ?I am using >> ActivePython 2.6.1.1. ?Any clues would be appreciated. >> >> >> >> pattern = re.compile(r'10\.191\.239\.0') >> files = glob.glob("*.csv") >> >> csv.reader(open (files), delimiter=' ', quotechar='|') >> for f in files: > > do the open here > >> ? ?for row in f: >> ? ? ? ?for cell in row: >> ? ? ? ? ? ?if pattern.search(cell): >> ? ? ? ? ? ? ? ?print ', '.join(row) >> > > > Emile > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From emile at fenx.com Sat Jun 6 22:13:09 2009 From: emile at fenx.com (Emile van Sebille) Date: Sat, 06 Jun 2009 13:13:09 -0700 Subject: [Tutor] creating a range above & below a given number In-Reply-To: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> Message-ID: On 6/6/2009 12:31 PM Gonzalo Garcia-Perate said... > Hello tutor, What's the simplest way of creating a list with a range > of numbers above and below a given number? > > see the function below: > > def within_range( self, number, median, threshold=5 ): > # build a list of (threshold) numbers above and below median > range_list = range( median - threshold, median ) > range_list.extend( range( median, median + ( threshold + 1 ) ) ) > if __debug__: print "number %s, median %s, within range %s, > list %s, list length %s" % ( number, median, number in range_list, > range_list, len( range_list ) ) > if number not in range_list: return False > return True > > this works fine, but is there a simpler way of doing it? a one liner? :) This either returns True or False depending upon whether the passed in number is within threshold of the median ... something like (untested): def within_range(number, median, threshold=5): return threshold-median > Thanks, > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From emile at fenx.com Sat Jun 6 22:19:45 2009 From: emile at fenx.com (Emile van Sebille) Date: Sat, 06 Jun 2009 13:19:45 -0700 Subject: [Tutor] converting xls to csv In-Reply-To: <3a13c8e50906061307n26de74c2m2efac94b09d4cfd@mail.gmail.com> References: <3a13c8e50905302151k41e5221bj7d3d4287a1df1da@mail.gmail.com> <3a13c8e50905310209h2c2ff914g3b216b3f57e2d1@mail.gmail.com> <3a13c8e50905310248p50027487l51ac7fe2c8c5061d@mail.gmail.com> <3a13c8e50906061219o3b9d6d0fh54401775d754b730@mail.gmail.com> <3a13c8e50906061307n26de74c2m2efac94b09d4cfd@mail.gmail.com> Message-ID: On 6/6/2009 1:07 PM Nick Burgess said... > f seems to be a string containing the file names, so csv.reader isnt > actually opening them.. maybe i will play with os.walk..? > > files = glob.glob("*.csv") > Almost there... > for f in files: > print f > csv.reader(open (f), delimiter=' ', quotechar='|') you open it here, but don't save a reference to the opened file. Try... ff = csv.reader(open (f), delimiter=' ', quotechar='|') > for row in f: then here, try: for row in ff: > for cell in row: > if pattern.search(cell): > print ', '.join(row) > > > XLS.xls.org1.csv > XLS.xls.org2.csv > XLS.xls.org3.csv From the interactive interpreter, import csv, then you can ask help(csv) snipped from that you find... reader(...) csv_reader = reader(iterable [, dialect='excel'] [optional keyword args]) for row in csv_reader: process(row) HTH, Emile > > On Sat, Jun 6, 2009 at 3:33 PM, Emile van Sebille wrote: >> On 6/6/2009 12:19 PM Nick Burgess said... >>> Thank you. The data is pretty much random throughout the csv's so I >>> think I it would have to iterate over the entire rows . I need to >>> search all .csv files in the current directory. I can get glob to >>> return a list of files. How could I get csv.reader to open all the >>> files in the list? >> Open the files from within your loop. >> >>> My loop logic must be bad.. I am using >>> ActivePython 2.6.1.1. Any clues would be appreciated. >>> >>> >>> >>> pattern = re.compile(r'10\.191\.239\.0') >>> files = glob.glob("*.csv") >>> >>> csv.reader(open (files), delimiter=' ', quotechar='|') >>> for f in files: >> do the open here >> >>> for row in f: >>> for cell in row: >>> if pattern.search(cell): >>> print ', '.join(row) >>> >> >> Emile >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From e_mitges at hotmail.com Sat Jun 6 22:20:29 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Sat, 6 Jun 2009 16:20:29 -0400 Subject: [Tutor] gui problem Message-ID: from math import sin, cos, pi import pygame displayWidth = 640displayHeight = 480fpsLimit = 90 def sinInterpolation(start, end, steps=30): values = [start] delta = end - start for i in range(1, steps): n = (pi / 2.0) * (i / float(steps - 1)) values.append(start + delta * sin(n)) return values class RotatingMenu: def __init__(self, x, y, radius, arc=pi*2, defaultAngle=0, wrap=False): """ @param x: The horizontal center of this menu in pixels. @param y: The vertical center of this menu in pixels. @param radius: The radius of this menu in pixels(note that this is the size of the circular path in which the elements are placed, the actual size of the menu may vary depending on item sizes. @param arc: The arc in radians which the menu covers. pi*2 is a full circle. @param defaultAngle: The angle at which the selected item is found. @param wrap: Whether the menu should select the first item after the last one or stop. """ self.x = x self.y = y self.radius = radius self.arc = arc self.defaultAngle = defaultAngle self.wrap = wrap self.rotation = 0 self.rotationTarget = 0 self.rotationSteps = [] #Used for interpolation self.items = [] self.selectedItem = None self.selectedItemNumber = 0 def addItem(self, item): self.items.append(item) if len(self.items) == 1: self.selectedItem = item def selectItem(self, itemNumber): if self.wrap == True: if itemNumber> len(self.items) - 1: itemNumber = 0 if itemNumber < 0: itemNumber = len(self.items) - 1 else: itemNumber = min(itemNumber, len(self.items) - 1) itemNumber = max(itemNumber, 0) self.selectedItem.deselect() self.selectedItem = self.items[itemNumber] self.selectedItem.select() self.selectedItemNumber = itemNumber self.rotationTarget = - self.arc * (itemNumber / float(len(self.items) - 1)) self.rotationSteps = sinInterpolation(self.rotation, self.rotationTarget, 45) def rotate(self, angle): """@param angle: The angle in radians by which the menu is rotated. """ for i in range(len(self.items)): item = self.items[i] n = i / float(len(self.items) - 1) rot = self.defaultAngle + angle + self.arc * n item.x = self.x + cos(rot) * self.radius item.y = self.y + sin(rot) * self.radius def update(self): if len(self.rotationSteps)> 0: self.rotation = self.rotationSteps.pop(0) self.rotate(self.rotation) def draw(self, display): """@param display: A pyGame display object """ for item in self.items: item.draw(display) class MenuItem: def __init__(self, text="Option"): self.text = text self.defaultColor = (255,255,255) self.selectedColor = (255,0,0) self.color = self.defaultColor self.x = 0 self.y = 0 #The menu will edit these self.font = pygame.font.Font(None, 20) self.image = self.font.render(self.text, True, self.color) size = self.font.size(self.text) self.xOffset = size[0] / 2 self.yOffset = size[1] / 2 def select(self): """Just visual stuff""" self.color = self.selectedColor self.redrawText() def deselect(self): """Just visual stuff""" self.color = self.defaultColor self.redrawText() def redrawText(self): self.font = pygame.font.Font(None, 20) self.image = self.font.render(self.text, True, self.color) size = self.font.size(self.text) self.xOffset = size[0] / 2 self.yOffset = size[1] / 2 def draw(self, display): display.blit(self.image, (self.x-self.xOffset, self.y-self.yOffset)) def main(): pygame.init() display = pygame.display.set_mode((displayWidth, displayHeight)) clock = pygame.time.Clock() menu = RotatingMenu(x=320, y=240, radius=220, arc=pi, defaultAngle=pi/2.0) for i in range(4): menu.addItem(MenuItem("Option" + str(i))) menu.selectItem(0) #Loop while True: #Handle events events = pygame.event.get() for event in events: if event.type == pygame.QUIT: return False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: menu.selectItem(menu.selectedItemNumber + 1) if event.key == pygame.K_RIGHT: menu.selectItem(menu.selectedItemNumber - 1) #Update stuff menu.update() #Draw stuff display.fill((0,0,0)) menu.draw(display) pygame.display.flip() #Show the updated scene clock.tick(fpsLimit) #Wait a little if __name__ == "__main__": main() I want to change this menu so I can use my own background in .png 800x532 and add 4 buttons 175x40 in .png one that initiates a .py called Guns.pyone that links you to a highscores.txt file thats read onlyone that links you to another .png file with the ability to go back to the main menuOne that terminates the window _________________________________________________________________ Attention all humans. We are your photos. Free us. http://go.microsoft.com/?linkid=9666046 -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Sat Jun 6 22:39:47 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 6 Jun 2009 22:39:47 +0200 Subject: [Tutor] converting xls to csv In-Reply-To: References: <3a13c8e50905302151k41e5221bj7d3d4287a1df1da@mail.gmail.com> <3a13c8e50905310209h2c2ff914g3b216b3f57e2d1@mail.gmail.com> <3a13c8e50905310248p50027487l51ac7fe2c8c5061d@mail.gmail.com> <3a13c8e50906061219o3b9d6d0fh54401775d754b730@mail.gmail.com> <3a13c8e50906061307n26de74c2m2efac94b09d4cfd@mail.gmail.com> Message-ID: 2009/6/6 Emile van Sebille : >> for f in files: >> ? ?print f >> ? ?csv.reader(open (f), delimiter=' ', quotechar='|') > > you open it here, but don't save a reference to the opened file. ?Try... > ? ? ?ff = csv.reader(open (f), delimiter=' ', quotechar='|') > ? ?reader(...) > ? ? ? ?csv_reader = reader(iterable [, dialect='excel'] > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[optional keyword args]) > ? ? ? ? ? ?for row in csv_reader: > ? ? ? ? ? ? ? ?process(row) If you are on windows you should open the file in binary mode. open(f, 'rb') Greets Sander From burgess.nick at gmail.com Sat Jun 6 23:37:52 2009 From: burgess.nick at gmail.com (Nick Burgess) Date: Sat, 6 Jun 2009 17:37:52 -0400 Subject: [Tutor] converting xls to csv In-Reply-To: References: <3a13c8e50905302151k41e5221bj7d3d4287a1df1da@mail.gmail.com> <3a13c8e50905310209h2c2ff914g3b216b3f57e2d1@mail.gmail.com> <3a13c8e50905310248p50027487l51ac7fe2c8c5061d@mail.gmail.com> <3a13c8e50906061219o3b9d6d0fh54401775d754b730@mail.gmail.com> <3a13c8e50906061307n26de74c2m2efac94b09d4cfd@mail.gmail.com> Message-ID: <3a13c8e50906061437v37afab47p911267e003050693@mail.gmail.com> Thanks everyone, the following code works great. It returns the name of the file and the row that matched the reqex. Is it posible to take the regex compile from user input? To make it take an argument, like > csvSearch.py 10.192.55 af = re.compile(sys.argv[1]) pattern = re.compile(af) ....? pattern = re.compile(r'10\.191\.2') files = glob.glob("*.csv") for f in files: ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') for row in f: for row in ff: for cell in row: if pattern.search(cell): print f print ', '.join(row) On Sat, Jun 6, 2009 at 4:39 PM, Sander Sweers wrote: > 2009/6/6 Emile van Sebille : >>> for f in files: >>> ? ?print f >>> ? ?csv.reader(open (f), delimiter=' ', quotechar='|') >> >> you open it here, but don't save a reference to the opened file. ?Try... >> ? ? ?ff = csv.reader(open (f), delimiter=' ', quotechar='|') > > > >> ? ?reader(...) >> ? ? ? ?csv_reader = reader(iterable [, dialect='excel'] >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[optional keyword args]) >> ? ? ? ? ? ?for row in csv_reader: >> ? ? ? ? ? ? ? ?process(row) > > If you are on windows you should open the file in binary mode. > ?open(f, 'rb') > > Greets > Sander > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From sander.sweers at gmail.com Sun Jun 7 00:54:44 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sun, 7 Jun 2009 00:54:44 +0200 Subject: [Tutor] converting xls to csv In-Reply-To: <3a13c8e50906061437v37afab47p911267e003050693@mail.gmail.com> References: <3a13c8e50905302151k41e5221bj7d3d4287a1df1da@mail.gmail.com> <3a13c8e50905310209h2c2ff914g3b216b3f57e2d1@mail.gmail.com> <3a13c8e50905310248p50027487l51ac7fe2c8c5061d@mail.gmail.com> <3a13c8e50906061219o3b9d6d0fh54401775d754b730@mail.gmail.com> <3a13c8e50906061307n26de74c2m2efac94b09d4cfd@mail.gmail.com> <3a13c8e50906061437v37afab47p911267e003050693@mail.gmail.com> Message-ID: 2009/6/6 Nick Burgess : > Is it posible to take > the regex compile from user input? ?To make it take an argument, ?like > >> csvSearch.py 10.192.55 You can use raw_inpout() see [1] for the docs user_input = raw_input('Please provide input') Greets Sander [1] http://docs.python.org/library/functions.html#raw_input From alan.gauld at btinternet.com Sun Jun 7 00:57:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Jun 2009 23:57:06 +0100 Subject: [Tutor] creating a range above & below a given number References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> Message-ID: "Gonzalo Garcia-Perate" wrote > Hello tutor, What's the simplest way of creating a list with a range > of numbers above and below a given number? > ... > this works fine, but is there a simpler way of doing it? a one liner? :) I'd probably use a list comprehesion: L = [n for n in range(lower, upper+!) if n < median-threshold or n > medianthreshold] eg: >>> [n for n in range(5,21) if n < 10 or n > 16] [5, 6, 7, 8, 9, 17, 18, 19, 20] >>> HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dkuhlman at rexx.com Sun Jun 7 02:55:33 2009 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 6 Jun 2009 17:55:33 -0700 Subject: [Tutor] python workspace In-Reply-To: <333efb450906021440j43472538i5c555d5027ca7c26@mail.gmail.com> References: <4A256FC5.60601@ieee.org> <333efb450906021440j43472538i5c555d5027ca7c26@mail.gmail.com> Message-ID: <20090607005533.GA50323@cutter.rexx.com> On Tue, Jun 02, 2009 at 04:40:43PM -0500, W W wrote: > > On Tue, Jun 2, 2009 at 1:30 PM, Dave Angel <[1]davea at ieee.org> wrote: > > You could use the commercial Komodo IDE. It's got a debugger that > runs the Python code as a separate process, so it can be used for > GUI debugging as well as console work. I use it with wxPython, and > Python 2.6.2 > [3]http://www.activestate.com/komodo/ > > Wingware also has a commercial IDE, and most of the functionality is > included in the free student/personal use version. They were also > generous enough to donate I think it was 4 or 8 commercial licensees > to our PyArkansas un-conference. I played around with it a bit and it > seemed like quite a solid IDE. > HTH, > Wayne On Linux, try the Eric IDE: http://eric-ide.python-projects.org/ It will show you local variables. But, remember that these are the local variables at *run-time*. They are names to which values have been bound at that point in the execution of your code. And, as Alan pointed out elsewhere in this thread, the variable has no type. It's the value (what the variable is bound to) that has a type. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From kent37 at tds.net Sun Jun 7 06:04:42 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Jun 2009 00:04:42 -0400 Subject: [Tutor] gui problem In-Reply-To: References: Message-ID: <1c2a2c590906062104m5b7777b2w936a12f8b2e58a49@mail.gmail.com> Can you try that again? Kent On Sat, Jun 6, 2009 at 4:20 PM, Essah Mitges wrote: > > from math import sin, cos, pi import pygame displayWidth = 640displayHeight > = 480fpsLimit = 90 def sinInterpolation(start, end, steps=30):?? ?values = > [start]?? ?delta = end - start?? ?for i in range(1, steps):?? ? ? ?n = (pi / > 2.0) * (i / float(steps - 1))?? ? ? ?values.append(start + delta * sin(n)) > ?return values class RotatingMenu:?? ?def __init__(self, x, y, radius, > arc=pi*2, defaultAngle=0, wrap=False):?? ? ? ?"""?? ? ? ?@param x: > ?The horizontal center of this menu in pixels.?? ? ? ??? ? ? ?@param y: > ? ? ? ?The vertical center of this menu in pixels.?? ? ? ??? ? ? ?@param > radius:?? ? ? ? ? ?The radius of this menu in pixels(note that this is the > size of?? ? ? ? ? ?the circular path in which the elements are placed, the > actual?? ? ? ? ? ?size of the menu may vary depending on item sizes. > ?@param arc:?? ? ? ? ? ?The arc in radians which the menu covers. pi*2 is a > full circle.?? ? ? ??? ? ? ?@param defaultAngle:?? ? ? ? ? ?The angle at > which the selected item is found.?? ? ? ??? ? ? ?@param wrap: > ?Whether the menu should select the first item after the last one > ?or stop.?? ? ? ?"""?? ? ? ?self.x = x?? ? ? ?self.y = y?? ? ? ?self.radius > = radius?? ? ? ?self.arc = arc?? ? ? ?self.defaultAngle = defaultAngle > ?self.wrap = wrap?? ? ? ??? ? ? ?self.rotation = 0 > ?self.rotationTarget = 0?? ? ? ?self.rotationSteps = [] #Used for > interpolation?? ? ? ??? ? ? ?self.items = []?? ? ? ?self.selectedItem = > None?? ? ? ?self.selectedItemNumber = 0?? ??? ?def addItem(self, item): > ? ?self.items.append(item)?? ? ? ?if len(self.items) == 1: > ?self.selectedItem = item?? ??? ?def selectItem(self, itemNumber):?? ? ? ?if > self.wrap == True:?? ? ? ? ? ?if itemNumber> len(self.items) - 1: itemNumber > = 0?? ? ? ? ? ?if itemNumber < 0: itemNumber = len(self.items) - 1 > ?else:?? ? ? ? ? ?itemNumber = min(itemNumber, len(self.items) - 1) > ? ?itemNumber = max(itemNumber, 0) > ?self.selectedItem.deselect()?? ? ? ?self.selectedItem = > self.items[itemNumber]?? ? ? ?self.selectedItem.select() > ?self.selectedItemNumber = itemNumber?? ? ? ??? ? ? ?self.rotationTarget = - > self.arc * (itemNumber / float(len(self.items) - 1)) > ?self.rotationSteps = sinInterpolation(self.rotation, > ? ? ? ? ? ? ? ? ? ? ? ?self.rotationTarget, 45)?? ??? ?def rotate(self, > angle):?? ? ? ?"""@param angle: The angle in radians by which the menu is > rotated.?? ? ? ?"""?? ? ? ?for i in range(len(self.items)):?? ? ? ? ? ?item > = self.items[i]?? ? ? ? ? ?n = i / float(len(self.items) - 1)?? ? ? ? ? ?rot > = self.defaultAngle + angle + self.arc * n?? ? ? ? ? ??? ? ? ? ? ?item.x = > self.x + cos(rot) * self.radius?? ? ? ? ? ?item.y = self.y + sin(rot) * > self.radius?? ??? ?def update(self):?? ? ? ?if len(self.rotationSteps)> 0: > ? ? ? ? ?self.rotation = self.rotationSteps.pop(0) > ?self.rotate(self.rotation)?? ??? ?def draw(self, display):?? ? ? ?"""@param > display: A pyGame display object?? ? ? ?"""?? ? ? ?for item in self.items: > ? ? ? ? ?item.draw(display) class MenuItem:?? ?def __init__(self, > text="Option"):?? ? ? ?self.text = text?? ? ? ??? ? ? ?self.defaultColor = > (255,255,255)?? ? ? ?self.selectedColor = (255,0,0)?? ? ? ?self.color = > self.defaultColor?? ? ? ??? ? ? ?self.x = 0?? ? ? ?self.y = 0 #The menu will > edit these?? ? ? ??? ? ? ?self.font = pygame.font.Font(None, 20) > ?self.image = self.font.render(self.text, True, self.color)?? ? ? ?size = > self.font.size(self.text)?? ? ? ?self.xOffset = size[0] / 2 > ?self.yOffset = size[1] / 2?? ??? ?def select(self):?? ? ? ?"""Just visual > stuff"""?? ? ? ?self.color = self.selectedColor?? ? ? ?self.redrawText() > ??? ?def deselect(self):?? ? ? ?"""Just visual stuff"""?? ? ? ?self.color = > self.defaultColor?? ? ? ?self.redrawText()?? ??? ?def redrawText(self): > ? ?self.font = pygame.font.Font(None, 20)?? ? ? ?self.image = > self.font.render(self.text, True, self.color)?? ? ? ?size = > self.font.size(self.text)?? ? ? ?self.xOffset = size[0] / 2 > ?self.yOffset = size[1] / 2?? ??? ?def draw(self, display): > ?display.blit(self.image, (self.x-self.xOffset, self.y-self.yOffset)) def > main():?? ?pygame.init()?? ??? ?display = > pygame.display.set_mode((displayWidth, displayHeight))?? ?clock = > pygame.time.Clock()?? ??? ?menu = RotatingMenu(x=320, y=240, radius=220, > arc=pi, defaultAngle=pi/2.0)?? ??? ?for i in range(4): > ?menu.addItem(MenuItem("Option" + str(i)))?? ?menu.selectItem(0) > ?#Loop?? ?while True:?? ? ? ?#Handle events?? ? ? ?events = > pygame.event.get()?? ? ? ?for event in events:?? ? ? ? ? ?if event.type == > pygame.QUIT:?? ? ? ? ? ? ? ?return False?? ? ? ? ? ?if event.type == > pygame.KEYDOWN:?? ? ? ? ? ? ? ?if event.key == pygame.K_LEFT: > ? ? ?menu.selectItem(menu.selectedItemNumber + 1)?? ? ? ? ? ? ? ?if > event.key == pygame.K_RIGHT: > ?menu.selectItem(menu.selectedItemNumber - 1)?? ? ? ??? ? ? ?#Update stuff > ? ? ?menu.update()?? ? ? ??? ? ? ?#Draw stuff?? ? ? ?display.fill((0,0,0)) > ? ? ?menu.draw(display)?? ? ? ?pygame.display.flip() #Show the updated > scene?? ? ? ?clock.tick(fpsLimit) #Wait a little if __name__ == > "__main__":?? ?main() I want to change this menu so I can use my own > background in .png 800x532 and add 4 buttons 175x40 in .png one that > initiates a .py called Guns.pyone that links you to a highscores.txt file > thats read onlyone that links you to another .png file with the ability to > go back to the main menuOne that terminates the window > ________________________________ > Attention all humans. We are your photos. Free us. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Sun Jun 7 06:11:44 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Jun 2009 00:11:44 -0400 Subject: [Tutor] converting xls to csv In-Reply-To: <3a13c8e50906061437v37afab47p911267e003050693@mail.gmail.com> References: <3a13c8e50905302151k41e5221bj7d3d4287a1df1da@mail.gmail.com> <3a13c8e50905310209h2c2ff914g3b216b3f57e2d1@mail.gmail.com> <3a13c8e50905310248p50027487l51ac7fe2c8c5061d@mail.gmail.com> <3a13c8e50906061219o3b9d6d0fh54401775d754b730@mail.gmail.com> <3a13c8e50906061307n26de74c2m2efac94b09d4cfd@mail.gmail.com> <3a13c8e50906061437v37afab47p911267e003050693@mail.gmail.com> Message-ID: <1c2a2c590906062111p39d72828t4bfa55fbe21132e2@mail.gmail.com> On Sat, Jun 6, 2009 at 5:37 PM, Nick Burgess wrote: > Thanks everyone, the following code works great. ?It returns the name > of the file and the row that matched the reqex. ?Is it posible to take > the regex compile from user input? ?To make it take an argument, ?like > >> csvSearch.py 10.192.55 > > af = re.compile(sys.argv[1]) > pattern = re.compile(af) ? ? ? ? ?....? You only have to compile it once, but you should escape it so . becomes \. like this: pattern = re.compile(re.escape(sys.argv[1]) > pattern = re.compile(r'10\.191\.2') > files = glob.glob("*.csv") > > for f in files: > ? ?ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') > ? ?for row in f: You don't need the above, it is iterating over the characters of the file name. > ? ? ? ?for row in ff: > ? ? ? ? ? ?for cell in row: > ? ? ? ? ? ? ? ?if pattern.search(cell): The above two lines can be written as if any(pattern.search(cell) for cell in row): Kent From wescpy at gmail.com Sun Jun 7 07:10:10 2009 From: wescpy at gmail.com (wesley chun) Date: Sat, 6 Jun 2009 22:10:10 -0700 Subject: [Tutor] Need better understanding of **kwargs In-Reply-To: References: <9356b9f30906061044i4ded250fif3b387e64a11700d@mail.gmail.com> Message-ID: <78b3a9580906062210i78165f81r93efd0ef9f746393@mail.gmail.com> >> Hello, I thought I understood **kwargs until I stumbled with this >> function: >> >> def changeflexion(myword, mytag, **dicty): >> : >> >> but when I import the module and call: >> a = conjugate.changeflexion('estaban', 'VLFin', conjugate.mydict) >> I get this error: >> TypeError: changeflexion() takes exactly 2 arguments (3 given) >> Isn't the 3rd argument supposed to be a dictionary? > > No, **dicty means the function takes zero or more keyword parameters: > >>>> def f(a,b,**k): > > ... ?print a,b,k > ... >>>> >>>> f(1,2) # no keyword parameters > > 1 2 {} >>>> >>>> f(1,2,c=3) # one keyword parameter > > 1 2 {'c': 3} >>>> >>>> f(1,2,{'c':3}) # a dictionary > > Traceback (most recent call last): > ?File "", line 1, in > TypeError: f() takes exactly 2 arguments (3 given) > > But there is a syntax to pass keyword arguments as a dictionary: > >>>> f(1,2,**{'c':3}) > > 1 2 {'c': 3} bob and mark are both correct, in their own special way. :-) what they really meant to say is something like this: 1. if your entire purpose of the function is to accept a dictionary of values and process them like you do in your function, there's no need to make it a kwargs dict. as bob suggested, you can just remove the "**" and keep the rest as-is. 2. however, if you're calling the function where there are a variable number of keyword arguments, like mark's example: f('foo', 20, c=3, d=4, g='bar') f('boo', -10, e=2.718, pi=3.14) f('one', 'two', d=-40, e=2.718) ...where both the number of arguments may vary, or if the names may vary, i.e., (c,d,g) vs. (e, pi) vs. (d, e), etc., then this is more of a correct use case for a **kwargs variable. it's whole purpose is for keyword arguments and not necessarily a mechanism to pass a dictionary to a function even though you can do it. one exception is when you're trying to cascade a kwargs dictionary to begin with, IOW, you're trying to continue to pass it on to yet another function: def f1(...., **kwargs): : def f2(...., **kwargs): : if 'bar' not in kwargs: # add another value to kwargs kwargs['bar'] = 'foo' rv = f1(..., **kwargs) # process by passing to f1() hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From sander.sweers at gmail.com Sun Jun 7 16:04:18 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sun, 07 Jun 2009 16:04:18 +0200 Subject: [Tutor] converting xls to csv In-Reply-To: References: <3a13c8e50905302151k41e5221bj7d3d4287a1df1da@mail.gmail.com> <3a13c8e50905310209h2c2ff914g3b216b3f57e2d1@mail.gmail.com> <3a13c8e50905310248p50027487l51ac7fe2c8c5061d@mail.gmail.com> <3a13c8e50906061219o3b9d6d0fh54401775d754b730@mail.gmail.com> <3a13c8e50906061307n26de74c2m2efac94b09d4cfd@mail.gmail.com> <3a13c8e50906061437v37afab47p911267e003050693@mail.gmail.com> Message-ID: <1244383458.18910.9.camel@infirit.homelinux.org> On Sun, 2009-06-07 at 00:54 +0200, Sander Sweers wrote: > 2009/6/6 Nick Burgess : > > Is it posible to take > > the regex compile from user input? To make it take an argument, like > > > >> csvSearch.py 10.192.55 > > You can use raw_input() see [1] for the docs > user_input = raw_input('Please provide input') Ugh, I really should not write e-mail 2 in the morning.... :( What you are looking for is command line options. Command line options are stored in sys.argv, see [1]. import sys opts = sys.argv[1:] #sys.argv[0] is filename print opts You will need to validate the input so your module does not raise an exception. If you are planning to do more advanced commandline options you should look at the optparse module [2]. Greets Sander [1] http://docs.python.org/library/sys.html#sys.argv [2] http://docs.python.org/library/optparse.html From gonzillaaa at gmail.com Sun Jun 7 16:08:32 2009 From: gonzillaaa at gmail.com (Gonzalo Garcia-Perate) Date: Sun, 7 Jun 2009 15:08:32 +0100 Subject: [Tutor] creating a range above & below a given number In-Reply-To: References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> Message-ID: <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> the solution laid somewhere in between: def within_range(self, n, n2, threshold=5): if n in range(n2-threshold, n2+threshold+1) and n < n2+threshold or n > n2 + threshold : return True return False This seems a bit more pythonic than my original function. Thank you both. 2009/6/6 Alan Gauld : > > "Gonzalo Garcia-Perate" wrote > >> Hello tutor, What's the simplest way of creating a list with a range >> of numbers above and below a given number? >> ... >> this works fine, but is there a simpler way of doing it? a one liner? ?:) > > I'd probably use a list comprehesion: > > L = [n for n in range(lower, upper+!) if n < median-threshold or ?n > > medianthreshold] > > eg: > >>>> [n for n in range(5,21) if n < 10 or n > 16] > > [5, 6, 7, 8, 9, 17, 18, 19, 20] >>>> > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From emile at fenx.com Sun Jun 7 17:44:41 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 07 Jun 2009 08:44:41 -0700 Subject: [Tutor] creating a range above & below a given number In-Reply-To: <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> Message-ID: On 6/7/2009 7:08 AM Gonzalo Garcia-Perate said... > the solution laid somewhere in between: > > def within_range(self, n, n2, threshold=5): > if n in range(n2-threshold, n2+threshold+1) and n < > n2+threshold or n > n2 + threshold : return True > return False > Be careful here -- you probably will get stung mixing ands and ors without parens. >>> print False and False or True True >>> print False and (False or True) False The range test here can only serve to verify n as an integer, so you can simplify to: def within_range(self, n, n2, threshold=5): if n == int(n) and ( n < n2+threshold or n > n2 + threshold) : return True return False Of course, the test in the function is a boolean, so you can return the result of the boolean directly and eliminate the return True and False statements: def within_range(self, n, n2, threshold=5): return n == int(n) and ( n < n2+threshold or n > n2 + threshold) Emile From emile at fenx.com Sun Jun 7 17:48:27 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 07 Jun 2009 08:48:27 -0700 Subject: [Tutor] creating a range above & below a given number In-Reply-To: References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> Message-ID: On 6/7/2009 8:44 AM Emile van Sebille said... > On 6/7/2009 7:08 AM Gonzalo Garcia-Perate said... >> the solution laid somewhere in between: >> >> def within_range(self, n, n2, threshold=5): >> if n in range(n2-threshold, n2+threshold+1) and n < >> n2+threshold or n > n2 + threshold : return True >> return False >> Besides the obvious typo you've got there and I cut and paste below. (+ threshold twice instead of +/- threshold) Emile > > Be careful here -- you probably will get stung mixing ands and ors > without parens. > > >>> print False and False or True > True > >>> print False and (False or True) > False > > > The range test here can only serve to verify n as an integer, so you can > simplify to: > > def within_range(self, n, n2, threshold=5): > if n == int(n) and ( > n < n2+threshold or n > n2 + threshold) : > return True > return False > > > Of course, the test in the function is a boolean, so you can return the > result of the boolean directly and eliminate the return True and False > statements: > > > def within_range(self, n, n2, threshold=5): > return n == int(n) and ( > n < n2+threshold or n > n2 + threshold) > > > Emile > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Jun 7 19:04:39 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Jun 2009 13:04:39 -0400 Subject: [Tutor] creating a range above & below a given number In-Reply-To: <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> Message-ID: <1c2a2c590906071004p7cf00083sd661faae5000c496@mail.gmail.com> On Sun, Jun 7, 2009 at 10:08 AM, Gonzalo Garcia-Perate wrote: > ?the solution laid somewhere in between: > > def within_range(self, n, n2, threshold=5): > ? ? ? ?if n in range(n2-threshold, n2+threshold+1) and n < > n2+threshold or n > n2 + threshold : return True > ? ? ? ?return False This is a bit strange and I doubt it does what you want: In [36]: def within_range(n, n2, threshold=5): ....: if (n in range(n2-threshold, n2+threshold+1) and n < ....: n2+threshold or n > n2 + threshold) : return True ....: return False In [37]: within_range(10, 11, 5) Out[37]: True In [38]: within_range(20, 11, 5) Out[38]: True Your conditional is equivalent to (n in range(n2-threshold, n2+threshold+1) and n < n2+threshold) or n > n2 + threshold which will be true for any n > n2 + threshold. Can you describe in words what you are trying to test? If you want to know if n is in the range n2-threshold to n2+threshold, just test it directly: if n2-threshold <= n <= n2+threshold: If you also want to ensure that n is an integer then use if n==int(n) and (n2-threshold <= n <= n2+threshold): or if isinstance(n, int) and (n2-threshold <= n <= n2+threshold): Kent From gonzillaaa at gmail.com Sun Jun 7 19:17:51 2009 From: gonzillaaa at gmail.com (Gonzalo Garcia-Perate) Date: Sun, 7 Jun 2009 18:17:51 +0100 Subject: [Tutor] creating a range above & below a given number In-Reply-To: <1c2a2c590906071004p7cf00083sd661faae5000c496@mail.gmail.com> References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> <1c2a2c590906071004p7cf00083sd661faae5000c496@mail.gmail.com> Message-ID: <6b6a049d0906071017qc899c3n51e546fbc27b85dd@mail.gmail.com> Emile, Kent thank you both for your reply, after sending my previous email I realised that it wasn't working as expected in all cases. this does work: def within_range_final(self, n, n2, threshold=5): return n in range(n2-threshold, n2+threshold+1) What I have is an ultrasound sensor that gives me a range from 0cm to 6m, what I'm testing is if the new reading goes beyond a threshold and log it subsequently. So n is the previous reading, n2 is the new reading and threshold is what I set to be a significant change, 5cm in the default case. Thanks again for your help. 2009/6/7 Kent Johnson : > On Sun, Jun 7, 2009 at 10:08 AM, Gonzalo > Garcia-Perate wrote: >> ?the solution laid somewhere in between: >> >> def within_range(self, n, n2, threshold=5): >> ? ? ? ?if n in range(n2-threshold, n2+threshold+1) and n < >> n2+threshold or n > n2 + threshold : return True >> ? ? ? ?return False > > This is a bit strange and I doubt it does what you want: > > In [36]: def within_range(n, n2, threshold=5): > ? ....: ? ? ? if (n in range(n2-threshold, n2+threshold+1) and n < > ? ....: ? ? n2+threshold or n > n2 + threshold) : return True > ? ....: ? return False > > In [37]: within_range(10, 11, 5) > Out[37]: True > > In [38]: within_range(20, 11, 5) > Out[38]: True > > Your conditional is equivalent to > (n in range(n2-threshold, n2+threshold+1) and n < n2+threshold) or n > > n2 + threshold > > which will be true for any n > n2 + threshold. > > Can you describe in words what you are trying to test? If you want to > know if n is in the range n2-threshold to n2+threshold, just test it > directly: > ?if n2-threshold <= n <= n2+threshold: > > If you also want to ensure that n is an integer then use > ?if n==int(n) and (n2-threshold <= n <= n2+threshold): > or > ?if isinstance(n, int) and (n2-threshold <= n <= n2+threshold): > > Kent > From roberto03 at gmail.com Sun Jun 7 19:48:27 2009 From: roberto03 at gmail.com (roberto) Date: Sun, 7 Jun 2009 19:48:27 +0200 Subject: [Tutor] vpython compatibility Message-ID: <4bcde3e10906071048q6f0972a5t68b2809708b54381@mail.gmail.com> hello i have a short question: is vpython usable in conjunction with python 3.0 ? i hope so, also vpython site for download doesn't issue any warning about this topic thank you -- roberto From emile at fenx.com Sun Jun 7 20:05:12 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 07 Jun 2009 11:05:12 -0700 Subject: [Tutor] vpython compatibility In-Reply-To: <4bcde3e10906071048q6f0972a5t68b2809708b54381@mail.gmail.com> References: <4bcde3e10906071048q6f0972a5t68b2809708b54381@mail.gmail.com> Message-ID: On 6/7/2009 10:48 AM roberto said... > hello > i have a short question: > is vpython usable in conjunction with python 3.0 ? > This is likely better answered by the vpython crowd -- I've not used or previously hear of vpython, but they're rather explicit on their download pages here http://vpython.org/contents/download_windows.html and here http://vpython.org/contents/download_linux.html that they recommend python 2.5 or 2.6. I'd suspect that working beyond recommended compatibilities is for the bleeding edge developers. Most of Python3 still falls in that arena. Emile > i hope so, also vpython site for download doesn't issue any warning > about this topic > > thank you > From e_mitges at hotmail.com Sun Jun 7 20:36:10 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Sun, 7 Jun 2009 14:36:10 -0400 Subject: [Tutor] gui menu Message-ID: import sys, pygame pygame.init() background = pygame.image.load(""My png image 800x 532) backgroundRect = background.get_rect() size = (width, height) = background.get.size() screen = pygame.display.set_mode(size) screen.blit(background, backgroundRect) pygame.display.flip() I want to use pygame to create 4 buttons from 175x67 png image one button that initiates the Team.py fileone button that links to read a hs.txtone button that initiates 800x532 png image in a new windowone button that quits pygame window _________________________________________________________________ Windows Live helps you keep up with all your friends, in one place. http://go.microsoft.com/?linkid=9660826 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Jun 7 21:32:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Jun 2009 15:32:18 -0400 Subject: [Tutor] creating a range above & below a given number In-Reply-To: <6b6a049d0906071017qc899c3n51e546fbc27b85dd@mail.gmail.com> References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> <1c2a2c590906071004p7cf00083sd661faae5000c496@mail.gmail.com> <6b6a049d0906071017qc899c3n51e546fbc27b85dd@mail.gmail.com> Message-ID: <1c2a2c590906071232j744499acl6f606b5da974492d@mail.gmail.com> On Sun, Jun 7, 2009 at 1:17 PM, Gonzalo Garcia-Perate wrote: > Emile, Kent thank you both for your reply, after sending my previous > email I realised that it wasn't working as expected in all cases. > > this does work: > > def within_range_final(self, n, n2, threshold=5): > ? ? return n in range(n2-threshold, n2+threshold+1) > > What I have is an ultrasound sensor that gives me a range from 0cm to > 6m, what I'm testing is if the new reading goes beyond a threshold and > log it subsequently. So n is the previous reading, n2 is the new > reading and threshold is what I set to be a significant change, 5cm in > the default case. So why not use simple conditionals? You may not realize that range(a, b) creates a new list and 'n in range(a, b)' seaches the list for n. Numeric comparisons are much less work and also express your intent clearly. Kent From emile at fenx.com Sun Jun 7 21:34:51 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 07 Jun 2009 12:34:51 -0700 Subject: [Tutor] creating a range above & below a given number In-Reply-To: <6b6a049d0906071017qc899c3n51e546fbc27b85dd@mail.gmail.com> References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> <1c2a2c590906071004p7cf00083sd661faae5000c496@mail.gmail.com> <6b6a049d0906071017qc899c3n51e546fbc27b85dd@mail.gmail.com> Message-ID: On 6/7/2009 10:17 AM Gonzalo Garcia-Perate said... > Emile, Kent thank you both for your reply, after sending my previous > email I realised that it wasn't working as expected in all cases. > > this does work: > > def within_range_final(self, n, n2, threshold=5): > return n in range(n2-threshold, n2+threshold+1) To explain why we've tended to suggest using int and minvalpython timeit.py "6 in range(10)" 1000000 loops, best of 3: 1.22 usec per loop C:\Python26\Lib>python timeit.py "0< 6 < 10 and 6==int(6)" 1000000 loops, best of 3: 0.676 usec per loop C:\Python26\Lib>python timeit.py "0< 6 < 10 and isinstance(6,int)" 1000000 loops, best of 3: 0.526 usec per loop Granted, it only takes twice as long, and it's certainly not a long time, but the point is that there is a time penalty you're paying to construct the range object, then pass it one at a time to test for inclusion, only to immediately have the construct pass out of scope and be garbage collected. Those who've worked with python over time tend to favor constructs and idioms that perform better as a matter of course. Further, as the threshold range increases, the difference becomes more noticeable. For example, testing with 100 and 1000 : C:\Python26\Lib>python timeit.py "0< 6 < 100 and isinstance(6,int)" 1000000 loops, best of 3: 0.532 usec per loop C:\Python26\Lib>python timeit.py "6 in range(100)" 100000 loops, best of 3: 2.52 usec per loop C:\Python26\Lib>python timeit.py "6 in range(1000)" 100000 loops, best of 3: 19.1 usec per loop C:\Python26\Lib>python timeit.py "0< 6 < 1000 and isinstance(6,int)" 1000000 loops, best of 3: 0.527 usec per loop Emile From alan.gauld at btinternet.com Sun Jun 7 23:24:15 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 Jun 2009 22:24:15 +0100 Subject: [Tutor] gui menu References: Message-ID: "Essah Mitges" wrote > import sys, pygame > pygame.init() > background = pygame.image.load(""My png image 800x 532) > backgroundRect = background.get_rect() > size = (width, height) = background.get.size() > screen = pygame.display.set_mode(size) > screen.blit(background, backgroundRect) > pygame.display.flip() > I want to use pygame to create 4 buttons from 175x67 png image I dont know what you are using for email but it seems to be scrambling your messages. I assume what you want is: > one button that initiates the Team.py file > one button that links to read a hs.txt > one button that initiates 800x532 png image in a new window > one button that quits pygame window Now, I'm no expert on pygame but can you tell us more specifically what you are finding so hard about putting your 4 buttons on the image? It is creating the button objects or is it linking them to the functions? Or is it displaying them using the image? The more specific your question the more likely that someone will answer it. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Jun 7 23:48:55 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 7 Jun 2009 21:48:55 +0000 (GMT) Subject: [Tutor] gui menu In-Reply-To: References: Message-ID: <57668.68110.qm@web86711.mail.ird.yahoo.com> Forwarding to group. Please use Reply All when responding to the tutor group. Thanks for the extra information it is helpful. From: Essah Mitges To: alan.gauld at btinternet.com Sent: Sunday, 7 June, 2009 10:32:27 PM Subject: RE: [Tutor] gui menu http://osdir.com/ml/python.pygame/2002-11/msg00051.html I'm using this to try to program the buttons I'm tying to make 4 class to make a module called but.py When i tryed putting a quit button on the menu the error Traceback (most recent call last): File "C:\Users\John Doe\Desktop\WODDS2\data\back.py", line 17, in qbut = QButton(175,67,"Quit.png") File "C:\Users\John Doe\Desktop\WODDS2\data\but.py", line 102, in __init__ self.insideimg = pygame.image.load(imagefile).convert_alpha() error: No video mode has been set The thing is that I can't start my Team.py from this menu and once it is started I want the menu to exit I can't start a new window if another button is pressed and have esc as the exit key I can't make the button that displays a read only text file > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Sun, 7 Jun 2009 22:24:15 +0100 > Subject: Re: [Tutor] gui menu > > "Essah Mitges" wrote > >> import sys, pygame >> pygame.init() >> background = pygame.image.load(""My png image 800x 532) >> backgroundRect = background.get_rect() >> size = (width, height) = background.get.size() >> screen = pygame.display.set_mode(size) >> screen.blit(background, backgroundRect) >> pygame.display.flip() >> I want to use pygame to create 4 buttons from 175x67 png image > > I dont know what you are using for email but it seems to be > scrambling your messages. I assume what you want is: > >> one button that initiates the Team.py file >> one button that links to read a hs.txt >> one button that initiates 800x532 png image in a new window >> one button that quits pygame window > > Now, I'm no expert on pygame but can you tell us more > specifically what you are finding so hard about putting > your 4 buttons on the image? > > It is creating the button objects or is it linking them to the functions? > Or is it displaying them using the image? > > The more specific your question the more likely that someone > will answer it. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor ________________________________ Windows Live helps you keep up with all your friends, in one place. -------------- next part -------------- An HTML attachment was scrubbed... URL: From e_mitges at hotmail.com Mon Jun 8 02:49:45 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Sun, 7 Jun 2009 20:49:45 -0400 Subject: [Tutor] gui menu In-Reply-To: <57668.68110.qm@web86711.mail.ird.yahoo.com> References: <57668.68110.qm@web86711.mail.ird.yahoo.com> Message-ID: read bottom Date: Sun, 7 Jun 2009 21:48:55 +0000 From: alan.gauld at btinternet.com Subject: Re: [Tutor] gui menu To: e_mitges at hotmail.com CC: tutor at python.org Forwarding to group. Please use Reply All when responding to the tutor group. Thanks for the extra information it is helpful. From: Essah Mitges To: alan.gauld at btinternet.com Sent: Sunday, 7 June, 2009 10:32:27 PM Subject: RE: [Tutor] gui menu http://osdir.com/ml/python.pygame/2002-11/msg00051.htmlI'm using this to try to program the buttons I'm tying to make 4 class to make a module called but.pyWhen i tryed putting a quit button on the menu the errorTraceback (most recent call last): File "C:\Users\John Doe\Desktop\WODDS2\data\back.py", line 17, in qbut = QButton(175,67,"Quit.png") File "C:\Users\John Doe\Desktop\WODDS2\data\but.py", line 102, in __init__ self.insideimg = pygame.image.load(imagefile).convert_alpha()error: No video mode has been setThe thing is that I can't start my Team.py from this menu and once it is started I want the menu to exitI can't start a new window if another button is pressed and have esc as the exit keyI can't make the button that displays a read only text file > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Sun, 7 Jun 2009 22:24:15 +0100 > Subject: Re: [Tutor] gui menu > > "Essah Mitges" wrote > >> import sys, pygame >> pygame.init() >> background = pygame.image.load(""My png image 800x 532) >> backgroundRect = background.get_rect() >> size = (width, height) = background.get.size() >> screen = pygame.display.set_mode(size) >> screen.blit(background, backgroundRect) >> pygame.display.flip() >> I want to use pygame to create 4 buttons from 175x67 png image > > I dont know what you are using for email but it seems to be > scrambling your messages. I assume what you want is: > >> one button that initiates the Team.py file >> one button that links to read a hs.txt >> one button that initiates 800x532 png image in a new window >> one button that quits pygame window > > Now, I'm no expert on pygame but can you tell us more > specifically what you are finding so hard about putting > your 4 buttons on the image? > > It is creating the button objects or is it linking them to the functions? > Or is it displaying them using the image? > > The more specific your question the more likely that someone > will answer it. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Windows Live helps you keep up with all your friends, in one place. _________________________________________________________________ We are your photos. Share us now with Windows Live Photos. http://go.microsoft.com/?linkid=9666047 -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Mon Jun 8 03:37:48 2009 From: david at abbottdavid.com (David) Date: Sun, 07 Jun 2009 21:37:48 -0400 Subject: [Tutor] What is this kind of loop called Message-ID: <4A2C6B6C.3080507@abbottdavid.com> In one of my questions to this list, Kent explained to me how to use a loop like this; #!/usr/bin/python from time import sleep def get(numbers): print 'Calling ', numbers sleep(1) print 'Connected ' sleep(1) def call_numbers(): for i in range(9549355543, 9549355560): numbers = i get(numbers) call_numbers() Is there a technical name for a loop like this? thanks -david -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From bgailer at gmail.com Mon Jun 8 04:08:13 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 07 Jun 2009 22:08:13 -0400 Subject: [Tutor] What is this kind of loop called In-Reply-To: <4A2C6B6C.3080507@abbottdavid.com> References: <4A2C6B6C.3080507@abbottdavid.com> Message-ID: <4A2C728D.2010103@gmail.com> David wrote: > In one of my questions to this list, Kent explained to me how to use a > loop like this; > > #!/usr/bin/python > from time import sleep > > def get(numbers): > print 'Calling ', numbers > sleep(1) > print 'Connected ' > sleep(1) > > def call_numbers(): > for i in range(9549355543, 9549355560): > numbers = i > get(numbers) > call_numbers() > > Is there a technical name for a loop like this? For loop? That is what I call it. -- Bob Gailer Chapel Hill NC 919-636-4239 From david at abbottdavid.com Mon Jun 8 04:53:45 2009 From: david at abbottdavid.com (David) Date: Sun, 07 Jun 2009 22:53:45 -0400 Subject: [Tutor] [Fwd: Re: What is this kind of loop called] Message-ID: <4A2C7D39.5050606@abbottdavid.com> Forwarding to the list, forgot again :( -- Powered by Gentoo GNU/Linux http://linuxcrazy.com -------------- next part -------------- An embedded message was scrubbed... From: David Subject: Re: [Tutor] What is this kind of loop called Date: Sun, 07 Jun 2009 22:52:38 -0400 Size: 1281 URL: From kent37 at tds.net Mon Jun 8 04:56:22 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 7 Jun 2009 22:56:22 -0400 Subject: [Tutor] creating a range above & below a given number In-Reply-To: References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> <1c2a2c590906071004p7cf00083sd661faae5000c496@mail.gmail.com> <6b6a049d0906071017qc899c3n51e546fbc27b85dd@mail.gmail.com> Message-ID: <1c2a2c590906071956h70a47705n83705455966b4447@mail.gmail.com> On Sun, Jun 7, 2009 at 3:34 PM, Emile van Sebille wrote: > To explain why we've tended to suggest using int and minval tests and avoid the range inclusion test, consider the following timeit > results: The performance penalty for 'in range(...)' is even greater when the value is not found, because the entire list must be searched: kent $ python -m timeit "0 <= 6000 <= 1000" 10000000 loops, best of 3: 0.111 usec per loop kent $ python -m timeit "6 in range(100)" 100000 loops, best of 3: 1.89 usec per loop kent $ python -m timeit "6000 in range(100)" 100000 loops, best of 3: 5.55 usec per loop kent $ python -m timeit "6 in range(1000)" 100000 loops, best of 3: 19 usec per loop kent $ python -m timeit "6000 in range(1000)" 10000 loops, best of 3: 55.4 usec per loop Kent From rabidpoobear at gmail.com Mon Jun 8 06:48:43 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 07 Jun 2009 23:48:43 -0500 Subject: [Tutor] [Fwd: Re: What is this kind of loop called] In-Reply-To: <4A2C7D39.5050606@abbottdavid.com> References: <4A2C7D39.5050606@abbottdavid.com> Message-ID: <4A2C982B.9060608@gmail.com> >>> >>> def get(numbers): >>> print 'Calling ', numbers >>> sleep(1) >>> print 'Connected ' >>> sleep(1) >>> >>> def call_numbers(): >>> for i in range(9549355543, 9549355560): >>> numbers = i >>> get(numbers) >>> call_numbers() >>> >>> Is there a technical name for a loop like this? >> >> For loop? That is what I call it. >> >> > As usual I am not very clear, see how the call_numbers() for loop gets > passes to the get(numbers) to do something else, that is what I was > asking about. > That part is not considered a loop. There is a type of programming paradigm called "recursion" that is similar to loops, perhaps that's what you're thinking of? def recursive_sum(num): if num == 0: return 0 else: return num + recursive(num - 1) >>> recursive_sum(15) 120 >>> sum(range(16)) 120 However your example is not recursion, because the function does not call itself repeatedly; rather, call_numbers is called once, and then it repeatedly calls a _different_ function. Savvy the difference? HTH, -Luke __________ Information from ESET NOD32 Antivirus, version of virus signature database 4136 (20090606) __________ The message was checked by ESET NOD32 Antivirus. http://www.eset.com From emile at fenx.com Mon Jun 8 07:04:16 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 07 Jun 2009 22:04:16 -0700 Subject: [Tutor] What is this kind of loop called In-Reply-To: <4A2C6B6C.3080507@abbottdavid.com> References: <4A2C6B6C.3080507@abbottdavid.com> Message-ID: On 6/7/2009 6:37 PM David said... > In one of my questions to this list, Kent explained to me how to use a > loop like this; > > #!/usr/bin/python > from time import sleep > > def get(numbers): > print 'Calling ', numbers > sleep(1) > print 'Connected ' > sleep(1) > > def call_numbers(): > for i in range(9549355543, 9549355560): > numbers = i > get(numbers) > call_numbers() > > Is there a technical name for a loop like this? You mean like, automated junk call dialer? duck-and-cover... :) Emile > thanks > -david From xboxmuncher at gmail.com Mon Jun 8 07:17:17 2009 From: xboxmuncher at gmail.com (xbmuncher) Date: Mon, 8 Jun 2009 01:17:17 -0400 Subject: [Tutor] Stop a long loop in python console or in wxpython? Message-ID: I have this script: import time def hello(): print "yay you got me to print" def longLoop(): x = 0 for n in range(100000): time.sleep(5) x = x + n longLoop() It will run in the console for a long time. How can I send a command and cause it to stop and pursue hello() function? I don't think this is possible in the console.. and really I'd like to create a GUI that will run the longLoop() function after I push a button and then press another button to stop the longLoop() function and run the hello() function. How can I do this in the wxPython, which is gui of choice for python. I'll settle for a way to do it via console as well. The overall idea is, is that I want to cut short the process of a piece of code in order to start another piece of code. Can you help me with this? Thanks. -xbmuncher -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 8 10:23:08 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 8 Jun 2009 09:23:08 +0100 Subject: [Tutor] Stop a long loop in python console or in wxpython? References: Message-ID: "xbmuncher" wrote > def longLoop(): > x = 0 > for n in range(100000): > time.sleep(5) > x = x + n > > It will run in the console for a long time. How can I send a command and > cause it to stop and pursue hello() function? You can use Ctrl-C and put the loop insiode a try/except clause to catch the Interrupt. Or.... > in the console.. and really I'd like to create a GUI that will run the > longLoop() function after I push a button and then press another button > to > stop the longLoop() function and run the hello() function. There are two normal ways to do this in a GUI: 1) break the loop into small chunks and run them in response to timer events. The function then calls the timer at the end of each chunk until it completes its task. This frees up the GUI to detect user events between timers. 2) Use threads. This has the advantage of working in a GUI or a commandline. But is a little bit more complex and you need to make sure your loop isn't messing with (or being messed with) the rest of the priogram via shared data/resources. > in the wxPython, which is gui of choice for python. I'll settle for a way > to > do it via console as well. The overall idea is, is that I want to cut > short > the process of a piece of code in order to start another piece of code. You can put a terminating flag in the timer code or you can send a message to stop a thread, either way will work. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From hoym74 at gmail.com Mon Jun 8 11:57:47 2009 From: hoym74 at gmail.com (Mike Hoy) Date: Mon, 8 Jun 2009 04:57:47 -0500 Subject: [Tutor] Can't figure out why this is printing twice Message-ID: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> I have the following code: import gzip import datetime date = datetime.date.today() name = date.strftime('%m-%d-%Y')+'.gz' date.strftime('%m-%d-%Y')+'.gz' print "The name of the file will be", name the output is: The name of the file will be The name of the file will be 06-08-2009.gz I can't figure out why 'The name of the file will be' is printing twice. Any help appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From thegreentealeaf at gmail.com Mon Jun 8 12:02:13 2009 From: thegreentealeaf at gmail.com (The Green Tea Leaf) Date: Mon, 8 Jun 2009 12:02:13 +0200 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> Message-ID: <3753b0ed0906080302i2e6e14c3y826dbd777b6296c6@mail.gmail.com> This doesn't happen on my machine. What is the filename ? -- The Green Tea Leaf thegreentealeaf at gmail.com thegreentealeaf.blogspot.com From andreengels at gmail.com Mon Jun 8 12:03:09 2009 From: andreengels at gmail.com (Andre Engels) Date: Mon, 8 Jun 2009 12:03:09 +0200 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> Message-ID: <6faf39c90906080303s6cd3612r7531d1742514928@mail.gmail.com> On Mon, Jun 8, 2009 at 11:57 AM, Mike Hoy wrote: > I have the following code: > > import gzip > import datetime > date = datetime.date.today() > name = date.strftime('%m-%d-%Y')+'.gz' > date.strftime('%m-%d-%Y')+'.gz' > print "The name of the file will be", name > > the output is: > The name of the file will be > The name of the file will be 06-08-2009.gz > > > I can't figure out why 'The name of the file will be' is printing twice. Any > help appreciated. How exactly are you running this? It seems to work correctly for me. Looking at your code, the following couple of lines look strange: > name = date.strftime('%m-%d-%Y')+'.gz' > date.strftime('%m-%d-%Y')+'.gz' The first calculates a name based on the current date, and puts the result in the variable 'name'. The second calculates the name again, then throws the result away. Why not remove the second line? -- Andr? Engels, andreengels at gmail.com From cwitts at compuscan.co.za Mon Jun 8 12:25:55 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 08 Jun 2009 12:25:55 +0200 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> Message-ID: <4A2CE733.8070506@compuscan.co.za> Mike Hoy wrote: > I have the following code: > > import gzip > import datetime > date = datetime.date.today() > name = date.strftime('%m-%d-%Y')+'.gz' > date.strftime('%m-%d-%Y')+'.gz' > print "The name of the file will be", name > > the output is: > The name of the file will be > The name of the file will be 06-08-2009.gz > > > I can't figure out why 'The name of the file will be' is printing > twice. Any help appreciated. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Running from a console the expected output would actually be 06-08-2009.gz The name of the file will be 06-08-2009.gz Other than that side effect it works with only 1 print. -- Kind Regards, Christian Witts Data Management C o m p u s c a n | Confidence in Credit Telephone: +27 21 888 6000 National Cell Centre: 0861 51 41 31 Fax: +27 21 413 2424 E-mail: cwitts at compuscan.co.za NOTE: This e-mail (including attachments )is subject to the disclaimer published at: http://www.compuscan.co.za/live/content.php?Item_ID=494. If you cannot access the disclaimer, request it from email.disclaimer at compuscan.co.za or 0861 514131. From eddie9139 at gmail.com Mon Jun 8 13:30:35 2009 From: eddie9139 at gmail.com (Eddie) Date: Mon, 8 Jun 2009 21:30:35 +1000 Subject: [Tutor] Hi Message-ID: Hi, I'm new and just starting to learn Python. Just testing if this works or not and if anybody reads it lol. Eddie From kent37 at tds.net Mon Jun 8 13:39:22 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 8 Jun 2009 07:39:22 -0400 Subject: [Tutor] Hi In-Reply-To: References: Message-ID: <1c2a2c590906080439y7deb460did3ec6e2697ab78cc@mail.gmail.com> On Mon, Jun 8, 2009 at 7:30 AM, Eddie wrote: > Hi, I'm new and just starting to learn Python. Just testing if this > works or not and if anybody reads it lol. Yes, it works. Welcome! Kent From xboxmuncher at gmail.com Mon Jun 8 13:41:48 2009 From: xboxmuncher at gmail.com (xbmuncher) Date: Mon, 8 Jun 2009 07:41:48 -0400 Subject: [Tutor] Stop a long loop in python console or in wxpython? In-Reply-To: References: Message-ID: Thanks for the reply Alan. I'm unfamiliar on both methods you suggested. Can you give me examples with code of them? I saw this piece of code on your webpage: import msvcrt def doKeyEvent(key): if key == '\x00' or key == '\xe0': # non ASCII key = msvcrt.getch() # fetch second character print ord(key), def doQuitEvent(key): raise SystemExit # First, clear the screen of clutter then warn the user # of what to do to quit lines = 25 # set to number of lines in console for line in range(lines): print print "Hit space to end..." print # Now mainloop runs "forever" while True: ky = msvcrt.getch() length = len(ky) if length != 0: # send events to event handling functions if ky == " ": # check for quit event doQuitEvent(ky) else: doKeyEvent(ky) Is this similar to the try except clause method? How will breaking code into timed events help me? I wanted to stop the function on an event (like pushing a button). The part I don't really understand is how the program can be screening or "recognizing" a command or event while it hasn't finished this other process. How does the timer help in this? From my experiences with python, python doesn't let anything get in its way until its done with the current process unless you end it immediately with ctrl c or pressing X. It won't even let you type text into the console while it's "in process." On Mon, Jun 8, 2009 at 4:23 AM, Alan Gauld wrote: > "xbmuncher" wrote > > def longLoop(): >> x = 0 >> for n in range(100000): >> time.sleep(5) >> x = x + n >> >> It will run in the console for a long time. How can I send a command and >> cause it to stop and pursue hello() function? >> > > You can use Ctrl-C and put the loop insiode a try/except clause > to catch the Interrupt. Or.... > > in the console.. and really I'd like to create a GUI that will run the >> longLoop() function after I push a button and then press another button to >> stop the longLoop() function and run the hello() function. >> > > There are two normal ways to do this in a GUI: > 1) break the loop into small chunks and run them in response > to timer events. The function then calls the timer at the end of > each chunk until it completes its task. This frees up the GUI to > detect user events between timers. > > 2) Use threads. This has the advantage of working in a GUI > or a commandline. But is a little bit more complex and you > need to make sure your loop isn't messing with (or being > messed with) the rest of the priogram via shared data/resources. > > in the wxPython, which is gui of choice for python. I'll settle for a way >> to >> do it via console as well. The overall idea is, is that I want to cut >> short >> the process of a piece of code in order to start another piece of code. >> > > You can put a terminating flag in the timer code or you can > send a message to stop a thread, either way will work. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Mon Jun 8 13:55:31 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 08 Jun 2009 13:55:31 +0200 Subject: [Tutor] Hi In-Reply-To: References: Message-ID: <4A2CFC33.6030305@compuscan.co.za> Eddie wrote: > Hi, I'm new and just starting to learn Python. Just testing if this > works or not and if anybody reads it lol. > Eddie > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Welcome to the list and enjoy your stay. :) -- Kind Regards, Christian Witts From denis.spir at free.fr Mon Jun 8 14:25:37 2009 From: denis.spir at free.fr (spir) Date: Mon, 8 Jun 2009 14:25:37 +0200 Subject: [Tutor] Stop a long loop in python console or in wxpython? In-Reply-To: References: Message-ID: <20090608142537.2e15785b@o> Le Mon, 8 Jun 2009 09:23:08 +0100, "Alan Gauld" s'exprima ainsi: > There are two normal ways to do this in a GUI: > 1) break the loop into small chunks and run them in response > to timer events. The function then calls the timer at the end of > each chunk until it completes its task. This frees up the GUI to > detect user events between timers. > > 2) Use threads. This has the advantage of working in a GUI > or a commandline. But is a little bit more complex and you > need to make sure your loop isn't messing with (or being > messed with) the rest of the priogram via shared data/resources. I don't really understand why it is necessary to complicate the design. As it is a GUi app, there is no problem to catch the 'stop-loop' event. So why not simply check (a flag memo of) the event at the end of each loop? Except of course for very fast response time requirement -- but this is not such common, I guess (in a GUI app where 'fast' is measured from the user POV). Denis ------ la vita e estrany From phpfood at gmail.com Mon Jun 8 13:41:02 2009 From: phpfood at gmail.com (phpfood) Date: Mon, 8 Jun 2009 07:41:02 -0400 Subject: [Tutor] Stop a long loop in python console or in wxpython? In-Reply-To: References: Message-ID: Thanks for the reply Alan. I'm unfamiliar on both methods you suggested. Can you give me examples with code of them? I saw this piece of code on your webpage: import msvcrt def doKeyEvent(key): if key == '\x00' or key == '\xe0': # non ASCII key = msvcrt.getch() # fetch second character print ord(key), def doQuitEvent(key): raise SystemExit # First, clear the screen of clutter then warn the user # of what to do to quit lines = 25 # set to number of lines in console for line in range(lines): print print "Hit space to end..." print # Now mainloop runs "forever" while True: ky = msvcrt.getch() length = len(ky) if length != 0: # send events to event handling functions if ky == " ": # check for quit event doQuitEvent(ky) else: doKeyEvent(ky) Is this similar to the try except clause method? How will breaking code into timed events help me? I wanted to stop the function on an event (like pushing a button). The part I don't really understand is how the program can be screening or "recognizing" a command or event while it hasn't finished this other process. How does the timer help in this? From my experiences with python, python doesn't let anything get in its way until its done with the current process unless you end it immediately with ctrl c or pressing X. It won't even let you type text into the console while it's "in process." On Mon, Jun 8, 2009 at 4:23 AM, Alan Gauld wrote: > "xbmuncher" wrote > > def longLoop(): >> x = 0 >> for n in range(100000): >> time.sleep(5) >> x = x + n >> >> It will run in the console for a long time. How can I send a command and >> cause it to stop and pursue hello() function? >> > > You can use Ctrl-C and put the loop insiode a try/except clause > to catch the Interrupt. Or.... > > in the console.. and really I'd like to create a GUI that will run the >> longLoop() function after I push a button and then press another button to >> stop the longLoop() function and run the hello() function. >> > > There are two normal ways to do this in a GUI: > 1) break the loop into small chunks and run them in response > to timer events. The function then calls the timer at the end of > each chunk until it completes its task. This frees up the GUI to > detect user events between timers. > > 2) Use threads. This has the advantage of working in a GUI > or a commandline. But is a little bit more complex and you > need to make sure your loop isn't messing with (or being > messed with) the rest of the priogram via shared data/resources. > > in the wxPython, which is gui of choice for python. I'll settle for a way >> to >> do it via console as well. The overall idea is, is that I want to cut >> short >> the process of a piece of code in order to start another piece of code. >> > > You can put a terminating flag in the timer code or you can > send a message to stop a thread, either way will work. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 8 16:03:01 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 8 Jun 2009 15:03:01 +0100 Subject: [Tutor] Stop a long loop in python console or in wxpython? References: Message-ID: "xbmuncher" wrote > Thanks for the reply Alan. I'm unfamiliar on both methods you suggested. > Can > you give me examples with code of them? Yes: In a console(untested): ############# x = 0 try: while True: x += 1 print x sleep(0.1) except KeyboardInterrupt: print 'stopped' ############# in a GUI using tkinter(tested) but wxpython should be similar, it definitely has a timer. ############### from Tkinter import * # global vars total = 0 stop = False def counter(): global total, stop if stop == False: print "Starting..." for n in range(50): total += 1 result['text'] = "Total = %09s" % total print "Total = %09s" % total # set timer to call again after 100ms tk.after(100, counter) else: print "Stopped" def doStop(): global stop stop = True tk = Tk() result = Label(tk, text="Not started yet") result.pack() Button(tk,text="Start", command=counter).pack() Button(tk, text="Stop", command=doStop).pack() tk.mainloop() ############### hth, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jun 8 16:11:05 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 8 Jun 2009 15:11:05 +0100 Subject: [Tutor] Can't figure out why this is printing twice References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> Message-ID: "Mike Hoy" wrote >I have the following code: Is this in a file or are you typing it at the python interpreter >>> primpt? > import gzip > import datetime > date = datetime.date.today() > name = date.strftime('%m-%d-%Y')+'.gz' > date.strftime('%m-%d-%Y')+'.gz' > print "The name of the file will be", name If its in a file you should only get one print If its at the >>> prompt you should get a string after the second call to date.strftime and then your print. > the output is: > The name of the file will be > The name of the file will be 06-08-2009.gz > I can't figure out why 'The name of the file will be' is printing twice. > Any > help appreciated. If that is what you get then me neither! Alan G. From alan.gauld at btinternet.com Mon Jun 8 16:13:21 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 8 Jun 2009 15:13:21 +0100 Subject: [Tutor] Hi References: Message-ID: "Eddie" wrote > Hi, I'm new and just starting to learn Python. Just testing if this > works or not and if anybody reads it lol. Welcome! If you take a look at the archive on the web site you'll see that quite a lot of folks read it - and many reply too! You might even find answers to a lot of your own questions :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From thegreentealeaf at gmail.com Mon Jun 8 17:07:55 2009 From: thegreentealeaf at gmail.com (The Green Tea Leaf) Date: Mon, 8 Jun 2009 17:07:55 +0200 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> Message-ID: <3753b0ed0906080807wcadeb3dtf49c9ac6e750630c@mail.gmail.com> Could it be some import statement? That the gzip file is "shadowed" in some way? On Mon, Jun 8, 2009 at 16:11, Alan Gauld wrote: > > "Mike Hoy" wrote > > >> I have the following code: > > Is this in a file or are you typing it at the python > interpreter >>> primpt? > >> import gzip >> import datetime >> date = datetime.date.today() >> name = date.strftime('%m-%d-%Y')+'.gz' >> date.strftime('%m-%d-%Y')+'.gz' >> print "The name of the file will be", name > > If its in a file you should only get one print > If its at the >>> prompt you should get a string after > the second call to date.strftime and then your print. > >> the output is: >> The name of the file will be >> The name of the file will be 06-08-2009.gz >> I can't figure out why 'The name of the file will be' is printing twice. >> Any >> help appreciated. > > If that is what you get then me neither! > > Alan G. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- The Green Tea Leaf thegreentealeaf at gmail.com thegreentealeaf.blogspot.com From srilyk at gmail.com Mon Jun 8 17:26:06 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 8 Jun 2009 10:26:06 -0500 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <3753b0ed0906080807wcadeb3dtf49c9ac6e750630c@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> <3753b0ed0906080807wcadeb3dtf49c9ac6e750630c@mail.gmail.com> Message-ID: <333efb450906080826q28e135a0g9aa483bb0ac6a729@mail.gmail.com> On Mon, Jun 8, 2009 at 10:07 AM, The Green Tea Leaf < thegreentealeaf at gmail.com> wrote: > Could it be some import statement? That the gzip file is "shadowed" in some > way? based on what the OP said, there's really nothing that should produce that that I can think of that would produce the given output! I'd love to see a screenshot, though. Because it's printing the string twice - not the date. If it were a problem with the date or gzip you would think you'd get problems with something unrelated to the string. The only thing I can think of is if his stack/heap is somehow getting altered from outside python (or inside, I suppose) So Mike, can you provide a screenshot of your code/execution? Sending it directly (at least to me) will prevent it getting delayed while the attachment is approved. -Wayne > > On Mon, Jun 8, 2009 at 16:11, Alan Gauld wrote: > > > > "Mike Hoy" wrote > > > > > >> I have the following code: > > > > Is this in a file or are you typing it at the python > > interpreter >>> primpt? > > > >> import gzip > >> import datetime > >> date = datetime.date.today() > >> name = date.strftime('%m-%d-%Y')+'.gz' > >> date.strftime('%m-%d-%Y')+'.gz' > >> print "The name of the file will be", name > > > > If its in a file you should only get one print > > If its at the >>> prompt you should get a string after > > the second call to date.strftime and then your print. > > > >> the output is: > >> The name of the file will be > >> The name of the file will be 06-08-2009.gz > >> I can't figure out why 'The name of the file will be' is printing twice. > >> Any > >> help appreciated. > > > > If that is what you get then me neither! > > > > Alan G. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > The Green Tea Leaf thegreentealeaf at gmail.com > thegreentealeaf.blogspot.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From thegreentealeaf at gmail.com Mon Jun 8 17:53:27 2009 From: thegreentealeaf at gmail.com (The Green Tea Leaf) Date: Mon, 8 Jun 2009 17:53:27 +0200 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <333efb450906080826q28e135a0g9aa483bb0ac6a729@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> <3753b0ed0906080807wcadeb3dtf49c9ac6e750630c@mail.gmail.com> <333efb450906080826q28e135a0g9aa483bb0ac6a729@mail.gmail.com> Message-ID: <3753b0ed0906080853w3cd3704cq8b94a74028e8240b@mail.gmail.com> On Mon, Jun 8, 2009 at 17:26, Wayne wrote: > On Mon, Jun 8, 2009 at 10:07 AM, The Green Tea Leaf > wrote: >> >> Could it be some import statement? That the gzip file is "shadowed" in >> some way? > > based on what the OP said, there's really nothing that should produce that > that I can think of that would produce the given output! I agree but that was the best idea that I could come with (that there is a gzip file with some half-duplicated code that got called. Not much of an idea though :D -- The Green Tea Leaf thegreentealeaf at gmail.com thegreentealeaf.blogspot.com From gonzillaaa at gmail.com Mon Jun 8 18:56:07 2009 From: gonzillaaa at gmail.com (Gonzalo Garcia-Perate) Date: Mon, 8 Jun 2009 17:56:07 +0100 Subject: [Tutor] creating a range above & below a given number In-Reply-To: <1c2a2c590906071956h70a47705n83705455966b4447@mail.gmail.com> References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> <1c2a2c590906071004p7cf00083sd661faae5000c496@mail.gmail.com> <6b6a049d0906071017qc899c3n51e546fbc27b85dd@mail.gmail.com> <1c2a2c590906071956h70a47705n83705455966b4447@mail.gmail.com> Message-ID: <6b6a049d0906080956j503dd972xe0db0274de292efd@mail.gmail.com> Kent, Emile thank you both. You're absolutely right, I was going for range because I thought it made the code more readable/more explicit. I hadn't taken into account the performance hit of creating the list and iterating through it. I'm not sure it was more readable either. the function now reads: def within_range_final(self, n, n2, threshold=5): return n2-threshold <= n <= n2+threshold+1 thanks again for you input. G. 2009/6/8 Kent Johnson : > On Sun, Jun 7, 2009 at 3:34 PM, Emile van Sebille wrote: > >> To explain why we've tended to suggest using int and minval> tests and avoid the range inclusion test, consider the following timeit >> results: > > The performance penalty for 'in range(...)' is even greater when the > value is not found, because the entire list must be searched: > > kent $ python -m timeit "0 <= 6000 <= 1000" > 10000000 loops, best of 3: 0.111 usec per loop > > kent $ python -m timeit "6 in range(100)" > 100000 loops, best of 3: 1.89 usec per loop > > kent $ python -m timeit "6000 in range(100)" > 100000 loops, best of 3: 5.55 usec per loop > > kent $ python -m timeit "6 in range(1000)" > 100000 loops, best of 3: 19 usec per loop > > kent $ python -m timeit "6000 in range(1000)" > 10000 loops, best of 3: 55.4 usec per loop > > Kent > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From eduardo.susan at gmail.com Mon Jun 8 19:28:35 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 8 Jun 2009 11:28:35 -0600 Subject: [Tutor] Need better understanding of **kwargs In-Reply-To: <78b3a9580906062210i78165f81r93efd0ef9f746393@mail.gmail.com> References: <9356b9f30906061044i4ded250fif3b387e64a11700d@mail.gmail.com> <78b3a9580906062210i78165f81r93efd0ef9f746393@mail.gmail.com> Message-ID: <9356b9f30906081028h35693e85j7532c8aebb464b70@mail.gmail.com> On Sat, Jun 6, 2009 at 11:10 PM, wesley chun wrote: >>> Hello, I thought I understood **kwargs until I stumbled with this >>> function: >>> >>> def changeflexion(myword, mytag, **dicty): >>> ? ? ? ?: >>> >>> but when I import the module and call: >>> a = conjugate.changeflexion('estaban', 'VLFin', conjugate.mydict) >>> I get this error: >>> TypeError: changeflexion() takes exactly 2 arguments (3 given) >>> Isn't the 3rd argument supposed to be a dictionary? >> >> No, **dicty means the function takes zero or more keyword parameters: >> >>>>> def f(a,b,**k): >> >> ... ?print a,b,k >> ... >>>>> >>>>> f(1,2) # no keyword parameters >> >> 1 2 {} >>>>> >>>>> f(1,2,c=3) # one keyword parameter >> >> 1 2 {'c': 3} >>>>> >>>>> f(1,2,{'c':3}) # a dictionary >> >> Traceback (most recent call last): >> ?File "", line 1, in >> TypeError: f() takes exactly 2 arguments (3 given) >> >> But there is a syntax to pass keyword arguments as a dictionary: >> >>>>> f(1,2,**{'c':3}) >> >> 1 2 {'c': 3} > > > bob and mark are both correct, in their own special way. :-) what they > really meant to say is something like this: > > 1. if your entire purpose of the function is to accept a dictionary of > values and process them like you do in your function, there's no need > to make it a kwargs dict. as bob suggested, you can just remove the > "**" and keep the rest as-is. > > 2. however, if you're calling the function where there are a variable > number of keyword arguments, like mark's example: > > f('foo', 20, c=3, d=4, g='bar') > f('boo', -10, e=2.718, pi=3.14) > f('one', 'two', d=-40, e=2.718) > > ...where both the number of arguments may vary, or if the names may > vary, i.e., (c,d,g) vs. (e, pi) vs. (d, e), etc., then this is more of > a correct use case for a **kwargs variable. it's whole purpose is for > keyword arguments and not necessarily a mechanism to pass a dictionary > to a function even though you can do it. > > one exception is when you're trying to cascade a kwargs dictionary to > begin with, IOW, you're trying to continue to pass it on to yet > another function: > > def f1(...., **kwargs): > ? ?: > > def f2(...., **kwargs): > ? ?: > ? ?if 'bar' not in kwargs: ? ? ? ?# add another value to kwargs > ? ? ? ?kwargs['bar'] = 'foo' > ? ? ? ?rv = f1(..., **kwargs) ? ? # process by passing to f1() > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > ? ?http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > Thanks you all. I only had time to read the replies today. Now it's more clear the meaning of **kwargs. I had also figured out that without using ** the 3rd argument (dicty) worked fine. Regards, Eduardo From allen.fowler at yahoo.com Mon Jun 8 20:12:03 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Mon, 8 Jun 2009 11:12:03 -0700 (PDT) Subject: [Tutor] Suggested source code folder layout In-Reply-To: <312f43620906061002i22bf826cm350c4b210a1c1055@mail.gmail.com> References: <616626.98865.qm@web45616.mail.sp1.yahoo.com> <312f43620906061002i22bf826cm350c4b210a1c1055@mail.gmail.com> Message-ID: <104502.67598.qm@web45614.mail.sp1.yahoo.com> > > My 2 cents... > > 1) Since you are describing your source code layout, any virtual > environment should be outside. A virtual environment (virtualenv) is > part of deployment and not part of source. If you need to make a > reproducible deployment environment, then you need a deployment system > such as zc.buildout. You would store just the recipe for the > environment in source, but not the resulting buildout. Your build > recipe will typically go in the top of your source tree. > > http://pypi.python.org/pypi/zc.buildout/ > Good point about keeping the virtualenv out of the source tree in favor of "recipe", and copying the modules to lib or site-packages upon deployment. zc.buildout seems like a powerful tool, but I'm not at all clear on how to use it for this sort of task. (All the tutorials I can find to seem to zope related.) Do you have any examples you can share? From srilyk at gmail.com Mon Jun 8 20:45:12 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 8 Jun 2009 13:45:12 -0500 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <3753b0ed0906080853w3cd3704cq8b94a74028e8240b@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> <3753b0ed0906080807wcadeb3dtf49c9ac6e750630c@mail.gmail.com> <333efb450906080826q28e135a0g9aa483bb0ac6a729@mail.gmail.com> <3753b0ed0906080853w3cd3704cq8b94a74028e8240b@mail.gmail.com> Message-ID: <333efb450906081145j2c25570cu2a8c3411a53f57ba@mail.gmail.com> On Mon, Jun 8, 2009 at 10:53 AM, The Green Tea Leaf < thegreentealeaf at gmail.com> wrote: > On Mon, Jun 8, 2009 at 17:26, Wayne wrote: > > On Mon, Jun 8, 2009 at 10:07 AM, The Green Tea Leaf > > wrote: > >> > >> Could it be some import statement? That the gzip file is "shadowed" in > >> some way? > > > > based on what the OP said, there's really nothing that should produce > that > > that I can think of that would produce the given output! > > I agree but that was the best idea that I could come with (that there > is a gzip file with some half-duplicated code that got called. Not > much of an idea though :D You mean the one that's imported? I suppose that could be possible if his install were pooched and something broke the print function. That's an interesting theory... and until the OP responds I fear my curiosity may cause me to explore how such a thing might be possible! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Mon Jun 8 23:15:27 2009 From: fomcl at yahoo.com (Albert-jan Roskam) Date: Mon, 8 Jun 2009 14:15:27 -0700 (PDT) Subject: [Tutor] smptlib question Message-ID: <182927.56693.qm@web110704.mail.gq1.yahoo.com> (sorry for posting this again, but something might have gone wrong) Hi, I made a very simple program to send everybody I know a change of address I am parsing the .msg files with another function, which returns a set called 'recipients'. The code below works, but it displays all recipients in the 'to' field. That is, in the Nth iteration, N recipients are shown. So the first mail has one recipient in the 'to' field, the second mail has the first and the second recipient, and so forth. I only want one recipient to be shown in the 'to' field. It's ugly and since I have a lot of email addresses to parse (4 years worth of emails!), it would become a very long list. Pointers, anyone? Thanks! Albert-Jan Python 2.5, Windows XP import smtplib, email.utils from email.mime.text import MIMEText msg = MIMEText("""Dear reader:\n\nblaaaaah blaah blaah.\nSincerely,\nThe dude""") sender = 'ren at stimpy.com' recipients = ['happyhappy at joy.com', 'you at eediot.com] for no, recipient in enumerate(recipients): print "--> Sending message to: %s (%s of %s)" % (recipient, no+1, len(recipients)) msg['To'] = email.utils.formataddr((recipient, recipient)) print msg['To'] msg['From'] = email.utils.formataddr(('Cool dude', sender)) msg['Subject'] = 'Change of email address' server = smtplib.SMTP("mysmtpserver.isp.com") server.set_debuglevel(True) try: server.sendmail(sender, [recipient], msg.as_string()) finally: server.quit() From david at abbottdavid.com Tue Jun 9 02:13:15 2009 From: david at abbottdavid.com (David) Date: Mon, 08 Jun 2009 20:13:15 -0400 Subject: [Tutor] smptlib question In-Reply-To: <182927.56693.qm@web110704.mail.gq1.yahoo.com> References: <182927.56693.qm@web110704.mail.gq1.yahoo.com> Message-ID: <4A2DA91B.7010803@abbottdavid.com> Albert-jan Roskam wrote: > (sorry for posting this again, but something might have gone wrong) > > Hi, > > I made a very simple program to send everybody I know a change of address I am parsing the .msg files with another function, which returns a set called 'recipients'. > > The code below works, but it displays all recipients in the 'to' field. That is, in the Nth iteration, N recipients are shown. So the first mail has one recipient in the 'to' field, the second mail has the first and the second recipient, and so forth. I only want one recipient to be shown in the 'to' field. It's ugly and since I have a lot of email addresses to parse (4 years worth of emails!), it would become a very long list. > > Pointers, anyone? > > Thanks! > Albert-Jan > Python 2.5, Windows XP > > import smtplib, email.utils > from email.mime.text import MIMEText > > msg = MIMEText("""Dear reader:\n\nblaaaaah blaah blaah.\nSincerely,\nThe dude""") > > sender = 'ren at stimpy.com' > recipients = ['happyhappy at joy.com', 'you at eediot.com] > for no, recipient in enumerate(recipients): > print "--> Sending message to: %s (%s of %s)" % (recipient, no+1, len(recipients)) > msg['To'] = email.utils.formataddr((recipient, recipient)) > print msg['To'] > msg['From'] = email.utils.formataddr(('Cool dude', sender)) > msg['Subject'] = 'Change of email address' > > server = smtplib.SMTP("mysmtpserver.isp.com") > server.set_debuglevel(True) > try: > server.sendmail(sender, [recipient], msg.as_string()) > finally: > server.quit() > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hi Albert, I got this to work; #!/usr/bin/python import smtplib, email.utils from email.mime.text import MIMEText from email.MIMEMultipart import MIMEMultipart from email.Utils import COMMASPACE, formatdate def recipients(): recipients = ['happyhappy at joy.com', 'you at eediot.com] for no, recipient in enumerate(recipients): print "--> Sending message to: %s (%s of %s)" % (recipient, no+1, len(recipients)) message(recipient) def message(recipient): body = "Dear reader:\n\nblaaaaah blaah blaah.\nSincerely,\nThe dude" send_mail([recipient], 'Change of email address', body) def send_mail(send_to, subject, text, server="mail.stimpy.com"): send_from = "ren at stimpy.com" msg = MIMEMultipart() msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['From'] = send_from msg['Subject'] = subject msg.attach( MIMEText(text) ) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() recipients() -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From oberoc at gmail.com Tue Jun 9 02:19:58 2009 From: oberoc at gmail.com (Tino Dai) Date: Mon, 8 Jun 2009 20:19:58 -0400 Subject: [Tutor] smptlib question In-Reply-To: <182927.56693.qm@web110704.mail.gq1.yahoo.com> References: <182927.56693.qm@web110704.mail.gq1.yahoo.com> Message-ID: <2ac5d4850906081719r4c111f2cpb41a90ac47086379@mail.gmail.com> On Mon, Jun 8, 2009 at 5:15 PM, Albert-jan Roskam wrote: > > (sorry for posting this again, but something might have gone wrong) > > Hi, > > I made a very simple program to send everybody I know a change of address I > am parsing the .msg files with another function, which returns a set called > 'recipients'. > > The code below works, but it displays all recipients in the 'to' field. > That is, in the Nth iteration, N recipients are shown. So the first mail has > one recipient in the 'to' field, the second mail has the first and the > second recipient, and so forth. I only want one recipient to be shown in the > 'to' field. It's ugly and since I have a lot of email addresses to parse (4 > years worth of emails!), it would become a very long list. > > Pointers, anyone? > Are you familiar with the python debugger? Look up pdb in google. It's such a hndy tool -HTH, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Mon Jun 8 20:42:00 2009 From: fomcl at yahoo.com (Albert-jan Roskam) Date: Mon, 8 Jun 2009 11:42:00 -0700 (PDT) Subject: [Tutor] smtplib question Message-ID: <816320.41266.qm@web110703.mail.gq1.yahoo.com> Hi, I made a very simple program to send everybody I know a change of address I am parsing the .msg files with another function, which returns a set called 'recipients'. The code below works, but it displays all recipients in the 'to' field. That is, in the Nth iteration, N recipients are shown. So the first mail has one recipient in the 'to' field, the second mail has the first and the second recipient, and so forth. I only want one recipient to be shown in the 'to' field. Pointers, anyone? Thanks! Albert-Jan import smtplib, email.utils from email.mime.text import MIMEText msg = MIMEText("""Dear reader:\n\nblaaaaah blaah blaah.\nSincerely,\nThe dude""") sender = 'ren at stimpy.com' recipients = ['happyhappy at joy.com', 'you at eediot.com] for no, recipient in enumerate(recipients): print "--> Sending message to: %s (%s of %s)" % (recipient, no+1, len(recipients)) msg['To'] = email.utils.formataddr((recipient, recipient)) print msg['To'] msg['From'] = email.utils.formataddr(('Cool dude', sender)) msg['Subject'] = 'Change of email address' server = smtplib.SMTP("mysmtpserver.isp.com") server.set_debuglevel(True) try: server.sendmail(sender, [recipient], msg.as_string()) finally: server.quit() From vincent at vincentdavis.net Tue Jun 9 01:25:09 2009 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 8 Jun 2009 17:25:09 -0600 Subject: [Tutor] question about class Message-ID: <77e831100906081625m135a06c5wfda04729397a604a@mail.gmail.com> I am reading several tutorials about classes and trying to figure out how to apply it to my project. I have a working program that basically matches up applicants and schools. Schools and applicants have and "true" quality and an "observed" quality. Then there is an algorithm that matches them up. Right now I do this all with lists which works ok but I would like to try using classes. Questions 1, does it make seens to have a applicant and a schools class (based on this brief explanation) 2, is it possible to have a class for the algorithim that will modify values in the applicant and schools class Thanks Vincent Davis 720-301-3003 From vincent at vincentdavis.net Tue Jun 9 01:31:23 2009 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 8 Jun 2009 17:31:23 -0600 Subject: [Tutor] question about class In-Reply-To: <77e831100906081625m135a06c5wfda04729397a604a@mail.gmail.com> References: <77e831100906081625m135a06c5wfda04729397a604a@mail.gmail.com> Message-ID: <77e831100906081631v7999c432u7bb853fc9159fcd0@mail.gmail.com> Accidentally sent I have added the rest (by the way I refrain from using the terms attribute, method,.... as I will likely miss use them) > I am reading several tutorials about classes and trying to figure out > how to apply it to my project. I have a working program that basically > matches up applicants and schools. Schools and applicants have and > "true" quality and an "observed" quality. Then there is an algorithm > that matches them up. Right now I do this all with lists which works > ok but I would like to try using classes. > > Questions > 1, does it make seens to have a applicant and a schools class (based > on this brief explanation) > 2, is it possible to have a class for the algorithm that will modify > values in the applicant and schools class for example applicant.matched = 4 and school.matched = 343 meaning applicant 343 is matched to school 4 3, is I have a value set in a class applicant.foo = 5 and I what to use a (method?) in the class to change this, what is the right way to do this? Ok that's all for now From kent37 at tds.net Tue Jun 9 03:29:15 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 8 Jun 2009 21:29:15 -0400 Subject: [Tutor] creating a range above & below a given number In-Reply-To: <6b6a049d0906080956j503dd972xe0db0274de292efd@mail.gmail.com> References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> <1c2a2c590906071004p7cf00083sd661faae5000c496@mail.gmail.com> <6b6a049d0906071017qc899c3n51e546fbc27b85dd@mail.gmail.com> <1c2a2c590906071956h70a47705n83705455966b4447@mail.gmail.com> <6b6a049d0906080956j503dd972xe0db0274de292efd@mail.gmail.com> Message-ID: <1c2a2c590906081829pce74705p5681569054f4f428@mail.gmail.com> On Mon, Jun 8, 2009 at 12:56 PM, Gonzalo Garcia-Perate wrote: > Kent, Emile thank you both. You're absolutely right, I was going for > range because I thought it made the code more readable/more explicit. > I hadn't taken into account the performance hit of creating the list > and iterating through it. I'm not sure it was more readable either. > > the function now reads: > def within_range_final(self, n, n2, threshold=5): > ? ?return n2-threshold <= n <= n2+threshold+1 You probably don't want the +1. What should be the result of self.within_range_final(7, 5, 1) ? You might think a bit about testing your functions, since you have posted several that don't do what you think they do. It's important to test common cases, edge cases, and failure cases. For example you might test all the combinations 1, 5, 1 - far outlier 3, 5, 1 - edge case 4, 5, 1 - edge case 5, 5, 1 - average case 6, 5, 1 - edge case 7, 5, 1 - edge case 10, 5, 1 - far outlier Kent From walker.hale.iv at gmail.com Tue Jun 9 03:43:21 2009 From: walker.hale.iv at gmail.com (Walker Hale IV) Date: Mon, 8 Jun 2009 20:43:21 -0500 Subject: [Tutor] Suggested source code folder layout In-Reply-To: <104502.67598.qm@web45614.mail.sp1.yahoo.com> References: <616626.98865.qm@web45616.mail.sp1.yahoo.com> <312f43620906061002i22bf826cm350c4b210a1c1055@mail.gmail.com> <104502.67598.qm@web45614.mail.sp1.yahoo.com> Message-ID: <312f43620906081843w3a9f3606vf48660587671d25e@mail.gmail.com> On Mon, Jun 8, 2009 at 1:12 PM, Allen Fowler wrote: > >> > >> My 2 cents... >> >> 1) Since you are describing your source code layout, any virtual >> environment should be outside. A virtual environment (virtualenv) is >> part of deployment and not part of source. If you need to make a >> reproducible deployment environment, then you need a deployment system >> such as zc.buildout. You would store just the recipe for the >> environment in source, but not the resulting buildout. Your build >> recipe will typically go in the top of your source tree. >> >> http://pypi.python.org/pypi/zc.buildout/ > > > Good point about keeping the virtualenv out of the source tree in favor of "recipe", and copying the modules to lib or site-packages upon deployment. > > zc.buildout seems like a powerful tool, but I'm not at all clear on how to use it for this sort of task. (All the tutorials I can find to seem to zope related.) > > > Do you have any examples you can share? Heh heh. I guess the documentation at that URL is ... um ... utterly incomprehensible to anyone not intimately familiar with Buildout. I've only played with Buildout a little bit, and I couldn't make sense of it. I suppose if you read it with a magnifying glass, you would eventually figure out what you need. OK... Go here: http://www.buildout.org/screencasts.html Watch the first screencast. Things will start making sense then. -- Walker Hale From cspears2002 at yahoo.com Tue Jun 9 04:20:01 2009 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 8 Jun 2009 19:20:01 -0700 (PDT) Subject: [Tutor] Where is www.wxpython.org? Message-ID: <383897.29850.qm@web51601.mail.re2.yahoo.com> Hey, I am trying to get to www.wxpython.org, but my connection keeps timing out. Is the site down? I just want to download wxPython for Python 2.6 (Windows Vista 32 bit). Thanks. From emile at fenx.com Tue Jun 9 07:08:27 2009 From: emile at fenx.com (Emile van Sebille) Date: Mon, 08 Jun 2009 22:08:27 -0700 Subject: [Tutor] Where is www.wxpython.org? In-Reply-To: <383897.29850.qm@web51601.mail.re2.yahoo.com> References: <383897.29850.qm@web51601.mail.re2.yahoo.com> Message-ID: On 6/8/2009 7:20 PM Christopher Spears said... > Hey, > > I am trying to get to www.wxpython.org, but my connection keeps timing out. Is the site down? I just want to download wxPython for Python 2.6 (Windows Vista 32 bit). > Will this one work? http://sourceforge.net/project/showfiles.php?group_id=10718 Emile From denis.spir at free.fr Tue Jun 9 09:12:38 2009 From: denis.spir at free.fr (spir) Date: Tue, 9 Jun 2009 09:12:38 +0200 Subject: [Tutor] question about class In-Reply-To: <77e831100906081631v7999c432u7bb853fc9159fcd0@mail.gmail.com> References: <77e831100906081625m135a06c5wfda04729397a604a@mail.gmail.com> <77e831100906081631v7999c432u7bb853fc9159fcd0@mail.gmail.com> Message-ID: <20090609091238.74ce8c7b@o> Le Mon, 8 Jun 2009 17:31:23 -0600, Vincent Davis s'exprima ainsi: > Accidentally sent I have added the rest > (by the way I refrain from using the terms attribute, method,.... as I > will likely miss use them) > > > I am reading several tutorials about classes and trying to figure out > > how to apply it to my project. I have a working program that basically > > matches up applicants and schools. Schools and applicants have and > > "true" quality and an "observed" quality. Then there is an algorithm > > that matches them up. Right now I do this all with lists which works > > ok but I would like to try using classes. > > Questions > > 1, does it make seens to have a applicant and a schools class (based > > on this brief explanation) Based on your explanations, I don't really understand the problem you're trying to solve, nore the algorithm. Still, probably it makes sense to use Applicant and School classes for the simple reason these notions in your program represent "objects": there are single, identified, things ; as opposed to "values" (in the ordinary sense of the term) that represent qualities or information such as color, position, number, or "true" and "observed" above. (By the way, don't use 'true', it's too misleading. Maybe 'truth' instead.) This notion of object identity would allow you, for instance, to match an applicant to a school by letting the applicant's attribute 'matched_school' directly point to a school itself, instead of a number that indirectly represents the school. Also, you've got a collection of schools and applicants, which probably means they will be stored in a set or a list. Once you have a type for them, it's easier to safely manipulate them in a unified manner. Even if they have only one single data attribute, I would do it: this also brings a centralised place to expose the object type's structure and behaviour. > > 2, is it possible to have a class for the algorithm that will modify > > values in the applicant and schools class > for example applicant.matched = 4 and school.matched = 343 meaning > applicant 343 is matched to school 4 No, if I understand what you mean. You won't have a separate "class" only to store actions (python is not java), but instead you should precisely attribute these as methods to the Applicant or School types. > 3, is I have a value set in a class applicant.foo = 5 and I what to > use a (method?) in the class to change this, what is the right way to > do this? Below an example: ==================== class Point(object): def __init__(self, x=0,y=0): self.x = x self.y = y def move(self, dx,dy): print self, self.x += dx self.y += dy print "--> %s" % self def __str__(self): return "Point (%s,%s)" % (self.x,self.y) p0 = Point() ; print p0 p = Point(9,8) ; print p p.move(-11,11) ==================== ==> ==================== Point (0,0) Point (9,8) Point (9,8) --> Point (-2,19) ==================== Denis ------ la vita e estrany From fomcl at yahoo.com Tue Jun 9 09:20:25 2009 From: fomcl at yahoo.com (Albert-jan Roskam) Date: Tue, 9 Jun 2009 00:20:25 -0700 (PDT) Subject: [Tutor] smptlib question Message-ID: <571780.84672.qm@web110711.mail.gq1.yahoo.com> Hi David and Tino, Thanks! I will try this tonight when I'm back home from the office. It's interesting to see how you split up the code into several little functions. Maybe it's typical for a newbie (like myself) to have the tendency to put everything into one function, instead of letting each function have its own purpose. Cheers!! Albert-Jan --- On Tue, 6/9/09, David wrote: > From: David > Subject: Re: [Tutor] smptlib question > To: "Albert-jan Roskam" > Cc: "*tutor python" > Date: Tuesday, June 9, 2009, 2:13 AM > Albert-jan Roskam wrote: > > (sorry for posting this again, but something might > have gone wrong) > > > > Hi, > > > > I made a very simple program to send everybody I know > a change of address I am parsing the .msg files with another > function, which returns a set called 'recipients'. > > > > The code below works, but it displays all recipients > in the 'to' field. That is, in the Nth iteration, N > recipients are shown. So the first mail has one recipient in > the 'to' field, the second mail has the first and the second > recipient, and so forth. I only want one recipient to be > shown in the 'to' field. It's ugly and since I have a lot of > email addresses to parse (4 years worth of emails!), it > would become a very long list. > > > > Pointers, anyone? > > > > Thanks! > > Albert-Jan > > Python 2.5, Windows XP > > > > import smtplib, email.utils > > from email.mime.text import MIMEText > > > > msg = MIMEText("""Dear reader:\n\nblaaaaah blaah > blaah.\nSincerely,\nThe dude""") > > > > sender = 'ren at stimpy.com' > > recipients = ['happyhappy at joy.com', > 'you at eediot.com] > > for no, recipient in enumerate(recipients): > >? ???print "--> Sending message > to: %s (%s of %s)" % (recipient, no+1, len(recipients)) > >? ???msg['To'] = > email.utils.formataddr((recipient, recipient)) > >? ???print msg['To'] > >? ???msg['From'] = > email.utils.formataddr(('Cool dude', sender)) > >? ???msg['Subject'] = 'Change of > email address' > > > >? ???server = > smtplib.SMTP("mysmtpserver.isp.com") > >? ???server.set_debuglevel(True) > >? ???try: > >? ? ? > ???server.sendmail(sender, [recipient], > msg.as_string()) > >? ???finally: > >? ? ? ???server.quit() > > > > > >? ? > ???_______________________________________________ > > Tutor maillist? -? Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > Hi Albert, > I got this to work; > > #!/usr/bin/python > > import smtplib, email.utils > from email.mime.text import MIMEText > from email.MIMEMultipart import MIMEMultipart > from email.Utils import COMMASPACE, formatdate > > def recipients(): > ? ? recipients = ['happyhappy at joy.com', > 'you at eediot.com] > ? ? for no, recipient in enumerate(recipients): > ? ? ? ? print "--> Sending message > to: %s (%s of %s)" % (recipient, no+1, len(recipients)) > ? ? ? ? message(recipient) > > def message(recipient): > ? ? body = "Dear reader:\n\nblaaaaah blaah > blaah.\nSincerely,\nThe dude" > ? ? send_mail([recipient], 'Change of email > address', body) > > > def send_mail(send_to, subject, text, > server="mail.stimpy.com"): > ? ? send_from = "ren at stimpy.com" > ? ? msg = MIMEMultipart() > ? ? msg['To'] = COMMASPACE.join(send_to) > ? ? msg['Date'] = formatdate(localtime=True) > ? ? msg['From'] = send_from > ? ? msg['Subject'] = subject > ? ? msg.attach( MIMEText(text) ) > ? ? smtp = smtplib.SMTP(server) > ? ? smtp.sendmail(send_from, send_to, > msg.as_string()) > ? ? smtp.close() > > recipients() > > -- Powered by Gentoo GNU/Linux > http://linuxcrazy.com > From a.t.hofkamp at tue.nl Tue Jun 9 09:23:57 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 09 Jun 2009 09:23:57 +0200 Subject: [Tutor] question about class In-Reply-To: <77e831100906081631v7999c432u7bb853fc9159fcd0@mail.gmail.com> References: <77e831100906081625m135a06c5wfda04729397a604a@mail.gmail.com> <77e831100906081631v7999c432u7bb853fc9159fcd0@mail.gmail.com> Message-ID: <4A2E0E0D.4010209@tue.nl> Vincent Davis wrote: > Accidentally sent I have added the rest > (by the way I refrain from using the terms attribute, method,.... as I > will likely miss use them) > >> I am reading several tutorials about classes and trying to figure out >> how to apply it to my project. I have a working program that basically >> matches up applicants and schools. Schools and applicants have and >> "true" quality and an "observed" quality. Then there is an algorithm >> that matches them up. Right now I do this all with lists which works >> ok but I would like to try using classes. sounds like a good plan. >> Questions >> 1, does it make seens to have a applicant and a schools class (based >> on this brief explanation) Most likely, yes. >> 2, is it possible to have a class for the algorithm that will modify >> values in the applicant and schools class > for example applicant.matched = 4 and school.matched = 343 meaning > applicant 343 is matched to school 4 I don't understand the example, but that may not matter. Yes it is possible to make an object of your algorithm. However, if you have exactly one such algorithm, there is little point imho to wrap it into a class. You may also want to wrap the result in an object. (but your approach of modifying the applicant or school objects is fine too!) > 3, is I have a value set in a class applicant.foo = 5 and I what to > use a (method?) in the class to change this, what is the right way to > do this? If you want to make a setter, below is an example. class X(object): """ Example class with a value. @ivar v: Value of the object. """ def __init__(self, v): self.v = v def set_v(self, new_v): self.v = new_v my_x = X(5) my_x.set_v(4) is the way to use a method for setting a value. However, Python discourages the use of such methods, since you are mostly adding boiler plate code without gaining anything. So instead, I'd suggest to forget about getters and setters, drop the X.set_v() method, and do my_x = X(5) my_x.v = 4 which is cleaner and equally precise in your intention. Albert From a.t.hofkamp at tue.nl Tue Jun 9 09:27:32 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 09 Jun 2009 09:27:32 +0200 Subject: [Tutor] smptlib question In-Reply-To: <571780.84672.qm@web110711.mail.gq1.yahoo.com> References: <571780.84672.qm@web110711.mail.gq1.yahoo.com> Message-ID: <4A2E0EE4.8000100@tue.nl> Albert-jan Roskam wrote: > Hi David and Tino, > > Thanks! I will try this tonight when I'm back home from the office. It's > interesting to see how you split up the code into several little functions. > Maybe it's typical for a newbie (like myself) to have the tendency to put > everything into one function, instead of letting each function have its own > purpose. No, experienced programmers do that too. They only recognize earlier that code loses its focus and needs to be partitioned :) Albert From hoym74 at gmail.com Tue Jun 9 10:03:16 2009 From: hoym74 at gmail.com (Mike Hoy) Date: Tue, 9 Jun 2009 03:03:16 -0500 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <87d8ca690906090100la3a9326ucd5ba0400983635c@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> <3753b0ed0906080807wcadeb3dtf49c9ac6e750630c@mail.gmail.com> <333efb450906080826q28e135a0g9aa483bb0ac6a729@mail.gmail.com> <3753b0ed0906080853w3cd3704cq8b94a74028e8240b@mail.gmail.com> <333efb450906081145j2c25570cu2a8c3411a53f57ba@mail.gmail.com> <87d8ca690906090100la3a9326ucd5ba0400983635c@mail.gmail.com> Message-ID: <87d8ca690906090103r56fe45f1yeca162fc2ee6444b@mail.gmail.com> On Tue, Jun 9, 2009 at 3:00 AM, Mike Hoy wrote: > Here's the screenshot: > > http://img40.imageshack.us/img40/7124/printtwice.png > > In case the image goes down here's the code: > import gzip > import datetime > date = datetime.date.today() > name = date.strftime('%m-%d-%Y')+'.gz' > print "The name of the file will be", name > > Here's the output: > ----------------------------- > mhoy06 at Blackbox:~/code/python$ python gzip2.py > The name of the file will be > The name of the file will be 06-09-2009.gz > ----------------------------- > It's Python 2.6.2 on Ubuntu 9.04 > > -Mike Hoy > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 9 10:08:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 9 Jun 2009 09:08:53 +0100 Subject: [Tutor] question about class References: <77e831100906081625m135a06c5wfda04729397a604a@mail.gmail.com> <77e831100906081631v7999c432u7bb853fc9159fcd0@mail.gmail.com> Message-ID: "Vincent Davis" wrote >> I am reading several tutorials about classes and trying to figure out >> how to apply it to my project. I have a working program that basically >> matches up applicants and schools. Schools and applicants have and >> "true" quality and an "observed" quality. Then there is an algorithm >> that matches them up. Right now I do this all with lists which works >> ok but I would like to try using classes. OK, The algorithm, is one of the key things that will likely change in your program. When converting procedural code to use objects it is often the case that algorithms (ie functions) get split up to put part of the code in one object and part in another. Thus in your case (depending on the actual algorithm,) you may move some testing code into the school object (to determine if the school wants the pupil!) and/or some into the applicant object (to determine if the pupil wants the school). Finally you might retain an application level function that simply iterates over each pupil finding them a school by asking each school if they will accept the pupil. Or you might iterate over the schools finding out if the pupil wants that school (which way is most appropriate depends on the app!). The point is each object only knows about part of the solution. The ownershp of the matching process probably stays outside - maybe in another object - who/what wants to do the matching for example? >> Questions >> 1, does it make seens to have a applicant and a schools class (based >> on this brief explanation) Yes, almost certainly >> 2, is it possible to have a class for the algorithm that will modify >> values in the applicant and schools class > for example applicant.matched = 4 and school.matched = 343 meaning > applicant 343 is matched to school 4 Its very bad practice to have an algorithm outside a class modifying attributes classes/objects should "do it to themselves". In some languages its common to implement a bunch of get/set methods to acces attributes and people think this meets the "DIY" principle but it doesn't really. The point is the attributes should be supporting a higher level operation and that operation is what should change the data. Some get/set methods may be appropriate if they are truly what the class is for, but they should be the minority. (And in Python we generally just use direct access to attributes rather than writing one-liner get/set methods!) So in your case you may determine that pupil A should go to school B. You probably want to have an enrolPupil method of school or a joinSchool method of applicant (again depends on the perspective of the application) That method will be responsible for adding the pupil to the list of enrolled pupils and/or assigning the schoool to the pupil. > 3, is I have a value set in a class applicant.foo = 5 and I what to > use a (method?) in the class to change this, what is the right way to > do this? As mentioned above you could write a get/set method, but in Python we usually just use direct access. But in general it's best to call a higher level method of the class and let it make the change! Remember to ask yourself what is this class's responsibilities, what do I want it to do for me? Think about behaviours first, data second. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From thegreentealeaf at gmail.com Tue Jun 9 10:33:22 2009 From: thegreentealeaf at gmail.com (The Green Tea Leaf) Date: Tue, 9 Jun 2009 10:33:22 +0200 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <87d8ca690906090103r56fe45f1yeca162fc2ee6444b@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> <3753b0ed0906080807wcadeb3dtf49c9ac6e750630c@mail.gmail.com> <333efb450906080826q28e135a0g9aa483bb0ac6a729@mail.gmail.com> <3753b0ed0906080853w3cd3704cq8b94a74028e8240b@mail.gmail.com> <333efb450906081145j2c25570cu2a8c3411a53f57ba@mail.gmail.com> <87d8ca690906090100la3a9326ucd5ba0400983635c@mail.gmail.com> <87d8ca690906090103r56fe45f1yeca162fc2ee6444b@mail.gmail.com> Message-ID: <3753b0ed0906090133u58cb3135qd3927c3a718ad6c3@mail.gmail.com> You don't happen to have a file called gzip.py in that catalog? On Tue, Jun 9, 2009 at 10:03, Mike Hoy wrote: > > > On Tue, Jun 9, 2009 at 3:00 AM, Mike Hoy wrote: >> >> Here's the screenshot: >> >> http://img40.imageshack.us/img40/7124/printtwice.png >> >> In case the image goes down here's the code: >> import gzip >> import datetime >> date = datetime.date.today() >> name = date.strftime('%m-%d-%Y')+'.gz' >> print "The name of the file will be", name >> >> Here's the output: >> ----------------------------- >> mhoy06 at Blackbox:~/code/python$ python gzip2.py >> The name of the file will be >> The name of the file will be 06-09-2009.gz >> ----------------------------- >> It's Python 2.6.2 on Ubuntu 9.04 >> >> -Mike Hoy > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- The Green Tea Leaf thegreentealeaf at gmail.com thegreentealeaf.blogspot.com From gonzillaaa at gmail.com Tue Jun 9 12:10:12 2009 From: gonzillaaa at gmail.com (Gonzalo Garcia-Perate) Date: Tue, 9 Jun 2009 11:10:12 +0100 Subject: [Tutor] creating a range above & below a given number In-Reply-To: <1c2a2c590906081829pce74705p5681569054f4f428@mail.gmail.com> References: <6b6a049d0906061231r19b65921j25e820f9b451e70b@mail.gmail.com> <6b6a049d0906070708qed65e51tae513c4cdb0ba9d6@mail.gmail.com> <1c2a2c590906071004p7cf00083sd661faae5000c496@mail.gmail.com> <6b6a049d0906071017qc899c3n51e546fbc27b85dd@mail.gmail.com> <1c2a2c590906071956h70a47705n83705455966b4447@mail.gmail.com> <6b6a049d0906080956j503dd972xe0db0274de292efd@mail.gmail.com> <1c2a2c590906081829pce74705p5681569054f4f428@mail.gmail.com> Message-ID: <6b6a049d0906090310u7bafe12bh9d26ca674f9bba88@mail.gmail.com> Kent thanks again for your input, rest assured is just the haste of my responses that goes unchecked :) many thanks, Gonzalo. 2009/6/9 Kent Johnson : > On Mon, Jun 8, 2009 at 12:56 PM, Gonzalo > Garcia-Perate wrote: >> Kent, Emile thank you both. You're absolutely right, I was going for >> range because I thought it made the code more readable/more explicit. >> I hadn't taken into account the performance hit of creating the list >> and iterating through it. I'm not sure it was more readable either. >> >> the function now reads: >> def within_range_final(self, n, n2, threshold=5): >> ? ?return n2-threshold <= n <= n2+threshold+1 > > You probably don't want the +1. What should be the result of > ?self.within_range_final(7, 5, 1) > ? > > You might think a bit about testing your functions, since you have > posted several that don't do what you think they do. It's important to > test common cases, edge cases, and failure cases. For example you > might test all the combinations > 1, 5, 1 - far outlier > 3, 5, 1 - edge case > 4, 5, 1 - edge case > 5, 5, 1 - average case > 6, 5, 1 - edge case > 7, 5, 1 - edge case > 10, 5, 1 - far outlier > > Kent > From lie.1296 at gmail.com Tue Jun 9 12:17:59 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 09 Jun 2009 20:17:59 +1000 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <3753b0ed0906090133u58cb3135qd3927c3a718ad6c3@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> <3753b0ed0906080807wcadeb3dtf49c9ac6e750630c@mail.gmail.com> <333efb450906080826q28e135a0g9aa483bb0ac6a729@mail.gmail.com> <3753b0ed0906080853w3cd3704cq8b94a74028e8240b@mail.gmail.com> <333efb450906081145j2c25570cu2a8c3411a53f57ba@mail.gmail.com> <87d8ca690906090100la3a9326ucd5ba0400983635c@mail.gmail.com> <87d8ca690906090103r56fe45f1yeca162fc2ee6444b@mail.gmail.com> <3753b0ed0906090133u58cb3135qd3927c3a718ad6c3@mail.gmail.com> Message-ID: The Green Tea Leaf wrote: > You don't happen to have a file called gzip.py in that catalog? > > On Tue, Jun 9, 2009 at 10:03, Mike Hoy wrote: >> >> On Tue, Jun 9, 2009 at 3:00 AM, Mike Hoy wrote: >>> Here's the screenshot: >>> >>> http://img40.imageshack.us/img40/7124/printtwice.png >>> >>> In case the image goes down here's the code: >>> import gzip >>> import datetime >>> date = datetime.date.today() >>> name = date.strftime('%m-%d-%Y')+'.gz' >>> print "The name of the file will be", name >>> >>> Here's the output: >>> ----------------------------- >>> mhoy06 at Blackbox:~/code/python$ python gzip2.py >>> The name of the file will be >>> The name of the file will be 06-09-2009.gz >>> ----------------------------- >>> It's Python 2.6.2 on Ubuntu 9.04 >>> >>> -Mike Hoy >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> try running this: print "START" print "import gzip" import gzip print "import datetime" import datetime print "date = datetime.date.today()" date = datetime.date.today() print "name = date.strftime('%m-%d-%Y')+'.gz'" name = date.strftime('%m-%d-%Y')+'.gz' print "print "The name of the file will be", name" print "The name of the file will be", name print "END" and on the shell, what's the output of `ls`? From thegreentealeaf at gmail.com Tue Jun 9 13:34:32 2009 From: thegreentealeaf at gmail.com (The Green Tea Leaf) Date: Tue, 9 Jun 2009 13:34:32 +0200 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> <3753b0ed0906080807wcadeb3dtf49c9ac6e750630c@mail.gmail.com> <333efb450906080826q28e135a0g9aa483bb0ac6a729@mail.gmail.com> <3753b0ed0906080853w3cd3704cq8b94a74028e8240b@mail.gmail.com> <333efb450906081145j2c25570cu2a8c3411a53f57ba@mail.gmail.com> <87d8ca690906090100la3a9326ucd5ba0400983635c@mail.gmail.com> <87d8ca690906090103r56fe45f1yeca162fc2ee6444b@mail.gmail.com> <3753b0ed0906090133u58cb3135qd3927c3a718ad6c3@mail.gmail.com> Message-ID: <3753b0ed0906090434l25ae197fv4421e89a3a6893ee@mail.gmail.com> I got an email from him that he had a gzip.pyc file in that folder. Once he deleted that everything works OK. From srilyk at gmail.com Tue Jun 9 14:03:03 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 9 Jun 2009 07:03:03 -0500 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <3753b0ed0906090434l25ae197fv4421e89a3a6893ee@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> <3753b0ed0906080807wcadeb3dtf49c9ac6e750630c@mail.gmail.com> <333efb450906080826q28e135a0g9aa483bb0ac6a729@mail.gmail.com> <3753b0ed0906080853w3cd3704cq8b94a74028e8240b@mail.gmail.com> <333efb450906081145j2c25570cu2a8c3411a53f57ba@mail.gmail.com> <87d8ca690906090100la3a9326ucd5ba0400983635c@mail.gmail.com> <87d8ca690906090103r56fe45f1yeca162fc2ee6444b@mail.gmail.com> <3753b0ed0906090133u58cb3135qd3927c3a718ad6c3@mail.gmail.com> <3753b0ed0906090434l25ae197fv4421e89a3a6893ee@mail.gmail.com> Message-ID: <333efb450906090503q6c6bcd89nde429252e9b22d53@mail.gmail.com> On Tue, Jun 9, 2009 at 6:34 AM, The Green Tea Leaf < thegreentealeaf at gmail.com> wrote: > I got an email from him that he had a gzip.pyc file in that folder. > Once he deleted that everything works OK. Heh... I think I've made that mistake before; "My import statement doesn't work right! When I "import " it tells me none of the methods are available!" And then I realize my file was named that. Doh! live and learn though, eh? -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Jun 9 14:13:47 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 9 Jun 2009 07:13:47 -0500 Subject: [Tutor] smtplib question In-Reply-To: <816320.41266.qm@web110703.mail.gq1.yahoo.com> References: <816320.41266.qm@web110703.mail.gq1.yahoo.com> Message-ID: <333efb450906090513w839567cq56c35dcad99de1aa@mail.gmail.com> On Mon, Jun 8, 2009 at 1:42 PM, Albert-jan Roskam wrote: > > Hi, > > I made a very simple program to send everybody I know a change of address I > am parsing the .msg files with another function, which returns a set called > 'recipients'. > > The code below works, but it displays all recipients in the 'to' field. > That is, in the Nth iteration, N recipients are shown. So the first mail has > one recipient in the 'to' field, the second mail has the first and the > second recipient, and so forth. I only want one recipient to be shown in the > 'to' field. So your code would, in this case, print out "happyhappy at joy.com" "you at eediot.com" or does it print out "happyhappy at joy.com" "happyhappy at joy.com" "you at eediot.com" If it's the former, that's what you have told it to do. If it's the latter, I'm not sure what the problem is, unless it has something to do with your debug level. HTH, Wayne > > > Pointers, anyone? > > Thanks! > Albert-Jan > > import smtplib, email.utils > from email.mime.text import MIMEText > > msg = MIMEText("""Dear reader:\n\nblaaaaah blaah blaah.\nSincerely,\nThe > dude""") > > sender = 'ren at stimpy.com' > recipients = ['happyhappy at joy.com', 'you at eediot.com] > for no, recipient in enumerate(recipients): > print "--> Sending message to: %s (%s of %s)" % (recipient, no+1, > len(recipients)) > msg['To'] = email.utils.formataddr((recipient, recipient)) > print msg['To'] > msg['From'] = email.utils.formataddr(('Cool dude', sender)) > msg['Subject'] = 'Change of email address' > > server = smtplib.SMTP("mysmtpserver.isp.com") > server.set_debuglevel(True) > try: > server.sendmail(sender, [recipient], msg.as_string()) > finally: > server.quit() > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From hoym74 at gmail.com Tue Jun 9 14:47:33 2009 From: hoym74 at gmail.com (Mike Hoy) Date: Tue, 9 Jun 2009 07:47:33 -0500 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <333efb450906090503q6c6bcd89nde429252e9b22d53@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> <333efb450906080826q28e135a0g9aa483bb0ac6a729@mail.gmail.com> <3753b0ed0906080853w3cd3704cq8b94a74028e8240b@mail.gmail.com> <333efb450906081145j2c25570cu2a8c3411a53f57ba@mail.gmail.com> <87d8ca690906090100la3a9326ucd5ba0400983635c@mail.gmail.com> <87d8ca690906090103r56fe45f1yeca162fc2ee6444b@mail.gmail.com> <3753b0ed0906090133u58cb3135qd3927c3a718ad6c3@mail.gmail.com> <3753b0ed0906090434l25ae197fv4421e89a3a6893ee@mail.gmail.com> <333efb450906090503q6c6bcd89nde429252e9b22d53@mail.gmail.com> Message-ID: <87d8ca690906090547y4879f6aenfc1b498bf8865a9b@mail.gmail.com> > > On Tue, Jun 9, 2009 at 6:34 AM, The Green Tea Leaf < > thegreentealeaf at gmail.com> wrote: > >> I got an email from him that he had a gzip.pyc file in that folder. >> Once he deleted that everything works OK. > > > Heh... I think I've made that mistake before; > > "My import statement doesn't work right! When I "import " it tells > me none of the methods are available!" > > And then I realize my file was named that. Doh! > > live and learn though, eh? > Yea and I knew better than to do that too. Guess I had to make the mistake to really get it into my head. Funny how that works. You read all about that stuff in books, but you don't actually know it until you put it into practice. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent at vincentdavis.net Tue Jun 9 15:02:28 2009 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 9 Jun 2009 07:02:28 -0600 Subject: [Tutor] question about class In-Reply-To: <20090609091238.74ce8c7b@o> References: <77e831100906081625m135a06c5wfda04729397a604a@mail.gmail.com> <77e831100906081631v7999c432u7bb853fc9159fcd0@mail.gmail.com> <20090609091238.74ce8c7b@o> Message-ID: <77e831100906090602x642da43dy29dcf13e608a81b2@mail.gmail.com> Thanks for the help and comments, I think my questions have been answered, I will know if I understand when I try to implement them. The Match algorithm. algorithm is described in the link below. The Applicant and School rankings will be (Attributes ?) of the Applicant and School class, and I simulate this ranking process by considering Applicants and Schools attributes, but basically similar qualities get mutually ranked. (I go go on if someone is interested but I thought it best to keep the discution on what I am trying to learn about classes) http://www.nrmp.org/res_match/about_res/algorithms.html Thanks Again Vincent Davis On Tue, Jun 9, 2009 at 1:12 AM, spir wrote: > Le Mon, 8 Jun 2009 17:31:23 -0600, > Vincent Davis s'exprima ainsi: > >> Accidentally sent I have added the rest >> (by the way I refrain from using the terms attribute, method,.... as I >> will likely miss use them) >> >> > I am reading several tutorials about classes and trying to figure out >> > how to apply it to my project. I have a working program that basically >> > matches up applicants and schools. Schools and applicants have and >> > "true" quality and an "observed" quality. Then there is an algorithm >> > that matches them up. Right now I do this all with lists which works >> > ok but I would like to try using classes. > >> > Questions >> > 1, does it make seens to have a applicant and a schools class (based >> > on this brief explanation) > > Based on your explanations, I don't really understand the problem you're trying to solve, nore the algorithm. Still, probably it makes sense to use Applicant and School classes for the simple reason these notions in your program represent "objects": there are single, identified, things ; as opposed to "values" (in the ordinary sense of the term) that represent qualities or information such as color, position, number, or "true" and "observed" above. > (By the way, don't use 'true', it's too misleading. Maybe 'truth' instead.) > > This notion of object identity would allow you, for instance, to match an applicant to a school by letting the applicant's attribute 'matched_school' directly point to a school itself, instead of a number that indirectly represents the school. > > Also, you've got a collection of schools and applicants, which probably means they will be stored in a set or a list. Once you have a type for them, it's easier to safely manipulate them in a unified manner. Even if they have only one single data attribute, I would do it: this also brings a centralised place to expose the object type's structure and behaviour. > >> > 2, is it possible to have a class for the algorithm that will modify >> > values in the applicant and schools class >> for example applicant.matched = 4 and school.matched = 343 meaning >> applicant 343 is matched to school 4 > > No, if I understand what you mean. You won't have a separate "class" only to store actions (python is not java), but instead you should precisely attribute these as methods to the Applicant or School types. > >> 3, is I have a value set in a class applicant.foo = 5 and I what to >> use a (method?) in the class to change this, what is the right way to >> do this? > > Below an example: > > ==================== > class Point(object): > ? ? ? ?def __init__(self, x=0,y=0): > ? ? ? ? ? ? ? ?self.x = x > ? ? ? ? ? ? ? ?self.y = y > ? ? ? ?def move(self, dx,dy): > ? ? ? ? ? ? ? ?print self, > ? ? ? ? ? ? ? ?self.x += dx > ? ? ? ? ? ? ? ?self.y += dy > ? ? ? ? ? ? ? ?print "--> %s" % self > ? ? ? ?def __str__(self): > ? ? ? ? ? ? ? ?return "Point (%s,%s)" % (self.x,self.y) > > p0 = Point() ; print p0 > p = Point(9,8) ; print p > p.move(-11,11) > ==================== > ==> > ==================== > Point (0,0) > Point (9,8) > Point (9,8) --> Point (-2,19) > ==================== > > Denis > ------ > la vita e estrany > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From lie.1296 at gmail.com Tue Jun 9 15:31:37 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 09 Jun 2009 23:31:37 +1000 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: <87d8ca690906090547y4879f6aenfc1b498bf8865a9b@mail.gmail.com> References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> <333efb450906080826q28e135a0g9aa483bb0ac6a729@mail.gmail.com> <3753b0ed0906080853w3cd3704cq8b94a74028e8240b@mail.gmail.com> <333efb450906081145j2c25570cu2a8c3411a53f57ba@mail.gmail.com> <87d8ca690906090100la3a9326ucd5ba0400983635c@mail.gmail.com> <87d8ca690906090103r56fe45f1yeca162fc2ee6444b@mail.gmail.com> <3753b0ed0906090133u58cb3135qd3927c3a718ad6c3@mail.gmail.com> <3753b0ed0906090434l25ae197fv4421e89a3a6893ee@mail.gmail.com> <333efb450906090503q6c6bcd89nde429252e9b22d53@mail.gmail.com> <87d8ca690906090547y4879f6aenfc1b498bf8865a9b@mail.gmail.com> Message-ID: Mike Hoy wrote: > On Tue, Jun 9, 2009 at 6:34 AM, The Green Tea Leaf > > wrote: > > I got an email from him that he had a gzip.pyc file in that folder. > Once he deleted that everything works OK. > > > Heh... I think I've made that mistake before; > > "My import statement doesn't work right! When I "import " > it tells me none of the methods are available!" > > And then I realize my file was named that. Doh! > > live and learn though, eh? > > Yea and I knew better than to do that too. Guess I had to make the > mistake to really get it into my head.. Funny how that works. You read > all about that stuff in books, but you don't actually know it until you > put it into practice. I think most people have done this at least once in their life; I still remember when I did it... not only once, in fact... And I think it is one of the most frequent cause of "misbehaving libraries"... Maybe python should issue some kind of warning when a module being imported from a local path has the same name as an installed module? It is never a good idea to name a module the same as an installed library unless you're deliberately trying to shadow the library for some reason (in which case you're a fully consenting adult). From srilyk at gmail.com Tue Jun 9 15:49:46 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 9 Jun 2009 08:49:46 -0500 Subject: [Tutor] Can't figure out why this is printing twice In-Reply-To: References: <87d8ca690906080257j7270c173j77d7e3aaf0629697@mail.gmail.com> <333efb450906081145j2c25570cu2a8c3411a53f57ba@mail.gmail.com> <87d8ca690906090100la3a9326ucd5ba0400983635c@mail.gmail.com> <87d8ca690906090103r56fe45f1yeca162fc2ee6444b@mail.gmail.com> <3753b0ed0906090133u58cb3135qd3927c3a718ad6c3@mail.gmail.com> <3753b0ed0906090434l25ae197fv4421e89a3a6893ee@mail.gmail.com> <333efb450906090503q6c6bcd89nde429252e9b22d53@mail.gmail.com> <87d8ca690906090547y4879f6aenfc1b498bf8865a9b@mail.gmail.com> Message-ID: <333efb450906090649t39324402t724699395958b42e@mail.gmail.com> On Tue, Jun 9, 2009 at 8:31 AM, Lie Ryan wrote: > > Maybe python should issue some kind of warning when a module being > imported from a local path has the same name as an installed module? It > is never a good idea to name a module the same as an installed library > unless you're deliberately trying to shadow the library for some reason > (in which case you're a fully consenting adult). > > so I guess it would search the library, then local path, and warn and import if it finds from the local path? That's one thing that would be useful to borrow from C(?)/C++ - if you import then it only looks in the standard location. If you import "somelib" then it looks in the local path and if it's not found it looks in the standard location. I think there's some other syntax that only looks for the library locally, too. I wonder what the BDFL would/has said. /me wanders off to see what he can find... -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Tue Jun 9 16:49:19 2009 From: denis.spir at free.fr (spir) Date: Tue, 9 Jun 2009 16:49:19 +0200 Subject: [Tutor] glob.glob(pattern, dir) ? Message-ID: <20090609164919.7c77f5b9@o> Hello, is there a way to make glob work in a specified dir? (or is it necessary to use os.chdir first?) Thank you, denis ------ la vita e estrany From sander.sweers at gmail.com Tue Jun 9 17:40:26 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 9 Jun 2009 17:40:26 +0200 Subject: [Tutor] glob.glob(pattern, dir) ? In-Reply-To: <20090609164919.7c77f5b9@o> References: <20090609164919.7c77f5b9@o> Message-ID: 2009/6/9 spir : > is there a way to make glob work in a specified dir? glob needs a pathname and uses the current dir if no full path is given. Prepend the path to your match (*.txt in example below) and it works like you want it. >>> import glob >>> glob.glob('c:\\GTK\\*.txt') ['c:\\GTK\\license.txt'] Greets Sander From lie.1296 at gmail.com Tue Jun 9 18:12:17 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 10 Jun 2009 02:12:17 +1000 Subject: [Tutor] glob.glob(pattern, dir) ? In-Reply-To: <20090609164919.7c77f5b9@o> References: <20090609164919.7c77f5b9@o> Message-ID: spir wrote: > Hello, > > is there a way to make glob work in a specified dir? > (or is it necessary to use os.chdir first?) > > Thank you, > denis > ------ > la vita e estrany > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ... glob(pathname) Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. ... >>> glob.glob("/*r*/*/portage") ['/var/tmp/portage', '/var/lib/portage', '/var/log/portage', '/usr/share/portage', '/usr/X11R6/portage', '/usr/tmp/portage', '/usr/lib/portage', '/usr/lib64/portage'] From vincent at vincentdavis.net Tue Jun 9 19:47:53 2009 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 9 Jun 2009 11:47:53 -0600 Subject: [Tutor] question about class In-Reply-To: <77e831100906090602x642da43dy29dcf13e608a81b2@mail.gmail.com> References: <77e831100906081625m135a06c5wfda04729397a604a@mail.gmail.com> <77e831100906081631v7999c432u7bb853fc9159fcd0@mail.gmail.com> <20090609091238.74ce8c7b@o> <77e831100906090602x642da43dy29dcf13e608a81b2@mail.gmail.com> Message-ID: <77e831100906091047r50ab1155kceb4aeda3a681342@mail.gmail.com> Thanks again for the help, A little followup. For my applicant class I have a few initial values that need to be set but I what to choose the value (actually the calculation to set the value) for each applicant (instance?) Here is the start of my Applicant Class class Applicant(object): "quality is refers to the quality of the Applicant observe refers to the accuracy of which they assess the quality of the school" def __init__(self, quality = 0, observe = 0): self. quality = quality self. observe = observe def Quality(self, mean, sd): print self, self.quality = normalvariate(mean, sd) print "--> %s" % self def Observe(self, mean, sd): print self, self. observe = normalvariate(mean, sd) print "--> %s" % self Or I could I guess do it this way, Is this better? I will only be setting the quality and observe values once for each instance. class Applicant(object): "quality is refers to the quality of the Applicant observe refers to the accuracy of which they assess the quality of the school" def __init__(self, mquality = 0, sdquality = 0, mobserve = 0, sdobserve = 0): self. quality = normalvariate(mquality, sdquality) self. observe = normalvariate(mobserve, sdobserve) Thanks Vincent Davis 720-301-3003 On Tue, Jun 9, 2009 at 7:02 AM, Vincent Davis wrote: > Thanks for the help and comments, I think my questions have been > answered, I will know if I understand when I try to implement them. > The Match algorithm. algorithm is described in the link below. The > Applicant and School rankings will be (Attributes ?) of the Applicant > and School class, and I simulate this ranking process by considering > Applicants and Schools attributes, but basically similar qualities get > mutually ranked. (I go go on if someone is interested but I thought it > best to keep the discution on what I am trying to learn about classes) > > http://www.nrmp.org/res_match/about_res/algorithms.html > > Thanks Again > Vincent Davis > > > > > On Tue, Jun 9, 2009 at 1:12 AM, spir wrote: >> Le Mon, 8 Jun 2009 17:31:23 -0600, >> Vincent Davis s'exprima ainsi: >> >>> Accidentally sent I have added the rest >>> (by the way I refrain from using the terms attribute, method,.... as I >>> will likely miss use them) >>> >>> > I am reading several tutorials about classes and trying to figure out >>> > how to apply it to my project. I have a working program that basically >>> > matches up applicants and schools. Schools and applicants have and >>> > "true" quality and an "observed" quality. Then there is an algorithm >>> > that matches them up. Right now I do this all with lists which works >>> > ok but I would like to try using classes. >> >>> > Questions >>> > 1, does it make seens to have a applicant and a schools class (based >>> > on this brief explanation) >> >> Based on your explanations, I don't really understand the problem you're trying to solve, nore the algorithm. Still, probably it makes sense to use Applicant and School classes for the simple reason these notions in your program represent "objects": there are single, identified, things ; as opposed to "values" (in the ordinary sense of the term) that represent qualities or information such as color, position, number, or "true" and "observed" above. >> (By the way, don't use 'true', it's too misleading. Maybe 'truth' instead.) >> >> This notion of object identity would allow you, for instance, to match an applicant to a school by letting the applicant's attribute 'matched_school' directly point to a school itself, instead of a number that indirectly represents the school. >> >> Also, you've got a collection of schools and applicants, which probably means they will be stored in a set or a list. Once you have a type for them, it's easier to safely manipulate them in a unified manner. Even if they have only one single data attribute, I would do it: this also brings a centralised place to expose the object type's structure and behaviour. >> >>> > 2, is it possible to have a class for the algorithm that will modify >>> > values in the applicant and schools class >>> for example applicant.matched = 4 and school.matched = 343 meaning >>> applicant 343 is matched to school 4 >> >> No, if I understand what you mean. You won't have a separate "class" only to store actions (python is not java), but instead you should precisely attribute these as methods to the Applicant or School types. >> >>> 3, is I have a value set in a class applicant.foo = 5 and I what to >>> use a (method?) in the class to change this, what is the right way to >>> do this? >> >> Below an example: >> >> ==================== >> class Point(object): >> ? ? ? ?def __init__(self, x=0,y=0): >> ? ? ? ? ? ? ? ?self.x = x >> ? ? ? ? ? ? ? ?self.y = y >> ? ? ? ?def move(self, dx,dy): >> ? ? ? ? ? ? ? ?print self, >> ? ? ? ? ? ? ? ?self.x += dx >> ? ? ? ? ? ? ? ?self.y += dy >> ? ? ? ? ? ? ? ?print "--> %s" % self >> ? ? ? ?def __str__(self): >> ? ? ? ? ? ? ? ?return "Point (%s,%s)" % (self.x,self.y) >> >> p0 = Point() ; print p0 >> p = Point(9,8) ; print p >> p.move(-11,11) >> ==================== >> ==> >> ==================== >> Point (0,0) >> Point (9,8) >> Point (9,8) --> Point (-2,19) >> ==================== >> >> Denis >> ------ >> la vita e estrany >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From denis.spir at free.fr Tue Jun 9 20:23:45 2009 From: denis.spir at free.fr (spir) Date: Tue, 9 Jun 2009 20:23:45 +0200 Subject: [Tutor] glob.glob(pattern, dir) ? In-Reply-To: References: <20090609164919.7c77f5b9@o> Message-ID: <20090609202345.10f65912@o> Le Tue, 9 Jun 2009 17:40:26 +0200, Sander Sweers s'exprima ainsi: > 2009/6/9 spir : > > is there a way to make glob work in a specified dir? > > glob needs a pathname and uses the current dir if no full path is > given. Prepend the path to your match (*.txt in example below) and it > works like you want it. > > >>> import glob > >>> glob.glob('c:\\GTK\\*.txt') > ['c:\\GTK\\license.txt'] > > Greets > Sander Thank you. That was so simple I couldn't figure it out myself ;-) What I was expecting is: import os, glob def dirglob(dir, pattern): fullPattern = os.path.join(dir,pattern) return glob.glob(fullPattern) (used e.g. print dirglob("/home/spir/prog/*/doc", "*.txt") to get .txt files from only doc subdirs of all projects) Denis ------ la vita e estrany From davea at ieee.org Tue Jun 9 20:39:19 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 09 Jun 2009 14:39:19 -0400 Subject: [Tutor] glob.glob(pattern, dir) ? In-Reply-To: References: Message-ID: <4A2EAC57.6070304@ieee.org> spir wrote: > Hello, > > is there a way to make glob work in a specified dir? > (or is it necessary to use os.chdir first?) > > Thank you, > denis > You can hand glob.glob either a relative pathname (in which it's relative to the current directory), or an absolute pathname. From sander.sweers at gmail.com Tue Jun 9 20:50:35 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 09 Jun 2009 20:50:35 +0200 Subject: [Tutor] glob.glob(pattern, dir) ? In-Reply-To: <20090609202345.10f65912@o> References: <20090609164919.7c77f5b9@o> <20090609202345.10f65912@o> Message-ID: <1244573435.5894.5.camel@infirit.homelinux.org> On Tue, 2009-06-09 at 20:23 +0200, spir wrote: > Le Tue, 9 Jun 2009 17:40:26 +0200, > Sander Sweers s'exprima ainsi: > > 2009/6/9 spir : > > > is there a way to make glob work in a specified dir? > > > > >>> import glob > > >>> glob.glob('c:\\GTK\\*.txt') > Thank you. That was so simple I couldn't figure it out myself ;-) OK, sorry I misunderstood the question. > What I was expecting is: > > (used e.g. > print dirglob("/home/spir/prog/*/doc", "*.txt") > to get .txt files from only doc subdirs of all projects) This time you explained it way better then before ;-) Greets Sander From alan.gauld at btinternet.com Tue Jun 9 21:38:59 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 9 Jun 2009 20:38:59 +0100 Subject: [Tutor] question about class References: <77e831100906081625m135a06c5wfda04729397a604a@mail.gmail.com><77e831100906081631v7999c432u7bb853fc9159fcd0@mail.gmail.com><20090609091238.74ce8c7b@o><77e831100906090602x642da43dy29dcf13e608a81b2@mail.gmail.com> <77e831100906091047r50ab1155kceb4aeda3a681342@mail.gmail.com> Message-ID: "Vincent Davis" wrote > Here is the start of my Applicant Class class Applicant(object): "quality is refers to the quality of the Applicant observe refers to the accuracy of which they assess the quality of the school" I guess you intended those to be triple quotes? def __init__(self, quality = 0, observe = 0): self. quality = quality self. observe = observe def Quality(self, mean, sd): print self, self.quality = normalvariate(mean, sd) print "--> %s" % self Its normal to use lowercase letters to start a method name. ot needed but convention. But of course you'd need to change the name to avoid conflicts with the attribute. Do you really want to priont self? That will say something like "" You could however provide a __str__ method that will print out what you do want to see. def Observe(self, mean, sd): print self, self. observe = normalvariate(mean, sd) print "--> %s" % self > Or I could I guess do it this way, Is this better? I will only be > setting the quality and observe values once for each instance. This is a class with only an __init__ method, that's usually a suspicious sign. What does the class do? BTW its also unusual to have verbs as attributes. (Unless they are boolean flags and even then its better to make it a question eg. doesObserve. Should your self.observe be self.observation say? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From e_mitges at hotmail.com Tue Jun 9 23:41:41 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Tue, 9 Jun 2009 17:41:41 -0400 Subject: [Tutor] gui Message-ID: I was wondering in a python made in pyg4m3 menu how to initialize another pyg4m3 Destruction.py from a button in the event handler this is the error i keep gettingTraceback (most recent call last): File "C:\Users\John Doe\Desktop\Destruction\back.py", line 47, in main() File "C:\Users\John Doe\Desktop\Destruction\back.py", line 37, in main elif sbut.clicked(k.pos): File "C:\Users\John Doe\Desktop\WODDS\but.py", line 200, in clicked subprocess.Popen(["Destruction", "Destruction.py"]) File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo)WindowsError: [Error 2] The system cannot find the file specifiedAlso could anyone help me to display the contents of a text file in a pyg4m3 window _________________________________________________________________ Internet explorer 8 lets you browse the web faster. http://go.microsoft.com/?linkid=9655582 -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Wed Jun 10 00:20:11 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 10 Jun 2009 00:20:11 +0200 Subject: [Tutor] gui In-Reply-To: References: Message-ID: <1244586011.5894.16.camel@infirit.homelinux.org> Can you try this again but please use plain text instead of html.. If you can not send in plain text then use a pastebin like python.pastebin.com to show your code and/or error messages. Greets Sander On Tue, 2009-06-09 at 17:41 -0400, Essah Mitges wrote: > I was wondering in a python made in pyg4m3 menu how to initialize > another pyg4m3 Destruction.py from a button in the event handler this > is the error i keep getting Traceback (most recent call last): File > "C:\Users\John Doe\Desktop\Destruction\back.py", line 47, in > main() File "C:\Users\John Doe\Desktop\Destruction\back.py", line > 37, in main elif sbut.clicked(k.pos): File "C:\Users\John Doe > \Desktop\WODDS\but.py", line 200, in clicked > subprocess.Popen(["Destruction", "Destruction.py"]) File "C: > \Python26\lib\subprocess.py", line 595, in __init__ errread, > errwrite) File "C:\Python26\lib\subprocess.py", line 804, in > _execute_child startupinfo) WindowsError: [Error 2] The system > cannot find the file specified Also could anyone help me to display > the contents of a text file in a pyg4m3 window From e_mitges at hotmail.com Wed Jun 10 00:26:24 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Tue, 9 Jun 2009 18:26:24 -0400 Subject: [Tutor] gui In-Reply-To: <1244586011.5894.16.camel@infirit.homelinux.org> References: <1244586011.5894.16.camel@infirit.homelinux.org> Message-ID: What I am trying to do is using a pygame window I want to list the contents of a text call high_score.txt in that windowThe second thing I am trying to do is initiate my game also made in pygame to start off a button that a programmed called Destruction.pyThe error was what had happened was that the module i made for pygame is not initiating my game properly > Subject: Re: [Tutor] gui > From: sander.sweers at gmail.com > To: e_mitges at hotmail.com > CC: tutor at python.org > Date: Wed, 10 Jun 2009 00:20:11 +0200 > > Can you try this again but please use plain text instead of html.. If > you can not send in plain text then use a pastebin like > python.pastebin.com to show your code and/or error messages. > > Greets > Sander > > On Tue, 2009-06-09 at 17:41 -0400, Essah Mitges wrote: >> I was wondering in a python made in pyg4m3 menu how to initialize >> another pyg4m3 Destruction.py from a button in the event handler this >> is the error i keep getting Traceback (most recent call last): File >> "C:\Users\John Doe\Desktop\Destruction\back.py", line 47, in >> main() File "C:\Users\John Doe\Desktop\Destruction\back.py", line >> 37, in main elif sbut.clicked(k.pos): File "C:\Users\John Doe >> \Desktop\WODDS\but.py", line 200, in clicked >> subprocess.Popen(["Destruction", "Destruction.py"]) File "C: >> \Python26\lib\subprocess.py", line 595, in __init__ errread, >> errwrite) File "C:\Python26\lib\subprocess.py", line 804, in >> _execute_child startupinfo) WindowsError: [Error 2] The system >> cannot find the file specified Also could anyone help me to display >> the contents of a text file in a pyg4m3 window > _________________________________________________________________ Windows Live helps you keep up with all your friends, in one place. http://go.microsoft.com/?linkid=9660826 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jun 10 00:35:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 9 Jun 2009 23:35:04 +0100 Subject: [Tutor] gui References: <1244586011.5894.16.camel@infirit.homelinux.org> Message-ID: "Essah Mitges" wrote > What I am trying to do is using a pygame window I want > to list the contents of a text call high_score.txt in that window Have you tried asking on the PyGame forums/mailing lists? I'm sure such things exist. This forum is for general Ptython programming, specifically for learners. While we are happy to try to help I don't know that we have many pygame experts here. > The second thing I am trying to do is initiate my game also > made in pygame to start off a button that a programmed > called Destruction.py I have no idea how pygame works for buildng GUIs but usually you tie a button to a python function not a program. Are you sure that is not what you should be doing? > The error was what had happened was that the module > i made for pygame is not initiating my game properly The other error you made was posting unreadable emails to the list. We are keen to help where we can but don't force us to manually unpick a steam of text. Please senmd plain text - your email system should have a setting to allow that. > On Tue, 2009-06-09 at 17:41 -0400, Essah Mitges wrote: >> I was wondering in a python made in pyg4m3 menu how to initialize >> another pyg4m3 Destruction.py from a button in the event handler this >> is the error i keep getting Traceback (most recent call last): File >> "C:\Users\John Doe\Desktop\Destruction\back.py", line 47, in >> main() File "C:\Users\John Doe\Desktop\Destruction\back.py", line >> 37, in main elif sbut.clicked(k.pos): File "C:\Users\John Doe >> \Desktop\WODDS\but.py", line 200, in clicked >> subprocess.Popen(["Destruction", "Destruction.py"]) File "C: >> \Python26\lib\subprocess.py", line 595, in __init__ errread, >> errwrite) File "C:\Python26\lib\subprocess.py", line 804, in >> _execute_child startupinfo) WindowsError: [Error 2] The system >> cannot find the file specified Also could anyone help me to display >> the contents of a text file in a pyg4m3 window HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From e_mitges at hotmail.com Wed Jun 10 00:42:51 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Tue, 9 Jun 2009 18:42:51 -0400 Subject: [Tutor] gui In-Reply-To: References: <1244586011.5894.16.camel@infirit.homelinux.org> Message-ID: Traceback (most recent call last): File "C:\Users\John Doe\Desktop\D-Day\back.py", line 47, in main() File "C:\Users\John Doe\Desktop\D-Day\back.py", line 37, in main elif sbut.clicked(k.pos): File "C:\Users\John Doe\Desktop\D-day\but.py", line 200, in clicked subprocess.Popen(["D-Day", "Destruction.py"]) File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo)WindowsError: [Error 2] The system cannot find the file specifiedThe error in readable form > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Tue, 9 Jun 2009 23:35:04 +0100 > Subject: Re: [Tutor] gui > > > "Essah Mitges" wrote > >> What I am trying to do is using a pygame window I want >> to list the contents of a text call high_score.txt in that window > > Have you tried asking on the PyGame forums/mailing lists? > I'm sure such things exist. This forum is for general Ptython > programming, specifically for learners. While we are happy > to try to help I don't know that we have many pygame experts > here. > >> The second thing I am trying to do is initiate my game also >> made in pygame to start off a button that a programmed >> called Destruction.py > > I have no idea how pygame works for buildng GUIs but usually > you tie a button to a python function not a program. Are you > sure that is not what you should be doing? > >> The error was what had happened was that the module >> i made for pygame is not initiating my game properly > > The other error you made was posting unreadable emails to > the list. We are keen to help where we can but don't force > us to manually unpick a steam of text. Please senmd plain text > - your email system should have a setting to allow that. > >> On Tue, 2009-06-09 at 17:41 -0400, Essah Mitges wrote: >>> I was wondering in a python made in pyg4m3 menu how to initialize >>> another pyg4m3 Destruction.py from a button in the event handler this >>> is the error i keep getting Traceback (most recent call last): File >>> "C:\Users\John Doe\Desktop\Destruction\back.py", line 47, in >>> main() File "C:\Users\John Doe\Desktop\Destruction\back.py", line >>> 37, in main elif sbut.clicked(k.pos): File "C:\Users\John Doe >>> \Desktop\WODDS\but.py", line 200, in clicked >>> subprocess.Popen(["Destruction", "Destruction.py"]) File "C: >>> \Python26\lib\subprocess.py", line 595, in __init__ errread, >>> errwrite) File "C:\Python26\lib\subprocess.py", line 804, in >>> _execute_child startupinfo) WindowsError: [Error 2] The system >>> cannot find the file specified Also could anyone help me to display >>> the contents of a text file in a pyg4m3 window > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Windows Live helps you keep up with all your friends, in one place. http://go.microsoft.com/?linkid=9660826 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mkhawarzia at hotmail.com Wed Jun 10 00:38:54 2009 From: mkhawarzia at hotmail.com (Mohammad Khawar Zia) Date: Tue, 9 Jun 2009 18:38:54 -0400 Subject: [Tutor] What is nntp news reader address for this mailing list? Message-ID: Hello All, I am new to this mailing list. I am trying to setup outlook to read the posts on this mailing list. What is the nntp address for thsi mailing list? nntp://news.gmane.org/gmane.comp.python.tutor doesn't work. Thanks, --Zia From emile at fenx.com Wed Jun 10 01:03:10 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 09 Jun 2009 16:03:10 -0700 Subject: [Tutor] What is nntp news reader address for this mailing list? In-Reply-To: References: Message-ID: On 6/9/2009 3:38 PM Mohammad Khawar Zia said... > Hello All, > > I am new to this mailing list. I am trying to setup outlook Which version? Older ones don't do news right and you'll need to be on outlook express if you must use something called outlook. Try Thunderbird. > to read the > posts on this mailing list. > > What is the nntp address for thsi mailing list? The news server is nntp://news.gmane.org/ Then subscribe to the lists you're interested in. Emile > > nntp://news.gmane.org/gmane.comp.python.tutor > doesn't work. > > Thanks, > --Zia > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From mkhawarzia at hotmail.com Wed Jun 10 01:24:14 2009 From: mkhawarzia at hotmail.com (Zia) Date: Tue, 9 Jun 2009 19:24:14 -0400 Subject: [Tutor] What is nntp news reader address for this mailing list? References: Message-ID: Thanks It works now. http://www.parglena.co.uk/outlookexpress.htm -Zia "Emile van Sebille" wrote in message news:h0mpjl$7bk$1 at ger.gmane.org... > On 6/9/2009 3:38 PM Mohammad Khawar Zia said... >> Hello All, >> >> I am new to this mailing list. I am trying to setup outlook > > Which version? Older ones don't do news right and you'll need to be on > outlook express if you must use something called outlook. Try > Thunderbird. > >> to read the posts on this mailing list. >> >> What is the nntp address for thsi mailing list? > > The news server is nntp://news.gmane.org/ > > Then subscribe to the lists you're interested in. > > Emile > > >> >> nntp://news.gmane.org/gmane.comp.python.tutor >> doesn't work. >> >> Thanks, >> --Zia >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ayyaz84 at gmail.com Wed Jun 10 01:36:45 2009 From: ayyaz84 at gmail.com (ayyaz) Date: Tue, 9 Jun 2009 19:36:45 -0400 Subject: [Tutor] What is nntp news reader address for this mailing list? References: Message-ID: Testing "Zia" wrote in message news:h0mqv0$b06$1 at ger.gmane.org... > Thanks > It works now. > > http://www.parglena.co.uk/outlookexpress.htm > > -Zia > "Emile van Sebille" wrote in message > news:h0mpjl$7bk$1 at ger.gmane.org... >> On 6/9/2009 3:38 PM Mohammad Khawar Zia said... >>> Hello All, >>> >>> I am new to this mailing list. I am trying to setup outlook >> >> Which version? Older ones don't do news right and you'll need to be on >> outlook express if you must use something called outlook. Try >> Thunderbird. >> >>> to read the posts on this mailing list. >>> >>> What is the nntp address for thsi mailing list? >> >> The news server is nntp://news.gmane.org/ >> >> Then subscribe to the lists you're interested in. >> >> Emile >> >> >>> >>> nntp://news.gmane.org/gmane.comp.python.tutor >>> doesn't work. >>> >>> Thanks, >>> --Zia >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From e_mitges at hotmail.com Wed Jun 10 01:49:55 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Tue, 9 Jun 2009 19:49:55 -0400 Subject: [Tutor] gui further explained Message-ID: What I am trying to do is start my pygame game from my pygame menuI do not think I am using the right code to do this I am trying to use the subprocess module to open a child window with the game inside of it but python doesn't like thatThe second thing that i'd like to know how I could list the content of a text file inside a pygame window(this is a different file)Traceback (most recent call last): File "C:\Users\John Doe\Desktop\D-Day\back.py", line 47, in main() File "C:\Users\John Doe\Desktop\D-Day\back.py", line 37, in main elif sbut.clicked(k.pos): File "C:\Users\John Doe\Desktop\D-day\but.py", line 200, in clicked subprocess.Popen(["D-Day", "Destruction.py"]) File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo)WindowsError: [Error 2] The system cannot find the file specified _________________________________________________________________ Attention all humans. We are your photos. Free us. http://go.microsoft.com/?linkid=9666046 From david at abbottdavid.com Wed Jun 10 02:07:15 2009 From: david at abbottdavid.com (David) Date: Tue, 09 Jun 2009 20:07:15 -0400 Subject: [Tutor] gui further explained (The error in unreadable form) In-Reply-To: References: Message-ID: <4A2EF933.4060702@abbottdavid.com> Essah Mitges wrote: > What I am trying to do is start my pygame game from my pygame menuI do not think I am using the right code to do this I am trying to use the subprocess module to open a child window with the game inside of it but python doesn't like thatThe second thing that i'd like to know how I could list the content of a text file inside a pygame window(this is a different file)Traceback (most recent call last): File "C:\Users\John Doe\Desktop\D-Day\back.py", line 47, in main() File "C:\Users\John Doe\Desktop\D-Day\back.py", line 37, in main elif sbut.clicked(k.pos): File "C:\Users\John Doe\Desktop\D-day\but.py", line 200, in clicked subprocess.Popen(["D-Day", "Destruction.py"]) File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo)WindowsError: [Error 2] The system cannot find the file specified > _________________________________________________________________ > Attention all humans. We are your photos. Free us. > http://go.microsoft.com/?linkid=9666046 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From srilyk at gmail.com Wed Jun 10 02:11:03 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 9 Jun 2009 19:11:03 -0500 Subject: [Tutor] gui further explained In-Reply-To: References: Message-ID: <333efb450906091711n6e18a56bief72e03b7a64b6b2@mail.gmail.com> On Tue, Jun 9, 2009 at 6:49 PM, Essah Mitges wrote: > > What I am trying to do is start my pygame game from my pygame menuI do not > think I am using the right code to do this I am trying to use the subprocess > module to open a child window with the game inside of it but python doesn't > like thatThe second thing that i'd like to know how I could list the content > of a text file inside a pygame window(this is a different file)Traceback > (most recent call last): File "C:\Users\John Doe\Desktop\D-Day\back.py", > line 47, in main() File "C:\Users\John Doe\Desktop\D-Day\back.py", line > 37, in main elif sbut.clicked(k.pos): File "C:\Users\John > Doe\Desktop\D-day\but.py", line 200, in clicked > subprocess.Popen(["D-Day", "Destruction.py"]) File > "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) > File "C:\Python26\lib\subprocess.py", line 804, in _execute_child > startupinfo)WindowsError: [Error 2] The system cannot find the file > specified > As far as I can tell, since your error formatting was lost, is that Popen can't find the the file. The other problem is that what you're thinking of really makes no sense. Pygame doesn't need (and shouldn't) run a program "inside" the window. You should have all of your game processes available to the main program and when you want to start the game it should just be a part of it - not a subprocess. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From e_mitges at hotmail.com Wed Jun 10 02:17:27 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Tue, 9 Jun 2009 20:17:27 -0400 Subject: [Tutor] gui further explained (The error in unreadable form) In-Reply-To: <4A2EF933.4060702@abbottdavid.com> References: <4A2EF933.4060702@abbottdavid.com> Message-ID: ok I follows like 3 ppl instructions for making readable errors I'lll manually type it out lolTraceback (most recent call last): File "C:\Users\John Doe\Desktop\D-Day\back.py", line 47, in main() File "C:\Users\John Doe\Desktop\D-Day\back.py", line 37, in main elif sbut.clicked(k.pos): File "C:\Users\John Doe\Desktop\D-Day\back.py", line 200, in clicked subprocess.Popen(["D-Day", "Destruction.py"]) File "C:\Python26\lib\subprocess.py", line 595, in ___init___ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo)WindowsError: [Error 2} The system cannot find the file specified ---------------------------------------- > Date: Tue, 9 Jun 2009 20:07:15 -0400 > From: david at abbottdavid.com > To: e_mitges at hotmail.com > CC: tutor at python.org > Subject: Re: [Tutor] gui further explained (The error in unreadable form) > > Essah Mitges wrote: >> What I am trying to do is start my pygame game from my pygame menuI do not think I am using the right code to do this I am trying to use the subprocess module to open a child window with the game inside of it but python doesn't like thatThe second thing that i'd like to know how I could list the content of a text file inside a pygame window(this is a different file)Traceback (most recent call last): File "C:\Users\John Doe\Desktop\D-Day\back.py", line 47, in main() File "C:\Users\John Doe\Desktop\D-Day\back.py", line 37, in main elif sbut.clicked(k.pos): File "C:\Users\John Doe\Desktop\D-day\but.py", line 200, in clicked subprocess.Popen(["D-Day", "Destruction.py"]) File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo)WindowsError: [Error 2] The system cannot find the file specified >> _________________________________________________________________ >> Attention all humans. We are your photos. Free us. >> http://go.microsoft.com/?linkid=9666046 >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Powered by Gentoo GNU/Linux > http://linuxcrazy.com _________________________________________________________________ Attention all humans. We are your photos. Free us. http://go.microsoft.com/?linkid=9666046 From e_mitges at hotmail.com Wed Jun 10 02:18:38 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Tue, 9 Jun 2009 20:18:38 -0400 Subject: [Tutor] gui further explained In-Reply-To: <333efb450906091711n6e18a56bief72e03b7a64b6b2@mail.gmail.com> References: <333efb450906091711n6e18a56bief72e03b7a64b6b2@mail.gmail.com> Message-ID: lol i was trying to open it while keeping my menu open to have it in a different window ________________________________ > From: srilyk at gmail.com > Date: Tue, 9 Jun 2009 19:11:03 -0500 > Subject: Re: [Tutor] gui further explained > To: e_mitges at hotmail.com > CC: tutor at python.org > > On Tue, Jun 9, 2009 at 6:49 PM, Essah Mitges> wrote: > > > > > What I am trying to do is start my pygame game from my pygame menuI do not think I am using the right code to do this I am trying to use the subprocess module to open a child window with the game inside of it but python doesn't like thatThe second thing that i'd like to know how I could list the content of a text file inside a pygame window(this is a different file)Traceback (most recent call last): File "C:\Users\John Doe\Desktop\D-Day\back.py", line 47, in main() File "C:\Users\John Doe\Desktop\D-Day\back.py", line 37, in main elif sbut.clicked(k.pos): File "C:\Users\John Doe\Desktop\D-day\but.py", line 200, in clicked subprocess.Popen(["D-Day", "Destruction.py"]) File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo)WindowsError: [Error 2] The system cannot find the file specified > > > > As far as I can tell, since your error formatting was lost, is that Popen can't find the the file. > > The other problem is that what you're thinking of really makes no sense. Pygame doesn't need (and shouldn't) run a program "inside" the window. You should have all of your game processes available to the main program and when you want to start the game it should just be a part of it - not a subprocess. > > > > HTH, > Wayne > _________________________________________________________________ Windows Live helps you keep up with all your friends, in one place. http://go.microsoft.com/?linkid=9660826 From ranjeeth_gecmail at yahoo.com Wed Jun 10 04:12:43 2009 From: ranjeeth_gecmail at yahoo.com (Ranjeeth P T) Date: Tue, 9 Jun 2009 19:12:43 -0700 (PDT) Subject: [Tutor] python and serial port Message-ID: <795061.52762.qm@web59509.mail.ac4.yahoo.com> sir, I am new to python i want to communicate i.e send and receive b/n an arm device and pc via a serial port,arm part is fine i want to know abt the pc part in python which library and module should i use and also the funtions. Please help me Ranjeeth p t http://ranjeethpt.wordpress.com/ Govt Engineering College Palakkad Kerala India -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Wed Jun 10 04:40:37 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 9 Jun 2009 21:40:37 -0500 Subject: [Tutor] python and serial port In-Reply-To: <795061.52762.qm@web59509.mail.ac4.yahoo.com> References: <795061.52762.qm@web59509.mail.ac4.yahoo.com> Message-ID: <333efb450906091940ga2e1217pa1026ffaaa62d507@mail.gmail.com> On Tue, Jun 9, 2009 at 9:12 PM, Ranjeeth P T wrote: > sir, > I am new to python i want to communicate i.e send and receive b/n an arm > device and pc via a serial port,arm part is fine i want to know abt the pc > part in python > which library and module should i use and also the funtions. > Please help me check this out: http://pyserial.wiki.sourceforge.net/pySerial and there are plenty of tutorials online. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Wed Jun 10 04:48:28 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 9 Jun 2009 21:48:28 -0500 Subject: [Tutor] gui further explained In-Reply-To: References: <333efb450906091711n6e18a56bief72e03b7a64b6b2@mail.gmail.com> Message-ID: <333efb450906091948n72379a83na026c4a8c73b9569@mail.gmail.com> On Tue, Jun 9, 2009 at 7:18 PM, Essah Mitges wrote: > > lol i was trying to open it while keeping my menu open to have it in a > different window > So you have a pygame window that is just a menu? and when you select it will try to run another python script? Your description of your desired goal isn't terribly clear, and hence it's difficult to offer good advice. When you say "menu" and "different window" that could mean a host of things. If you say "I have a pygame window that consists of a menu; here is my code . I'm having problems when I select - I want it to , but . The interesting this is that often when I take the time to write out a detailed question I find that the answer is right there in front of me. I've probably almost posted about 10-15 questions in the past 6 months and then just by virtue of taking the time to really look over my code I find the solution to my problem. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Wed Jun 10 05:24:48 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 10 Jun 2009 13:24:48 +1000 Subject: [Tutor] gui In-Reply-To: References: <1244586011.5894.16.camel@infirit.homelinux.org> Message-ID: Essah Mitges wrote: > 1. > Traceback (most recent call last): > 2. > File "C:\Users\John Doe\Desktop\D-Day\back.py", line 47, in > 3. > main() > 4. > File "C:\Users\John Doe\Desktop\D-Day\back.py", line 37, in main > 5. > elif sbut.clicked(k.pos): > 6. > File "C:\Users\John Doe\Desktop\D-day\but.py", line 200, in clicked > 7. > subprocess.Popen(["D-Day", "Destruction.py"]) > 8. > File "C:\Python26\lib\subprocess.py", line 595, in __init__ > 9. > errread, errwrite) > 10. > File "C:\Python26\lib\subprocess.py", line 804, in _execute_child > 11. > startupinfo) > 12. > WindowsError: [Error 2] The system cannot find the file specified > > The error in readable form Readable doesn't mean it have to be colored and line numbered, although this is more readable than the previous one -- at least on a newsreader that supports HTML -- it's better to keep messages in plain text (i.e. not only unformatted text but change the newsreader's settings to pure, plain text) All right to the problem, the problem is not related to pygame at all; it's in your subprocess.Popen() call. The traceback says that subprocess.Popen cannot find the executable/script that would be run. A quick look at the traceback: subprocess.Popen(["D-Day", "Destruction.py"]) That line is executing an executable/script named "D-Day" and pass an argument "Destruction.py" to it. Probably not something you wanted to do. What you want to do is something like: subprocess.Popen(["D-Day\Destruction.py"]) or perhaps: subprocess.Popen(["python", "D-Day\Destruction.py"]) depending on whether the file association is setup correctly and whether the shell's search path is set to search python's install directory. From e_mitges at hotmail.com Wed Jun 10 05:31:23 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Tue, 9 Jun 2009 23:31:23 -0400 Subject: [Tutor] gui further explained In-Reply-To: <333efb450906091948n72379a83na026c4a8c73b9569@mail.gmail.com> References: <333efb450906091711n6e18a56bief72e03b7a64b6b2@mail.gmail.com> <333efb450906091948n72379a83na026c4a8c73b9569@mail.gmail.com> Message-ID: i don't know if its what i am searching that is wrong but what i am trying to do is link my game i made in pygame to my pygame menu the menu has 4 button classes on it one foe instruction one to quit one for high scores and one to start the game the 3 other buttons work all but the one to start the game this is basicly the menu i want people to see first the main menu From: srilyk at gmail.com Date: Tue, 9 Jun 2009 21:48:28 -0500 Subject: Re: [Tutor] gui further explained To: e_mitges at hotmail.com CC: tutor at python.org On Tue, Jun 9, 2009 at 7:18 PM, Essah Mitges wrote: lol i was trying to open it while keeping my menu open to have it in a different window So you have a pygame window that is just a menu? and when you select it will try to run another python script? Your description of your desired goal isn't terribly clear, and hence it's difficult to offer good advice. When you say "menu" and "different window" that could mean a host of things. If you say "I have a pygame window that consists of a menu; here is my code . I'm having problems when I select - I want it to , but . The interesting this is that often when I take the time to write out a detailed question I find that the answer is right there in front of me. I've probably almost posted about 10-15 questions in the past 6 months and then just by virtue of taking the time to really look over my code I find the solution to my problem. HTH, Wayne _________________________________________________________________ Attention all humans. We are your photos. Free us. http://go.microsoft.com/?linkid=9666046 -------------- next part -------------- An HTML attachment was scrubbed... URL: From strax-haber.m at neu.edu Wed Jun 10 05:01:33 2009 From: strax-haber.m at neu.edu (Matthew Strax-Haber) Date: Tue, 09 Jun 2009 23:01:33 -0400 Subject: [Tutor] Multi-Threading and KeyboardInterrupt Message-ID: <6AC49076-B62B-4FEB-BD41-9A0D5BCA3798@neu.edu> Hey everyone, I hope one of you can help me with this. This is my first foray into multi-threaded programming. I have tried to boil my code down to it's simplest demonstrative form. My program runs interactively by allowing the user to directly interact with the python prompt. This program has a runAll() method that runs a series of subprocesses with a cap on how many instances are running at a time. My intent is to allow the user to use Ctrl-C to break these subprocesses. Note that while not reflected in the demo below, each subprocess needs to be able to run clean-up code before shutting down (in single-threaded mode I just wrap in try-finally). When I run DB.py, and interrupt it with Ctrl-C, things do not run so cleanly. Please let me know what I can change to make this work properly. My intent is to have the following output: 'key interrupt 1' 'key interrupt 2' 'key interrupt 3' 'key interrupt 4' '********* stopped midway ********' Here is the code for a demo: ############################################################################## DB.py (run this): ############################################################################## #!/usr/bin/env python from subprocess import Popen from threading import Thread, BoundedSemaphore RUN_PERMISSION = BoundedSemaphore(3) def runSingle(i): with RUN_PERMISSION: Popen(['./Sub.py', str(i)]).wait() def runAll(): workers = [ Thread(target = runSingle, args = [i]) for i in xrange(RUN_PERMISSION._initial_value + 1) ] try: for w in workers: w.start() except KeyboardInterrupt: ## This should be shown on a KeyboardInterrupt print '********* stopped midway ********' for w in workers: w.join() runAll() ############################################################################## Sub.py (called by DB.py): ############################################################################## #!/usr/bin/env python import sys, time try: while True: pass except KeyboardInterrupt: print 'key interrupt %s' % sys.argv[1] raise ############################################################################## From mindimer at mac.com Wed Jun 10 06:57:48 2009 From: mindimer at mac.com (Melinda Roberts) Date: Tue, 09 Jun 2009 21:57:48 -0700 Subject: [Tutor] Help running a simple python script for one time operation (noob) Message-ID: Hi - I would like to export a large amount of data from ExpressionEngine to Wordpress, and have had lots of trouble finding something that isn't miles over my head. I did find these three scripts, which seem to be perfect for this purpose, but I don't know how to go about implementing them. It's a three-step process: 1. Configure and run Databases.cfg 2. Run ExpressionEngineExport.py 3. Run WordPressImport.py. I have a mac, am all set with access to my dbs on my host, all I need is to be pointed in the right direction. Anyone? Thank you! Mindy ................................................. Melinda Roberts Author of The Mommy Blog and Mommy Confidential Co-Founder, PearSoup.com Panelist, Momversation.com Creative Hub Resume and Portfolio Find me online: http://clicktoadd.me/MelindaRoberts -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Databases.cfg Type: application/octet-stream Size: 155 bytes Desc: not available URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ExpressionEngineExport.py Type: text/x-python-script Size: 7682 bytes Desc: not available URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: WordPressImporter.py Type: text/x-python-script Size: 8947 bytes Desc: not available URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Wed Jun 10 08:28:35 2009 From: denis.spir at free.fr (spir) Date: Wed, 10 Jun 2009 08:28:35 +0200 Subject: [Tutor] recursive glob -- recursive dir walk Message-ID: <20090610082835.5140d674@o> Hello, A foolow-up ;-) from previous question about glob.glob(). I need to 'glob' files recursively from a top dir (parameter). Tried to use os.walk, but the structure of its return value is really unhandy for such a use (strange, because it seems to me this precise use is typical). On the other hand, os.path.walk seemed to meet my needs, but it is deprecated. I'd like to know if there are standard tools to do that. And your comments on the 2 approaches below. Thank you, denis -1- I first wrote the following recurseDirGlob() tool func. ======================================================== import os, glob def dirGlob(dir, pattern): ''' File names matching pattern in directory dir. ''' fullPattern = os.path.join(dir,pattern) return glob.glob(fullPattern) def recurseDirGlob(topdir=None, pattern="*.*", nest=False, verbose=False): ''' ''' allFilenames = list() # current dir if verbose: print "*** %s" %topdir if topdir is None: topdir = os.getcwd() filenames = dirGlob(topdir, pattern) if verbose: for filename in [os.path.basename(d) for d in filenames]: print " %s" %filename allFilenames.extend(filenames) # possible sub dirs names = [os.path.join(topdir, dir) for dir in os.listdir(topdir)] dirs = [n for n in names if os.path.isdir(n)] if verbose: print "--> %s" % [os.path.basename(d) for d in dirs] if len(dirs) > 0: for dir in dirs: filenames = recurseDirGlob(dir, pattern, nest, verbose) if nest: allFilenames.append(filenames) else: allFilenames.extend(filenames) # final result return allFilenames ======================================================== Example with the following dir structure ; the version with nest=True will recursively nest files from subdirs. ======================================================== d0 d01 d02 d020 2 .txt files and 1 with a different pattern, in each dir recurseDirGlob("/home/spir/prog/d0", "*.txt", verbose=True) --> *** /home/spir/prog/d0 t01.txt t02.txt --> ['d01', 'd02'] *** /home/spir/prog/d0/d01 t011.txt t012.txt --> [] *** /home/spir/prog/d0/d02 t021.txt t022.txt --> ['d020'] *** /home/spir/prog/d0/d02/d020 t0201.txt t0202.txt --> [] ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', '/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt', '/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', '/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt'] recurseDirGlob("/home/spir/prog/d0", "*.txt") --> ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', '/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt', '/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', '/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt'] recurseDirGlob("/home/spir/prog/d0", "*.txt", nest=True) --> ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', ['/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt'], ['/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', ['/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt']]] ======================================================== -2- Another approach was to build a general 'dirWalk' tool func, similar to os.path.walk: ======================================================== def dirWalk(topdir=None, func=None, args=[], nest=False, verbose=False): ''' ''' allResults = list() # current dir if verbose: print "*** %s" %topdir if topdir is None: topdir = os.getcwd() results = func(topdir, *args) if verbose: print " %s" % results allResults.extend(results) # possible sub dirs names = [os.path.join(topdir, dir) for dir in os.listdir(topdir)] dirs = [n for n in names if os.path.isdir(n)] if verbose: print "--> %s" % [os.path.basename(d) for d in dirs] if len(dirs) > 0: for dir in dirs: results = dirWalk(dir, func, args, nest, verbose) if nest: allResults.append(results) else: allResults.extend(results) # final allResults return allResults ======================================================== Example uses to bring the same results, calling dirGlob, would be: dirWalk("/home/spir/prog/d0", dirGlob, args=["*.txt"], verbose=True) --> dirWalk("/home/spir/prog/d0", dirGlob, args=["*.txt"]) dirWalk("/home/spir/prog/d0", dirGlob, args=["*.txt"], nest=True) Denis ------ la vita e estrany From johan at accesstel.com.au Wed Jun 10 05:25:57 2009 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Wed, 10 Jun 2009 13:25:57 +1000 Subject: [Tutor] XML: changing value of elements Message-ID: <20090610032630.HKZY2116.nskntotgx01p.mx.bigpond.com@JohanPC> Hi all, I have a rather complex XML file and I need to change some values inside this file. So far I have been using minidom, but I can't find the thing I am looking for. My code so far: """ from xml.dom import minidom xmlFile = 'signal1.xml' xmlDocument = minidom.parse(xmlFile) SignalsNode = xmlDocument.firstChild signalNode = SignalsNode.childNodes[1] signalNode.removeAttribute("name") signalNode.setAttribute("name", "Test_Name") signalNode.getAttribute("name") descElem = signalNode.childNodes[1] """ I know how to manipulate the value of the attributes, but I can't seem to change the values of eg: "Description" Snippet from my XML file: """ - - Some description Model_X - normal Model X 1 - minor Model X 2 """ Any suggestions on how to change some of the values of the elements? Thanks Johan -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Wed Jun 10 12:20:28 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 10 Jun 2009 05:20:28 -0500 Subject: [Tutor] gui further explained In-Reply-To: References: <333efb450906091711n6e18a56bief72e03b7a64b6b2@mail.gmail.com> <333efb450906091948n72379a83na026c4a8c73b9569@mail.gmail.com> Message-ID: <333efb450906100320k653c2283me584e7273d4c36a5@mail.gmail.com> On Tue, Jun 9, 2009 at 10:31 PM, Essah Mitges wrote: > i don't know if its what i am searching that is wrong but what i am trying > to do is > link my game i made in pygame to my pygame menu the menu has 4 button > classes on it one foe instruction one to quit one for high scores and one to > start the game > the 3 other buttons work all but the one to start the game this is basicly > the menu i want people to see first the main menu > So why don't you put your menu in your game? Consider the following: # Lamegame.py - probably the lamest game ever! print "Welcome to Lame Game!" raw_input("Please type something and press enter: ") print "You win!" So there's a game. Now let's add a menu: # lamegameimproved.py - the lamest game, now with a menu! import sys print "Welcome to Lame Game!" print "\nMenu:\n" print "(Q)uit" print "(P)lay" choice = raw_input("Your Choice? (P or Q): ") if choice.lower() == 'q': sys.exit(0) elif choice.lower() == 'p': # add original code here See? Quite simple. Even with pygame it shouldn't be a whole lot more complex than that. And that's really the most simple example I could think of and it's really not very good. For instance you could put the original code into a "game" function and then call it if the choice was P. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Wed Jun 10 12:32:55 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 10 Jun 2009 05:32:55 -0500 Subject: [Tutor] Help running a simple python script for one time operation (noob) In-Reply-To: References: Message-ID: <333efb450906100332x293a9402ge89742c2beb9542e@mail.gmail.com> On Tue, Jun 9, 2009 at 11:57 PM, Melinda Roberts wrote: > Hi - > > I would like to export a large amount of data from ExpressionEngine to > Wordpress, and have had lots of trouble finding something that isn't miles > over my head. I did find these three scripts, which seem to be perfect for > this purpose, but I don't know how to go about implementing them. It's a > three-step process: > > 1. Configure and run Databases.cfg > 2. Run ExpressionEngineExport.py > 3. Run WordPressImport.py. > > I have a mac, am all set with access to my dbs on my host, all I need is to > be pointed in the right direction. Anyone? > It looks like it should be straightforward. I don't have the sqlobject library installed though, so it complains to me. Traceback (most recent call last): File "C:\Documents and Settings\Wayne\My Documents\Downloads\ExpressionEngineE xport.py", line 4, in from sqlobject import * ImportError: No module named sqlobject What that means is that I need to install sqlobject from http://www.sqlobject.org/ Python should be installed on your mac by default. It appears that you've already got the Databases.cfg file configured, so you should just be able to run the other two files in the same directory as your .cfg file and everything should be fine. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Wed Jun 10 14:30:43 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 10 Jun 2009 14:30:43 +0200 Subject: [Tutor] recursive glob -- recursive dir walk In-Reply-To: <20090610082835.5140d674@o> References: <20090610082835.5140d674@o> Message-ID: 2009/6/10 spir : > A foolow-up ;-) from previous question about glob.glob(). Hopefully no misunderstanding this time :-) > I need to 'glob' files recursively from a top dir (parameter). Tried to use os.walk, but the structure of its return value is really unhandy for such a use (strange, because it seems to me this precise use is typical). On the other hand, os.path.walk seemed to meet my needs, but it is deprecated. Is it really derecated? It is still in the 3.0 docs with no mention of this.. > I'd like to know if there are standard tools to do that. And your comments on the 2 approaches below. Well, this is what I came up with which I am sure someone can improve on. >>> patern = '*.txt' >>> topdir = 'C:\\GTK\\' >>> textfiles = [f[0] for f in [glob.glob(os.path.join(d[0], patern)) for d in os.walk(topdir)] if f] >>> textfiles ['C:\\GTK\\license.txt'] Greets Sander > -1- I first wrote the following recurseDirGlob() tool func. > > ======================================================== > import os, glob > > def dirGlob(dir, pattern): > ? ? ? ?''' File names matching pattern in directory dir. ''' > ? ? ? ?fullPattern = os.path.join(dir,pattern) > ? ? ? ?return glob.glob(fullPattern) > > def recurseDirGlob(topdir=None, pattern="*.*", nest=False, verbose=False): > ? ? ? ?''' ?''' > ? ? ? ?allFilenames = list() > ? ? ? ?# current dir > ? ? ? ?if verbose: > ? ? ? ? ? ? ? ?print "*** %s" %topdir > ? ? ? ?if topdir is None: topdir = os.getcwd() > ? ? ? ?filenames = dirGlob(topdir, pattern) > ? ? ? ?if verbose: > ? ? ? ? ? ? ? ?for filename in [os.path.basename(d) for d in filenames]: > ? ? ? ? ? ? ? ? ? ? ? ?print " ? %s" %filename > ? ? ? ?allFilenames.extend(filenames) > ? ? ? ?# possible sub dirs > ? ? ? ?names = [os.path.join(topdir, dir) for dir in os.listdir(topdir)] > ? ? ? ?dirs = [n for n in names if os.path.isdir(n)] > ? ? ? ?if verbose: > ? ? ? ? ? ? ? ?print "--> %s" % [os.path.basename(d) for d in dirs] > ? ? ? ?if len(dirs) > 0: > ? ? ? ? ? ? ? ?for dir in dirs: > ? ? ? ? ? ? ? ? ? ? ? ?filenames = recurseDirGlob(dir, pattern, nest, verbose) > ? ? ? ? ? ? ? ? ? ? ? ?if nest: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?allFilenames.append(filenames) > ? ? ? ? ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?allFilenames.extend(filenames) > ? ? ? ?# final result > ? ? ? ?return allFilenames > ======================================================== > > Example with the following dir structure ; the version with nest=True will recursively nest files from subdirs. > > ======================================================== > d0 > ? ? ? ?d01 > ? ? ? ?d02 > ? ? ? ? ? ? ? ?d020 > 2 .txt files and 1 with a different pattern, in each dir > > recurseDirGlob("/home/spir/prog/d0", "*.txt", verbose=True) --> > *** /home/spir/prog/d0 > ? t01.txt > ? t02.txt > --> ['d01', 'd02'] > *** /home/spir/prog/d0/d01 > ? t011.txt > ? t012.txt > --> [] > *** /home/spir/prog/d0/d02 > ? t021.txt > ? t022.txt > --> ['d020'] > *** /home/spir/prog/d0/d02/d020 > ? t0201.txt > ? t0202.txt > --> [] > ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', '/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt', '/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', '/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt'] > > recurseDirGlob("/home/spir/prog/d0", "*.txt") --> > ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', '/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt', '/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', '/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt'] > > recurseDirGlob("/home/spir/prog/d0", "*.txt", nest=True) --> > ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', ['/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt'], ['/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', ['/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt']]] > ======================================================== > > > > -2- Another approach was to build a general 'dirWalk' tool func, similar to os.path.walk: > > ======================================================== > def dirWalk(topdir=None, func=None, args=[], nest=False, verbose=False): > ? ? ? ?''' ?''' > ? ? ? ?allResults = list() > ? ? ? ?# current dir > ? ? ? ?if verbose: > ? ? ? ? ? ? ? ?print "*** %s" %topdir > ? ? ? ?if topdir is None: topdir = os.getcwd() > ? ? ? ?results = func(topdir, *args) > ? ? ? ?if verbose: > ? ? ? ? ? ? ? ?print " ? ?%s" % results > ? ? ? ?allResults.extend(results) > ? ? ? ?# possible sub dirs > ? ? ? ?names = [os.path.join(topdir, dir) for dir in os.listdir(topdir)] > ? ? ? ?dirs = [n for n in names if os.path.isdir(n)] > ? ? ? ?if verbose: > ? ? ? ? ? ? ? ?print "--> %s" % [os.path.basename(d) for d in dirs] > ? ? ? ?if len(dirs) > 0: > ? ? ? ? ? ? ? ?for dir in dirs: > ? ? ? ? ? ? ? ? ? ? ? ?results = dirWalk(dir, func, args, nest, verbose) > ? ? ? ? ? ? ? ? ? ? ? ?if nest: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?allResults.append(results) > ? ? ? ? ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?allResults.extend(results) > ? ? ? ?# final allResults > ? ? ? ?return allResults > ======================================================== > > Example uses to bring the same results, calling dirGlob, would be: > > dirWalk("/home/spir/prog/d0", dirGlob, args=["*.txt"], verbose=True) --> > dirWalk("/home/spir/prog/d0", dirGlob, args=["*.txt"]) > dirWalk("/home/spir/prog/d0", dirGlob, args=["*.txt"], nest=True) > > Denis > ------ > la vita e estrany > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Jun 10 15:08:03 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Jun 2009 09:08:03 -0400 Subject: [Tutor] recursive glob -- recursive dir walk In-Reply-To: <20090610082835.5140d674@o> References: <20090610082835.5140d674@o> Message-ID: <1c2a2c590906100608ucddb3d6kfd40ad2cd65ce5f2@mail.gmail.com> On Wed, Jun 10, 2009 at 2:28 AM, spir wrote: > Hello, > > A foolow-up ;-) from previous question about glob.glob(). > > I need to 'glob' files recursively from a top dir (parameter). Tried to use os.walk, but the structure of its return value is really unhandy for such a use (strange, because it seems to me this precise use is typical). On the other hand, os.path.walk seemed to meet my needs, but it is deprecated. > > I'd like to know if there are standard tools to do that. And your comments on the 2 approaches below. I would use os.walk(), with fnmatch.fnmatch() to do the pattern matching, and write the function as a generator (using yield). It would look something like this (untested): import os, fnmatch def findFiles(topDir, pattern): for dirpath, dirnames, filenames in os.walk(topDir): for filename in filenames: if fnmatch.fnmatch(filename, pattern): yield os.path.join(dirpath, filename) To get a list of matches you would call list(findFiles(topDir, pattern)) but if you just want to iterate over the paths you don't need the list. Kent From mwalsh at mwalsh.org Wed Jun 10 15:11:26 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Wed, 10 Jun 2009 08:11:26 -0500 Subject: [Tutor] recursive glob -- recursive dir walk In-Reply-To: <20090610082835.5140d674@o> References: <20090610082835.5140d674@o> Message-ID: <4A2FB0FE.4000603@mwalsh.org> spir wrote: > Hello, > > A foolow-up ;-) from previous question about glob.glob(). > > I need to 'glob' files recursively from a top dir (parameter). Tried to use os.walk, but the structure of its return value is really unhandy for such a use (strange, because it seems to me this precise use is typical). On the other hand, os.path.walk seemed to meet my needs, but it is deprecated. I often use Fredrik Lundh's implementation, when I need a recursive 'glob'. And even though it was contributed some time ago, it appears to be 3.x compatible. http://mail.python.org/pipermail/python-list/2001-February/069987.html HTH, Marty From cyberjacob at googlemail.com Wed Jun 10 14:17:41 2009 From: cyberjacob at googlemail.com (Jacob Mansfield) Date: Wed, 10 Jun 2009 13:17:41 +0100 Subject: [Tutor] gui further explained In-Reply-To: References: Message-ID: does anyone know how to make a parallel or serial interface with respective software, i would prefer parallel because it is easy to utilise -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Wed Jun 10 15:35:30 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 10 Jun 2009 15:35:30 +0200 Subject: [Tutor] gui further explained In-Reply-To: References: Message-ID: <4A2FB6A2.1000509@tue.nl> Jacob Mansfield wrote: > does anyone know how to make a parallel or serial interface with respective > software, i would prefer parallel because it is easy to utilise Both the serial and the parallel interface seem to be covered by pyserial http://pyserial.wiki.sourceforge.net and http://pyserial.wiki.sourceforge.net/pyParallel . With these libraries you can program the ports from Python. Albert From taserian at gmail.com Wed Jun 10 18:05:18 2009 From: taserian at gmail.com (taserian) Date: Wed, 10 Jun 2009 12:05:18 -0400 Subject: [Tutor] GUI recommendations/tutorials? Message-ID: <70dbc4d40906100905i51c39089ode86f561433ffba2@mail.gmail.com> I think I'm ready to start working with some simple graphic output. Currently, I've got the basics of a Python program that calculates full tours of a honeycomb structure, going through each cell exactly once. The output from the program shows the paths as coordinates of each cell; what I'd like to do is create a simple window that would show the tour in graphical format, and using keystrokes to go through all of the tours that have been collected. I'm already accounting for eliminating duplicates by rotational symmetry by restricting the starting point to the cells in the "northernmost" row of hexes, but the ending point to be any of the edge hexes. I'm trying to identify duplicates by reflexive symmetries as well, but I'd like to get the visualization component up first. My problem is that I have no GUI experience outside of Visual Studio-style drag-and-drop IDEs. Which Python GUI system would you recommend for neophytes that would allow line drawing and a simple graphic load of a honeycomb structure in a JPG, for example, as a background? Tony R. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bhaaluu at gmail.com Wed Jun 10 18:25:58 2009 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 10 Jun 2009 12:25:58 -0400 Subject: [Tutor] GUI recommendations/tutorials? In-Reply-To: <70dbc4d40906100905i51c39089ode86f561433ffba2@mail.gmail.com> References: <70dbc4d40906100905i51c39089ode86f561433ffba2@mail.gmail.com> Message-ID: Have you looked at PyGame yet? http://www.pygame.org/ On Wed, Jun 10, 2009 at 12:05 PM, taserian wrote: > I think I'm ready to start working with some simple graphic output. > Currently, I've got the basics of a Python program that calculates full > tours of a honeycomb structure, going through?each cell exactly once. The > output from the program shows the paths as coordinates of each cell; what > I'd like to do is create a simple window that would show the tour in > graphical format, and using keystrokes to go through all of the tours that > have been collected. I'm already accounting for?eliminating duplicates by > rotational symmetry by restricting the starting point to the cells in the > "northernmost" row of hexes, but the ending point to be any of the edge > hexes. I'm trying to?identify duplicates by reflexive symmetries as well, > but I'd like to get the visualization component up first. > > My problem is that I have no GUI experience outside of Visual Studio-style > drag-and-drop IDEs. Which Python GUI system would you recommend for > neophytes that would allow line drawing and a simple graphic load of a > honeycomb structure in a JPG, for example, as a background? > > Tony R. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From ayyaz84 at gmail.com Wed Jun 10 19:14:46 2009 From: ayyaz84 at gmail.com (ayyaz) Date: Wed, 10 Jun 2009 13:14:46 -0400 Subject: [Tutor] What is nntp news reader address for this mailing list? In-Reply-To: References: Message-ID: testing again ayyaz wrote: > Testing > "Zia" wrote in message > news:h0mqv0$b06$1 at ger.gmane.org... >> Thanks >> It works now. >> >> http://www.parglena.co.uk/outlookexpress.htm >> >> -Zia >> "Emile van Sebille" wrote in message >> news:h0mpjl$7bk$1 at ger.gmane.org... >>> On 6/9/2009 3:38 PM Mohammad Khawar Zia said... >>>> Hello All, >>>> >>>> I am new to this mailing list. I am trying to setup outlook >>> Which version? Older ones don't do news right and you'll need to be on >>> outlook express if you must use something called outlook. Try >>> Thunderbird. >>> >>>> to read the posts on this mailing list. >>>> >>>> What is the nntp address for thsi mailing list? >>> The news server is nntp://news.gmane.org/ >>> >>> Then subscribe to the lists you're interested in. >>> >>> Emile >>> >>> >>>> nntp://news.gmane.org/gmane.comp.python.tutor >>>> doesn't work. >>>> >>>> Thanks, >>>> --Zia >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From srilyk at gmail.com Wed Jun 10 19:18:05 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 10 Jun 2009 12:18:05 -0500 Subject: [Tutor] GUI recommendations/tutorials? In-Reply-To: <70dbc4d40906100905i51c39089ode86f561433ffba2@mail.gmail.com> References: <70dbc4d40906100905i51c39089ode86f561433ffba2@mail.gmail.com> Message-ID: <333efb450906101018l73812d6drc01e27022e318750@mail.gmail.com> On Wed, Jun 10, 2009 at 11:05 AM, taserian wrote: > I think I'm ready to start working with some simple graphic output. > Currently, I've got the basics of a Python program that calculates full > tours of a honeycomb structure, going through each cell exactly once. The > output from the program shows the paths as coordinates of each cell; what > I'd like to do is create a simple window that would show the tour in > graphical format, and using keystrokes to go through all of the tours that > have been collected. I'm already accounting for eliminating duplicates by > rotational symmetry by restricting the starting point to the cells in the > "northernmost" row of hexes, but the ending point to be any of the edge > hexes. I'm trying to identify duplicates by reflexive symmetries as well, > but I'd like to get the visualization component up first. > > My problem is that I have no GUI experience outside of Visual Studio-style > drag-and-drop IDEs. Which Python GUI system would you recommend for > neophytes that would allow line drawing and a simple graphic load of a > honeycomb structure in a JPG, for example, as a background? > I don't *think* the turtle module allows loading a jpg as a background, but definitely allows you to draw a line. Tkinter's canvas PyGTK's DrawingArea Pygame pyglet matplotlib and even just using the PIL (Python Image(ing?) Library) could all accomplish parts if not all of your goals. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From roberto03 at gmail.com Wed Jun 10 19:52:05 2009 From: roberto03 at gmail.com (roberto) Date: Wed, 10 Jun 2009 19:52:05 +0200 Subject: [Tutor] vpython compatibility In-Reply-To: References: <4bcde3e10906071048q6f0972a5t68b2809708b54381@mail.gmail.com> Message-ID: <4bcde3e10906101052l2be23f0bs85327058822d7667@mail.gmail.com> On Sun, Jun 7, 2009 at 8:05 PM, Emile van Sebille wrote: > On 6/7/2009 10:48 AM roberto said... >> >> hello >> i have a short question: >> is vpython usable in conjunction with python 3.0 ? >> > > This is likely better answered by the vpython crowd -- I've not used or > previously hear of vpython, but they're rather explicit on their download > pages here http://vpython.org/contents/download_windows.html and here > http://vpython.org/contents/download_linux.html that they recommend python > 2.5 or 2.6. and last question: may python 3.0 and 2.6 be installed on the same pc ? thank you again -- roberto From lie.1296 at gmail.com Wed Jun 10 19:53:27 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 11 Jun 2009 03:53:27 +1000 Subject: [Tutor] question about class In-Reply-To: <77e831100906091047r50ab1155kceb4aeda3a681342@mail.gmail.com> References: <77e831100906081625m135a06c5wfda04729397a604a@mail.gmail.com> <77e831100906081631v7999c432u7bb853fc9159fcd0@mail.gmail.com> <20090609091238.74ce8c7b@o> <77e831100906090602x642da43dy29dcf13e608a81b2@mail.gmail.com> <77e831100906091047r50ab1155kceb4aeda3a681342@mail.gmail.com> Message-ID: Vincent Davis wrote: > Thanks again for the help, A little followup. > For my applicant class I have a few initial values that need to be set > but I what to choose the value (actually the calculation to set the > value) for each applicant (instance?) > Here is the start of my Applicant Class > > class Applicant(object): > "quality is refers to the quality of the Applicant > observe refers to the accuracy of which they assess the > quality of the school" > def __init__(self, quality = 0, observe = 0): > self. quality = quality > self. observe = observe > def Quality(self, mean, sd): > print self, > self.quality = normalvariate(mean, sd) > print "--> %s" % self > def Observe(self, mean, sd): > print self, > self. observe = normalvariate(mean, sd) > print "--> %s" % self The problem with that approach is that repeated calls to Quality and Observe would change the value of self.quality and self.observe and it will be therefore unnecessary (and dangerous) to call self.Quality/Observe again in the future Usually I'd go with something like this: class Applicant(object): def __init__(self, quality, observe): self.quality = quality self.observe = observe def norm_quality(self, mean, sd): return normalvariate(mean, sd, self.quality) def norm_observe(self, mean, sd): return normalvariate(mean, sd, self.observe) Additionally-- although it is a matter of style --instead of passing mean and sd to norm_quality, I'd use functools.partial with normalvariate, mean, and sd. Then since they now don't take parameters they can then be easily turned into property using decorator. > Or I could I guess do it this way, Is this better? I will only be > setting the quality and observe values once for each instance. > > class Applicant(object): > "quality is refers to the quality of the Applicant > observe refers to the accuracy of which they assess the > quality of the school" > def __init__(self, mquality = 0, sdquality = 0, mobserve = 0, > sdobserve = 0): > self. quality = normalvariate(mquality, sdquality) > self. observe = normalvariate(mobserve, sdobserve) That approach is fine as well, however it wouldn't be much different than using a tuple. From kent37 at tds.net Wed Jun 10 20:01:42 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Jun 2009 14:01:42 -0400 Subject: [Tutor] vpython compatibility In-Reply-To: <4bcde3e10906101052l2be23f0bs85327058822d7667@mail.gmail.com> References: <4bcde3e10906071048q6f0972a5t68b2809708b54381@mail.gmail.com> <4bcde3e10906101052l2be23f0bs85327058822d7667@mail.gmail.com> Message-ID: <1c2a2c590906101101k3e8c253mbca06d56d6651ce5@mail.gmail.com> On Wed, Jun 10, 2009 at 1:52 PM, roberto wrote: > and last question: may python 3.0 and 2.6 be installed on the same pc ? Yes, no problem. Kent From stefan at lsd.co.za Wed Jun 10 20:44:25 2009 From: stefan at lsd.co.za (Stefan Lesicnik) Date: Wed, 10 Jun 2009 20:44:25 +0200 Subject: [Tutor] Parse Text File Message-ID: <5cb309e70906101144r2050a75dpf6d0db27e9d8f86b@mail.gmail.com> Hi Guys, I have the following text [08 Jun 2009] DSA-1813-1 evolution-data-server - several vulnerabilities {CVE-2009-0547 CVE-2009-0582 CVE-2009-0587} [etch] - evolution-data-server 1.6.3-5etch2 [lenny] - evolution-data-server 2.22.3-1.1+lenny1 [04 Jun 2009] DSA-1812-1 apr-util - several vulnerabilities {CVE-2009-0023 CVE-2009-1955} [etch] - apr-util 1.2.7+dfsg-2+etch2 [lenny] - apr-util 1.2.12+dfsg-8+lenny2 ... (and a whole lot more) I would like to parse this so I can get it into a format I can work with. I don't know anything about parsers, and my brief google has made me think im not sure I wan't to know about them quite yet! :) (It looks very complex) For previous fixed string things, i would normally split each line and address each element, but this is not the case as there could be multiple [lenny] or even other entries. I would like to parse from the date to the next date and treat that all as one element (if that makes sense) Does anyone have any suggestions - should I be learning a parser for doing this? Or is there perhaps an easier way. Tia! Stefan -------------- next part -------------- An HTML attachment was scrubbed... URL: From cosmicsand27 at yahoo.com Wed Jun 10 22:08:21 2009 From: cosmicsand27 at yahoo.com (Raj Medhekar) Date: Wed, 10 Jun 2009 13:08:21 -0700 (PDT) Subject: [Tutor] Need help solving this problem Message-ID: <638923.28755.qm@web43402.mail.sp1.yahoo.com> I have been teaching myself Python using a book. The chapter I am on currently, covers branching, while loops and program planning. I am stuck on on of the challenges at the end of this chapter, and I was hoping to get some help with this. Here it is: Write a program that flips a coin 100 times and the tells you the number of heads and tails. I have tried to think about several ways to go about doing this but I have hit a wall. Even though I understand the general concept of branching and looping, I have been having trouble writing a program with these. I look forward to your reply that will help me understand these structures better. Sincerely, Raj -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Wed Jun 10 22:38:34 2009 From: fomcl at yahoo.com (Albert-jan Roskam) Date: Wed, 10 Jun 2009 13:38:34 -0700 (PDT) Subject: [Tutor] Need help solving this problem Message-ID: <390642.16872.qm@web110701.mail.gq1.yahoo.com> hi! This is how I would do it, but I'm still learning this too, so I'm very much open for suggestions. Cheers!! Albert-Jan import random def draw (): return random.sample(["head", "tail"], 1) def toss (): heads, tails = 0, 0 for flip in range(100): if draw() == ["head"]: heads += 1 else: tails += 1 return heads, tails for attempt in range(20): print "attempt:", attempt+1, "heads:", toss()[0], "tails:", toss()[1] --- On Wed, 6/10/09, Raj Medhekar wrote: > From: Raj Medhekar > Subject: [Tutor] Need help solving this problem > To: "Python Tutor" > Date: Wednesday, June 10, 2009, 10:08 PM > I > have been teaching myself Python using a book. The chapter I > am on currently, covers branching, while loops and program > planning. I am stuck on on of the challenges at the end of > this chapter, and I was hoping to get some help with this. > Here it is: > > Write a program that flips a coin 100 times and the tells > you the number of heads and tails. > > I have tried to think about several ways to go about doing > this but I have hit a wall. Even though I understand the > general concept of branching and looping, I have been having > trouble writing a program with these.? I look forward > to your reply that will help me understand these structures > better. > > Sincerely, > Raj > > > > > -----Inline Attachment Follows----- > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bermanrl at cfl.rr.com Wed Jun 10 22:50:35 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 10 Jun 2009 16:50:35 -0400 Subject: [Tutor] Need help solving this problem In-Reply-To: <638923.28755.qm@web43402.mail.sp1.yahoo.com> References: <638923.28755.qm@web43402.mail.sp1.yahoo.com> Message-ID: <1244667035.5460.19.camel@bermanrl-desktop> What you are looking at is a simulation whereby a coin having 2 outcomes (heads or tails) is flipped exactly 100 times. You need to tell how many times the coin falls heads up and how many times the coin falls tails up. First become familiar with the random module. Assign a value of 1 for heads and a value of 2 for tails. Then you are going to use a structure of the random module which will return only two possible outcomes. Either a one or a two. You are going to loop (look at range(1,101) or range(0,100). (Side question; why 101 or 0 to 100?; look closely at the meaning of the range arguments). Simply count the number of ones and the number of two's in the 100 flips then print the results. Good luck. Robert On Wed, 2009-06-10 at 13:08 -0700, Raj Medhekar wrote: > I have been teaching myself Python using a book. The chapter I am on > currently, covers branching, while loops and program planning. I am > stuck on on of the challenges at the end of this chapter, and I was > hoping to get some help with this. Here it is: > > Write a program that flips a coin 100 times and the tells you the > number of heads and tails. > > I have tried to think about several ways to go about doing this but I > have hit a wall. Even though I understand the general concept of > branching and looping, I have been having trouble writing a program > with these. I look forward to your reply that will help me understand > these structures better. > > Sincerely, > Raj > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From eduardo.susan at gmail.com Wed Jun 10 22:56:10 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Wed, 10 Jun 2009 14:56:10 -0600 Subject: [Tutor] Parse Text File In-Reply-To: <5cb309e70906101144r2050a75dpf6d0db27e9d8f86b@mail.gmail.com> References: <5cb309e70906101144r2050a75dpf6d0db27e9d8f86b@mail.gmail.com> Message-ID: <9356b9f30906101356kb66f6b7o9b3b1dec5b969ab0@mail.gmail.com> On Wed, Jun 10, 2009 at 12:44 PM, Stefan Lesicnik wrote: > Hi Guys, > > I have the following text > > [08 Jun 2009] DSA-1813-1 evolution-data-server - several vulnerabilities > ??????? {CVE-2009-0547 CVE-2009-0582 CVE-2009-0587} > ??????? [etch] - evolution-data-server 1.6.3-5etch2 > ??????? [lenny] - evolution-data-server 2.22.3-1.1+lenny1 > [04 Jun 2009] DSA-1812-1 apr-util - several vulnerabilities > ??????? {CVE-2009-0023 CVE-2009-1955} > ??????? [etch] - apr-util 1.2.7+dfsg-2+etch2 > ??????? [lenny] - apr-util 1.2.12+dfsg-8+lenny2 > > ... (and a whole lot more) > > I would like to parse this so I can get it into a format I can work with. > > I don't know anything about parsers, and my brief google has made me think > im not sure I wan't to know about them quite yet!? :) > (It looks very complex) > > For previous fixed string things, i would normally split each line and > address each element, but this is not the case as there could be multiple > [lenny] or even other entries. > > I would like to parse from the date to the next date and treat that all as > one element (if that makes sense) > > Does anyone have any suggestions - should I be learning a parser for doing > this? Or is there perhaps an easier way. > > Tia! > > Stefan Hello, maybe if you would show a sample on how you would like the ouput to look like it could help us give more suggestions. Regards, Eduardo From dorjetarap at googlemail.com Wed Jun 10 23:07:09 2009 From: dorjetarap at googlemail.com (karma) Date: Wed, 10 Jun 2009 23:07:09 +0200 Subject: [Tutor] Need help solving this problem In-Reply-To: <638923.28755.qm@web43402.mail.sp1.yahoo.com> References: <638923.28755.qm@web43402.mail.sp1.yahoo.com> Message-ID: Hi Raj, I'm another learner, I used the following: >>> def toss(n): heads = 0 for i in range(n): heads += random.randint(0,1) return heads, n-heads >>> print "%d heads, %d tails" % toss(100) Best of luck in your python endeavors! 2009/6/10 Raj Medhekar : > I have been teaching myself Python using a book. The chapter I am on > currently, covers branching, while loops and program planning. I am stuck on > on of the challenges at the end of this chapter, and I was hoping to get > some help with this. Here it is: > > Write a program that flips a coin 100 times and the tells you the number of > heads and tails. > > I have tried to think about several ways to go about doing this but I have > hit a wall. Even though I understand the general concept of branching and > looping, I have been having trouble writing a program with these.? I look > forward to your reply that will help me understand these structures better. > > Sincerely, > Raj > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Wed Jun 10 23:17:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Jun 2009 22:17:00 +0100 Subject: [Tutor] python and serial port References: <795061.52762.qm@web59509.mail.ac4.yahoo.com> Message-ID: "Ranjeeth P T" wrote > I am new to python i want to communicate i.e send and > receive b/n an arm device and pc via a serial port, and "Jacob Mansfield" wrote > does anyone know how to make a parallel or serial interface with > respective > software, i would prefer parallel because it is easy to utilise It never fails to amaze me how often a subject can be untouched on this list for months then come up twice in the same day from two different places. Bizarre, Alan G From e_mitges at hotmail.com Wed Jun 10 23:23:07 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Wed, 10 Jun 2009 17:23:07 -0400 Subject: [Tutor] gui In-Reply-To: References: <1244586011.5894.16.camel@infirit.homelinux.org> Message-ID: thx lol fixed part of the problem ---------------------------------------- > To: tutor at python.org > From: lie.1296 at gmail.com > Date: Wed, 10 Jun 2009 13:24:48 +1000 > Subject: Re: [Tutor] gui > > Essah Mitges wrote: >> 1. >> Traceback (most recent call last): >> 2. >> File "C:\Users\John Doe\Desktop\D-Day\back.py", line 47, in >> 3. >> main() >> 4. >> File "C:\Users\John Doe\Desktop\D-Day\back.py", line 37, in main >> 5. >> elif sbut.clicked(k.pos): >> 6. >> File "C:\Users\John Doe\Desktop\D-day\but.py", line 200, in clicked >> 7. >> subprocess.Popen(["D-Day", "Destruction.py"]) >> 8. >> File "C:\Python26\lib\subprocess.py", line 595, in __init__ >> 9. >> errread, errwrite) >> 10. >> File "C:\Python26\lib\subprocess.py", line 804, in _execute_child >> 11. >> startupinfo) >> 12. >> WindowsError: [Error 2] The system cannot find the file specified >> >> The error in readable form > > Readable doesn't mean it have to be colored and line numbered, although > this is more readable than the previous one -- at least on a newsreader > that supports HTML -- it's better to keep messages in plain text (i.e. > not only unformatted text but change the newsreader's settings to pure, > plain text) > > All right to the problem, the problem is not related to pygame at all; > it's in your subprocess.Popen() call. The traceback says that > subprocess.Popen cannot find the executable/script that would be run. > > A quick look at the traceback: > subprocess.Popen(["D-Day", "Destruction.py"]) > > That line is executing an executable/script named "D-Day" and pass an > argument "Destruction.py" to it. Probably not something you wanted to > do. What you want to do is something like: > > subprocess.Popen(["D-Day\Destruction.py"]) > > or perhaps: > subprocess.Popen(["python", "D-Day\Destruction.py"]) > > depending on whether the file association is setup correctly and whether > the shell's search path is set to search python's install directory. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Internet explorer 8 lets you browse the web faster. http://go.microsoft.com/?linkid=9655582 From alan.gauld at btinternet.com Wed Jun 10 23:21:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Jun 2009 22:21:40 +0100 Subject: [Tutor] GUI recommendations/tutorials? References: <70dbc4d40906100905i51c39089ode86f561433ffba2@mail.gmail.com> Message-ID: "taserian" wrote > My problem is that I have no GUI experience outside of Visual > Studio-style > drag-and-drop IDEs. Which Python GUI system would you recommend for > neophytes that would allow line drawing and a simple graphic load of a > honeycomb structure in a JPG, for example, as a background? The two most common Python GUI frameworks are Tkinter (in the standard library) and wxPython - an add on. Both have a canvas widget that will cater to your requirements fairly easily. Another approach might be to investigate pygame since it excells at graphics. There are a couple of other options too but I suspect a simple canvas widget is nearly all you need and Tkinter or wxPython will both procvidfe that. There are several tutorials (and at least 1 book) for either option. The GUI programming topic on my tutorial will give you the very bare bones and show an example in both frameworks for comparison. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From david at abbottdavid.com Wed Jun 10 23:28:16 2009 From: david at abbottdavid.com (David) Date: Wed, 10 Jun 2009 17:28:16 -0400 Subject: [Tutor] Need help solving this problem In-Reply-To: <638923.28755.qm@web43402.mail.sp1.yahoo.com> References: <638923.28755.qm@web43402.mail.sp1.yahoo.com> Message-ID: <4A302570.1090802@abbottdavid.com> Raj Medhekar wrote: > I have been teaching myself Python using a book. The chapter I am on > currently, covers branching, while loops and program planning. I am > stuck on on of the challenges at the end of this chapter, and I was > hoping to get some help with this. Here it is: > > Write a program that flips a coin 100 times and the tells you the number > of heads and tails. > > I have tried to think about several ways to go about doing this but I > have hit a wall. Even though I understand the general concept of > branching and looping, I have been having trouble writing a program with > these. I look forward to your reply that will help me understand these > structures better. > > Sincerely, > Raj > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor I am learning also, I came up with; #!/usr/bin/python import random random = random.Random() choice = ['heads', 'tails'] head_wins = 0 tail_wins = 0 def coin_flip(): flip = random.choice(choice) global head_wins global tail_wins if flip == 'heads': head_wins += 1 elif flip == 'tails': tail_wins += 1 def number_flips(): for i in range(100): coin_flip() number_flips() print 'Head Total Wins =', head_wins print 'Tail Total Wins =', tail_wins -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From alan.gauld at btinternet.com Wed Jun 10 23:26:35 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Jun 2009 22:26:35 +0100 Subject: [Tutor] Need help solving this problem References: <638923.28755.qm@web43402.mail.sp1.yahoo.com> Message-ID: "Raj Medhekar" wrote > Write a program that flips a coin 100 times and the tells you the number > of heads and tails. > > I have tried to think about several ways to go about doing this but I > have hit a wall. > Even though I understand the general concept of branching and looping, > I have been having trouble writing a program with these. You also need to understand the concept of variables as data stores. And you will probably need to use a mechanism to generate random values. The random module will help or you can simply read the time and strip off the last two digits - that will be good enough for your purposes! Otherwise take a look at my tutorial for the various topics Raw Materials - variables and data Loops Branches File handling - for a very brief intro to reading the time HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From e_mitges at hotmail.com Wed Jun 10 23:00:56 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Wed, 10 Jun 2009 17:00:56 -0400 Subject: [Tutor] file/subprocess error Message-ID: So no one is confused about the error i screenshot it I am not sure of the problemWhen I run the game outside the menu it works fine but when I call it as a child window it start then the modules attached cannnot load the games images which couse this error is there a subprocess command to fix thisTried python.org btw _________________________________________________________________ Create a cool, new character for your Windows Live? Messenger. http://go.microsoft.com/?linkid=9656621 -------------- next part -------------- A non-text attachment was scrubbed... Name: error.png Type: image/png Size: 44926 bytes Desc: not available URL: From e_mitges at hotmail.com Wed Jun 10 23:21:46 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Wed, 10 Jun 2009 17:21:46 -0400 Subject: [Tutor] subprocess/files help Message-ID: The problem I am have now is that once my game is initiated from the menu file the modules that are with cannot import the imagesthe folder looks like thisWODDS data All images and sound for game gamelib Objects Utilities ___init___ WODDS.py Png error file attachedAny one know the code in subprocesses to fix this _________________________________________________________________ Attention all humans. We are your photos. Free us. http://go.microsoft.com/?linkid=9666046 -------------- next part -------------- A non-text attachment was scrubbed... Name: error.png Type: image/png Size: 44926 bytes Desc: not available URL: From srilyk at gmail.com Thu Jun 11 00:09:51 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 10 Jun 2009 17:09:51 -0500 Subject: [Tutor] file/subprocess error In-Reply-To: References: Message-ID: <333efb450906101509g4ea1d318kc75ebcfc7b45a1c0@mail.gmail.com> On Wed, Jun 10, 2009 at 4:00 PM, Essah Mitges wrote: > > So no one is confused about the error i screenshot it I am not sure of the > problemWhen I run the game outside the menu it works fine but when I call it > as a child window it start then the modules attached cannnot load the games > images which couse this error is there a subprocess command to fix thisTried > python.org btw The last error specifically tells you what it is and what is wrong: pygame.error: Couldn't open data\up-1-.png it can't find that file. Are you sure it exists? HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Thu Jun 11 00:16:43 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 10 Jun 2009 17:16:43 -0500 Subject: [Tutor] subprocess/files help In-Reply-To: References: Message-ID: <333efb450906101516u5ba86295k2095a115d440f43@mail.gmail.com> On Wed, Jun 10, 2009 at 4:21 PM, Essah Mitges wrote: > > The problem I am have now is that once my game is initiated from the menu > file the modules that are with cannot import the imagesthe folder looks like > thisWODDS data All images and sound for game gamelib > Objects Utilities ___init___ WODDS.py > Png error file attachedAny one know the code in subprocesses to fix this The problem has nothing to do with subprocess (and in the future please combine your questions into one email). As I mentioned before it's specifically looking for a file "data/up-1.png" which either doesn't exist or permissions are wrong. Remember, relative paths are not absolute. On *nix, /home/user/file/image.jpg is an absolute reference. No matter where you execute a program it will be able to find it. On Windows you would see something like C:\Documents and Settings\Users\MyGuy\MyFile\image.jpg A relative path would be, as the name suggests, relative. files/image.jpg will access a different location on the disk depending on where you are. Take a look at this that specifically deals with web programming but is applicable. http://www.communitymx.com/content/article.cfm?cid=230ad HTH -------------- next part -------------- An HTML attachment was scrubbed... URL: From e_mitges at hotmail.com Thu Jun 11 00:29:22 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Wed, 10 Jun 2009 18:29:22 -0400 Subject: [Tutor] subprocess/files help In-Reply-To: <333efb450906101516u5ba86295k2095a115d440f43@mail.gmail.com> References: <333efb450906101516u5ba86295k2095a115d440f43@mail.gmail.com> Message-ID: game runs fine out of the WODDS.py it when I start it from the menu lies the problemup-1.png is the first pic file used in the program so I'm guessing that all of the imported files from data have a problem if i took away up-1 up-2 would start a problem then side-1 and so on ________________________________ > From: srilyk at gmail.com > Date: Wed, 10 Jun 2009 17:16:43 -0500 > Subject: Re: [Tutor] subprocess/files help > To: e_mitges at hotmail.com > CC: tutor at python.org > > On Wed, Jun 10, 2009 at 4:21 PM, Essah Mitges> wrote: > > > > > The problem I am have now is that once my game is initiated from the menu file the modules that are with cannot import the imagesthe folder looks like thisWODDS data All images and sound for game gamelib Objects Utilities ___init___ WODDS.py > > > > Png error file attachedAny one know the code in subprocesses to fix this > > The problem has nothing to do with subprocess (and in the future please combine your questions into one email). As I mentioned before it's specifically looking for a file "data/up-1.png" which either doesn't exist or permissions are wrong. > > > > Remember, relative paths are not absolute. > > On *nix, /home/user/file/image.jpg is an absolute reference. No matter where you execute a program it will be able to find it. On Windows you would see something like C:\Documents and Settings\Users\MyGuy\MyFile\image.jpg > > > > A relative path would be, as the name suggests, relative. files/image.jpg will access a different location on the disk depending on where you are. Take a look at this that specifically deals with web programming but is applicable. > > > http://www.communitymx.com/content/article.cfm?cid=230ad > > HTH > > _________________________________________________________________ Internet explorer 8 lets you browse the web faster. http://go.microsoft.com/?linkid=9655582 From alan.gauld at btinternet.com Thu Jun 11 00:57:35 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Jun 2009 23:57:35 +0100 Subject: [Tutor] file/subprocess error References: Message-ID: "Essah Mitges" wrote > So no one is confused about the error i screenshot it Thanks. > I am not sure of the problem It says it can't find the file. Does a file C:\Users\John Doe\Desktop\WODDS\WODDS\gamelib\data\up-1.png actually exist? And is it readable by the user running the program? > When I run the game outside the menu it works fine Are you running it from the same directory? > but when I call it as a child window it start then the modules > attached cannnot load the games images which couse this > error is there a subprocess command to fix this No, you need to set up the correct environment for the game to run before calling subprocess. However as I and others have pointed out this is almost certainly the wrong way to approach your problem, even if you can get it to work! You would be better putting the game code into a function in Utilities.py and then importing that into your menu module. You can then call the game function using import Utilities # menu code here Utilities.startGame() And so that you can still ru n it as Utilities.py add a clause at the end of IUtilities.py like if __name__ == "__main__": startGame() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ayyaz84 at gmail.com Thu Jun 11 02:27:07 2009 From: ayyaz84 at gmail.com (ayyaz) Date: Wed, 10 Jun 2009 20:27:07 -0400 Subject: [Tutor] Need help solving this problem In-Reply-To: <638923.28755.qm@web43402.mail.sp1.yahoo.com> References: <638923.28755.qm@web43402.mail.sp1.yahoo.com> Message-ID: Raj Medhekar wrote: > I have been teaching myself Python using a book. The chapter I am on > currently, covers branching, while loops and program planning. I am > stuck on on of the challenges at the end of this chapter, and I was > hoping to get some help with this. Here it is: > > Write a program that flips a coin 100 times and the tells you the number > of heads and tails. > > I have tried to think about several ways to go about doing this but I > have hit a wall. Even though I understand the general concept of > branching and looping, I have been having trouble writing a program with > these. I look forward to your reply that will help me understand these > structures better. > > Sincerely, > Raj > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor A very simple solution import random # you need to import this module to generate random # numbers heads = 0; #init number of heads; tails = 0; #init number of tails; cnt = 0 # variable to store number of coin tosses while cnt<100: # we want this loop to 100 times toss = random.randrange(0,2,1) # this line will randomly choose # between 0 and 1 if toss == 0: tails += 1 # if the random generator gives 0, then we increase # count of tail by one else: heads += 1 # if the random generator gives 1, then we increase # count of head by one cnt += 1 # increase count of coin toss by one print "Number of heads", heads # print the number of heads print "Number of tails", tails # print the number of tails raw_input("\nPress enter to exit") From e_mitges at hotmail.com Thu Jun 11 03:02:47 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Wed, 10 Jun 2009 21:02:47 -0400 Subject: [Tutor] file/subprocess error In-Reply-To: References: Message-ID: But will it work I run 3 module for this game utilites is just 1 ---------------------------------------- > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Wed, 10 Jun 2009 23:57:35 +0100 > Subject: Re: [Tutor] file/subprocess error > > "Essah Mitges" wrote >> So no one is confused about the error i screenshot it > > Thanks. > >> I am not sure of the problem > > It says it can't find the file. > Does a file > > C:\Users\John Doe\Desktop\WODDS\WODDS\gamelib\data\up-1.png > > actually exist? And is it readable by the user running the program? > >> When I run the game outside the menu it works fine > > Are you running it from the same directory? > >> but when I call it as a child window it start then the modules >> attached cannnot load the games images which couse this >> error is there a subprocess command to fix this > > No, you need to set up the correct environment for the game > to run before calling subprocess. > > However as I and others have pointed out this is almost > certainly the wrong way to approach your problem, even if > you can get it to work! You would be better putting the game > code into a function in Utilities.py and then importing that into > your menu module. You can then call the game function > using > > import Utilities > > # menu code here > > Utilities.startGame() > > And so that you can still ru n it as Utilities.py add a clause > at the end of IUtilities.py like > > if __name__ == "__main__": > startGame() > > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Create a cool, new character for your Windows Live? Messenger. http://go.microsoft.com/?linkid=9656621 From mattie289404 at gmail.com Thu Jun 11 04:02:54 2009 From: mattie289404 at gmail.com (Randy Trahan) Date: Wed, 10 Jun 2009 22:02:54 -0400 Subject: [Tutor] Syntax Error First Example Message-ID: <82bf08860906101902r477408b6w7b1106cba41bc983@mail.gmail.com> Hi, Just opened the book Python Programming, Second Edition by Michael Dawson and have my first question. Instead of the usual "Hello World" as the first example he asked to type this: print "Game Over" raw input("\n\nPress the enter key to exit.") First, I am suppose to put this in the script mode vs the IDLE mode correct? He failed to mention where.. Also, I get a syntax error at "input"? Since its my first day/hour I don't know how to debug and its typed in exactly as he wrote it... Finally, I'm running Python 2.6 on Vista. It loaded but the book did not mention Vista it only went up to XP. Is that ok? Any help would be appreciated. -- Randy Trahan Owner, BullDog Computer Services, LLC 478-396-2516 -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jun 11 04:12:18 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 10 Jun 2009 22:12:18 -0400 Subject: [Tutor] Syntax Error First Example In-Reply-To: <82bf08860906101902r477408b6w7b1106cba41bc983@mail.gmail.com> References: <82bf08860906101902r477408b6w7b1106cba41bc983@mail.gmail.com> Message-ID: <4A306802.60409@gmail.com> Randy Trahan wrote: > Hi, > Just opened the book Python Programming, Second Edition by Michael > Dawson and have my first question. Instead of the usual "Hello World" > as the first example he asked to type this: > > print "Game Over" > raw input("\n\nPress the enter key to exit.") Try raw_input("\n\nPress the enter key to exit.") > > First, I am suppose to put this in the script mode vs the IDLE mode > correct? He failed to mention where.. > > Also, I get a syntax error at "input"? Since its my first day/hour I > don't know how to debug and its typed in exactly as he wrote it... > > Finally, I'm running Python 2.6 on Vista. It loaded but the book did > not mention Vista it only went up to XP. Is that ok? > > Any help would be appreciated. > > -- > Randy Trahan > Owner, BullDog Computer Services, LLC > 478-396-2516 > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer Chapel Hill NC 919-636-4239 From srilyk at gmail.com Thu Jun 11 04:12:15 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 10 Jun 2009 21:12:15 -0500 Subject: [Tutor] Syntax Error First Example In-Reply-To: <4A306802.60409@gmail.com> References: <82bf08860906101902r477408b6w7b1106cba41bc983@mail.gmail.com> <4A306802.60409@gmail.com> Message-ID: <333efb450906101912x5b555dehff4fd3168cc4eadb@mail.gmail.com> On Wed, Jun 10, 2009 at 9:12 PM, bob gailer wrote: > Randy Trahan wrote: > >> First, I am suppose to put this in the script mode vs the IDLE mode >> correct? He failed to mention where.. > > It really doesn't matter - although presumably he meant you to write a script instead of in the shell/interactive interpreter (the prompt starting >>> ) > Also, I get a syntax error at "input"? Since its my first day/hour I >> don't know how to debug and its typed in exactly as he wrote it... >> Finally, I'm running Python 2.6 on Vista. It loaded but the book did not >> mention Vista it only went up to XP. Is that ok? >> > Python works(ed?) fine on my computer when I ran Vista. As long as you keep to the 2.XX series of Python you shouldn't have too much trouble picking up python - it's really only if you start switching to Python 3 that you'll have a problem - specifically a lot of statements have turned into functions... but that's a discussion for a different day :) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Jun 11 08:08:57 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 11 Jun 2009 16:08:57 +1000 Subject: [Tutor] Syntax Error First Example In-Reply-To: <82bf08860906101902r477408b6w7b1106cba41bc983@mail.gmail.com> References: <82bf08860906101902r477408b6w7b1106cba41bc983@mail.gmail.com> Message-ID: Randy Trahan wrote: > Hi, > Just opened the book Python Programming, Second Edition by Michael > Dawson and have my first question. Instead of the usual "Hello World" as > the first example he asked to type this: > > print "Game Over" > raw input("\n\nPress the enter key to exit.") > > First, I am suppose to put this in the script mode vs the IDLE mode > correct? He failed to mention where.. There are a few subtle differences between running in script mode and interactive mode; notably that you can print the repr of an object without a print statement/function in interactive mode. However for this particular example, the difference are not significant. > Also, I get a syntax error at "input"? Since its my first day/hour I > don't know how to debug and its typed in exactly as he wrote it... > Finally, I'm running Python 2.6 on Vista. It loaded but the book did not > mention Vista it only went up to XP. Is that ok? Python supports Vista; maybe the book is a bit old. From lie.1296 at gmail.com Thu Jun 11 08:25:16 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 11 Jun 2009 16:25:16 +1000 Subject: [Tutor] subprocess/files help In-Reply-To: References: <333efb450906101516u5ba86295k2095a115d440f43@mail.gmail.com> Message-ID: Essah Mitges wrote: > game runs fine out of the WODDS.py it when I start it from the menu lies the problemup-1.png is the first pic file used in the program so I'm guessing that all of the imported files from data have a problem if i took away up-1 up-2 would start a problem then side-1 and so on > Let me guess, the menu script is in different directory than the game script? The current working directory is thus pointing to the menu's directory instead of script's. Two possible fix is to 1) move the menu script to the game's script directory or 2) pass cwd="" argument to subprocess.Popen However, as others have said, both of them are the WRONG approach to your problem... since both scripts are python scripts, both under your control, and most importantly both scripts are integrated part of a unity (i.e. the game); it will be MUCH easier to import the game script and call the function that started the game. From stefan_ml at behnel.de Thu Jun 11 08:37:17 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 11 Jun 2009 08:37:17 +0200 Subject: [Tutor] XML: changing value of elements In-Reply-To: <20090610032630.HKZY2116.nskntotgx01p.mx.bigpond.com@JohanPC> References: <20090610032630.HKZY2116.nskntotgx01p.mx.bigpond.com@JohanPC> Message-ID: Hi, it's funny how many times I see Python users go: "I have an XML problem, so I'll use minidom." Because then they have two problems. Johan Geldenhuys wrote: > I have a rather complex XML file and I need to change some values inside > this file. > > So far I have been using minidom, but I can't find the thing I am looking > for. > > My code so far: > """ > from xml.dom import minidom > > xmlFile = 'signal1.xml' > xmlDocument = minidom.parse(xmlFile) > > SignalsNode = xmlDocument.firstChild > signalNode = SignalsNode.childNodes[1] > > signalNode.removeAttribute("name") > signalNode.setAttribute("name", "Test_Name") > signalNode.getAttribute("name") > > descElem = signalNode.childNodes[1] That is a lot of code just to say import xml.etree.ElementTree as ET doc = ET.parse('signal1.xml') signal_node = doc.getroot()[0] signal_node.set('name', 'Test_Name') > I know how to manipulate the value of the attributes, but I can't seem to > change the values of eg: "Description" description = signal_node[0] description.text = "New value" > Snippet from my XML file: > > """ > > > > - What's that "" bit? > - name="Model_X" type="Flyer"> > > Some description > > Model_X > > > > - > > normal > > Model X 1 > > > > - type="close"> > > minor > > Model X 2 > > > > > > > """ Stefan From alan.gauld at btinternet.com Thu Jun 11 09:25:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Jun 2009 08:25:06 +0100 Subject: [Tutor] file/subprocess error References: Message-ID: "Essah Mitges" wrote > But will it work I run 3 module for this game utilites is just 1 It doesn't matter how many modules you use, although it changes how many you have to import maybe. But in princiople if your game is started by calling a single function then you only need to import the module with that function. BTW You still haven't answered the question: > Does a file > > C:\Users\John Doe\Desktop\WODDS\WODDS\gamelib\data\up-1.png > > actually exist? And is it readable by the user running the program? Alan G. From cheesman at titan.physx.u-szeged.hu Thu Jun 11 10:42:44 2009 From: cheesman at titan.physx.u-szeged.hu (andy) Date: Thu, 11 Jun 2009 10:42:44 +0200 Subject: [Tutor] delphi, pascal and Python In-Reply-To: <42065.160.114.38.31.1244035373.squirrel@titan.physx.u-szeged.hu> References: <40af687b0905201916p3d09e7c6je672f7c7fb07ee3@mail.gmail.com> <48766.87.97.16.29.1243939651.squirrel@titan.physx.u-szeged.hu> <42065.160.114.38.31.1244035373.squirrel@titan.physx.u-szeged.hu> Message-ID: <20090611084244.GA14001@titan.physx.u-szeged.hu> Hi People The error in this code was that the free pascal compiler command listed below included a framework command suitable only for mac compilations fpc -MDelphi -Cirot -O1 -gl -XX -k-framework -kpython -WG -vewnhi -l -Fu. -oPyMinMod.so PyMinMod.dpr The removal of this framework command cause the compliation to work beautifully However, the imported module generates a new error ImportError: PyMinMod.so: undefined symbol: Py_InitModule4 This error seems to crop up regularly within other python programs and I've not found an obvious solution ... Does anyone know what causes this type of error? (I'm on 64bit ubuntu btw) Thanks for any suggestions/help Andy > > By the way, the error was generated by following the tutorial and > compiling in lazarus > > > > After Much Looking and pointers from the author, There is this most > > excellent post by the same author at > > > > http://wiki.lazarus.freepascal.org/Developing_Python_Modules_with_Pascal > > > > This nearly works but I have issue with the linking of the new module. The > > error is > > > > Linking PyMinMod.so > > /usr/bin/ld: Python: No such file: No such file or directory > > > > I've no clue what the issue is and I don't understand what should be going > > on. I'm running 64bit ubuntu. I know this might be a bit off topic, but if > > someone could point me in the right direction, I would be rather grateful > > > > Thanks > > Andy > > > > > > > >> > >> "Marc Tompkins" wrote > >> > >>>> Is there a Method for wrapping delphi and/or pascal code into python > >>>> like > >>>>> SWIG? > >>>> http://membres.lycos.fr/marat/delphi/python.htm > >>> > >>> That's a package to let you embed Python in Delphi; the OP wants to go > >>> the > >>> other direction. > >> > >> So it is, I didn't read the OP question closely enough. > >> > >> On Windows you could create a DLL and use ctypes to access it, > >> but thats not the same as creating an importable module as could > >> be done with SWIG > >> > >> Alan G. > >> > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From denis.spir at free.fr Thu Jun 11 11:10:14 2009 From: denis.spir at free.fr (spir) Date: Thu, 11 Jun 2009 11:10:14 +0200 Subject: [Tutor] file enigma Message-ID: <20090611111014.02fd41f5@o> Hello, text = file(filename).read() (or: open(filename).read()) How do you close() the file? ;-) Is it, in fact, automagically closed after end-of-statement if not bound to a name? Or when the execution path quits the present scope (func, module), like if it had been bound to a local var? Or what else? Said differently: in this case, how long does the python file object live / does the file in file system remain locked? I would love case #1. This may be implementation-dependant, no? Denis ------ la vita e estrany From mail at timgolden.me.uk Thu Jun 11 11:21:31 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 11 Jun 2009 10:21:31 +0100 Subject: [Tutor] file enigma In-Reply-To: <20090611111014.02fd41f5@o> References: <20090611111014.02fd41f5@o> Message-ID: <4A30CC9B.7030500@timgolden.me.uk> spir wrote: > Hello, > > text = file(filename).read() > > (or: open(filename).read()) > > How do you close() the file? ;-) Well, in any version of Python, you can do this: f = open (filename) text = f.read () f.close () or, slightly more robsustly: f = open (filename) try: text = f.read () finally: f.close () But in Python 2.5+ that can be spelt: with open (filename) as f: text = f.read () As it happens, in CPython at the moment, the file object will be closed when all references are released -- which would be at the end of the line in your example. I don't know whether that's guaranteed by the implementation, or merely the case at present. It's certainly *not* the case in other implementations, such as IronPython & Jython which don't use the same kind of refcounting. FWIW, in non-critical code I often use the style you illustrate above: text = open (filename).read (). But in production code, I usually use the with statement. TJG From denis.spir at free.fr Thu Jun 11 12:40:49 2009 From: denis.spir at free.fr (spir) Date: Thu, 11 Jun 2009 12:40:49 +0200 Subject: [Tutor] Parse Text File In-Reply-To: <5cb309e70906110253g63fc910ew41bada54f7913e89@mail.gmail.com> References: <5cb309e70906101144r2050a75dpf6d0db27e9d8f86b@mail.gmail.com> <20090610225814.3111cc05@o> <5cb309e70906110253g63fc910ew41bada54f7913e89@mail.gmail.com> Message-ID: <20090611124049.2aa97667@o> [Hope you don't mind I copy to the list. Not only it can help others, but pyparsing users read tutor, including Paul MacGuire (author).] Le Thu, 11 Jun 2009 11:53:31 +0200, Stefan Lesicnik s'exprima ainsi: [...] I cannot really answer precisely for haven't used pyparsing for a while (*). So, below are only some hints. > Hi Denis, > > Thanks for your input. So i decided i should use a pyparser and try it (im a > relative python noob though!) > > This is what i have so far... > > import sys > from pyparsing import alphas, nums, ZeroOrMore, Word, Group, Suppress, > Combine, Literal, alphanums, Optional, OneOrMore, SkipTo, printables > > text=''' > [04 Jun 2009] DSA-1812-1 apr-util - several vulnerabilities > {CVE-2009-0023 CVE-2009-1955} > [etch] - apr-util 1.2.7+dfsg-2+etch2 > [lenny] - apr-util 1.2.12+dfsg-8+lenny2 > ''' > > date = Combine(Literal('[') + Word(nums, exact=2) + Word(alphas) + > Word(nums, exact=4) + Literal(']'),adjacent=False) > dsa = Combine(Word(alphanums) + Literal('-') + Word(nums, exact=4) + > Literal('-') + Word(nums, exact=1),adjacent=False) > app = Combine(OneOrMore(Word(printables)) + SkipTo(Literal('-'))) > desc = Combine(Literal('-') + ZeroOrMore(Word(alphas)) + > SkipTo(Literal('\n'))) > cve = Combine(Literal('{') + OneOrMore(Literal('CVE') + Literal('-') + > Word(nums, exact=4) + Literal('-') + Word(nums, exact=4)) ) > > record = date + dsa + app + desc + cve > > fields = record.parseString(text) > #fields = dsa.parseString(text) > print fields > > > What i get out of this is > > ['[04Jun2009]', 'DSA-1812-1', 'apr-util ', '- several vulnerabilities', > '{CVE-2009-0023'] > > Which i guess it heading towards the right track... For sure! Rather impressing you could write this so fast. Hope my littel PEG grammar helped. There seems to be some detail issues, such as in the app pattern I would write ...+ SkipTo(Literal(' - ')) Also, you could directly Suppress() probably useless delimiters such as [...] in date. Think at post-parse funcs to transform and/or reformat nodes: search for setParseAction() and addParseAction() in the doc. > I am unsure why I am not getting more than 1 CVE... I have the OneOrMore > match for the CVE stuff... This is due to Combine(), that glues (back) together matched string bits. To work safely, it disables the default separator-skipping behaviour of pyparsing. So that real = Combine(integral+fractional) would correctly not match "1 .2". Right? See a recent reply by Paul MacGuire about this topic on the pyparsing list http://sourceforge.net/mailarchive/forum.php?thread_name=FE0E2B47198D4F73B01E263034BDCE3C%40AWA2&forum_name=pyparsing-users and the pointer he gives there. There are several ways to correctly cope with that. > That being said, how does the parser scale across multiple lines and how > will it know that its finished? Basically, you probably should express line breaks explicitely, esp. because they seem to be part of the source format. Otherwise, there is a func or method to define which chars should be skipped as separators (default is sp/tab if I remember well). > Should i maybe look at getting the list first into one entry per line? (must > be easier to parse then?) What makes sense I guess is Group()-ing items that *conceptually* build a list. In your case, I see: * CVS items inside {...} * version entry lines ("[etch]...", "[lenny]...", ...) * whole records at a higher level > This parsing is a mini language in itself! Sure! A kind of rather big & complex parsing language. Hard to know it all well (and I don't even speak of all builtin helpers, and even less of all what you can do by mixing ordinary python code inside the grammar/parser: a whole new field in parsing/processing). > Thanks for your input :) My pleasure... > Stefan Denis (*) The reason is I'm developping my own parsing tool; see http://spir.wikidot.com/pijnu. The guide is also intended as a parsing tutorial, it may help, but is not exactly up-to-date. ------ la vita e estrany From alun.griffiths at dsl.pipex.com Thu Jun 11 10:08:11 2009 From: alun.griffiths at dsl.pipex.com (Alun Griffiths) Date: Thu, 11 Jun 2009 09:08:11 +0100 Subject: [Tutor] Replacing keyboard input to EXE file Message-ID: <7lcd7l$7kc1l6@smtp.pipex.tiscali.co.uk> Hi I have a legacy (FORTRAN) program called POLY.EXE which asks the user interactively for three inputs (file names) from the keyboard. I would like to run this program in batch and tried to replace the interactive prompts with file names stored in a separate file using this Python script: import subprocess try: poly_file = file("poly_files.txt","r") except: print "Could not open input file" else: x = subprocess.Popen(args="poly.exe", stdin=poly_file) x.wait() poly_files.txt contains the three file names as follows: polyin.dat polyout.dat polyout.plt On execution, I get these error messages Traceback (most recent call last): File "C:/Projects/Active/Alun/test_poly.py", line 4, in -toplevel- x = subprocess.Popen(args="poly.exe", stdin=poly_file) File "C:\Python24\lib\subprocess.py", line 533, in __init__ (p2cread, p2cwrite, File "C:\Python24\lib\subprocess.py", line 607, in _get_handles c2pwrite = self._make_inheritable(c2pwrite) File "C:\Python24\lib\subprocess.py", line 634, in _make_inheritable DUPLICATE_SAME_ACCESS) WindowsError: [Errno 6] The handle is invalid So, it looks like something is wrong with the way I am redirecting stdin, but I have no idea what the problem is. Any suggestions gratefully received Thanks in advance Alun Griffiths From robert.lummis at gmail.com Thu Jun 11 03:43:33 2009 From: robert.lummis at gmail.com (Robert Lummis) Date: Wed, 10 Jun 2009 21:43:33 -0400 Subject: [Tutor] How do I do this in python? Message-ID: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> I want to write a function that I can use for debugging purposes that prints the values of whatever list of object references it is given as arguments, without knowing in advance how many object references it will be called with or what they might be. For example, the call: show(a,b,c) would output the values of the arguments like this: a = 3 b = 'john' c = 'Monday' while show (x) would output (for example): x = 3.14 of course displaying whatever the actual current values are. For a collection object it would make sense to output just the first few values. So within the 'show' function definition I have to somehow get a list of the literal argument names it was called with and then use the names as globals to get the values. How do I do that? If this can't be done but there is a completely different way to achieve a similar result, what is it? I'm trying to learn python but it's a struggle because the documentation is so dispersed. If there is a solution to this question, what documentation could I have looked at to find it on my own? BTW I'm using python 3.01 if it matters. -- Robert Lummis From kent37 at tds.net Thu Jun 11 12:54:07 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Jun 2009 06:54:07 -0400 Subject: [Tutor] Syntax Error First Example In-Reply-To: <82bf08860906101902r477408b6w7b1106cba41bc983@mail.gmail.com> References: <82bf08860906101902r477408b6w7b1106cba41bc983@mail.gmail.com> Message-ID: <1c2a2c590906110354s7027e224ic64148baacff654b@mail.gmail.com> On Wed, Jun 10, 2009 at 10:02 PM, Randy Trahan wrote: > First, I am suppose to put this in the script mode vs the?IDLE mode correct? > He failed to mention where.. Generally the "Python Shell" window is for interactive exploration and to see the results of your scripts. To type in a complete program use a new editing window (File / New). You might find this tour of IDLE to be helpful: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ > Also, I get a syntax error at "input"? Since its my first day/hour I don't > know how to debug and its typed in exactly as he wrote it... It's very helpful to us if you copy and paste the exact error text, including the traceback, when you ask for help with errors. Welcome to Python! Kent From denis.spir at free.fr Thu Jun 11 12:56:10 2009 From: denis.spir at free.fr (spir) Date: Thu, 11 Jun 2009 12:56:10 +0200 Subject: [Tutor] file enigma In-Reply-To: <4A30CC9B.7030500@timgolden.me.uk> References: <20090611111014.02fd41f5@o> <4A30CC9B.7030500@timgolden.me.uk> Message-ID: <20090611125610.51a61693@o> Le Thu, 11 Jun 2009 10:21:31 +0100, Tim Golden s'exprima ainsi: > spir wrote: > > Hello, > > > > text = file(filename).read() > > > > (or: open(filename).read()) > > > > How do you close() the file? ;-) > > Well, in any version of Python, you can do this: > > > f = open (filename) > text = f.read () > f.close () > > > or, slightly more robsustly: > > > f = open (filename) > try: > text = f.read () > finally: > f.close () > > > But in Python 2.5+ that can be spelt: > > > with open (filename) as f: > text = f.read () > > > > As it happens, in CPython at the moment, the file object will > be closed when all references are released -- which would be > at the end of the line in your example. I don't know whether > that's guaranteed by the implementation, or merely the case > at present. It's certainly *not* the case in other implementations, > such as IronPython & Jython which don't use the same kind of > refcounting. Thank you, Tim, this really answers my question. My question was motivated by 2 reasons: * This "open(filename).read()" expression is very common, while there is seemingly no way to close the file. There's not even a way to check the flag file.closed, I guess! * I intended to write a helper func "filetext(filename)" to open/read/close/return (or equivalent using the with idiom). But if ever the expression above is rather safe, then there is no need for the said helper. I also thought at str methods (where the target string is a filename) .filetext() and .filebytes (the latter with file opening in 'rb' mode). Again, these methods would be useless if one can safely write "open(filename).read()". > FWIW, in non-critical code I often use the style you illustrate > above: text = open (filename).read (). But in production code, > I usually use the with statement. Right, thanks again. > TJG Denis ------ la vita e estrany From thegreentealeaf at gmail.com Thu Jun 11 12:56:27 2009 From: thegreentealeaf at gmail.com (The Green Tea Leaf) Date: Thu, 11 Jun 2009 12:56:27 +0200 Subject: [Tutor] How do I do this in python? In-Reply-To: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> References: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> Message-ID: <3753b0ed0906110356p2f203946uf48185642d9eb2db@mail.gmail.com> My advice: "Learning Python" very nice book def show(*args): print args def show2(*args): for item in args: print "Blabla:",item show(1,2,"hello") show2(1,2,"hello") On Thu, Jun 11, 2009 at 03:43, Robert Lummis wrote: > I want to write a function that I can use for debugging purposes that > prints the values of whatever list of object references it is given as > arguments, without knowing in advance how many object references it > will be called with or what they might be. For example, the call: > show(a,b,c) would output the values of the arguments like this: > > ? ?a = 3 > ? ?b = 'john' > ? ?c = 'Monday' > > while show (x) would output (for example): > > ? ?x = 3.14 > > of course displaying whatever the actual current values are. For a > collection object it would make sense to output just the first few > values. > > So within the 'show' function definition I have to somehow get a list > of the literal argument names it was called with and then use the > names as globals to get the values. How do I do that? > > If this can't be done but there is a completely different way to > achieve a similar result, what is it? > > I'm trying to learn python but it's a struggle because the > documentation is so dispersed. If there is a solution to this > question, what documentation could I have looked at to find it on my > own? > > BTW I'm using python 3.01 if it matters. > > -- > Robert Lummis > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- The Green Tea Leaf thegreentealeaf at gmail.com thegreentealeaf.blogspot.com From mail at timgolden.me.uk Thu Jun 11 13:03:24 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 11 Jun 2009 12:03:24 +0100 Subject: [Tutor] file enigma In-Reply-To: <20090611125610.51a61693@o> References: <20090611111014.02fd41f5@o> <4A30CC9B.7030500@timgolden.me.uk> <20090611125610.51a61693@o> Message-ID: <4A30E47C.10906@timgolden.me.uk> spir wrote: > Thank you, Tim, this really answers my question. Glad to be of help :) > > * I intended to write a helper func "filetext(filename)" to > open/read/close/return (or equivalent using the with idiom). This is one of those tricky things in Python: when the "raw" code is possibly one line long, and at most two (for Python 2.5+), it's only marginally worth creating a function for it unless you've got some substantial extra functionality. Ultimately it's a matter for personal taste / project needs. TJG From kent37 at tds.net Thu Jun 11 13:08:13 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Jun 2009 07:08:13 -0400 Subject: [Tutor] How do I do this in python? In-Reply-To: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> References: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> Message-ID: <1c2a2c590906110408i3f9270e7g24e8722e0f07692e@mail.gmail.com> On Wed, Jun 10, 2009 at 9:43 PM, Robert Lummis wrote: > I want to write a function that I can use for debugging purposes that > prints the values of whatever list of object references it is given as > arguments, without knowing in advance how many object references it > will be called with or what they might be. For example, the call: > show(a,b,c) would output the values of the arguments like this: > > ? ?a = 3 > ? ?b = 'john' > ? ?c = 'Monday' > > while show (x) would output (for example): > > ? ?x = 3.14 > > of course displaying whatever the actual current values are. For a > collection object it would make sense to output just the first few > values. > > So within the 'show' function definition I have to somehow get a list > of the literal argument names it was called with and then use the > names as globals to get the values. How do I do that? I don't know of a straightforward way to do this. You can use sys._getframe() to get the caller's context but I don't think it will tell you what variables were used for the call. > If this can't be done but there is a completely different way to > achieve a similar result, what is it? You could pass keyword arguments: def show(**kwargs): for k, v in kwargs.items(): print(k, '=', v) show(a=a, b=b, c=c) Kent From a.t.hofkamp at tue.nl Thu Jun 11 13:12:02 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 11 Jun 2009 13:12:02 +0200 Subject: [Tutor] How do I do this in python? In-Reply-To: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> References: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> Message-ID: <4A30E682.70208@tue.nl> Robert Lummis wrote: > I want to write a function that I can use for debugging purposes that > prints the values of whatever list of object references it is given as > arguments, without knowing in advance how many object references it > will be called with or what they might be. For example, the call: > show(a,b,c) would output the values of the arguments like this: > > a = 3 > b = 'john' > c = 'Monday' > > while show (x) would output (for example): > > x = 3.14 > > of course displaying whatever the actual current values are. For a > collection object it would make sense to output just the first few > values. To catch any number of arguments, you could do something like def show(*args): print args but that gives you just a list of values, like [3, 'john', 'Monday'] Inside a function there is no way of finding out how the values ended up as argument (or even whether a value has a name in the first place). In general, a value may have several names, eg a = [] b = a or no names at all like show(1) In other words, what you want is not possible. > So within the 'show' function definition I have to somehow get a list > of the literal argument names it was called with and then use the > names as globals to get the values. How do I do that? globals is not enough. What if I use show in a function? If you really insist on using 'show()', you could do show(('a', a), ('b', b), ('c', c)) with def show(*args): print '\n'.join(['%s = %s' % a for a in args]) but I think it is too complicated to type, compared to the 'print' statement below. > If this can't be done but there is a completely different way to > achieve a similar result, what is it? print "abc=", a, b, c is what I always use. > I'm trying to learn python but it's a struggle because the > documentation is so dispersed. If there is a solution to this > question, what documentation could I have looked at to find it on my > own? Dispersed? Everything is documented at docs.python.org. (your Python version may be the cause of your problems here though) > BTW I'm using python 3.01 if it matters. That version is not ready for real use yet. For learning Python you better use a 2.X version (2.6 is current). Albert From srilyk at gmail.com Thu Jun 11 13:12:31 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 11 Jun 2009 06:12:31 -0500 Subject: [Tutor] Replacing keyboard input to EXE file In-Reply-To: <7lcd7l$7kc1l6@smtp.pipex.tiscali.co.uk> References: <7lcd7l$7kc1l6@smtp.pipex.tiscali.co.uk> Message-ID: <333efb450906110412i66df88earfa7719e6412075b4@mail.gmail.com> On Thu, Jun 11, 2009 at 3:08 AM, Alun Griffiths < alun.griffiths at dsl.pipex.com> wrote: > Hi > > I have a legacy (FORTRAN) program called POLY.EXE which asks the user > interactively for three inputs (file names) from the keyboard. I would like > to run this program in batch and tried to replace the interactive prompts > with file names stored in a separate file using this Python script: > > import subprocess > > try: > poly_file = file("poly_files.txt","r") > except: > print "Could not open input file" > else: > x = subprocess.Popen(args="poly.exe", stdin=poly_file) > x.wait() > > poly_files.txt contains the three file names as follows: > > polyin.dat > polyout.dat > polyout.plt > > On execution, I get these error messages > Traceback (most recent call last): > File "C:/Projects/Active/Alun/test_poly.py", line 4, in -toplevel- > x = subprocess.Popen(args="poly.exe", stdin=poly_file) > File "C:\Python24\lib\subprocess.py", line 533, in __init__ > (p2cread, p2cwrite, > File "C:\Python24\lib\subprocess.py", line 607, in _get_handles > c2pwrite = self._make_inheritable(c2pwrite) > File "C:\Python24\lib\subprocess.py", line 634, in _make_inheritable > DUPLICATE_SAME_ACCESS) > WindowsError: [Errno 6] The handle is invalid > > So, it looks like something is wrong with the way I am redirecting stdin, > but I have no idea what the problem is. Any suggestions gratefully received > I've not done much with subprocess, but I know you can use the subprocess.PIPE to redirect stdin/stdout. This may be of some help too, http://www.oreillynet.com/onlamp/blog/2007/08/pymotw_subprocess_1.html -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Thu Jun 11 13:19:53 2009 From: denis.spir at free.fr (spir) Date: Thu, 11 Jun 2009 13:19:53 +0200 Subject: [Tutor] How do I do this in python? In-Reply-To: <3753b0ed0906110356p2f203946uf48185642d9eb2db@mail.gmail.com> References: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> <3753b0ed0906110356p2f203946uf48185642d9eb2db@mail.gmail.com> Message-ID: <20090611131953.417654b9@o> Le Thu, 11 Jun 2009 12:56:27 +0200, The Green Tea Leaf s'exprima ainsi: > My advice: "Learning Python" very nice book > > def show(*args): > print args > > def show2(*args): > for item in args: > print "Blabla:",item > > show(1,2,"hello") > show2(1,2,"hello") Well, it's not what the poster asked for: where are the (var) names? Denis > On Thu, Jun 11, 2009 at 03:43, Robert Lummis wrote: > > I want to write a function that I can use for debugging purposes that > > prints the values of whatever list of object references it is given as > > arguments, without knowing in advance how many object references it > > will be called with or what they might be. For example, the call: > > show(a,b,c) would output the values of the arguments like this: > > > > ? ?a = 3 > > ? ?b = 'john' > > ? ?c = 'Monday' > > > > while show (x) would output (for example): > > > > ? ?x = 3.14 > > > > of course displaying whatever the actual current values are. For a > > collection object it would make sense to output just the first few > > values. > > > > So within the 'show' function definition I have to somehow get a list > > of the literal argument names it was called with and then use the > > names as globals to get the values. How do I do that? > > > > If this can't be done but there is a completely different way to > > achieve a similar result, what is it? > > > > I'm trying to learn python but it's a struggle because the > > documentation is so dispersed. If there is a solution to this > > question, what documentation could I have looked at to find it on my > > own? > > > > BTW I'm using python 3.01 if it matters. > > > > -- > > Robert Lummis > > _______________________________________________ > > Tutor maillist ?- ?Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > ------ la vita e estrany From denis.spir at free.fr Thu Jun 11 13:45:00 2009 From: denis.spir at free.fr (spir) Date: Thu, 11 Jun 2009 13:45:00 +0200 Subject: [Tutor] How do I do this in python? In-Reply-To: <4A30E682.70208@tue.nl> References: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> <4A30E682.70208@tue.nl> Message-ID: <20090611134500.610f0e9c@o> Le Thu, 11 Jun 2009 13:12:02 +0200, "A.T.Hofkamp" s'exprima ainsi: > > If this can't be done but there is a completely different way to > > achieve a similar result, what is it? > > print "abc=", a, b, c > > is what I always use. Well, I do find the OP's demand really sensible. Had the same need (and still have), esp. for everyday quick debugging. Strangely enough, I also called this show() and had a need for a kind of "polyShow()", and for a "treeShow()", too... Actually, python (only) knows the name. There is no implementation issue, I guess: I would love a builtin (can only be builtin) func, or better a statement, to do that. May accept only name(s) and raise NameError on wrong call. Then, we could insert in code lines like show(count, result) instead of eg print "count:%s, result:%s" %(count,result) A statement version may be: show count, result or why not ? count, result In the case of a statement, it's much more consistent to require the parameter list to contain only names. This would really make my life nicer. It's *so* stupid to be obliged to repeat the name! And even more when you think python knows it!! And even more when you realise _you_ have no way to know it, for most objects don't have a __name__ attribute!!! By the way, for funcs, bound & unbound methods, classes/types, modules, you can use this attr: ======= def show(*args): for arg in args: try: print "%s:%r" %(arg.__name__,arg) except AttributeError: print "?:%r" % arg def f():pass n=1 show(f,n) ==> output ==> f: ?:1 ======= But this does not bring much, sure... Denis ------ la vita e estrany From etrade.griffiths at dsl.pipex.com Thu Jun 11 14:06:14 2009 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Thu, 11 Jun 2009 13:06:14 +0100 Subject: [Tutor] Replacing keyboard input to EXE file In-Reply-To: <333efb450906110412i66df88earfa7719e6412075b4@mail.gmail.co m> References: <7lcd7l$7kc1l6@smtp.pipex.tiscali.co.uk> <333efb450906110412i66df88earfa7719e6412075b4@mail.gmail.com> Message-ID: <7jho38$3am1hj@smtp.pipex.tiscali.co.uk> >Hi > >I have a legacy (FORTRAN) program called POLY.EXE which asks the >user interactively for three inputs (file names) from the >keyboard. I would like to run this program in batch and tried to >replace the interactive prompts with file names stored in a separate >file using this Python script: > >import subprocess > >try: > poly_file = file("poly_files.txt","r") >except: > print "Could not open input file" >else: > x = subprocess.Popen(args="poly.exe", stdin=poly_file) > x.wait() > >poly_files.txt contains the three file names as follows: > >polyin.dat >polyout.dat >polyout.plt > >On execution, I get these error messages >Traceback (most recent call last): > File "C:/Projects/Active/Alun/test_poly.py", line 4, in -toplevel- > x = subprocess.Popen(args="poly.exe", stdin=poly_file) > File "C:\Python24\lib\subprocess.py", line 533, in __init__ > (p2cread, p2cwrite, > File "C:\Python24\lib\subprocess.py", line 607, in _get_handles > c2pwrite = self._make_inheritable(c2pwrite) > File "C:\Python24\lib\subprocess.py", line 634, in _make_inheritable > DUPLICATE_SAME_ACCESS) >WindowsError: [Errno 6] The handle is invalid > >So, it looks like something is wrong with the way I am redirecting >stdin, but I have no idea what the problem is. Any suggestions >gratefully received > > >I've not done much with subprocess, but I know you can use the >subprocess.PIPE to redirect stdin/stdout. > >This may be of some help too, > >http://www.oreillynet.com/onlamp/blog/2007/08/pymotw_subprocess_1.html > >-Wayne Wayne I did try using stdin but got the same problem. I also hacked the following from the website you suggested: import subprocess x = subprocess.Popen(args="poly.exe",stdin=subprocess.PIPE) for item in ["polyin.dat", "polyout.dat", "polyout.plt"]: x.stdin.write('%s\n' % item) but got the same error message Best regards Alun -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Thu Jun 11 14:26:08 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 11 Jun 2009 14:26:08 +0200 Subject: [Tutor] Replacing keyboard input to EXE file In-Reply-To: <7jho38$3am1hj@smtp.pipex.tiscali.co.uk> References: <7lcd7l$7kc1l6@smtp.pipex.tiscali.co.uk> <333efb450906110412i66df88earfa7719e6412075b4@mail.gmail.com> <7jho38$3am1hj@smtp.pipex.tiscali.co.uk> Message-ID: <4A30F7E0.2030704@tue.nl> eShopping wrote: > import subprocess > > x = subprocess.Popen(args="poly.exe",stdin=subprocess.PIPE) > > for item in ["polyin.dat", "polyout.dat", "polyout.plt"]: > x.stdin.write('%s\n' % item) > > but got the same error message Above code would seem to be correct. Are you sure the Fortran program accepts the names? One easy way to test this is to try C:\> poly.exe < poly_files.txt in a CMD program (or COMMAND or whatever the console program is called nowadays at Win* systems). Albert From lie.1296 at gmail.com Thu Jun 11 14:30:51 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 11 Jun 2009 22:30:51 +1000 Subject: [Tutor] How do I do this in python? In-Reply-To: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> References: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> Message-ID: Robert Lummis wrote: > I want to write a function that I can use for debugging purposes that > prints the values of whatever list of object references it is given as > arguments, without knowing in advance how many object references it > will be called with or what they might be. For example, the call: > show(a,b,c) would output the values of the arguments like this: In python, most objects does not know its own name (there are few exceptions such as function and class object). An object may have multiple names and often no name at all (e.g. objects inside a list, constants). In fact, when the code is compiled to bytecode, all local names (but not globals) are discarded and turns into some sort of array access. So... the best solution would be: print("a = ", a) for globals this might work: >>> def show(name): ... value = eval("repr(%s)" % name) ... print('%s = %s' % (name, value)) ... >>> g = 10 >>> show("g") g = 10 for one that works with locals (although it's a bit of inconvenient as you have to pass the locals() around): >>> def show2(name, local): ... value = eval('repr(%s)' % name, globals(), local) ... print('%s = %s' % (name, value)) ... >>> g = 10 >>> show2('g', {}) g = 10 >>> def func(foo): ... bar = 'abc' ... show2('foo', locals()) ... show2('bar', locals()) ... >>> func(123) foo = 123 bar = 'abc' please note that some people might object to the liberal and careless use of eval()... a more sophisticated approach would check that `name` only contains alphanumeric characters that is valid identifiers Aa more sophisticated approach might also use the *args, **kargs variadic parameter construct... > a = 3 > b = 'john' > c = 'Monday' > > while show (x) would output (for example): > > x = 3.14 > > of course displaying whatever the actual current values are. For a > collection object it would make sense to output just the first few > values. If you need a custom print behavior, you need to override the object's __str__ (and sometimes __repr__). Either that or something like this: def myprint(*args): parens = {list: ('[', ']'), tuple: ('(', ')')} for arg in args: if isinstance(arg, (list, tuple)) and len(arg) > 5: open, close = parens[type(arg)] print('%s%s, %s, %s, ..., %s%s' % (open, arg[0], arg[1], arg[2], arg[-1], close)) else: print(arg) >>> myprint(12, 'acv', [1, 2], [1, 4, 5, 6, 7, 8, 3, 2]) 12 acv [1, 2] [1, 4, 5, ..., 2] > So within the 'show' function definition I have to somehow get a list > of the literal argument names it was called with and then use the > names as globals to get the values. How do I do that? If you're referring to this construct: def func(a, b, opt=None, *args, **kargs): # args is a `list` of extra positional arguments # kargs is a `dict` of extra keyword arguments # # a and b are required parameters # opt is optional parameter with default value None > If this can't be done but there is a completely different way to > achieve a similar result, what is it? > > I'm trying to learn python but it's a struggle because the > documentation is so dispersed. If there is a solution to this > question, what documentation could I have looked at to find it on my > own? > > BTW I'm using python 3.01 if it matters. You should use python 2.x for now. The documentations and various tutorials for python 3.x hasn't caught up with the amount that python 2.x already has. Python 3.0 beginner tutorial is still very rare; most python 3.x tutorials are aimed towards programmers that have used python 2.x and want to switch their codes to python 3.x. I guess it will be around the release of python 3.2 when most Linux/Unix python distro/projects have adapted their codes to python 3.x before we start seeing beginner python 3.x tutorials popping around. From etrade.griffiths at dsl.pipex.com Thu Jun 11 14:36:33 2009 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Thu, 11 Jun 2009 13:36:33 +0100 Subject: [Tutor] Replacing keyboard input to EXE file In-Reply-To: <4A30F7E0.2030704@tue.nl> References: <7lcd7l$7kc1l6@smtp.pipex.tiscali.co.uk> <333efb450906110412i66df88earfa7719e6412075b4@mail.gmail.com> <7jho38$3am1hj@smtp.pipex.tiscali.co.uk> <4A30F7E0.2030704@tue.nl> Message-ID: <7jho38$3amc6m@smtp.pipex.tiscali.co.uk> At 13:26 11/06/2009, you wrote: >eShopping wrote: >>import subprocess >>x = subprocess.Popen(args="poly.exe",stdin=subprocess.PIPE) >>for item in ["polyin.dat", "polyout.dat", "polyout.plt"]: >> x.stdin.write('%s\n' % item) >>but got the same error message > >Above code would seem to be correct. > >Are you sure the Fortran program accepts the names? >One easy way to test this is to try > >C:\> poly.exe < poly_files.txt > >in a CMD program (or COMMAND or whatever the console program is >called nowadays at Win* systems). Tried piping the input as suggested but POLY ignores the pipe and just asks me for the names of the files as if we were in interactive mode. From lie.1296 at gmail.com Thu Jun 11 14:49:19 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 11 Jun 2009 22:49:19 +1000 Subject: [Tutor] Replacing keyboard input to EXE file In-Reply-To: <7jho38$3amc6m@smtp.pipex.tiscali.co.uk> References: <7lcd7l$7kc1l6@smtp.pipex.tiscali.co.uk> <333efb450906110412i66df88earfa7719e6412075b4@mail.gmail.com> <7jho38$3am1hj@smtp.pipex.tiscali.co.uk> <4A30F7E0.2030704@tue.nl> <7jho38$3amc6m@smtp.pipex.tiscali.co.uk> Message-ID: eShopping wrote: > At 13:26 11/06/2009, you wrote: >> eShopping wrote: >>> import subprocess >>> x = subprocess.Popen(args="poly.exe",stdin=subprocess.PIPE) >>> for item in ["polyin.dat", "polyout.dat", "polyout.plt"]: >>> x.stdin.write('%s\n' % item) >>> but got the same error message >> >> Above code would seem to be correct. >> >> Are you sure the Fortran program accepts the names? >> One easy way to test this is to try >> >> C:\> poly.exe < poly_files.txt >> >> in a CMD program (or COMMAND or whatever the console program is called >> nowadays at Win* systems). > > Tried piping the input as suggested but POLY ignores the pipe and just > asks me for the names of the files as if we were in interactive mode. Can you provide an example of the Fortran program session? Especially the part where it asked for file name. From alan.gauld at btinternet.com Thu Jun 11 15:01:43 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Jun 2009 14:01:43 +0100 Subject: [Tutor] Replacing keyboard input to EXE file References: <7lcd7l$7kc1l6@smtp.pipex.tiscali.co.uk><333efb450906110412i66df88earfa7719e6412075b4@mail.gmail.com><7jho38$3am1hj@smtp.pipex.tiscali.co.uk> <4A30F7E0.2030704@tue.nl> <7jho38$3amc6m@smtp.pipex.tiscali.co.uk> Message-ID: "eShopping" wrote >>C:\> poly.exe < poly_files.txt >> >>in a CMD program (or COMMAND or whatever the console program is called >>nowadays at Win* systems). > > Tried piping the input as suggested but POLY ignores the pipe and just > asks me for the names of the files as if we were in interactive mode. That suggests POLY is not reading from stdin. Could it be a curses program or similar - ie it is directly accessing the screen? Does it use a form or is it a simple command line prompt? Alan G From a.t.hofkamp at tue.nl Thu Jun 11 15:08:11 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 11 Jun 2009 15:08:11 +0200 Subject: [Tutor] Replacing keyboard input to EXE file In-Reply-To: <7jho38$3amc6m@smtp.pipex.tiscali.co.uk> References: <7lcd7l$7kc1l6@smtp.pipex.tiscali.co.uk> <333efb450906110412i66df88earfa7719e6412075b4@mail.gmail.com> <7jho38$3am1hj@smtp.pipex.tiscali.co.uk> <4A30F7E0.2030704@tue.nl> <7jho38$3amc6m@smtp.pipex.tiscali.co.uk> Message-ID: <4A3101BB.1010309@tue.nl> eShopping wrote: > At 13:26 11/06/2009, you wrote: >> Are you sure the Fortran program accepts the names? >> One easy way to test this is to try >> >> C:\> poly.exe < poly_files.txt >> >> in a CMD program (or COMMAND or whatever the console program is >> called nowadays at Win* systems). > > Tried piping the input as suggested but POLY ignores the pipe and > just asks me for the names of the files as if we were in interactive mode. If the OS cannot convince the program to use stdin, than most certainly Python won't either (since the latter uses the former). You need a different approach to convince poly to accept file-names in a non-interactive way. At a Unix system, you'd step up to emulating a terminal. No idea whether that also works at a Win* system. You could have a look at 'expect', a program to emulate interactive interaction with another program, or pexpect, the python brother of that program. Albert From etrade.griffiths at dsl.pipex.com Thu Jun 11 15:45:53 2009 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Thu, 11 Jun 2009 14:45:53 +0100 Subject: [Tutor] Replacing keyboard input to EXE file In-Reply-To: References: Message-ID: <7jhnpr$5072hl@smtp.pipex.tiscali.co.uk> > >> eShopping wrote: > >>> import subprocess > >>> x = subprocess.Popen(args="poly.exe",stdin=subprocess.PIPE) > >>> for item in ["polyin.dat", "polyout.dat", "polyout.plt"]: > >>> x.stdin.write('%s\n' % item) > >>> but got the same error message > >> > >> Above code would seem to be correct. > >> > >> Are you sure the Fortran program accepts the names? > >> One easy way to test this is to try > >> > >> C:\> poly.exe < poly_files.txt > >> > >> in a CMD program (or COMMAND or whatever the console program is called > >> nowadays at Win* systems). > > > > Tried piping the input as suggested but POLY ignores the pipe and just > > asks me for the names of the files as if we were in interactive mode. > >Can you provide an example of the Fortran program session? Especially >the part where it asked for file name. An example of the session is =======start of snip C:\TEMP>poly PLEASE ENTER THE INPUT FILE NAME: polyin.dat PLEASE ENTER THE OUTPUT FILE NAME: polyout.dat PLEASE ENTER PLOT OUTPUT FILE NAME: polyout.plt Execution terminated: Normal stop C:\TEMP> =======end of snip From kent37 at tds.net Thu Jun 11 16:46:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Jun 2009 10:46:26 -0400 Subject: [Tutor] How do I do this in python? In-Reply-To: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> References: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> Message-ID: <1c2a2c590906110746m7defc991l7cd402a3589362b8@mail.gmail.com> On Wed, Jun 10, 2009 at 9:43 PM, Robert Lummis wrote: > I want to write a function that I can use for debugging purposes that > prints the values of whatever list of object references it is given as > arguments, without knowing in advance how many object references it > will be called with or what they might be. For example, the call: > show(a,b,c) would output the values of the arguments like this: > > ? ?a = 3 > ? ?b = 'john' > ? ?c = 'Monday' > > while show (x) would output (for example): > > ? ?x = 3.14 Here is a pretty clean solution. It passes names rather than values, then looks the values up in the caller's stack frame. Written for Python 2.x but should work for 3.x if you change the prints. In [1]: import sys In [11]: def show(names): ....: frame = sys._getframe(1) ....: for name in names.split(): ....: if name in frame.f_locals: ....: print name, '=', frame.f_locals[name] ....: else: ....: print name, 'not found' In [12]: a=1 In [13]: b='foo' In [14]: c='bar' In [15]: show('a b c') a = 1 b = foo c = bar In [18]: show('a x') a = 1 x not found Kent From oberoc at gmail.com Thu Jun 11 17:05:31 2009 From: oberoc at gmail.com (Tino Dai) Date: Thu, 11 Jun 2009 11:05:31 -0400 Subject: [Tutor] Replacing keyboard input to EXE file In-Reply-To: <7jhnpr$5072hl@smtp.pipex.tiscali.co.uk> References: <7jhnpr$5072hl@smtp.pipex.tiscali.co.uk> Message-ID: <2ac5d4850906110805i5fddc33ds6d79d8ffc03887d9@mail.gmail.com> Hi, I know that this is a python group but you might want to try the open source utility called Expect. It does what you need it to do without having having to go through this trial and error process with subprocess. http://expect.nist.gov/ -Tino On Thu, Jun 11, 2009 at 9:45 AM, eShopping wrote: > > >> eShopping wrote: >> >>> import subprocess >> >>> x = subprocess.Popen(args="poly.exe",stdin=subprocess.PIPE) >> >>> for item in ["polyin.dat", "polyout.dat", "polyout.plt"]: >> >>> x.stdin.write('%s\n' % item) >> >>> but got the same error message >> >> >> >> Above code would seem to be correct. >> >> >> >> Are you sure the Fortran program accepts the names? >> >> One easy way to test this is to try >> >> >> >> C:\> poly.exe < poly_files.txt >> >> >> >> in a CMD program (or COMMAND or whatever the console program is called >> >> nowadays at Win* systems). >> > >> > Tried piping the input as suggested but POLY ignores the pipe and just >> > asks me for the names of the files as if we were in interactive mode. >> >> Can you provide an example of the Fortran program session? Especially >> the part where it asked for file name. >> > > An example of the session is > > =======start of snip > C:\TEMP>poly > PLEASE ENTER THE INPUT FILE NAME: > polyin.dat > PLEASE ENTER THE OUTPUT FILE NAME: > polyout.dat > PLEASE ENTER PLOT OUTPUT FILE NAME: > polyout.plt > > Execution terminated: Normal stop > C:\TEMP> > =======end of snip > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Jun 11 17:37:38 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 11 Jun 2009 08:37:38 -0700 Subject: [Tutor] How do I do this in python? In-Reply-To: <1c2a2c590906110408i3f9270e7g24e8722e0f07692e@mail.gmail.com> References: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> <1c2a2c590906110408i3f9270e7g24e8722e0f07692e@mail.gmail.com> Message-ID: On 6/11/2009 4:08 AM Kent Johnson said... > On Wed, Jun 10, 2009 at 9:43 PM, Robert Lummis wrote: >> I want to write a function that I can use for debugging purposes that >> prints the values of whatever list of object references it is given as >> arguments, without knowing in advance how many object references it >> will be called with or what they might be. For example, the call: >> show(a,b,c) would output the values of the arguments like this: >> >> a = 3 >> b = 'john' >> c = 'Monday' >> >> while show (x) would output (for example): >> >> x = 3.14 >> >> of course displaying whatever the actual current values are. For a >> collection object it would make sense to output just the first few >> values. >> >> So within the 'show' function definition I have to somehow get a list >> of the literal argument names it was called with and then use the >> names as globals to get the values. How do I do that? > > I don't know of a straightforward way to do this. You can use > sys._getframe() to get the caller's context but I don't think it will > tell you what variables were used for the call. > Well, kind of. And somewhat OK for simple variables. OK. Let's see what's in _getframe... >>> import sys ... and a quick function to return _getframe from within a function >>> def rframe(*args,**kwargs): return sys._getframe() ... now to get one >>> a,b,c = 1,2,3 >>> xx = rframe(a,b,c) ...a bit of digging and we find these two... >>> xx.f_locals {'args': (1, 2, 3), 'kwargs': {}} >>> xx.f_back.f_code.co_names ('rframe', 'a', 'b', 'c', 'xx') So, a first cut at show... import sys from pprint import pprint def show(*args): F = sys._getframe() argnames = list(F.f_back.f_code.co_names) argnames = argnames[argnames.index('show')+1:] argvals = F.f_locals['args'] pprint( zip(argnames,argvals) ) ... and some interactive testing... >>> a,b,c = 1,2,3 >>> show(a,b,c) [('a', 1), ('b', 2), ('c', 3)] >>> show(d,e,a,b) [('d', 4), ('e', 5), ('a', 1), ('b', 2)] >>> L = [1,2,3] >>> show(d,e,a,b,L) [('d', 4), ('e', 5), ('a', 1), ('b', 2), ('L', [1, 2, 3])] ... but watch out for composite objects... >>> show(d,e,a,b,L[0]) [('d', 4), ('e', 5), ('a', 1), ('b', 2), ('L', 1)] >>> D = dict([('d', 4), ('e', 5), ('a', 1), ('b', 2), ('L', 1)]) >>> D['L'] 1 >>> show(d,e,a,b,D['L']) [('d', 4), ('e', 5), ('a', 1), ('b', 2), ('D', 1)] I wouldn't rely on this, but it may be of some use and shows a little of the introspection abilities python provides. Emile From eddie9139 at gmail.com Thu Jun 11 17:53:16 2009 From: eddie9139 at gmail.com (Eddie) Date: Fri, 12 Jun 2009 01:53:16 +1000 Subject: [Tutor] Simple factorial program Message-ID: I'm trying to write a simple factorial program and am unsure at what is wrong with it. Why Can't I go *factorial = factorial * number* where factorial and number are both integers? #Factorial program print "Factorial finder" number = input("Please enter a non-negative integer: " for number in range(number, 1) factorial = (factorial * number) print "Factorial:", factorial Thanks Eddie [?] -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 96 bytes Desc: not available URL: From vinces1979 at gmail.com Thu Jun 11 17:57:22 2009 From: vinces1979 at gmail.com (vince spicer) Date: Thu, 11 Jun 2009 09:57:22 -0600 Subject: [Tutor] Simple factorial program In-Reply-To: References: Message-ID: <1e53c510906110857id181a58w7cfe384fedd447c1@mail.gmail.com> did you declare factorial before trying to use it? factorial = 1 print "Factorial finder" number = int(input("Please enter a non-negative integer: ")) for number in range(number, 1) factorial = (factorial * number) print "Factorial:", factorial On Thu, Jun 11, 2009 at 9:53 AM, Eddie wrote: > I'm trying to write a simple factorial program and am unsure at what is > wrong with it. Why Can't I go *factorial = factorial * number* where > factorial and number are both integers? > > #Factorial program > > print "Factorial finder" > number = input("Please enter a non-negative integer: " > for number in range(number, 1) > factorial = (factorial * number) > > print "Factorial:", factorial > > Thanks Eddie [?] > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 96 bytes Desc: not available URL: From denis.spir at free.fr Thu Jun 11 17:58:54 2009 From: denis.spir at free.fr (spir) Date: Thu, 11 Jun 2009 17:58:54 +0200 Subject: [Tutor] How do I do this in python? In-Reply-To: <1c2a2c590906110746m7defc991l7cd402a3589362b8@mail.gmail.com> References: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> <1c2a2c590906110746m7defc991l7cd402a3589362b8@mail.gmail.com> Message-ID: <20090611175854.2fe5dd97@o> Le Thu, 11 Jun 2009 10:46:26 -0400, Kent Johnson s'exprima ainsi: > On Wed, Jun 10, 2009 at 9:43 PM, Robert Lummis > wrote: > > I want to write a function that I can use for debugging purposes that > > prints the values of whatever list of object references it is given as > > arguments, without knowing in advance how many object references it > > will be called with or what they might be. For example, the call: > > show(a,b,c) would output the values of the arguments like this: > > > > ? ?a = 3 > > ? ?b = 'john' > > ? ?c = 'Monday' > > > > while show (x) would output (for example): > > > > ? ?x = 3.14 > > Here is a pretty clean solution. It passes names rather than values, > then looks the values up in the caller's stack frame. Written for > Python 2.x but should work for 3.x if you change the prints. > > In [1]: import sys > In [11]: def show(names): > ....: frame = sys._getframe(1) > ....: for name in names.split(): > ....: if name in frame.f_locals: > ....: print name, '=', frame.f_locals[name] > ....: else: > ....: print name, 'not found' > [...] > > Kent Waow, great! Denis ------ la vita e estrany From eddie9139 at gmail.com Thu Jun 11 18:06:04 2009 From: eddie9139 at gmail.com (Eddie) Date: Fri, 12 Jun 2009 02:06:04 +1000 Subject: [Tutor] Simple factorial program In-Reply-To: <1e53c510906110857id181a58w7cfe384fedd447c1@mail.gmail.com> References: <1e53c510906110857id181a58w7cfe384fedd447c1@mail.gmail.com> Message-ID: Thanks, that is my problem. With that code, why is it giving an error (indenting?) at the end of* for number in range(number, 1) *? 2009/6/12 vince spicer > did you declare factorial before trying to use it? > > factorial = 1 > print "Factorial finder" > number = int(input("Please enter a non-negative integer: ")) > for number in range(number, 1) > factorial = (factorial * number) > > print "Factorial:", factorial > > On Thu, Jun 11, 2009 at 9:53 AM, Eddie wrote: > >> I'm trying to write a simple factorial program and am unsure at what is >> wrong with it. Why Can't I go *factorial = factorial * number* where >> factorial and number are both integers? >> >> #Factorial program >> >> print "Factorial finder" >> number = input("Please enter a non-negative integer: " >> for number in range(number, 1) >> factorial = (factorial * number) >> >> print "Factorial:", factorial >> >> Thanks Eddie [?] >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 96 bytes Desc: not available URL: From vinces1979 at gmail.com Thu Jun 11 18:08:37 2009 From: vinces1979 at gmail.com (vince spicer) Date: Thu, 11 Jun 2009 10:08:37 -0600 Subject: [Tutor] Simple factorial program In-Reply-To: References: <1e53c510906110857id181a58w7cfe384fedd447c1@mail.gmail.com> Message-ID: <1e53c510906110908x1b6745e7oea8ee5d504283bed@mail.gmail.com> no ":" after for statement Vince On Thu, Jun 11, 2009 at 10:06 AM, Eddie wrote: > Thanks, that is my problem. > > With that code, why is it giving an error (indenting?) at the end of* for > number in range(number, 1) *? > > 2009/6/12 vince spicer > > did you declare factorial before trying to use it? >> >> factorial = 1 >> print "Factorial finder" >> number = int(input("Please enter a non-negative integer: ")) >> for number in range(number, 1) >> factorial = (factorial * number) >> >> print "Factorial:", factorial >> >> On Thu, Jun 11, 2009 at 9:53 AM, Eddie wrote: >> >>> I'm trying to write a simple factorial program and am unsure at what is >>> wrong with it. Why Can't I go *factorial = factorial * number* where >>> factorial and number are both integers? >>> >>> #Factorial program >>> >>> print "Factorial finder" >>> number = input("Please enter a non-negative integer: " >>> for number in range(number, 1) >>> factorial = (factorial * number) >>> >>> print "Factorial:", factorial >>> >>> Thanks Eddie [?] >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 96 bytes Desc: not available URL: From ayyaz84 at gmail.com Thu Jun 11 18:11:27 2009 From: ayyaz84 at gmail.com (ayyaz) Date: Thu, 11 Jun 2009 12:11:27 -0400 Subject: [Tutor] Simple factorial program In-Reply-To: References: Message-ID: Eddie wrote: > I'm trying to write a simple factorial program and am unsure at what is > wrong with it. Why Can't I go *factorial = factorial * number* where > factorial and number are both integers? > > #Factorial program > > print "Factorial finder" > number = input("Please enter a non-negative integer: " > for number in range(number, 1) > factorial = (factorial * number) > > print "Factorial:", factorial > > Thanks Eddie > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Hello Eddie, You never initialized the variable factorial. So the line "factorial = (factorial * number)" will crash your program since the program doesn't know what the variable factorial is. I would modify your code as follows: factorial = int(raw_input("\nPlease enter a non-negative integer: ")) for i in range(1,factorial): factorial *= i print "Factorial:", factorial raw_input("\nPress enter to exit") I hope this helps. --ayyaz From eddie9139 at gmail.com Thu Jun 11 18:20:06 2009 From: eddie9139 at gmail.com (Eddie) Date: Fri, 12 Jun 2009 02:20:06 +1000 Subject: [Tutor] Simple factorial program In-Reply-To: References: Message-ID: Thanks guys, I got it working for what I need at the moment with #Factorial finder factorialNum = 1L print "Factorial finder" number = int(input("Please enter a non-negative integer: ")) for number in range(1, number): factorialNum = (factorialNum * (number + 1)) print factorialNum print "Factorial:", factorialNum On this mailing list, is there a general rule about how to place code? I.e. ident, italics, quotes??? 2009/6/12 ayyaz > Eddie wrote: > >> I'm trying to write a simple factorial program and am unsure at what is >> wrong with it. Why Can't I go *factorial = factorial * number* where >> factorial and number are both integers? >> >> #Factorial program >> >> print "Factorial finder" >> number = input("Please enter a non-negative integer: " >> for number in range(number, 1) >> factorial = (factorial * number) >> >> print "Factorial:", factorial >> Thanks Eddie >> >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > Hello Eddie, > > You never initialized the variable factorial. So the line > "factorial = (factorial * number)" will crash your program since > the program doesn't know what the variable factorial is. > > I would modify your code as follows: > > factorial = int(raw_input("\nPlease enter a non-negative integer: ")) > > for i in range(1,factorial): > factorial *= i > > print "Factorial:", factorial > > raw_input("\nPress enter to exit") > > > I hope this helps. > --ayyaz > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Thu Jun 11 18:44:37 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 11 Jun 2009 09:44:37 -0700 Subject: [Tutor] Simple factorial program In-Reply-To: References: Message-ID: <78b3a9580906110944l456bc4b4lbfe2353dbcc8b5c0@mail.gmail.com> hi eddie, a few more nits to tweak... > factorialNum = 1L change to "1" instead of "1L" -- "L" numbers are going away and will be permanently not available starting in 3.0. > print "Factorial finder" > number = int(input("Please enter a non-negative integer: ")) change "input" to "raw_input"... that is, *until* 3.0 when input() will be replaced by raw_input() and renamed to input()! > for number in range(1, number): since you started at "1", to avoid skipping, change "1" to "2". > ? factorialNum = (factorialNum * (number + 1)) so that you can change this to: "factorialNum *= number" hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Thu Jun 11 19:15:22 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Jun 2009 18:15:22 +0100 Subject: [Tutor] Replacing keyboard input to EXE file References: <7jhnpr$5072hl@smtp.pipex.tiscali.co.uk> <2ac5d4850906110805i5fddc33ds6d79d8ffc03887d9@mail.gmail.com> Message-ID: "Tino Dai" wrote > > I know that this is a python group but you might want to try the open > source utility called Expect. It does what you need it to do without > having > having to go through this trial and error process with subprocess. > http://expect.nist.gov/ Or use the Python wrapper around expect - pyexpect??? Alan G From oberoc at gmail.com Thu Jun 11 19:19:51 2009 From: oberoc at gmail.com (Tino Dai) Date: Thu, 11 Jun 2009 13:19:51 -0400 Subject: [Tutor] Replacing keyboard input to EXE file In-Reply-To: References: <7jhnpr$5072hl@smtp.pipex.tiscali.co.uk> <2ac5d4850906110805i5fddc33ds6d79d8ffc03887d9@mail.gmail.com> Message-ID: <2ac5d4850906111019r3fe3213fo715ec29664a57e33@mail.gmail.com> On Thu, Jun 11, 2009 at 1:15 PM, Alan Gauld wrote: > > "Tino Dai" wrote > >> >> I know that this is a python group but you might want to try the open >> source utility called Expect. It does what you need it to do without >> having >> having to go through this trial and error process with subprocess. >> http://expect.nist.gov/ >> > > Or use the Python wrapper around expect - pyexpect??? > > Alan G > Alan, You're absolute right. I've been out of the python world for too long. :S -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Jun 11 19:25:33 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 11 Jun 2009 13:25:33 -0400 Subject: [Tutor] Simple factorial program In-Reply-To: References: Message-ID: <4A313E0D.3060108@ieee.org> Eddie wrote: > I'm trying to write a simple factorial program and am unsure at what is > wrong with it. Why Can't I go *factorial = factorial * number* where > factorial and number are both integers? > > #Factorial program > > print "Factorial finder" > number = input("Please enter a non-negative integer: " > for number in range(number, 1) > factorial = (factorial * number) > > print "Factorial:", factorial > > Thanks Eddie [?] > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > -------------- next part -------------- > A non-text attachment was scrubbed... > Name: not available > Type: image/gif > Size: 96 bytes > Desc: not available > URL: > > Six problems in that initial code. Two of them were identified already. But I'll repeat them to put them in one place. 1) Need closing parenthesis on the input function call 2) Need to give an initial value to factorial, sometime before the for loop 3) Must not indent the for loop statement; it should line up with the input statement 4) parameters to range don't make sense 5) Need to end the for loop with a colon 6) Need to indent the body of the for loop print "Factorial finder" number = input("Please enter a non-negative integer: ") factorial = 1 for number in range(1, number+1): factorial = (factorial * number) print "Factorial:", factorial From tanner989 at hotmail.com Thu Jun 11 19:08:09 2009 From: tanner989 at hotmail.com (tanner barnes) Date: Thu, 11 Jun 2009 12:08:09 -0500 Subject: [Tutor] Help with file editing Message-ID: Ok, so i am creating a program for my school's football team and in one part i need to store a list of variables (their name, height, weight, and grade) in a txt file to bring up later. i know how to create and read from files ( file = open("file_name", ''w/r/a") ). But what i need to do is create a individual file for each member on the roster as they add them in. here is my code: name = self.name.GetValue() < gets their name from the text box stats = str(self.name.GetValue()) + "\n" < gets their name to put into the file stats += str(self.height.GetValue()) + "\n" < gets their height stats += str(self.weight.GetValue()) + "\n" < gets their weight stats += str(self.grade.GetValue()) + "\n" < gets their grade info = open(name + ".txt", "r") < this creates the file for it to all go into using the name we get from above to name it. But when a try and write into the file wright after that last line it wont let me so is there anything i'am missing or should change? _________________________________________________________________ Windows Live?: Keep your life in sync. http://windowslive.com/explore?ocid=TXT_TAGLM_WL_BR_life_in_synch_062009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Jun 11 20:01:56 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 11 Jun 2009 11:01:56 -0700 Subject: [Tutor] Simple factorial program In-Reply-To: References: Message-ID: On 6/11/2009 8:53 AM Eddie said... > I'm trying to write a simple factorial program and am unsure at what is > wrong with it. Why Can't I go *factorial = factorial * number* where > factorial and number are both integers? > > #Factorial program > > print "Factorial finder" > number = input("Please enter a non-negative integer: " > for number in range(number, 1) > factorial = (factorial * number) > > print "Factorial:", factorial Another way to approach this is using reduce: from operator import mul number = input("Please enter a non-negative integer: ") factorial = reduce(mul,range(1,number+1),1) Emile From lie.1296 at gmail.com Thu Jun 11 20:19:15 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Jun 2009 04:19:15 +1000 Subject: [Tutor] Help with file editing In-Reply-To: References: Message-ID: tanner barnes wrote: > Ok, so i am creating a program for my school's football team and in one > part i need to store a list of variables (their name, height, weight, > and grade) in a txt file to bring up later. i know how to create and > read from files ( file = open("file_name", ''w/r/a") ). But what i need > to do is create a individual file for each member on the roster as they > add them in. here is my code: > > name = self.name.GetValue() < gets their name from the text box > > stats = str(self.name.GetValue()) + "\n" < gets their name > to put into the file > stats += str(self.height.GetValue()) + "\n" < gets their height > stats += str(self.weight.GetValue()) + "\n" < gets their weight > stats += str(self.grade.GetValue()) + "\n" < gets their grade > > info = open(name + ".txt", "r") < this creates the file for it > to all go into using the name we get from above to name it. > > But when a try and write into the file wright after that last line it > wont let me so is there anything i'am missing or should change? You opened the file with mode "r"ead-only. Use mode "w"rite or "a"ppend. From stefan at lsd.co.za Thu Jun 11 20:44:27 2009 From: stefan at lsd.co.za (Stefan Lesicnik) Date: Thu, 11 Jun 2009 20:44:27 +0200 Subject: [Tutor] Parse Text File In-Reply-To: <20090611124049.2aa97667@o> References: <5cb309e70906101144r2050a75dpf6d0db27e9d8f86b@mail.gmail.com> <20090610225814.3111cc05@o> <5cb309e70906110253g63fc910ew41bada54f7913e89@mail.gmail.com> <20090611124049.2aa97667@o> Message-ID: <5cb309e70906111144n3b7b9854ne0017555c75fc4ef@mail.gmail.com> > > Hi Denis, > > > > Thanks for your input. So i decided i should use a pyparser and try it > (im a > > relative python noob though!) > Hi Everyone! I have made some progress, although i believe it mainly due to luck and not a lot of understanding (vague understanding maybe). Hopefully this can help someone else out... This is due to Combine(), that glues (back) together matched string bits. To > work safely, it disables the default separator-skipping behaviour of > pyparsing. So that > real = Combine(integral+fractional) > would correctly not match "1 .2". Right? > See a recent reply by Paul MacGuire about this topic on the pyparsing list > http://sourceforge.net/mailarchive/forum.php?thread_name=FE0E2B47198D4F73B01E263034BDCE3C%40AWA2&forum_name=pyparsing-usersand the pointer he gives there. > There are several ways to correctly cope with that. > ^ was a useful link - I still sometime struggle with the whitespaces and combine / group... Below is my code that works as I expect (i think...) #!/usr/bin/python import sys from pyparsing import alphas, nums, ZeroOrMore, Word, Group, Suppress, Combine, Literal, OneOrMore, SkipTo, printables, White text=''' [04 Jun 2009] DSA-1812-1 apr-util - several vulnerabilities {CVE-2009-0023 CVE-2009-1955 CVE-2009-1243} [etch] - apr-util 1.2.7+dfsg-2+etch2 [lenny] - apr-util 1.2.12+dfsg-8+lenny2 [01 Jun 2009] DSA-1808-1 drupal6 - insufficient input sanitising {CVE-2009-1844} [lenny] - drupal6 6.6-3lenny2 [01 Jun 2009] DSA-1807-1 cyrus-sasl2 cyrus-sasl2-heimdal - arbitrary code execution {CVE-2009-0688} [lenny] - cyrus-sasl2-heimdal 2.1.22.dfsg1-23+lenny1 [lenny] - cyrus-sasl2 2.1.22.dfsg1-23+lenny1 [etch] - cyrus-sasl2 2.1.22.dfsg1-8+etch1 ''' lsquare = Literal('[') rsquare = Literal(']') lbrace = Literal('{') rbrace = Literal('}') dash = Literal('-') space = White('\x20') newline = White('\n') spaceapp = White('\x20') + Literal('-') + White('\x20') spaceseries = White('\t') date = Combine(lsquare.suppress() + Word(nums, exact=2) + Word(alphas) + Word(nums, exact=4) + rsquare.suppress(),adjacent=False,joinString='-') dsa = Combine(Literal('DSA') + dash + Word(nums, exact=4) + dash + Word(nums, exact=1)) app = Combine(Word(printables) + SkipTo(spaceapp)) desc = Combine(spaceapp.suppress() + ZeroOrMore(Word(alphas)) + SkipTo(newline)) cve = Combine(lbrace.suppress() + OneOrMore(Literal('CVE') + dash + Word(nums, exact=4) + dash + Word(nums, exact=4) + SkipTo(rbrace) + Suppress(rbrace) + SkipTo(newline))) series = OneOrMore(Group(lsquare.suppress() + OneOrMore(Literal('lenny') ^ Literal('etch') ^ Literal('sarge')) + rsquare.suppress() + spaceapp.suppress() + Word(printables) + SkipTo(newline))) record = date + dsa + app + desc + cve + series def parse(text): for data,dataStart,dataEnd in record.scanString(text): yield data for i in parse(text): print i My output is as follows ['04-Jun-2009', 'DSA-1812-1', 'apr-util', 'several vulnerabilities', 'CVE-2009-0023 CVE-2009-1955 CVE-2009-1243', ['etch', 'apr-util', '1.2.7+dfsg-2+etch2'], ['lenny', 'apr-util', '1.2.12+dfsg-8+lenny2']] ['01-Jun-2009', 'DSA-1808-1', 'drupal6', 'insufficient input sanitising', 'CVE-2009-1844', ['lenny', 'drupal6', '6.6-3lenny2']] ['01-Jun-2009', 'DSA-1807-1', 'cyrus-sasl2 cyrus-sasl2-heimdal', 'arbitrary code execution', 'CVE-2009-0688', ['lenny', 'cyrus-sasl2-heimdal', '2.1.22.dfsg1-23+lenny1'], ['lenny', 'cyrus-sasl2', '2.1.22.dfsg1-23+lenny1'], ['etch', 'cyrus-sasl2', '2.1.22.dfsg1-8+etch1']] Thanks for everyone that offered assistance and prodding in right directions. Stefan -------------- next part -------------- An HTML attachment was scrubbed... URL: From cosmicsand27 at yahoo.com Thu Jun 11 20:45:32 2009 From: cosmicsand27 at yahoo.com (Raj Medhekar) Date: Thu, 11 Jun 2009 11:45:32 -0700 (PDT) Subject: [Tutor] Need a solution. Message-ID: <801768.57354.qm@web43401.mail.sp1.yahoo.com> I have been having some difficulty modifying this program to where a player has limited number of guesses and if he fails to guess correctly within that number he is asked to "Try Again" The original program code and the code that I modified are given below. Thanks for your help. Sincerely, Raj The Original program code: # Guess my number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "Try to guess it in as few attempts as possible.\n" # set the initial values the_number = random.randrange(100)+1 guess = int(raw_input("Take a guess:")) tries = 1 #guessing loop while guess != the_number: if guess > the_number: print "Lower..." else: print "Higher..." guess = int(raw_input("Take a guess:")) tries += 1 print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" raw_input("\n\nPress the enter key to exit") My modifications that don't quite work right in the code: # Guess my number (Modified for Chapter 3 Challenge 3) # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money # The player has only Five guesses in which to guess correctly # otherwise he loses and is asked to try again # and the game ends import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "Try to guess it in as few attempts as possible.\n" # set the initial values the_number = random.randrange(100)+1 guess = int(raw_input("Take a guess:")) tries = 1 #guessing loop while guess != the_number: if guess > the_number: print "Lower..." else: print "Higher..." while tries < 5: if guess == the_number: print "You're right, the number is",the_number else: print "try again" guess = int(raw_input("Take a guess:")) tries += 1 raw_input("\n\nPress the enter key to exit") -------------- next part -------------- An HTML attachment was scrubbed... URL: From cosmicsand27 at yahoo.com Thu Jun 11 20:59:50 2009 From: cosmicsand27 at yahoo.com (Raj Medhekar) Date: Thu, 11 Jun 2009 11:59:50 -0700 (PDT) Subject: [Tutor] Need a Solution! Message-ID: <431220.22828.qm@web43413.mail.sp1.yahoo.com> This email contains another modified code that I tried working with but still doesn't do the job right, although performs closer to what i want. I have been having some difficulty modifying this program to where a player has limited number of guesses and if he fails to guess correctly within that number he is asked to "Try Again" The original program code and the code that I modified are given below. Thanks for your help. Sincerely, Raj The Original program code: # Guess my number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "Try to guess it in as few attempts as possible.\n" # set the initial values the_number = random.randrange(100)+1 guess = int(raw_input("Take a guess:")) tries = 1 #guessing loop while guess != the_number: if guess > the_number: print "Lower..." else: print "Higher..." guess = int(raw_input("Take a guess:")) tries += 1 print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" raw_input("\n\nPress the enter key to exit") My modifications that don't quite work right in the code: # Guess my number (Modified for Chapter 3 Challenge 3) # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money # The player has only Five guesses in which to guess correctly # otherwise he loses and is asked to try again # and the game ends import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "Try to guess it in as few attempts as possible.\n" # set the initial values the_number = random.randrange(100)+1 guess = int(raw_input("Take a guess:")) tries = 1 #guessing loop while guess != the_number: if guess > the_number: print "Lower..." else: print "Higher..." while tries < 5: if guess == the_number: print "You're right, the number is",the_number else: print "try again" guess = int(raw_input("Take a guess:")) tries += 1 raw_input("\n\nPress the enter key to exit") Modified Code #2 (Better than the last one but still not right) # Guess my number (Modified for Chapter 3 Challenge 3) # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money # The player has only Five guesses in which to guess correctly # otherwise he loses and is asked to try again # and the game ends import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "Try to guess it in as few attempts as possible.\n" # set the initial values the_number = random.randrange(100)+1 guess = int(raw_input("Take a guess:")) tries = 1 #guessing loop while guess != the_number and tries <5: if guess > the_number: print "Lower..." else: print "Higher..." guess = int(raw_input("Take a guess:")) tries += 1 if tries > 5: guess == the_number print "You're right" else: print "You lose" raw_input("\n\nPress the enter key to exit") -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Thu Jun 11 21:36:50 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 11 Jun 2009 14:36:50 -0500 Subject: [Tutor] Need a Solution! In-Reply-To: <431220.22828.qm@web43413.mail.sp1.yahoo.com> References: <431220.22828.qm@web43413.mail.sp1.yahoo.com> Message-ID: <333efb450906111236qc8aebb2lf55bf38ee97ad6c7@mail.gmail.com> On Thu, Jun 11, 2009 at 1:59 PM, Raj Medhekar wrote: > This email contains another modified code that I tried working with but > still doesn't do the job right, although performs closer to what i want. I > have been having some difficulty modifying this program to where a player > has limited number of guesses and if he fails to guess correctly within that > number he is asked to "Try Again" The original program code and the code > that I modified are given below. Thanks for your help. > > Sincerely, > Raj > > Modified Code #2 (Better than the last one but still not right) > # Guess my number (Modified for Chapter 3 Challenge 3) > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it and the computer lets > # the player know if the guess is too high, too low > # or right on the money > # The player has only Five guesses in which to guess correctly > # otherwise he loses and is asked to try again > # and the game ends > > import random > > print "\tWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 100." > print "Try to guess it in as few attempts as possible.\n" > > # set the initial values > the_number = random.randrange(100)+1 > guess = int(raw_input("Take a guess:")) > tries = 1 > > #guessing loop > while guess != the_number and tries <5: > if guess > the_number: > print "Lower..." > else: > print "Higher..." > > guess = int(raw_input("Take a guess:")) > tries += 1 > > if tries > 5: > guess == the_number > print "You're right" > else: > print "You lose" > > raw_input("\n\nPress the enter key to exit") > Why don't you write out your requirements in English - that usually helps! >From what I can tell it's really all fine until the last part... so what you might say is: after the user enters a guess, if the number of guesses is over 5, then check if the guess is correct. If the guess is correct, print "You win!" and finish the game. Otherwise, print "You lose!" and ask the user if they would like to try again. Now see if you can translate that into code. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From ayyaz84 at gmail.com Thu Jun 11 21:40:49 2009 From: ayyaz84 at gmail.com (ayyaz) Date: Thu, 11 Jun 2009 15:40:49 -0400 Subject: [Tutor] Need a Solution! In-Reply-To: <431220.22828.qm@web43413.mail.sp1.yahoo.com> References: <431220.22828.qm@web43413.mail.sp1.yahoo.com> Message-ID: Raj Medhekar wrote: > This email contains another modified code that I tried working with but > still doesn't do the job right, although performs closer to what i want. > I have been having some difficulty modifying this program to where a > player has limited number of guesses and if he fails to guess correctly > within that number he is asked to "Try Again" The original program code > and the code that I modified are given below. Thanks for your help. > > Sincerely, > Raj > > The Original program code: > > # Guess my number > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it and the computer lets > # the player know if the guess is too high, too low > # or right on the money > > import random > > print "\tWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 100." > print "Try to guess it in as few attempts as possible.\n" > > # set the initial values > the_number = random.randrange(100)+1 > guess = int(raw_input("Take a guess:")) > tries = 1 > > #guessing loop > while guess != the_number: > if guess > the_number: > print "Lower..." > else: > print "Higher..." > > guess = int(raw_input("Take a guess:")) > tries += 1 > > print "You guessed it! The number was", the_number > print "And it only took you", tries, "tries!\n" > > raw_input("\n\nPress the enter key to exit") > > My modifications that don't quite work right in the code: > > # Guess my number (Modified for Chapter 3 Challenge 3) > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it and the computer lets > # the player know if the guess is too high, too low > # or right on the money > # The player has only Five guesses in which to guess correctly > # otherwise he loses and is asked to try again > # and the game ends > > import random > > print "\tWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 100." > print "Try to guess it in as few attempts as possible.\n" > > # set the initial values > the_number = random.randrange(100)+1 > guess = int(raw_input("Take a guess:")) > tries = 1 > > #guessing loop > while guess != the_number: > if guess > the_number: > print "Lower..." > else: > print "Higher..." > &nbs p; > while tries < 5: > if guess == the_number: > print "You're right, the number is",the_number > else: > print "try again" > guess = int(raw_input("Take a guess:")) > tries += 1 > > > > raw_input("\n\nPress the enter key to exit") > > Modified Code #2 (Better than the last one but still not right) > # Guess my number (Modified for Chapter 3 Challenge 3) > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it ; and the computer lets > # the player know if the guess is too high, too low > # or right on the money > # The player has only Five guesses in which to guess correctly > # otherwise he loses and is asked to try again > # and the game ends > > import random > > print "\tWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 100." > print "Try to guess it in as few attempts as possible.\n" > > # set the initial values > the_number = random.randrange(100)+1 > guess = int(raw_input("Take a guess:")) > tries = 1 > > #guessing loop > while guess != the_number and tries <5: > if guess > the_number: > print "Lower..." > else: > print "Higher..." > > guess = int(raw_input("Take a guess:")) > tries += 1 > > if tri es > 5: > guess == the_number > print "You're right" > else: > print "You lose" > > raw_input("\n\nPress the enter key to exit") > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Hello Raj, Here is how I would modify the original program in the book. import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." max_tries = 10 ##### modification print "Try to guess it in no more than", max_tries, "attempts.\n" ##### modification # set the initial values the_number = random.randrange(100) + 1 guess = int(raw_input("Take a guess: ")) tries = 1 # guessing loop while (guess != the_number) and (tries < max_tries): ##### modification if (guess > the_number): print "Lower..." else: print "Higher..." guess = int(raw_input("Take a guess: ")) tries += 1 ##### modification if tries References: <71d330f00906101843u6ba415fdoea51d99f88aa5a4@mail.gmail.com> <1c2a2c590906110746m7defc991l7cd402a3589362b8@mail.gmail.com> <20090611175854.2fe5dd97@o> Message-ID: <71d330f00906111408r39d476d5ka2eb68841f092c41@mail.gmail.com> On Thu, Jun 11, 2009 at 11:58 AM, spir wrote: > Le Thu, 11 Jun 2009 10:46:26 -0400, > Kent Johnson s'exprima ainsi: > >> On Wed, Jun 10, 2009 at 9:43 PM, Robert Lummis >> wrote: >> > I want to write a function that I can use for debugging purposes that >> > prints the values of whatever list of object references it is given as >> > arguments, without knowing in advance how many object references it >> > will be called with or what they might be. For example, the call: >> > show(a,b,c) would output the values of the arguments like this: >> > >> > ? ?a = 3 >> > ? ?b = 'john' >> > ? ?c = 'Monday' >> > >> > while show (x) would output (for example): >> > >> > ? ?x = 3.14 >> >> Here is a pretty clean solution. It passes names rather than values, >> then looks the values up in the caller's stack frame. Written for >> Python 2.x but should work for 3.x if you change the prints. >> >> In [1]: import sys >> In [11]: def show(names): >> ? ?....: ? ? frame = sys._getframe(1) >> ? ?....: ? ? for name in names.split(): >> ? ?....: ? ? ? ? if name in frame.f_locals: >> ? ?....: ? ? ? ? ? ? print name, '=', frame.f_locals[name] >> ? ?....: ? ? ? ? else: >> ? ?....: ? ? ? ? ? ? print name, 'not found' >> > [...] >> >> Kent > > Waow, great! > > Denis > ------ > la vita e estrany > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Thanks for all the intelligent and thoughtful replies to my newB question. It looks like this tutor mailing list is going to be a big help! It's going to take me some time and trial and error to digest all the replies so I understand them fully but it will be instructive. I guess one thing I learned already, even though I didn't ask about it, is that using python3 isn't the best way to start out. Again, thank you all for taking the time to reply. -- Robert Lummis From alan.gauld at btinternet.com Thu Jun 11 23:12:20 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Jun 2009 22:12:20 +0100 Subject: [Tutor] Need a Solution! References: <431220.22828.qm@web43413.mail.sp1.yahoo.com> Message-ID: "Raj Medhekar" wrote > #guessing loop > while guess != the_number and tries <5: Well done you correctly spotted that you could use a boolean expression. > if guess > the_number: > print "Lower..." > else: > print "Higher..." > > guess = int(raw_input("Take a guess:")) > tries += 1 > > if tries > 5: > guess == the_number But you need to do the same thing here.... > print "You're right" > else: > print "You lose" > > raw_input("\n\nPress the enter key to exit") HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From johan at accesstel.com.au Thu Jun 11 22:40:56 2009 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Fri, 12 Jun 2009 06:40:56 +1000 Subject: [Tutor] XML: changing value of elements In-Reply-To: Message-ID: <20090611204059.DECE12022.nschwotgx01p.mx.bigpond.com@JohanPC> Thanks for the reply. Have been waiting a few days. When I started out, I still had Python 2.4 and etree is not available in that version. This part : must have snicked in wihen I copied the XML code. Sorry, but that is the location of my original XML file. I'll try your stuff and see how it goes. Thanks Johan -----Original Message----- From: tutor-bounces+johan=accesstel.com.au at python.org [mailto:tutor-bounces+johan=accesstel.com.au at python.org] On Behalf Of Stefan Behnel Sent: Thursday, 11 June 2009 16:37 PM To: tutor at python.org Subject: Re: [Tutor] XML: changing value of elements Hi, it's funny how many times I see Python users go: "I have an XML problem, so I'll use minidom." Because then they have two problems. Johan Geldenhuys wrote: > I have a rather complex XML file and I need to change some values inside > this file. > > So far I have been using minidom, but I can't find the thing I am looking > for. > > My code so far: > """ > from xml.dom import minidom > > xmlFile = 'signal1.xml' > xmlDocument = minidom.parse(xmlFile) > > SignalsNode = xmlDocument.firstChild > signalNode = SignalsNode.childNodes[1] > > signalNode.removeAttribute("name") > signalNode.setAttribute("name", "Test_Name") > signalNode.getAttribute("name") > > descElem = signalNode.childNodes[1] That is a lot of code just to say import xml.etree.ElementTree as ET doc = ET.parse('signal1.xml') signal_node = doc.getroot()[0] signal_node.set('name', 'Test_Name') > I know how to manipulate the value of the attributes, but I can't seem to > change the values of eg: "Description" description = signal_node[0] description.text = "New value" > Snippet from my XML file: > > """ > > > > - What's that "" bit? > - name="Model_X" type="Flyer"> > > Some description > > Model_X > > > > - > > normal > > Model X 1 > > > > - type="close"> > > minor > > Model X 2 > > > > > > > """ Stefan _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From acfleck at aol.com Fri Jun 12 02:18:48 2009 From: acfleck at aol.com (acfleck) Date: Thu, 11 Jun 2009 19:18:48 -0500 Subject: [Tutor] 3.0 on Mac Message-ID: <52F45400.F904.4E76.9451.9EA76BCECF73@aol.com> I'm a Python nubie and having trouble with 3.0.1 on Mac (10.4.11). I did a default install of MacPython 3.0.1. The IDLE.app works fine, but from a Terminal window, the 'python' command still gets me V2.5.3 (the original Apple installed version). A 'python3' command is not recognized. I'd like to know what I need to change to access V3.0.1 from a Terminal window. Thanks, ACF -------------- next part -------------- An HTML attachment was scrubbed... URL: From mattie289404 at gmail.com Fri Jun 12 03:00:00 2009 From: mattie289404 at gmail.com (Randy Trahan) Date: Thu, 11 Jun 2009 21:00:00 -0400 Subject: [Tutor] Help..Concatenaton Error Message-ID: <82bf08860906111759k7f95f91s8a2372a516655892@mail.gmail.com> Attached is an error I cannot get to work, I was doing a print concatenation but it won't let me get past "+ "ibly impressive. " \ (then to next line) Also Programming Lanquage Question: I have studied and an fairly proficient at XHTML and CSS, I tried Javascript but just didn't like it for some reason..so I am trying Python which so far fits my personality, needs, whatever that part is that makes you choose a lanquage. Will I be able to use Python in web pages as I would of used Javascript? From what I have read there are Python to Javascript converters?... Thanks in advance.. -- Randy Trahan Owner, BullDog Computer Services, LLC 478-396-2516 -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: screenbug1.gif Type: image/gif Size: 53527 bytes Desc: not available URL: From wescpy at gmail.com Fri Jun 12 03:40:01 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 11 Jun 2009 18:40:01 -0700 Subject: [Tutor] 3.0 on Mac In-Reply-To: <78b3a9580906111839p392e0d1qd628e6273cae8745@mail.gmail.com> References: <52F45400.F904.4E76.9451.9EA76BCECF73@aol.com> <78b3a9580906111839p392e0d1qd628e6273cae8745@mail.gmail.com> Message-ID: <78b3a9580906111840u21370ef9t53f030171ab8d062@mail.gmail.com> > A 'python3' command is not recognized. I'd like to > know what I need to change to access V3.0.1 from a Terminal window. try python3.0 if that doesn't work, then you may have to add the directory where it's installed to your PATH. hope this helps, and welcome to Python! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 ? ?http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ayyaz84 at gmail.com Fri Jun 12 03:40:53 2009 From: ayyaz84 at gmail.com (ayyaz) Date: Thu, 11 Jun 2009 21:40:53 -0400 Subject: [Tutor] Help..Concatenaton Error In-Reply-To: <82bf08860906111759k7f95f91s8a2372a516655892@mail.gmail.com> References: <82bf08860906111759k7f95f91s8a2372a516655892@mail.gmail.com> Message-ID: Randy Trahan wrote: > Attached is an error I cannot get to work, I was doing a print > concatenation but it won't let me get past "+ "ibly impressive. " \ > (then to next line) > > Also Programming Lanquage Question: > I have studied and an fairly proficient at XHTML and CSS, I tried > Javascript but just didn't like it for some reason..so I am trying > Python which so far fits my personality, needs, whatever that part is > that makes you choose a lanquage. Will I be able to use Python in web > pages as I would of used Javascript? From what I have read there are > Python to Javascript converters?... > > Thanks in advance.. > > -- > Randy Trahan > Owner, BullDog Computer Services, LLC > 478-396-2516 > > ------------------------------------------------------------------------ > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Hello Randy, You have two plus signs after "+ "ibly impressive. " \. That might be the problem. Post the code if you can. Thanks, --ayyaz From john at fouhy.net Fri Jun 12 03:46:38 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 12 Jun 2009 13:46:38 +1200 Subject: [Tutor] 3.0 on Mac In-Reply-To: <52F45400.F904.4E76.9451.9EA76BCECF73@aol.com> References: <52F45400.F904.4E76.9451.9EA76BCECF73@aol.com> Message-ID: <5e58f2e40906111846r217cd8c8l349106715683dca@mail.gmail.com> 2009/6/12 acfleck : > I'm a Python nubie and having trouble with 3.0.1 on Mac (10.4.11). I did a > default install of MacPython 3.0.1. The IDLE.app works fine, but from a > Terminal window, the 'python' command still gets me V2.5.3 (the original > Apple installed version). A 'python3' command is not recognized. I'd like to > know what I need to change to access V3.0.1 from a Terminal window. Type 'which python' into a terminal. That will show you the path to your executable. My mac is at home, so this is all from memory, but basically there are two places for python on macs. One place is the Apple-supplied install, which goes in /System/Library (I think). The other is pythons you install yourself. The paths will be something like: /Library/Frameworks/Python.framework/Versions/2.5/python /Library/Frameworks/Python.framework/Versions/3.0/python Finally, there will be a symbolic link: /Library/Frameworks/Python.framework/Versions/Current -> /Library/Frameworks/Python.framework/Versions/2.5 'which python' should show you .../Current/python. So, to change to version 3.0, you need to remove the symbolic link and put in one to 3.0: rm /Library/Frameworks/Python.framework/Versions/Current ln -s /Library/Frameworks/Python.framework/Versions/3.0 /Library/Frameworks/Python.framework/Versions/Current/ HTH! (and if your paths don't match correctly, do ask more questions if you're uncertain) (oh, there is a third source for python: MacPorts. Are you using macports?) -- John. From dsarmientos at gmail.com Fri Jun 12 03:49:43 2009 From: dsarmientos at gmail.com (Daniel Sarmiento) Date: Thu, 11 Jun 2009 20:49:43 -0500 Subject: [Tutor] PyQt Signal Message-ID: Hello I am starting to use PyQt, and I'm trying to send a signal across threads, but I get the following error: Traceback (most recent call last): File "/home/daniel/NetBeansProjects/aeropuerto/main.py", line 34, in form = AeropuertoDlg() File "/home/daniel/NetBeansProjects/aeropuerto/main.py", line 18, in __init__ self.connect(self.aeropuerto, SIGNAL("fin()"), self.fin) RuntimeError: underlying C/C++ object has been deleted The code is at pastebin: http://pastebin.com/m2aa3fbf9 // main.py Main QDialog Class http://pastebin.com/m7aea48a5 // aeropuerto.py (signal is emited here) -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Fri Jun 12 04:12:59 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Thu, 11 Jun 2009 21:12:59 -0500 Subject: [Tutor] Help..Concatenaton Error In-Reply-To: References: <82bf08860906111759k7f95f91s8a2372a516655892@mail.gmail.com> Message-ID: <4A31B9AB.1050508@mwalsh.org> ayyaz wrote: > Randy Trahan wrote: >> Attached is an error I cannot get to work, I was doing a print >> concatenation but it won't let me get past "+ "ibly impressive. " \ >> (then to next line) >> >> Also Programming Lanquage Question: >> I have studied and an fairly proficient at XHTML and CSS, I tried >> Javascript but just didn't like it for some reason..so I am trying >> Python which so far fits my personality, needs, whatever that part is >> that makes you choose a lanquage. Will I be able to use Python in web >> pages as I would of used Javascript? From what I have read there are >> Python to Javascript converters?... The only python to javascript project I am aware of is pyjamas (http://pyjs.org/), which is a python port of the Google Web Toolkit. Not sure if that's exactly what you're looking for. There are several javascript libraries available now-a-days that help make programming javascript more like programming in python. Mochikit comes to mind (http://www.mochikit.com/). But, I'm not a web developer. >> >> Thanks in advance.. >> -- >> Randy Trahan >> Owner, BullDog Computer Services, LLC >> 478-396-2516 > > Hello Randy, > > You have two plus signs after "+ "ibly impressive. " \. > > That might be the problem. And, it appears you've missed the quote before "\nThis string ", as well. Perhaps also important to note, the line continuation character '\' may not be followed by any character on the same line, including whitespace, so ... print "\nThis string " + \ "may not" ... where indicates the presence of ... er, well ... a whitespace character, would be invalid (a SyntaxError). PEP8 (http://www.python.org/dev/peps/pep-0008/) outlines some alternatives to the line continuation character. For example, >>> s = ("This is a " + ... "long line" + ... ".") >>> s 'This is a long line.' Or, you can leave out the +, as string concatenation is implicit in the following ... >>> s = ("This is a " ... "long line" ... ".") >>> s 'This is a long line.' ... but, beware -- it's easy to overlook when constructing a list (or tuple). >>> lst = ['This is a', ... 'long' # <- missing comma ... 'line', ... '.'] >>> lst ['This is a', 'longline', '.'] HTH, Marty From davea at ieee.org Fri Jun 12 05:46:58 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 11 Jun 2009 23:46:58 -0400 Subject: [Tutor] Help..Concatenaton Error In-Reply-To: References: Message-ID: <4A31CFB2.6050207@ieee.org> Randy Trahan wrote: > Attached is an error I cannot get to work, I was doing a print concatenation > but it won't let me get past "+ "ibly impressive. " \ > (then to next line) > > If you had included the sample lines in your message, instead of an attachment, then it'd be part of the mailing list, and I would've been happier to help. As it is, you attached a blurry image, rather than just pasting the actual text. Remember, this is a text mailing list. BTW, what shell is that? The error message seems to be singularly unhelpful. Where's your leading quote, the one before the \n ? And where's the trailing quote at the end of the last line? And why are there two + signs in a row on the second line? There may be other typos, but I can't tell, since it's not text that I can paste into my own shell. > Also Programming Lanquage Question: > I have studied and an fairly proficient at XHTML and CSS, I tried Javascript > but just didn't like it for some reason..so I am trying Python which so far > fits my personality, needs, whatever that part is that makes you choose a > lanquage. Will I be able to use Python in web pages as I would of used > Javascript? From what I have read there are Python to Javascript > converters?... > Thanks in advance.. > > > -- Randy Trahan Owner, BullDog Computer Services, LLC 478-396-2516 > -------------- next part -------------- An HTML attachment was scrubbed... > I don't know any way to run Python in the browser, without convincing the user to download something. That's what Javascript is (sort of) useful for. However, python makes a great language for the backend, in other words to run on the server, generating the pages. There's lots of overlap, but each can do things the other cannot. For the most obvious, javascript in the browser can run user interaction much more readily, and responsively. And python (or many other choices) can interact with the server's file system (eg. database) and other resources much more readily than javascript could. I use python for desktop programming, and for statically generating web pages. I haven't done any serious server-side programming yet, but I will. From davea at ieee.org Fri Jun 12 05:54:08 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 11 Jun 2009 23:54:08 -0400 Subject: [Tutor] 3.0 on Mac In-Reply-To: References: Message-ID: <4A31D160.3000409@ieee.org> acfleck wrote: > I'm a Python nubie and having trouble with 3.0.1 on Mac (10.4.11). I > did a default install of MacPython 3.0.1. The IDLE.app works fine, but > from a Terminal window, the 'python' command still gets me V2.5.3 (the > original Apple installed version). A 'python3' command is not > recognized. I'd like to know what I need to change to access V3.0.1 > from a Terminal window. > Use the 'which' command to see what versions of python are on your PATH. Then, since you have two different versions of Python you want available, create one or more scripts (on your path), to explicitly run the other installed versions. Probably, those scripts can be one line each, though you also might conceivably want to set an environment variable or two (such as pythonpath) As far as I know, the install will not create a script called python3, or anything else like it. That's up to you. And it's generally not good form to hide the system-installed version, since many utilities and scripts might depend on that particular version. From david at abbottdavid.com Fri Jun 12 06:02:05 2009 From: david at abbottdavid.com (David) Date: Fri, 12 Jun 2009 00:02:05 -0400 Subject: [Tutor] Need a solution. In-Reply-To: <801768.57354.qm@web43401.mail.sp1.yahoo.com> References: <801768.57354.qm@web43401.mail.sp1.yahoo.com> Message-ID: <4A31D33D.30400@abbottdavid.com> Raj Medhekar wrote: > I have been having some difficulty modifying this program to where a > player has limited number of guesses and if he fails to guess correctly > within that number he is asked to "Try Again" The original program code > and the code that I modified are given below. Thanks for your help. > > Sincerely, > Raj > > The Original program code: > > # Guess my number > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it and the computer lets > # the player know if the guess is too high, too low > # or right on the money > > import random > > print "\tWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 100." > print "Try to guess it in as few attempts as possible.\n" > > # set the initial values > the_number = random.randrange(100)+1 > guess = int(raw_input("Take a guess:")) > tries = 1 > > #guessing loop > while guess != the_number: > if guess > the_number: > print "Lower..." > else: > print "Higher..." > > guess = int(raw_input("Take a guess:")) > tries += 1 > > print "You guessed it! The number was", the_number > print "And it only took you", tries, "tries!\n" > > raw_input("\n\nPress the enter key to exit") > Hi Raj, I am also learning Python and never did any real programming before, I have been attempting to learn about classes, this is my version, comments, suggestions always welcome. -david #!/usr/bin/python from random import randrange from sys import exit class GuessNumber: def __init__(self): self.number = randrange(100)+1 self.count_tries = 1 self.total_tries = 5 def update_count(self): self.count_tries += 1 def guess_number(): gn = GuessNumber() number = gn.number tries = gn.total_tries attempts = gn.count_tries update_count = gn.update_count() guess = 'Take a guess: ' question = 'Try again? ' decision = 'Do you want to try again? y/n ' discription = \ """\n\tWelcome to 'Guess My Number'! I'm thinking of a number between 1 and 100. Try to guess it in 5 attempts!\n """ print discription answer = int(raw_input(guess)) while answer != number and attempts < tries: if answer > number: print 'Lower ...' else: print 'Higher ...' update_count print 'You have %i attempts left!' % (tries - attempts) answer = int(raw_input(guess)) attempts += 1 if answer == number: print 'You guessed it the number was', number print 'And it only took you %i attempts' % attempts choice = raw_input(decision) if choice == 'y': choice = choice.lower() guess_number() else: exit() else: print 'You did not pick the number!' print 'The number was', number choice = raw_input(decision) if choice == 'y': choice = choice.lower() guess_number() else: exit() if __name__ == "__main__": guess_number() -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From david at abbottdavid.com Fri Jun 12 07:01:14 2009 From: david at abbottdavid.com (David) Date: Fri, 12 Jun 2009 01:01:14 -0400 Subject: [Tutor] Need a solution. In-Reply-To: <82bf08860906112143h2b2491c5qd37f9a4b272b6bac@mail.gmail.com> References: <801768.57354.qm@web43401.mail.sp1.yahoo.com> <4A31D33D.30400@abbottdavid.com> <82bf08860906112114q76bd1b78v2cf9d32e3be17f23@mail.gmail.com> <82bf08860906112143h2b2491c5qd37f9a4b272b6bac@mail.gmail.com> Message-ID: <4A31E11A.7080504@abbottdavid.com> Randy Trahan wrote: > Well that didin't work I tried the program and it went into an infinite > loop...is that the problem you were asking about? > > On Fri, Jun 12, 2009 at 12:14 AM, Randy Trahan > wrote: > > Hi Raj, > > The only thing I see is that under #guessing Loop you do not have () > around the code; ie. > while (guess != the_number): > if (guess > the_number): > print "Lower.." > > > > On Fri, Jun 12, 2009 at 12:02 AM, David > wrote: > > Raj Medhekar wrote: > > I have been having some difficulty modifying this program to > where a player has limited number of guesses and if he fails > to guess correctly within that number he is asked to "Try > Again" The original program code and the code that I > modified are given below. Thanks for your help. > > Sincerely, > Raj > > The Original program code: > > # Guess my number > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it and the computer lets > # the player know if the guess is too high, too low > # or right on the money > > import random > > print "\tWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 100." > print "Try to guess it in as few attempts as possible.\n" > > # set the initial values > the_number = random.randrange(100)+1 > guess = int(raw_input("Take a guess:")) > tries = 1 > > #guessing loop > while guess != the_number: > if guess > the_number: > print "Lower..." > else: > print "Higher..." > > guess = int(raw_input("Take a guess:")) > tries += 1 > > print "You guessed it! The number was", the_number > print "And it only took you", tries, "tries!\n" > > raw_input("\n\nPress the enter key to exit") > > Hi Raj, > I am also learning Python and never did any real programming > before, I have been attempting to learn about classes, this is > my version, comments, suggestions always welcome. > -david > > #!/usr/bin/python > from random import randrange > from sys import exit > > class GuessNumber: > def __init__(self): > self.number = randrange(100)+1 > self.count_tries = 1 > self.total_tries = 5 > def update_count(self): > self.count_tries += 1 > > def guess_number(): > gn = GuessNumber() > number = gn.number > tries = gn.total_tries > attempts = gn.count_tries > update_count = gn.update_count() > guess = 'Take a guess: ' > question = 'Try again? ' > decision = 'Do you want to try again? y/n ' > discription = \ > """\n\tWelcome to 'Guess My Number'! > I'm thinking of a number between 1 and 100. > Try to guess it in 5 attempts!\n > """ > print discription > answer = int(raw_input(guess)) > while answer != number and attempts < tries: > if answer > number: > print 'Lower ...' > else: > print 'Higher ...' > update_count > print 'You have %i attempts left!' % (tries - attempts) > answer = int(raw_input(guess)) > attempts += 1 > if answer == number: > print 'You guessed it the number was', number > print 'And it only took you %i attempts' % attempts > choice = raw_input(decision) > if choice == 'y': > choice = choice.lower() > guess_number() > else: > exit() > else: > print 'You did not pick the number!' > print 'The number was', number > choice = raw_input(decision) > if choice == 'y': > choice = choice.lower() > guess_number() > else: > exit() > > if __name__ == "__main__": > guess_number() > > > > > > -- > Powered by Gentoo GNU/Linux > http://linuxcrazy.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Randy Trahan > Owner, BullDog Computer Services, LLC > 478-396-2516 > > > > > -- > Randy Trahan > Owner, BullDog Computer Services, LLC > 478-396-2516 Hi Randy, Looks like you are top posting, on most mailing lists the mail is read from top to bottom with the bottom being the most recent. So my attempt is on the bottom, the last one. Also on this list you will need to send your reply to reply all or reply list to sent the mail to the list. -david -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From andreengels at gmail.com Fri Jun 12 07:56:26 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 12 Jun 2009 07:56:26 +0200 Subject: [Tutor] Help..Concatenaton Error In-Reply-To: <82bf08860906111759k7f95f91s8a2372a516655892@mail.gmail.com> References: <82bf08860906111759k7f95f91s8a2372a516655892@mail.gmail.com> Message-ID: <6faf39c90906112256m5d2665dfu88816d4c710e772d@mail.gmail.com> On Fri, Jun 12, 2009 at 3:00 AM, Randy Trahan wrote: > Attached is an error I cannot get to work, I was doing a print concatenation > but it won't let me get past "+ "ibly impressive. " \ > (then to next line) It's wrong at a few places, but the first is at the very beginning. You need a quote mark before the first \n. The colour coding in your interface will help you here: All the literal text that you want to print, should be in green. The first place where it is black or another colour denotes a place where things have gone wrong. > Also?Programming Lanquage?Question: > I have studied and?an fairly?proficient at XHTML and CSS, I tried Javascript > but just didn't like?it?for some reason..so I am trying Python which so far > fits my personality, needs, whatever that part is that makes you choose a > lanquage.?Will I be able to use Python in web pages as I would of used > Javascript? ?From what I have read there are Python to Javascript > converters?... No, Javascript is (as far as I know) the only language that can be used _inside_ web pages. When you use Python (or some other language) in web design, what you do is create code that _generates_ web pages. The big difference is that the Python will be executed on the server's machine, the Javascript on the client's machine. -- Andr? Engels, andreengels at gmail.com From etrade.griffiths at dsl.pipex.com Fri Jun 12 09:49:05 2009 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Fri, 12 Jun 2009 08:49:05 +0100 Subject: [Tutor] Replacing keyboard input to EXE file In-Reply-To: References: Message-ID: <7jhs9m$6k17si@smtp.pipex.tiscali.co.uk> > >"Tino Dai" wrote > > > > I know that this is a python group but you might want to try the open > > source utility called Expect. It does what you need it to do without > > having > > having to go through this trial and error process with subprocess. > > http://expect.nist.gov/ > >Or use the Python wrapper around expect - pyexpect??? > >Alan G Installed pexpect and rewrote the code to look like this: import pexpect x = pexpect.spawn("poly.exe") for item in ["polyin.dat", "polyout.dat", "polyout.plt"]: x.sendline('%s\n' % item) Now I get these errors: Traceback (most recent call last): File "C:\Projects\Active\Alun\US_DOE_EOR\test_poly.py", line 1, in -toplevel- import pexpect File "C:\Python24\Lib\site-packages\pexpect.py", line 82, in -toplevel- raise ImportError (str(e) + """ ImportError: No module named resource A critical module was not found. Probably this operating system does not support it. Pexpect is intended for UNIX-like operating systems. Hm .....does this mean we are snookered on Win XP? Best regards Alun Griffiths From alan.gauld at btinternet.com Fri Jun 12 10:29:52 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Jun 2009 09:29:52 +0100 Subject: [Tutor] Help..Concatenaton Error References: <82bf08860906111759k7f95f91s8a2372a516655892@mail.gmail.com> Message-ID: "Randy Trahan" wrote > Attached is an error I cannot get to work, I was doing a print > concatenation > but it won't let me get past "+ "ibly impressive. " \ > (then to next line) You don;t appear to have a quote in front of the string - immediately after the print statement? BTW While that is OK as a test of string concatenation it is a very inefficient way of joining strings and is not considred good style. You can use the join() method to simplify it ''.join(("one","two","three")) or for string literals like this just miss out the plus signs print "one" "two" "three".... Both of these are much more efficient since they don't create multiple intermediate strings > Also Programming Lanquage Question: > lanquage. Will I be able to use Python in web pages as I would of used > Javascript? From what I have read there are Python to Javascript > converters?... Converters will get you so far but in general no, Python will not work in a web browser. This is a limitation of the browsers, they don't have a Python interpreter built in. Iy is possible to get Internet Explorer to do it using ActiveScripting but then you are confined to MS Windows users. Javascript and Flash are the only reliable client end scripting tools for web pages. From alan.gauld at btinternet.com Fri Jun 12 10:34:26 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Jun 2009 09:34:26 +0100 Subject: [Tutor] Replacing keyboard input to EXE file References: <7jhs9m$6k17si@smtp.pipex.tiscali.co.uk> Message-ID: "eShopping" wrote >>Or use the Python wrapper around expect - pyexpect??? >> >>Alan G > > Installed pexpect and rewrote the code to look like this: > > Now I get these errors: > > Traceback (most recent call last): > File "C:\Projects\Active\Alun\US_DOE_EOR\test_poly.py", line 1, > in -toplevel- > import pexpect > File "C:\Python24\Lib\site-packages\pexpect.py", line 82, in -toplevel- > raise ImportError (str(e) + """ > ImportError: No module named resource > > A critical module was not found. Probably this operating system does not > support it. Pexpect is intended for UNIX-like operating systems. > > Hm .....does this mean we are snookered on Win XP? Yes, Kent posted a mail that I assumed had gone to the list but apparently not. pexpect only works on *nix. A shame and very odd since expect works on Windows... You might find it works under cygwin if you have that installed. Sorry for the red herring, Alan G. From alan.gauld at btinternet.com Fri Jun 12 10:50:12 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Jun 2009 09:50:12 +0100 Subject: [Tutor] Need a solution. References: <801768.57354.qm@web43401.mail.sp1.yahoo.com> <4A31D33D.30400@abbottdavid.com> Message-ID: "David" wrote > have been attempting to learn about classes, this is my version, > comments, suggestions always welcome. > -david > > #!/usr/bin/python > from random import randrange > from sys import exit > > class GuessNumber: > def __init__(self): > self.number = randrange(100)+1 > self.count_tries = 1 > self.total_tries = 5 > def update_count(self): > self.count_tries += 1 This is a bad choice of class. It is a verb which is indicative that its not an object. Objects are nearly always nouns. You could use GuessableNumber. Then it would have a number attribute which is the number to guess. It could have a generate() ,method which produces a new random number, possibly within a given range? You could also add a compare method so you can compare your guesses. The compare method could count the number of calls and raise an exception if you compare more than N times. (The value of N would be in the constructor. Something like: class GuessError(Exception): pass class GuessedNumber: def __init__(self,tries=None,limits=None):... def generate(self, limits=None):... def __cmp__(self, aNumber): if self.count >= self.tries: raise GuessError ... So I'd expect the client code to look like target = GuessableNumber(tries=5, limits=(1,99)) # init calls generate internally guess = int(raw_input('Guess-> ')) while True: try: if guess == target: print "Well done!" break else: guess = int(raw_input('Guess again-> ')) except GuessError: print "Sorry, too many guesses, the number was", target.number You could add another loop to ask if the player wanted to go again, in which case you call target.generate() directly to reset the target. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From csaritabhandari737 at hotmail.com Fri Jun 12 09:48:28 2009 From: csaritabhandari737 at hotmail.com (csarita bhandari) Date: Fri, 12 Jun 2009 13:18:28 +0530 Subject: [Tutor] quarry, Message-ID: Dear sir/madam, I have download python version 3.0.1 windows installer, but problem occur during installing it. And the problem is " Your Administration don't permit to install this program". What should i do? I am new in python. thank you! _________________________________________________________________ Windows Live?: Keep your life in sync. Check it out! http://windowslive.com/explore?ocid=TXT_TAGLM_WL_t1_allup_explore_012009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jun 12 13:14:22 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Jun 2009 07:14:22 -0400 Subject: [Tutor] Help..Concatenaton Error In-Reply-To: <82bf08860906111759k7f95f91s8a2372a516655892@mail.gmail.com> References: <82bf08860906111759k7f95f91s8a2372a516655892@mail.gmail.com> Message-ID: <1c2a2c590906120414w5da566ecg2a89a4d6c2905cd9@mail.gmail.com> On Thu, Jun 11, 2009 at 9:00 PM, Randy Trahan wrote: > Also?Programming Lanquage?Question: > I have studied and?an fairly?proficient at XHTML and CSS, I tried Javascript > but just didn't like?it?for some reason..so I am trying Python which so far > fits my personality, needs, whatever that part is that makes you choose a > lanquage.?Will I be able to use Python in web pages as I would of used > Javascript? ?From what I have read there are Python to Javascript > converters?... Microsoft Silverlight allows you to run Python code and other .NET languages (IronPython, C#, IronRuby) in a browser. Kent From denis.spir at free.fr Fri Jun 12 13:54:47 2009 From: denis.spir at free.fr (spir) Date: Fri, 12 Jun 2009 13:54:47 +0200 Subject: [Tutor] use of __new__ Message-ID: <20090612135447.16ed1447@o> Hello, I have (again) some issue using __new__. What I need is basically to catch an object creation and yield an object of an alternate type, when a condition is met. Basically, the outline looks like: class Normal(object): def __new__(cls, arg): if cond(arg): # # expression is simply: Special(arg) # must be __init__ialised ! # Conceptually, nothing to change: # # must be __init__ialised ! But I got issues in both cases: * cannot find how to get Special objects initialised * cannot find how to return Normal object (also Normal's supertype has no explicite __new__, but it has an __init__) Denis ------ la vita e estrany From srilyk at gmail.com Fri Jun 12 14:05:16 2009 From: srilyk at gmail.com (Wayne) Date: Fri, 12 Jun 2009 07:05:16 -0500 Subject: [Tutor] quarry, In-Reply-To: References: Message-ID: <333efb450906120505h25b65592g625bf90dc649833e@mail.gmail.com> On Fri, Jun 12, 2009 at 2:48 AM, csarita bhandari < csaritabhandari737 at hotmail.com> wrote: > Dear sir/madam, > > I have download python version 3.0.1 windows installer, but problem occur > during installing it. And the problem is " Your Administration don't permit > to install this program". What should i do? I am new in python. > > Do you have administrator privileges on your Windows box? If not, you need to get your system administrator to install python for you. Nothing to do with Python, everything to do with Windows. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Fri Jun 12 14:20:24 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 12 Jun 2009 14:20:24 +0200 Subject: [Tutor] use of __new__ In-Reply-To: <20090612135447.16ed1447@o> References: <20090612135447.16ed1447@o> Message-ID: <4A324808.2060000@tue.nl> spir wrote: > Hello, > > I have (again) some issue using __new__. > What I need is basically to catch an object creation and yield an object of an alternate type, when a condition is met. > > Basically, the outline looks like: > > class Normal(object): > def __new__(cls, arg): > if cond(arg): > # > # expression is simply: Special(arg) > # must be __init__ialised ! > > # Conceptually, nothing to change: > # > # must be __init__ialised ! > > But I got issues in both cases: > * cannot find how to get Special objects initialised > * cannot find how to return Normal object > (also Normal's supertype has no explicite __new__, but it has an __init__) Maybe it's just me, but why don't you use a factory function? def make(args): if cond(args): return Special(args) else: return Normal(args) Albert From srilyk at gmail.com Fri Jun 12 14:27:23 2009 From: srilyk at gmail.com (Wayne) Date: Fri, 12 Jun 2009 07:27:23 -0500 Subject: [Tutor] Replacing keyboard input to EXE file In-Reply-To: <7jhs9m$6k17si@smtp.pipex.tiscali.co.uk> References: <7jhs9m$6k17si@smtp.pipex.tiscali.co.uk> Message-ID: <333efb450906120527y3602cb62p439eadd9c24c2bc3@mail.gmail.com> On Fri, Jun 12, 2009 at 2:49 AM, eShopping wrote: > > Hm .....does this mean we are snookered on Win XP? Well, strictly using python anyway. I'm not sure precisely how the ctypes module works, but it's a fairly simple amount of code in assembly to push characters into the keyboard buffer. I presume there may be some builtins in C that would allow you to do the same thing. Of course the real issue is making sure that the FORTRAN program actually is the program reading the buffer, which is probably the problem with your python program. I don't know if it makes a difference, but I know in assembly you can use an interrupt to read a character from stdin *or* you can use an interrupt to read a character from the keyboard buffer. If these lower level calls are different enough (i.e. a MS interrupt to read from stdin does some funky system-wide Windows stuff, and the keyboard call just reads direct from the buffer - so it's lower level than stdin) then FORTRAN might simply be reading straight from the buffer. However, I don't quite have that much knowledge, although I could presumably write up a few programs to test my theory, and if I have time today I'll have to try that. -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Jun 12 14:37:17 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Jun 2009 22:37:17 +1000 Subject: [Tutor] use of __new__ In-Reply-To: <20090612135447.16ed1447@o> References: <20090612135447.16ed1447@o> Message-ID: spir wrote: > Hello, > > I have (again) some issue using __new__. > What I need is basically to catch an object creation and yield an object of an alternate type, when a condition is met. > > Basically, the outline looks like: > > class Normal(object): > def __new__(cls, arg): > if cond(arg): > # > # expression is simply: Special(arg) > # must be __init__ialised ! > > # Conceptually, nothing to change: > # > # must be __init__ialised ! > > But I got issues in both cases: > * cannot find how to get Special objects initialised > * cannot find how to return Normal object roughly like this: >>> class Special(object): ... def __init__(self, arg): ... self.arg = arg ... >>> class Normal(object): ... def __new__(cls, arg): ... if arg: ... return Special(arg) ... else: ... ret = super(Normal, cls).__new__(cls) ... ret.__init__(arg) ... return ret ... def __init__(self, arg): ... self.arg = arg ... >>> a = Normal(True) >>> b = Normal(False) >>> a.arg True >>> b.arg False >>> generally though, avoid using __new__ > (also Normal's supertype has no explicite __new__, but it has an __init__) Haven't tested yet, but that should be no problem as python will use the supertype's supertype's __new__ and at the end of the method resolution order is object.__new__() From kent37 at tds.net Fri Jun 12 15:05:35 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Jun 2009 09:05:35 -0400 Subject: [Tutor] use of __new__ In-Reply-To: References: <20090612135447.16ed1447@o> Message-ID: <1c2a2c590906120605u78ebeabbv7949d99de21f8247@mail.gmail.com> On Fri, Jun 12, 2009 at 8:37 AM, Lie Ryan wrote: >>>> class Normal(object): > ... ? ? def __new__(cls, arg): > ... ? ? ? ? if arg: > ... ? ? ? ? ? ? return Special(arg) > ... ? ? ? ? else: > ... ? ? ? ? ? ? ret = super(Normal, cls).__new__(cls) > ... ? ? ? ? ? ? ret.__init__(arg) > ... ? ? ? ? ? ? return ret I think the else case should be ret = super(Normal, cls).__new__(cls, arg) return ret i.e. pass the same args to super.__new__() and don't explicitly call __init__(). Kent From denis.spir at free.fr Fri Jun 12 15:29:54 2009 From: denis.spir at free.fr (spir) Date: Fri, 12 Jun 2009 15:29:54 +0200 Subject: [Tutor] Fw: use of __new__ Message-ID: <20090612152954.701835d7@o> Le Fri, 12 Jun 2009 14:20:24 +0200, "A.T.Hofkamp" s'exprima ainsi: > spir wrote: > > Hello, > > > > I have (again) some issue using __new__. > > What I need is basically to catch an object creation and yield an object > > of an alternate type, when a condition is met. > > > > Basically, the outline looks like: > > > > class Normal(object): > > def __new__(cls, arg): > > if cond(arg): > > # > > # expression is simply: Special(arg) > > # must be __init__ialised ! > > > > # Conceptually, nothing to change: > > # > > # must be __init__ialised ! > > > > But I got issues in both cases: > > * cannot find how to get Special objects initialised > > * cannot find how to return Normal object > > (also Normal's supertype has no explicite __new__, but it has an __init__) > > Maybe it's just me, but why don't you use a factory function? > > def make(args): > if cond(args): > return Special(args) > else: > return Normal(args) ;-) Thank you, Albert -- but I (think I) can't. It's generated code (from a parser generator) that uses a library. At write time, arguments are not known -- not even existent. I could check their "type" (know by the node), but some could be names, instead of expressions. If this is too unclear, and you want to know more, read below in PS. Denis ------ la vita e estrany PS The parser generator simply write python code that basically initiates pattern object from a of various types from a library. The present issue happens for repetitions. The normal case works as follwows (I skip several arguments): grammar: foo : ('0'/"xyz")+ parser: foo = Repetition([Choice(Char('0',...), Word("xyz",...)],...) But in case the repeted pattern is a "Klass" (of characters, like in regexes), I want to yield instead a String, which is a specialised (char) repetition pattern type. The meta-parser knows all needed information if you write eg: digits : [0..9]+ You'll get a repetition node which holds (read: points to) a klass node. So I first let the generator sort out klass repetitions to write String expressions. Then I went back even higher to special-case strings in the meta-grammar itself. But in the following case: digit : [0..9] digits : digit+ the repetition node holds a "name"! It's very common, indeed. And in such cases you'll never get a String. Stupid, no? The reason why I have to wait until python objects are generated before sorting String-s out. I could let the code generator explore the parse tree to find a 'pattern' node which 'name' is 'digit' but it's overly complicated, compared to letting the generated code do this job -- I guess. ------ la vita e estrany From denis.spir at free.fr Fri Jun 12 15:48:13 2009 From: denis.spir at free.fr (spir) Date: Fri, 12 Jun 2009 15:48:13 +0200 Subject: [Tutor] use of __new__ In-Reply-To: References: <20090612135447.16ed1447@o> Message-ID: <20090612154813.62fc03ac@o> Le Fri, 12 Jun 2009 22:37:17 +1000, Lie Ryan s'exprima ainsi: > spir wrote: > > Hello, > > > > I have (again) some issue using __new__. > > What I need is basically to catch an object creation and yield an object > > of an alternate type, when a condition is met. > > > > Basically, the outline looks like: > > > > class Normal(object): > > def __new__(cls, arg): > > if cond(arg): > > # > > # expression is simply: Special(arg) > > # must be __init__ialised ! > > > > # Conceptually, nothing to change: > > # > > # must be __init__ialised ! > > > > But I got issues in both cases: > > * cannot find how to get Special objects initialised > > * cannot find how to return Normal object > > roughly like this: > > >>> class Special(object): > ... def __init__(self, arg): > ... self.arg = arg > ... > >>> class Normal(object): > ... def __new__(cls, arg): > ... if arg: > ... return Special(arg) > ... else: > ... ret = super(Normal, cls).__new__(cls) > ... ret.__init__(arg) > ... return ret > ... def __init__(self, arg): > ... self.arg = arg > ... Right, thank you. I continued my trials and ended with seemingly working code, close to yours. # case pattern is Klass: yield String instead if isinstance(pattern,Klass): self = String(pattern, numMin,numMax, expression,name) #~ self.__init__(pattern, numMin,numMax, expression,name) return self # else a Repetition self = Pattern.__new__(cls,pattern, numMin,numMax, expression,name) return self I have more questions: 1. For the 'normal' (second) case, I read in the docs that __new__ *must* return the new object. This should be done using the supertype's __new__. But you don't do it and it seems to work anyway. In this case, __init__ is (supposed to be) called automagically. 2. For the special case, as you can see the __init__ line is commented out and it works anyway. While the docs positively assert that __init__ *won't* be called if an object of a different type is returned, it is anyway. Of course, i checked that init methods are really used in both cases. So, how do things _actually_ work? (Such confusions are why each time I need __new__ I have to re-learn the real way to use it.) > >>> a = Normal(True) > >>> b = Normal(False) > >>> a.arg > True > >>> b.arg > False > >>> > > generally though, avoid using __new__ > > > > (also Normal's supertype has no explicite __new__, but it has an __init__) > > Haven't tested yet, but that should be no problem as python will use the > supertype's supertype's __new__ and at the end of the method resolution > order is object.__new__() That's what I thought, too. Thanks again, Denis ------ la vita e estrany From denis.spir at free.fr Fri Jun 12 15:52:16 2009 From: denis.spir at free.fr (spir) Date: Fri, 12 Jun 2009 15:52:16 +0200 Subject: [Tutor] use of __new__ In-Reply-To: References: <20090612135447.16ed1447@o> Message-ID: <20090612155216.468a016f@o> Le Fri, 12 Jun 2009 22:37:17 +1000, Lie Ryan s'exprima ainsi: > >>> class Normal(object): > ... def __new__(cls, arg): > ... if arg: > ... return Special(arg) > ... else: > ... ret = super(Normal, cls).__new__(cls) > ... ret.__init__(arg) > ... return ret > ... def __init__(self, arg): > ... self.arg = arg > ... Forgot a question. You & I create and return a special object directly (above: "Special(arg)"). But the docs say we should use __new__ instead. Denis ------ la vita e estrany From cyberjacob at googlemail.com Fri Jun 12 15:14:26 2009 From: cyberjacob at googlemail.com (Jacob Mansfield) Date: Fri, 12 Jun 2009 14:14:26 +0100 Subject: [Tutor] parallel port commands Message-ID: does anyone know how to replace the C comands inp() and outb() these are used for parallel port communication -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jun 12 16:03:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Jun 2009 10:03:08 -0400 Subject: [Tutor] use of __new__ In-Reply-To: <20090612154813.62fc03ac@o> References: <20090612135447.16ed1447@o> <20090612154813.62fc03ac@o> Message-ID: <1c2a2c590906120703o12718a9bx4f7dd21749152fc1@mail.gmail.com> On Fri, Jun 12, 2009 at 9:48 AM, spir wrote: > Right, thank you. I continued my trials and ended with seemingly working code, close to yours. > > ? ? ? ? ? ? ? ?# case pattern is Klass: yield String instead > ? ? ? ? ? ? ? ?if isinstance(pattern,Klass): > ? ? ? ? ? ? ? ? ? ? ? ?self = String(pattern, numMin,numMax, expression,name) > #~ ? ? ? ? ? ? ? ? ? ? ?self.__init__(pattern, numMin,numMax, expression,name) > ? ? ? ? ? ? ? ? ? ? ? ?return self > ? ? ? ? ? ? ? ?# else a Repetition > ? ? ? ? ? ? ? ?self = Pattern.__new__(cls,pattern, numMin,numMax, expression,name) > ? ? ? ? ? ? ? ?return self > > I have more questions: > 2. For the special case, as you can see the __init__ line is commented out and it works anyway. While the docs positively assert that __init__ *won't* be called if an object of a different type is returned, it is anyway. When you call String(...) you invoke String.__new__() and String.__init__(), so String.__init__() is not called by the normal mechanism. If your special case returned for example a cached instance of String(), then String.__init__() would not be called as part of the invocation of your __new__(). Kent From denis.spir at free.fr Fri Jun 12 16:03:26 2009 From: denis.spir at free.fr (spir) Date: Fri, 12 Jun 2009 16:03:26 +0200 Subject: [Tutor] use of __new__ In-Reply-To: <1c2a2c590906120605u78ebeabbv7949d99de21f8247@mail.gmail.com> References: <20090612135447.16ed1447@o> <1c2a2c590906120605u78ebeabbv7949d99de21f8247@mail.gmail.com> Message-ID: <20090612160326.688e4879@o> Le Fri, 12 Jun 2009 09:05:35 -0400, Kent Johnson s'exprima ainsi: > On Fri, Jun 12, 2009 at 8:37 AM, Lie Ryan wrote: > >>>> class Normal(object): > > ... ? ? def __new__(cls, arg): > > ... ? ? ? ? if arg: > > ... ? ? ? ? ? ? return Special(arg) > > ... ? ? ? ? else: > > ... ? ? ? ? ? ? ret = super(Normal, cls).__new__(cls) > > ... ? ? ? ? ? ? ret.__init__(arg) > > ... ? ? ? ? ? ? return ret > > I think the else case should be > ret = super(Normal, cls).__new__(cls, arg) > return ret > > i.e. pass the same args to super.__new__() and don't explicitly call > __init__(). > > Kent Hol?, Kent, Don't you have a comment in the 'if' case, too? Namely that __init__ is not invoked explicitely, while the docs clearly state: << f __new__() returns an instance of cls, then the new instance?s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__(). If __new__() does not return an instance of cls, then the new instance?s __init__() method will not be invoked.>> Denis ------ la vita e estrany From kent37 at tds.net Fri Jun 12 16:30:44 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Jun 2009 10:30:44 -0400 Subject: [Tutor] use of __new__ In-Reply-To: <20090612160326.688e4879@o> References: <20090612135447.16ed1447@o> <1c2a2c590906120605u78ebeabbv7949d99de21f8247@mail.gmail.com> <20090612160326.688e4879@o> Message-ID: <1c2a2c590906120730g7ecb0ec8vf12b08a92d99b844@mail.gmail.com> On Fri, Jun 12, 2009 at 10:03 AM, spir wrote: > Don't you have a comment in the 'if' case, too? Namely that __init__ is not invoked explicitely, while the docs clearly state: > > << f __new__() returns an instance of cls, then the new instance?s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__(). > > If __new__() does not return an instance of cls, then the new instance?s __init__() method will not be invoked.>> It's hard to talk about this clearly because there are *two* invocations of __new__(). Using your original names of Normal and Special, when you call Normal(), that invokes Normal.__new__(). If you then call Special(), that invokes Special.__new__(). This invocation returns an instance of Special, so Special.__init__() is also called. The invocation of Normal.__new__() will not invoke Special.__init__(). This all happens in type.__call__(), which is the special method that is invoked by Normal(). (Normal is an instance of type, so Normal() invokes type.__call__().) You can look at the source, it is in typeobject.c in the type_call method. Simplified, it looks something like this: def __call__(cls, *args, **kwds): # this is a metaclass method so 'self' is the class obj = cls.__new__(*args, **kwds) if obj is not None and isinstance(obj, cls): obj.__init__(*args, **kwds) return obj Kent From alan.gauld at btinternet.com Fri Jun 12 18:00:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Jun 2009 17:00:53 +0100 Subject: [Tutor] quarry, References: Message-ID: "csarita bhandari" wrote > I have download python version 3.0.1 windows installer, but problem > occur during installing it. And the problem is " Your Administration > don't permit to install this program". Thats a windows problem not Python. You need to get an account with Admin access. > What should i do? I am new in python. In that case don't use Python v3. Use Python v2.6 instead. v3 is so new that most beginners material has not cauht up yet and the changes from v2 are large. You will be much better off learning v2.6 and then converting to v3 later when it is more established. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ And if you insist on using v3: http://www.alan-g.me.uk/l2p/ (Which is still under construction) From alan.gauld at btinternet.com Fri Jun 12 18:18:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Jun 2009 17:18:11 +0100 Subject: [Tutor] parallel port commands References: Message-ID: "Jacob Mansfield" wrote > does anyone know how to replace the C comands inp() and outb() these are > used for parallel port communication These are non standard C functions and will depend on your compiler, OS and hardware. You might be able to access them from Python via the ctypes module, especially if they are in a Windows DLL. There is a way to access the parallel port from Python as was mentioned in a thread earlier this week(?) using pyParallel. http://pyserial.wiki.sourceforge.net/pyParallel But pyParallel is still in development... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lie.1296 at gmail.com Fri Jun 12 19:08:07 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 13 Jun 2009 03:08:07 +1000 Subject: [Tutor] use of __new__ In-Reply-To: <20090612154813.62fc03ac@o> References: <20090612135447.16ed1447@o> <20090612154813.62fc03ac@o> Message-ID: spir wrote: > Le Fri, 12 Jun 2009 22:37:17 +1000, > Lie Ryan s'exprima ainsi: > > Right, thank you. I continued my trials and ended with seemingly working code, close to yours. > > # case pattern is Klass: yield String instead > if isinstance(pattern,Klass): > self = String(pattern, numMin,numMax, expression,name) > #~ self.__init__(pattern, numMin,numMax, expression,name) > return self > # else a Repetition > self = Pattern.__new__(cls,pattern, numMin,numMax, expression,name) > return self > > I have more questions: > > 1. For the 'normal' (second) case, I read in the docs that __new__ *must* return the new object. This should be done using the supertype's __new__. But you don't do it and it seems to work anyway. In this case, __init__ is (supposed to be) called automagically. The super(Normal, cls) construct is semantically equivalent to the supertype on single inheritance cases. There is a bug in my previous code: I called "ret.__init__(arg)" manually. It is unnecessary to invoke __init__ for this since ret is an instance of super(Normal, cls) and python will do automagic __init__ call on it later after "return ret". > 2. For the special case, as you can see the __init__ line is commented out and it works anyway. While the docs positively assert that __init__ *won't* be called if an object of a different type is returned, it is anyway. When this statement is run: self = String(pattern, numMin,numMax, expression,name) String() is __init__ ed through normal class instantiation (the one we see everyday), therefore if you or python's automagic invoke __init__ again, __init__ will be called twice (or thrice) as a result (in short, the mechanism that invoked __init__ in this case is NOT python's automagic but String() ) > Of course, i checked that init methods are really used in both cases. > > So, how do things _actually_ work? > (Such confusions are why each time I need __new__ I have to re-learn the real way to use it.) It seems in this case python is a little bit out-of-character. Python is being a little bit protective by doing automagic __init__ call and automagically making __new__ classmethods. Understandable though, since we can never be sure what could happen if an object's __new__ and __init__ is never called. Rule of thumb: - no need to call __init__ manually for both Normal() nor Special() >>>>> a = Normal(True) >>>>> b = Normal(False) >>>>> a.arg >> True >>>>> b.arg >> False >> generally though, avoid using __new__ >> >> >>> (also Normal's supertype has no explicite __new__, but it has an __init__) >> Haven't tested yet, but that should be no problem as python will use the >> supertype's supertype's __new__ and at the end of the method resolution >> order is object.__new__() > > That's what I thought, too. > Thanks again, > Denis > ------ > la vita e estrany > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From david at abbottdavid.com Sat Jun 13 04:10:50 2009 From: david at abbottdavid.com (David) Date: Fri, 12 Jun 2009 22:10:50 -0400 Subject: [Tutor] Need a solution. In-Reply-To: References: <801768.57354.qm@web43401.mail.sp1.yahoo.com> <4A31D33D.30400@abbottdavid.com> Message-ID: <4A330AAA.6040807@abbottdavid.com> Alan Gauld wrote: > > This is a bad choice of class. It is a verb which is indicative > that its not an object. Objects are nearly always nouns. > > You could use GuessableNumber. > Then it would have a number attribute which is the number > to guess. It could have a generate() ,method which produces > a new random number, possibly within a given range? > > You could also add a compare method so you can compare > your guesses. The compare method could count the number > of calls and raise an exception if you compare more than N times. > (The value of N would be in the constructor. > Something like: > > class GuessError(Exception): pass > class GuessedNumber: > def __init__(self,tries=None,limits=None):... > def generate(self, limits=None):... > def __cmp__(self, aNumber): > if self.count >= self.tries: raise GuessError > ... > > So I'd expect the client code to look like > > target = GuessableNumber(tries=5, limits=(1,99)) # init calls > generate internally > guess = int(raw_input('Guess-> ')) > while True: > try: > if guess == target: > print "Well done!" > break > else: > guess = int(raw_input('Guess again-> ')) > except GuessError: > print "Sorry, too many guesses, the number was", target.number > > > You could add another loop to ask if the player wanted to go again, > in which case you call target.generate() directly to reset the target. > > HTH, > Hi Alan, Thanks always for the feedback, i came up with this, not sure if it is much better but I am learning as I prod along :) #!/usr/bin/python from random import randrange from sys import exit class GuessedNumber: def __init__(self, attempts=None): self.attempts = attempts self.number = randrange(1,99) class Counter: def __init__(self): self.value = 0 def step(self): self.value += 1 def current(self): return self.value def play(): c = Counter() guessit = GuessedNumber(attempts=5) target_number = guessit.number attempts = guessit.attempts guess = int(raw_input('Guess-> ')) c.step() while c.current() < attempts: try: if guess == target_number: print "Well Done" play_again() elif guess < target_number: print 'Higher ... ' guess = int(raw_input('Guess Again-> ')) c.step() elif guess > target_number: print 'Lower ... ' guess = int(raw_input('Guess Again-> ')) c.step() except ValueError: print 'You must enter a number' pass print 'Too many attempts, the number was', target_number play_again() def play_again(): answer = raw_input('Do you want to try again? y/n ') answer = answer.lower() if answer == 'y': play() else: exit() if __name__ == "__main__": play() -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From alan.gauld at btinternet.com Sat Jun 13 10:20:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Jun 2009 09:20:36 +0100 Subject: [Tutor] Need a solution. References: <801768.57354.qm@web43401.mail.sp1.yahoo.com> <4A31D33D.30400@abbottdavid.com> <4A330AAA.6040807@abbottdavid.com> Message-ID: "David" wrote >> class GuessError(Exception): pass >> class GuessedNumber: >> def __init__(self,tries=None,limits=None):... >> def generate(self, limits=None):... >> def __cmp__(self, aNumber): >> if self.count >= self.tries: raise GuessError > Thanks always for the feedback, i came up with this, not sure if it is > much better but I am learning as I prod along :) The big problem from an OO point of view is that you are not making the objects do any work. You are extracting the data from inside them and you are doing all the work in your main function. In OOP we should be trying to make the objects do everything and the main function just does some high level coordination. If you make your GuessedNumber class have comparison methods you can avoid much of that. And if you put the counting code inside the comparison that could save a lot of effort in main too. Remember that in theory you shold not know what data is inside the object. You should only interact with objects via their published operations. > #!/usr/bin/python > from random import randrange > from sys import exit > > class GuessedNumber: > def __init__(self, attempts=None): > self.attempts = attempts > self.number = randrange(1,99) Any time you have a class that just has an __init__ it means its not doing anything. And that's a bad sign. Classes are there to *do* things not just store data. We can use a tuple or dictionary to do that. > class Counter: > def __init__(self): > self.value = 0 > def step(self): > self.value += 1 > def current(self): > return self.value Whilst this is OK,, because it does something, its a lot of code to wrap an integer. I personally wouldn't bother. But at least it is doing things :-) > def play(): > c = Counter() > guessit = GuessedNumber(attempts=5) > target_number = guessit.number > attempts = guessit.attempts See, here is the problem, you create an object then immediately extract all the data and then just ignore the object. You might as well just assign the values to variables > guess = int(raw_input('Guess-> ')) > c.step() > while c.current() < attempts: So why not while c.current() < guessit.attempts use the object, thats why its there > try: > if guess == target_number: Whereas this could have been if guess == guessIt > print "Well Done" > play_again() > elif guess < target_number: and elif guess < guessit > print 'Higher ... ' > guess = int(raw_input('Guess Again-> ')) > c.step() > elif guess > target_number: > print 'Lower ... ' > guess = int(raw_input('Guess Again-> ')) > c.step() > > except ValueError: > print 'You must enter a number' > pass > > print 'Too many attempts, the number was', target_number > play_again() > def play_again(): > answer = raw_input('Do you want to try again? y/n ') > answer = answer.lower() > if answer == 'y': > play() > else: > exit() This recursive approach will work most of the time but remember that Python does limit recursion to 1000 levels so if your player was very keen you could run out of levels. A normal loop would be safer. HTH, Alan G. From eddie9139 at gmail.com Sat Jun 13 11:44:53 2009 From: eddie9139 at gmail.com (Eddie) Date: Sat, 13 Jun 2009 19:44:53 +1000 Subject: [Tutor] Best Python Editor Message-ID: Hi guys, What would you regard as the best free Python editor to use on Windows for a new guy? Searching Google i see that there is quite a few out there and is "VIM" the best one to go with? Regards Eddie From denis.spir at free.fr Sat Jun 13 12:09:14 2009 From: denis.spir at free.fr (spir) Date: Sat, 13 Jun 2009 12:09:14 +0200 Subject: [Tutor] Need a solution. In-Reply-To: References: <801768.57354.qm@web43401.mail.sp1.yahoo.com> <4A31D33D.30400@abbottdavid.com> <4A330AAA.6040807@abbottdavid.com> Message-ID: <20090613120914.62ceea2a@o> Le Sat, 13 Jun 2009 09:20:36 +0100, "Alan Gauld" s'exprima ainsi: > Any time you have a class that just has an __init__ it means > its not doing anything. And that's a bad sign. Classes are there > to *do* things not just store data. We can use a tuple or > dictionary to do that. While this is probably true for _single_ objects in most case, I guess it really makes sense to create a common structure for object collections. Eg Position, with x & y attributes, for a very simple case. But indeed there are complex ones, possibly with nested structures such as eg Point inlcluding position, color,... In addition, doing this helps readibility by clearly exposing the object (type) structure in a single & visible place. All of this applies both to "value" objects (pure information, such as a position) and "real" objects (distinct things, such as a point). What do you think? Denis ------ la vita e estrany From john at fouhy.net Sat Jun 13 12:16:02 2009 From: john at fouhy.net (John Fouhy) Date: Sat, 13 Jun 2009 22:16:02 +1200 Subject: [Tutor] Best Python Editor In-Reply-To: References: Message-ID: <5e58f2e40906130316p5f1473f7h373aa4df5368162c@mail.gmail.com> 2009/6/13 Eddie : > Hi guys, > > What would you regard as the best free Python editor to use on Windows > for a new guy? Searching Google i see that there is quite a few out > there and is "VIM" the best one to go with? Vim is a general purpose programmer's editor with python support, rather than a python-specific editor. Vim has incredibly powerful at editing text, but the learning curve is steep. Personally, I think it's great, though :-) But really, if you ask ten programmers what the best editor is, you'll probably get twelve answers. I'm sure you could find many discussions on this topic in the list archives. -- John. From davea at ieee.org Sat Jun 13 12:52:01 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 13 Jun 2009 06:52:01 -0400 Subject: [Tutor] Best Python Editor In-Reply-To: References: Message-ID: <4A3384D1.5030606@ieee.org> Eddie wrote: > Hi guys, > > What would you regard as the best free Python editor to use on Windows > for a new guy? Searching Google i see that there is quite a few out > there and is "VIM" the best one to go with? > > Regards > Eddie > > This is such a common question on the python forums it ought to be in a FAQ, and maybe it is. VI and EMACS are the two "standard" Unix editors, going back decades. Somebody used to the flexibility of either of those two, who is now stuck on Windows, would naturally not want to give up any of the "customizability" of these. And people have posted macros for each to automate some of the things you'd like for Python, such as auto-indent. VIM is an editor in that heritage. Somebody who's used Windows for 20 years, however, might expect that Ctrl-S, Ctrl-F4, Alt-F4, etc. have standard meanings. So they might be more comfortable in an editor that starts with the Windows interface, and builds on it. I use metapad for many things, though not for Python. Others use Notepad++. Next question is whether you want an IDE. The ability to single-step in the debugger, locate and fix a problem in source, and start again, in a single environment is appealing. When I have a stack trace showing in the debugger, I can use the debugger to locate the source at any level of that stack without having to explicitly load the file and jump to the specified line number. And no risk that the same file is already loaded into some other editor and I'm going to lose changes if some are made one place and some another. And of course, it's nice to have a locals window, a globals window, a watch window, ... People that do not like an IDE cite the advantage of using a single editor for several programming languages, for word processing, and for web design. If such an editor is highly programmable, that would seem very good as well. So then it comes down to opinion. I use the (not-free) Komodo IDE. There is a free Komodo-Edit with most of the same features, but I really don't know what subset it includes. It is programmable with many canned add-ins, or you can customize it yourself with recorded macros and with scripts in Python or (I think) Javascript. Its addin technology is related somehow to Firefox, and I think it used a lot of the Mozilla code in its engine. The default UI is very familiar to people with Windows experience, though I don't know how it works on Mac and Linux http://www.activestate.com/komodo/ Komodo IDE http://www.activestate.com/komodo_edit/ opensource Komodo Edit http://www.activestate.com/komodo_edit/comparison/ comparison between the two From xchimeras at gmail.com Sat Jun 13 13:48:45 2009 From: xchimeras at gmail.com (Tom Green) Date: Sat, 13 Jun 2009 07:48:45 -0400 Subject: [Tutor] Best Python Editor In-Reply-To: <4A3384D1.5030606@ieee.org> References: <4A3384D1.5030606@ieee.org> Message-ID: For Windows check out PyScripter. Its IDE is similar to Borland Delphi and I find it very easy to use. Whatever works for you would be "best" for you. PyScripter is FREE and I would highly recommend it for people who are new to Python or people with programming experience that are used to programming in a IDE. Regards, T. Green On Sat, Jun 13, 2009 at 6:52 AM, Dave Angel wrote: > Eddie wrote: > > Hi guys, >> >> What would you regard as the best free Python editor to use on Windows >> for a new guy? Searching Google i see that there is quite a few out >> there and is "VIM" the best one to go with? >> >> Regards >> Eddie >> >> >> > This is such a common question on the python forums it ought to be in a > FAQ, and maybe it is. > > VI and EMACS are the two "standard" Unix editors, going back decades. > Somebody used to the flexibility of either of those two, who is now stuck > on Windows, would naturally not want to give up any of the "customizability" > of these. And people have posted macros for each to automate some of the > things you'd like for Python, such as auto-indent. VIM is an editor in that > heritage. > > Somebody who's used Windows for 20 years, however, might expect that > Ctrl-S, Ctrl-F4, Alt-F4, etc. have standard meanings. So they might be more > comfortable in an editor that starts with the Windows interface, and builds > on it. I use metapad for many things, though not for Python. Others use > Notepad++. > > Next question is whether you want an IDE. The ability to single-step in > the debugger, locate and fix a problem in source, and start again, in a > single environment is appealing. When I have a stack trace showing in the > debugger, I can use the debugger to locate the source at any level of that > stack without having to explicitly load the file and jump to the specified > line number. And no risk that the same file is already loaded into some > other editor and I'm going to lose changes if some are made one place and > some another. And of course, it's nice to have a locals window, a globals > window, a watch window, ... > > People that do not like an IDE cite the advantage of using a single editor > for several programming languages, for word processing, and for web design. > If such an editor is highly programmable, that would seem very good as > well. > > So then it comes down to opinion. I use the (not-free) Komodo IDE. There > is a free Komodo-Edit with most of the same features, but I really don't > know what subset it includes. It is programmable with many canned add-ins, > or you can customize it yourself with recorded macros and with scripts in > Python or (I think) Javascript. Its addin technology is related somehow to > Firefox, and I think it used a lot of the Mozilla code in its engine. The > default UI is very familiar to people with Windows experience, though I > don't know how it works on Mac and Linux > > http://www.activestate.com/komodo/ Komodo IDE > http://www.activestate.com/komodo_edit/ opensource Komodo Edit > http://www.activestate.com/komodo_edit/comparison/ comparison between > the two > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jun 13 14:55:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Jun 2009 13:55:58 +0100 Subject: [Tutor] Need a solution. References: <801768.57354.qm@web43401.mail.sp1.yahoo.com><4A31D33D.30400@abbottdavid.com> <4A330AAA.6040807@abbottdavid.com> <20090613120914.62ceea2a@o> Message-ID: "spir" wrote >> Any time you have a class that just has an __init__ it means >> its not doing anything. And that's a bad sign. Classes are there >> to *do* things not just store data. We can use a tuple or >> dictionary to do that. > > While this is probably true for _single_ objects in most case, > I guess it really makes sense to create a common structure > for object collections. I'd say that's valid for a very small number of cases which would normally be addressed using a record in Pascal or struct in C/C++. Mainly for the advantage of self documenting data. But a dictionary can do that too, albeit you need to specify the field names on construction. But in the vast majority of such cases I'd still use a tuple. Where it gets more valid is where we have deeply nested data structures. But then, I've never seen such a structure that didn't have methods too. And then it becomes a valid class... > Position, with x & y attributes, for a very simple case. I'd use a tuple here even if p[0] is slightly less readable than p.x > But indeed there are complex ones, possibly with nested > structures such as eg Point inlcluding position, color,... In that case there will almost always be associated methods to be created. Even a "simple" x,y point often has comparison methods or draw() or move()... > In addition, doing this helps readibility by clearly exposing > the object (type) structure in a single & visible place. The visibility and naming aspect referred to above is the most valid reasopn I can think of for using a non behavioural class. But in most cases, non behavioural classes quickly become behavioural! After all what is the point(sic) of data if you don't do something to it? > All of this applies both to "value" objects (pure information, > such as a position) and "real" objects (distinct things, such > as a point). What do you think? I think that you have a valid point but that "pure value" objects occur far less often than you might think. I always treat a value object as a sign that I've probably put some processing code in the wrong place! Only when I've checked and convinced myself I'm wrong would I proceed. For example, what do we do with the values? Do we print them? Then maybe we should have a __str__ method? Do we save them in a file? Then maybe we need a save() method? Do we do some calculations? Maybe we should have a calculate() method? Do we draw them... well, I'm sure you get the idea :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jun 13 15:15:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Jun 2009 14:15:32 +0100 Subject: [Tutor] Best Python Editor References: Message-ID: "Eddie" wrote > What would you regard as the best free Python editor to use on Windows > for a new guy? Searching Google i see that there is quite a few out > there and is "VIM" the best one to go with? vim is a great editor, especially if you use multiple OS, but it has a steep learning curve. I'd recommend Pythonwin for a newbie learning Python. Or Scite as a general purpoase programmers editor - it has the advantage of tabbed editing windows for working with multiple windows, but otherwise is the same basic editing widget that Pythonwin uses. (Notepad++ also uses the same components and is very similar to scite) But there are zillions of programmers editors and choice is extremely personal. Other popular choices for Windows include Eclipse, Winedit, emacs, etc... But for Python specific work I'd go with Pythonwin. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jun 13 15:25:48 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Jun 2009 14:25:48 +0100 Subject: [Tutor] Best Python Editor References: <4A3384D1.5030606@ieee.org> Message-ID: "Tom Green" wrote > For Windows check out PyScripter. I just did, Wow!, this looks like a superb IDE. Thanks for posting, its a new one for me although its been out for quite a while. And the P4D delphi plugin looks useful too. Thanks again, Alan G. From alan.gauld at btinternet.com Sat Jun 13 15:35:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Jun 2009 14:35:06 +0100 Subject: [Tutor] Best Python Editor References: <4A3384D1.5030606@ieee.org> Message-ID: "Alan Gauld" wrote > I just did, Wow!, this looks like a superb IDE. I spoke a wee bit too soon. The editor is nice but the debugger and some of the other tools windows (eg variables) are broken. Pity, lots of potential here. Alan G. From python at bdurham.com Sat Jun 13 16:16:08 2009 From: python at bdurham.com (python at bdurham.com) Date: Sat, 13 Jun 2009 10:16:08 -0400 Subject: [Tutor] Best Python Editor In-Reply-To: References: <4A3384D1.5030606@ieee.org> Message-ID: <1244902568.12753.1320214169@webmail.messagingengine.com> Alan, > I spoke a wee bit too soon. The editor is nice but the debugger and some of the other tools windows (eg variables) are broken. Pity, lots of potential here. The current release of Pyscripter is not stable. Drop back one release and you'll find a very solid product. Malcolm From ksterling at mindspring.com Sat Jun 13 16:40:31 2009 From: ksterling at mindspring.com (Ken Oliver) Date: Sat, 13 Jun 2009 10:40:31 -0400 (GMT-04:00) Subject: [Tutor] Best Python Editor Message-ID: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> -----Original Message----- >From: python at bdurham.com >Sent: Jun 13, 2009 10:16 AM >To: Alan Gauld , tutor at python.org >Subject: Re: [Tutor] Best Python Editor > >Alan, > >> I spoke a wee bit too soon. The editor is nice but the debugger and some of the other tools windows (eg variables) are broken. Pity, lots of potential here. > >The current release of Pyscripter is not stable. > >Drop back one release and you'll find a very solid product. > >Malcolm Sounds interesting. What is the stable version and where can it be found? . From david at abbottdavid.com Sat Jun 13 18:01:46 2009 From: david at abbottdavid.com (David) Date: Sat, 13 Jun 2009 12:01:46 -0400 Subject: [Tutor] Need a solution. In-Reply-To: References: <801768.57354.qm@web43401.mail.sp1.yahoo.com> <4A31D33D.30400@abbottdavid.com> <4A330AAA.6040807@abbottdavid.com> Message-ID: <4A33CD6A.4080408@abbottdavid.com> Alan Gauld wrote: > "David" wrote >>> class GuessError(Exception): pass >>> class GuessedNumber: >>> def __init__(self,tries=None,limits=None):... >>> def generate(self, limits=None):... >>> def __cmp__(self, aNumber): >>> if self.count >= self.tries: raise GuessError >> Thanks always for the feedback, i came up with this, not sure if it is >> much better but I am learning as I prod along :) > > The big problem from an OO point of view is that you are not making the > objects do any work. You are extracting the data from inside them and > you are doing all the work in your main function. In OOP we should be > trying to make the objects do everything and the main function just does > some high level coordination. > > If you make your GuessedNumber class have comparison methods you can > avoid much of that. And if you put the counting code inside the > comparison that could save a lot of effort in main too. Remember that in > theory you shold not know what data is inside the object. You should > only interact with objects via their published operations. > >> #!/usr/bin/python >> from random import randrange >> from sys import exit >> >> class GuessedNumber: >> def __init__(self, attempts=None): >> self.attempts = attempts >> self.number = randrange(1,99) > > Any time you have a class that just has an __init__ it means its not > doing anything. And that's a bad sign. Classes are there to *do* things > not just store data. We can use a tuple or dictionary to do that. > >> class Counter: >> def __init__(self): >> self.value = 0 >> def step(self): >> self.value += 1 >> def current(self): >> return self.value > > Whilst this is OK,, because it does something, its a lot of code to wrap > an integer. I personally wouldn't bother. But at least it is doing > things :-) > >> def play(): >> c = Counter() >> guessit = GuessedNumber(attempts=5) >> target_number = guessit.number >> attempts = guessit.attempts > > See, here is the problem, you create an object then immediately extract > all the data and then just ignore the object. You might as well just > assign the values to variables > > >> guess = int(raw_input('Guess-> ')) >> c.step() >> while c.current() < attempts: > > So why not > while c.current() < guessit.attempts > > use the object, thats why its there > >> try: >> if guess == target_number: > > Whereas this could have been > if guess == guessIt > >> print "Well Done" >> play_again() >> elif guess < target_number: > > and elif guess < guessit > >> print 'Higher ... ' >> guess = int(raw_input('Guess Again-> ')) >> c.step() >> elif guess > target_number: >> print 'Lower ... ' >> guess = int(raw_input('Guess Again-> ')) >> c.step() >> >> except ValueError: >> print 'You must enter a number' >> pass >> >> print 'Too many attempts, the number was', target_number >> play_again() >> def play_again(): >> answer = raw_input('Do you want to try again? y/n ') >> answer = answer.lower() >> if answer == 'y': >> play() >> else: >> exit() > > This recursive approach will work most of the time but remember that > Python does limit recursion to 1000 levels so if your player was very > keen you could run out of levels. A normal loop would be safer. > > HTH, > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Ok, I think I am getting somewhere now :) #!/usr/bin/python from random import randrange from sys import exit class GuessedNumber: def __init__(self, count=0, attempts=None): self.attempts = attempts self.number = randrange(1,99) self.count = count def step(self): self.count += 1 def current(self): return self.count def play(): guessit = GuessedNumber(attempts=5) guess = int(raw_input('Guess-> ')) guessit.step() while guessit.current() < guessit.attempts: try: if guess == guessit.number: print "Well Done" play_again() elif guess < guessit.number: print 'Higher ... ' guess = int(raw_input('Guess Again-> ')) guessit.step() elif guess > guessit.number: print 'Lower ... ' guess = int(raw_input('Guess Again-> ')) guessit.step() except ValueError: print 'You must enter a number' pass print 'Too many attempts, the number was', guessit.number play_again() def play_again(): answer = raw_input('Do you want to try again? y/n ') answer = answer.lower() if answer == 'y': play() else: exit() if __name__ == "__main__": play() -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From python at bdurham.com Sat Jun 13 18:22:51 2009 From: python at bdurham.com (python at bdurham.com) Date: Sat, 13 Jun 2009 12:22:51 -0400 Subject: [Tutor] Best Python Editor In-Reply-To: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> Message-ID: <1244910171.3938.1320224125@webmail.messagingengine.com> >> The current release of Pyscripter is not stable. Drop back one release and you'll find a very solid product. > Sounds interesting. What is the stable version and where can it be found? Ken, Here's the version we use: Version 1.7.2, Oct 2006 http://mmm-experts.com/Downloads.aspx?ProductId=4 The most current release (w/2.6.x and 3.x support) can be found here: http://code.google.com/p/pyscripter/ We tried running newer releases earlier this year and had lots of problems. The very latest versions on code.google may be better, but we haven't looked at them. I am interested in hearing feedback on anyone running the most recent release of Pyscripter. Malcolm . From alan.gauld at btinternet.com Sat Jun 13 18:37:52 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 13 Jun 2009 16:37:52 +0000 (GMT) Subject: [Tutor] Need a solution. In-Reply-To: <4A33CD6A.4080408@abbottdavid.com> References: <801768.57354.qm@web43401.mail.sp1.yahoo.com> <4A31D33D.30400@abbottdavid.com> <4A330AAA.6040807@abbottdavid.com> <4A33CD6A.4080408@abbottdavid.com> Message-ID: <742628.79123.qm@web86709.mail.ird.yahoo.com> > Ok, I think I am getting somewhere now :) A lot better, now add the comparison methods: > class GuessedNumber: > def __init__(self, count=0, attempts=None): > self.attempts = attempts > self.number = randrange(1,99) > self.count = count > def step(self): > self.count += 1 > def current(self): > return self.count def __lt__(self,other): return self.number < other def __gt__(self,other): return self.number > other def __eq__(self,other): return self.numer == other [caveat: There are better ways of doing this but this illustrates the principle most clearly!] And now you can write your tests as > def play(): > guessit = GuessedNumber(attempts=5) > guess = int(raw_input('Guess-> ')) > guessit.step() > while guessit.current() < guessit.attempts: > try: if guess == guessit etc... HTH, Alan G. From ataulla at gmail.com Sat Jun 13 19:24:47 2009 From: ataulla at gmail.com (Ataulla S H) Date: Sat, 13 Jun 2009 22:54:47 +0530 Subject: [Tutor] Best Python Editor In-Reply-To: <1244910171.3938.1320224125@webmail.messagingengine.com> References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> Message-ID: Hi All, I have been using komodo from last two yrs..... Its really very good open source editor. we can use this editor to edit python, php, Ruby, html On Sat, Jun 13, 2009 at 9:52 PM, wrote: >>> The current release of Pyscripter is not stable. Drop back one release and you'll find a very solid product. > >> Sounds interesting. What is the stable version and where can it be found? > > Ken, > > Here's the version we use: > > Version 1.7.2, Oct 2006 > http://mmm-experts.com/Downloads.aspx?ProductId=4 > > The most current release (w/2.6.x and 3.x support) can be found here: > http://code.google.com/p/pyscripter/ > > We tried running newer releases earlier this year and had lots of > problems. The very latest versions on code.google may be better, but we > haven't looked at them. > > I am interested in hearing feedback on anyone running the most recent > release of Pyscripter. > > Malcolm > > > ?. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Ataulla SH web:www.kring.com personal blog:www.ataulla.objectis.net KRING Technologies India Pvt. Ltd. 1st Floor, Tower B, Infinity Towers, DLF II, Gurgaon-122 002 From eddie9139 at gmail.com Sat Jun 13 22:57:36 2009 From: eddie9139 at gmail.com (Eddie) Date: Sun, 14 Jun 2009 06:57:36 +1000 Subject: [Tutor] Best Python Editor In-Reply-To: References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> Message-ID: Thanks for the input guys. I think I'll give PyScripter (the previous version that was linked to) and Komodo a try and see which I like best. Eddie 2009/6/14 Ataulla S H : > Hi All, > > I have been using komodo from last two yrs..... > > Its really very good open source editor. > > we can use this editor to edit python, php, Ruby, html > > On Sat, Jun 13, 2009 at 9:52 PM, wrote: >>>> The current release of Pyscripter is not stable. Drop back one release and you'll find a very solid product. >> >>> Sounds interesting. What is the stable version and where can it be found? >> >> Ken, >> >> Here's the version we use: >> >> Version 1.7.2, Oct 2006 >> http://mmm-experts.com/Downloads.aspx?ProductId=4 >> >> The most current release (w/2.6.x and 3.x support) can be found here: >> http://code.google.com/p/pyscripter/ >> >> We tried running newer releases earlier this year and had lots of >> problems. The very latest versions on code.google may be better, but we >> haven't looked at them. >> >> I am interested in hearing feedback on anyone running the most recent >> release of Pyscripter. >> >> Malcolm >> >> >> ?. >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Ataulla SH > > web:www.kring.com > personal blog:www.ataulla.objectis.net > KRING Technologies India Pvt. Ltd. > 1st Floor, Tower B, Infinity Towers, DLF II, Gurgaon-122 002 > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cfuller084 at thinkingplanet.net Sat Jun 13 22:47:58 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 13 Jun 2009 15:47:58 -0500 Subject: [Tutor] Best Python Editor In-Reply-To: References: Message-ID: <200906131547.59498.cfuller084@thinkingplanet.net> On Saturday 13 June 2009 04:44, Eddie wrote: > Hi guys, > > What would you regard as the best free Python editor to use on Windows > for a new guy? Searching Google i see that there is quite a few out > there and is "VIM" the best one to go with? > > Regards > Eddie I've tried a lot of editors, and my current favorite (cross platform, many languages/just text) is Kate (http://www.kate-editor.org/kate), available on windoze via KDE on Windows (http://windows.kde.org/), select kdesdk-msvc from the list of packages while in the installion tool. Cheers From alan.gauld at btinternet.com Sun Jun 14 00:40:21 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Jun 2009 23:40:21 +0100 Subject: [Tutor] Best Python Editor References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> Message-ID: wrote >>> The current release of Pyscripter is not stable. > Drop back one release and you'll find a very solid product. > >> Sounds interesting. What is the stable version and where can it be >> found? > Here's the version we use: > > Version 1.7.2, Oct 2006 > http://mmm-experts.com/Downloads.aspx?ProductId=4 Thats the version I downloaded. The debugger was very iffy and the variables pane just threw up Windows exception dialogs. The core editor and shell windows seemed fine though Alan G From hoym74 at gmail.com Sun Jun 14 02:40:18 2009 From: hoym74 at gmail.com (Mike Hoy) Date: Sat, 13 Jun 2009 19:40:18 -0500 Subject: [Tutor] Best Python Editor In-Reply-To: References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> Message-ID: <87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com> Try out Vim. It may take you a week to get used to it. Best thing I ever did was finally get started on Vim. Once I got used to it I was very happy. Google around for Vim tutorials. There is a #VIM channel on freenode I believe. There is also a VIM mailing list that is very helpful. You won't need these for long. Once you get used to it and think you've learned all you can you find out there's even more stuff you can do with it. If you wanna try Emacs go for it. You don't need an IDE for python. In the very beginning of writing python I wrote on windows using notepad and Linux using Gedit. While Gedit was better it was nothing compared to Vim. My favorite thing to do is open vim one one document I'm working on, then split the screen horizonatally for each other relevent document I'm working on. I can thing split it vertically as well. I also know that once you have saved your python document in vim you can test out your code by typing :!python % and it invokes the python interpreter in a shell for that script. Then when the program is done it returns to Vim. It also indents and colors syntax for my other languages as well: C/Java/HTML/CSS. So it's something that you use for life once you get that feeling of enlightenment that comes from never having to remove your hands from the keyboard. -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sun Jun 14 02:57:50 2009 From: srilyk at gmail.com (Wayne) Date: Sat, 13 Jun 2009 19:57:50 -0500 Subject: [Tutor] Best Python Editor In-Reply-To: <87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com> References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> <87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com> Message-ID: <333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com> On Sat, Jun 13, 2009 at 7:40 PM, Mike Hoy wrote: > Try out Vim. It may take you a week to get used to it. Best thing I ever > did was finally get started on Vim. Once I got used to it I was very happy. > Google around for Vim tutorials. There is a #VIM channel on freenode I > believe. There is also a VIM mailing list that is very helpful. You won't > need these for long. Once you get used to it and think you've learned all > you can you find out there's even more stuff you can do with it. > > > So it's something that you use for life once you get that feeling of > enlightenment that comes from never having to remove your hands from the > keyboard. I'm another viim fanatic; I use two terminals - one with vim and one with ipython (I write most of my code on linux). When I'm on windows I have a cmd window open with Ipython and I have a gVim window open. I'm sure I barely scratch the surface of things I can do and I know I've stopped using some things that I'm sure I'll start using the more I code. I really like using F5 to run my code, so you can put in your .vimrc so you don't have to type it, or just type it every time: map :!python % and every time you hit it will run your current script. Of course I also write code in c++ for school, so I have a few different keys that will change the F5 bindings. Anyhow, the best way to write code is in what you're most comfortable with and enjoy. And of course I believe that everyone should enjoy vim ;) But you should give all the aforementioned tools a try and see what works best for you. HTH! Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From hoym74 at gmail.com Sun Jun 14 03:02:17 2009 From: hoym74 at gmail.com (Mike Hoy) Date: Sat, 13 Jun 2009 20:02:17 -0500 Subject: [Tutor] Best Python Editor In-Reply-To: <333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com> References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> <87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com> <333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com> Message-ID: <87d8ca690906131802o4802abb1r186bdb4989e8e9f3@mail.gmail.com> > > > > I really like using F5 to run my code, so you can put in your .vimrc so you > don't have to type it, or just type it every time: > > map :!python % > > and every time you hit it will run your current script. > > Thanks for that. It's even better than typing :!python % because it doesn't spawn a shell separate from the Vim window. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eddie9139 at gmail.com Sun Jun 14 06:54:33 2009 From: eddie9139 at gmail.com (Eddie) Date: Sun, 14 Jun 2009 14:54:33 +1000 Subject: [Tutor] Best Python Editor In-Reply-To: <87d8ca690906131802o4802abb1r186bdb4989e8e9f3@mail.gmail.com> References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> <87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com> <333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com> <87d8ca690906131802o4802abb1r186bdb4989e8e9f3@mail.gmail.com> Message-ID: I downloaded the previous version of PyScripter although couldn't get it to work and after googling it, I downloaded Python Portable 1.1 (Python 2.6.1 as most sites/books recommend this and not 3) which has PySCripter included and this then works fine.Ii also downloaded Komod0 5.1 and after messing around with these, I think I prefer PyScripter and will use that for the mean time. I'll also take a look at VIM as being able to use the same program for PHP/CSS/HTML (and Basic if it supports it) as well as hopefully Python (I've only just started learning it) would be an advantage. Thanks guys Eddie 2009/6/14 Mike Hoy : >> >> >> I really like using F5 to run my code, so you can put in your .vimrc so >> you don't have to type it, or just type it every time: >> >> map :!python % >> >> and every time you hit it will run your current script. >> > Thanks for that. It's even better than typing :!python % because it doesn't > spawn a shell separate from the Vim window. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From xchimeras at gmail.com Sun Jun 14 12:55:08 2009 From: xchimeras at gmail.com (Tom Green) Date: Sun, 14 Jun 2009 06:55:08 -0400 Subject: [Tutor] Best Python Editor In-Reply-To: References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> <87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com> <333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com> <87d8ca690906131802o4802abb1r186bdb4989e8e9f3@mail.gmail.com> Message-ID: Since VIM seems to be the editor of choice and I have been programming in Python for many years using Pyscripter and Eclipse I was wondering how I could transition away from the IDE world to VIM. My main issue is how do I go about using VIM to debug my code? With Pyscripter and other IDES its as simple as placing a breakpoint and pressing F7 to step thru the code and you have the ability to see the variable values etc. Also, with an IDE such as Pyscripter when calling a function a nice balloon hint appears showing you the number of parameters and their types. Coming from a Visual Studio background this is great, as I might be calling a function or method and I don't know off hand the values. Maybe someone could share how they go about programming a good size program with VIM as I would like to use it. Don't get me wrong for quick programs I will use VIM or notepad, but when it comes to building a OOP program I find Eclipse or Pyscripter much easier to use. Regards, T. Green On Sun, Jun 14, 2009 at 12:54 AM, Eddie wrote: > I downloaded the previous version of PyScripter although couldn't get > it to work and after googling it, I downloaded Python Portable 1.1 > (Python 2.6.1 as most sites/books recommend this and not 3) which has > PySCripter included and this then works fine.Ii also downloaded Komod0 > 5.1 and after messing around with these, I think I prefer PyScripter > and will use that for the mean time. > > I'll also take a look at VIM as being able to use the same program for > PHP/CSS/HTML (and Basic if it supports it) as well as hopefully Python > (I've only just started learning it) would be an advantage. > > Thanks guys > Eddie > > 2009/6/14 Mike Hoy : > >> > >> > >> I really like using F5 to run my code, so you can put in your .vimrc so > >> you don't have to type it, or just type it every time: > >> > >> map :!python % > >> > >> and every time you hit it will run your current script. > >> > > Thanks for that. It's even better than typing :!python % because it > doesn't > > spawn a shell separate from the Vim window. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jfabiani at yolo.com Sun Jun 14 14:00:37 2009 From: jfabiani at yolo.com (johnf) Date: Sun, 14 Jun 2009 05:00:37 -0700 Subject: [Tutor] Best Python Editor In-Reply-To: References: Message-ID: <200906140500.37286.jfabiani@yolo.com> On Saturday 13 June 2009 02:44:53 am Eddie wrote: > Hi guys, > > What would you regard as the best free Python editor to use on Windows > for a new guy? Searching Google i see that there is quite a few out > there and is "VIM" the best one to go with? > > Regards > Eddie > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Looks like no one has suggested "wing" (a free version and cost version). I've been using it for years - but I like ide's and it works well with wxpython. Also net-beans supports python, along with eclipse. Then there's eric if you like qt. Then something called drPython (I think). -- John Fabiani From srilyk at gmail.com Sun Jun 14 16:16:05 2009 From: srilyk at gmail.com (Wayne) Date: Sun, 14 Jun 2009 09:16:05 -0500 Subject: [Tutor] Best Python Editor In-Reply-To: References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> <87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com> <333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com> <87d8ca690906131802o4802abb1r186bdb4989e8e9f3@mail.gmail.com> Message-ID: <333efb450906140716x2d5f97edy6b61c7ed63d89774@mail.gmail.com> On Sun, Jun 14, 2009 at 5:55 AM, Tom Green wrote: > Since VIM seems to be the editor of choice and I have been programming in > Python for many years using Pyscripter and Eclipse I was wondering how I > could transition away from the IDE world to VIM. My main issue is how do I > go about using VIM to debug my code? I usually use print statements and/or raw_input's if you want break points. > With Pyscripter and other IDES its as simple as placing a breakpoint and > pressing F7 to step thru the code and you have the ability to see the > variable values etc. I know you can do some similar things with the python debugger but I've honestly never used it that much (or worked on a project large enough I needed to!) > Also, with an IDE such as Pyscripter when calling a function a nice balloon > hint appears showing you the number of parameters and their types. It's not precisely the same thing, but you can fold multiple lines, which allows you to have only the top line of a function showing. I find that rather helpful, and ctrl-n autocompletes the function name. Then you can mark the location with m then a-to-z (I use c as a mnemonic for 'current') then move on top of the name and push * - that will find the next occurence of the word, which is often the function declaration. I just hit "n" (next) until I find it, if that's not the case. Then I type ` (the one over the tilde) then c which takes me back to my 'current' location. If you really wanted, though, you could also have horizontal split of the same file, and you could probably write a macro that would move to that window/buffer and find the function declaraition (so it would search for def ). I don't know precisely how the dropdown autocomplete menu works but you could also probably edit your script to add parameters for the function call just like an IDE. > Coming from a Visual Studio background this is great, as I might be > calling a function or method and I don't know off hand the values. Maybe > someone could share how they go about programming a good size program with > VIM as I would like to use it. Don't get me wrong for quick programs I will > use VIM or notepad, but when it comes to building a OOP program I find > Eclipse or Pyscripter much easier to use. I suppose that's probably the case for a few people - and certainly the reason those tools exist in the first place. If I were working on a quite large program I might consider using an IDE, but in reality I'm probably just as comfortable jumping around code to look for the information I need as I would be using an IDE. HTH, Wayne > On Sun, Jun 14, 2009 at 12:54 AM, Eddie wrote: > >> I downloaded the previous version of PyScripter although couldn't get >> it to work and after googling it, I downloaded Python Portable 1.1 >> (Python 2.6.1 as most sites/books recommend this and not 3) which has >> PySCripter included and this then works fine.Ii also downloaded Komod0 >> 5.1 and after messing around with these, I think I prefer PyScripter >> and will use that for the mean time. >> >> I'll also take a look at VIM as being able to use the same program for >> PHP/CSS/HTML (and Basic if it supports it) as well as hopefully Python >> (I've only just started learning it) would be an advantage. >> >> Thanks guys >> Eddie >> >> 2009/6/14 Mike Hoy : >> >> >> >> >> >> I really like using F5 to run my code, so you can put in your .vimrc so >> >> you don't have to type it, or just type it every time: >> >> >> >> map :!python % >> >> >> >> and every time you hit it will run your current script. >> >> >> > Thanks for that. It's even better than typing :!python % because it >> doesn't >> > spawn a shell separate from the Vim window. >> > >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> > >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jun 14 17:04:35 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Jun 2009 16:04:35 +0100 Subject: [Tutor] Best Python Editor References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net><1244910171.3938.1320224125@webmail.messagingengine.com><87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com><333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com><87d8ca690906131802o4802abb1r186bdb4989e8e9f3@mail.gmail.com> Message-ID: "Tom Green" wrote > Since VIM seems to be the editor of choice and I have been programming in > Python for many years using Pyscripter and Eclipse I was wondering how I > could transition away from the IDE world to VIM. With great difficulty and to be honest I wouyldn't bother. If you are used to eclipse then there is little to be gained from moving to vim. vim is a more powerful and faster editor once you know it, but learning it takes a while. But the "Microsoft IDE" v the "Unix style" of programming are fundamentally different paradigms and if you are already comfortable with an IDE I'd stick with that style. Particul;arly with Eclipse which is cross platform and therefore available on most OS. > My main issue is how do I go about using VIM to debug my code? You set up a key mapping to either start the Python debugger or one of the GUI variants such as winpdb. To be honest the great thing about Python is you hardly ever need a debugger, especially if you are programming interactively using the >>> prompt (or IPython etc) > have the ability to see the variable values etc. Get to know the introspection capabilities of Python, dir() help() etc > Pyscripter when calling a function a nice balloon hint appears showing > you > the number of parameters and their types. Tooltip help is the biggest single reason for using an IDE. It is genuinely useful and not available on any straight editor I know of. However if you are using a >>> prompt you can type help() to get the same info, but it is slower. But if you are familiar with Python and its libraries its not needed all that often. (And some people do get irritated by tooltips, I used to in Delphi when I was an expert and I turned them off but now, as an occasional programmer I do find them helpful) > don't know off hand the values. Maybe someone could share how they go > about > programming a good size program with VIM as I would like to use it. You program the modules in small chunks. You design the structure of the program and build it bottom up. And I use the >>> prompt for ad-hoc testing and experimentation a lot. I bounce between the OS shell (to execute the program(*), the Python shell to try out code ideas, and the editor. (*) Some prefer to run the code from inside the editor but I find that loses the output which is often what I want to see so I use a separate OS window. That also means there is no strange environmental stuff altering the behaviour. > get me wrong for quick programs I will use VIM or notepad, but when it > comes > to building a OOP program I find Eclipse or Pyscripter much easier to > use. See I'm the opposite, I use Pythonwin or Eclipse for building small programs but bigger things with multiple modukles I go for vim or Scite. PyScripter looks like it might just win me over if I persevere, pity I can't get the debugger to work at all... Some of this might just be what we are used to too. Remember that IDEs as such didn't really come into existence till about 12-15 years ago. Those of us who have notched up more than 2 or 3 decades of coding have probably just not got used to the new concepts yet! Unix was the original IDE! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jsseabold at gmail.com Sun Jun 14 17:25:59 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Sun, 14 Jun 2009 11:25:59 -0400 Subject: [Tutor] Discussion of super Message-ID: Hello all, I am working under the umbrella of the Python Software Foundation for the Google Summer of Code and am keeping a blog about the work. Part of my work is refactoring and extending some existing code. This code makes use of Python's super, and so I am trying to understand the ins and outs of super. I recently summarized my understanding of super on my blog, and I was wondering if anyone would care to comment on my write up. I am particularly worried about my handling of my multiple inheritance example and explanation of class F. I apologize for the length and if this is an inappropriate request for this list, but I read the discussions here almost daily, and often the points that come up add to my Python understanding very much. Everyone seems to have a great grasp of Python and programming and that rare ability (and willingness) to *explain* topics. The post is here But if it's easier for the ML, comments can be inlined below. The In/Out prompts are the iPython interpreter if anyone is wondering, and I tried to preserve indents. Cheers, Skipper -------------------------------------------------------------------------------------------------------------- The current statistical models package is housed in the NiPy, Neuroimaging in Python, project. Right now, it is designed to rely on Python's built-in super to handle class inheritance. This post will dig a little more into the super function and what it means for the design of the project and future extensions. Note that there are plenty of good places to learn about super and that this post is to help me as much as anyone else. You can find the documentation for super here. If this is a bit confusing, it will, I hope, become clearer after I demonstrate the usage. First, let's take a look at how super actually works for the simple case of single inheritance (right now, we are not planning on using multiple inheritance in the project) and an __init__ chain (note that super can call any of its parent class's methods, but using __init__ is my current use case). The following examples were adapted from some code provided by mentors (thank you!). class A(object): def __init__(self, a): self.a = a print 'executing A().__init__' class B(A): def __init__(self, a): self.ab = a*2 print 'executing B().__init__' super(B,self).__init__(a) class C(B): def __init__(self, a): self.ac = a*3 print 'executing C().__init__' super(C,self).__init__(a) Now let's have a look at creating an instance of C. In [2]: cinst = C(10) executing C().__init__ executing B().__init__ executing A().__init__ In [3]: vars(cinst) Out[3]: {'a': 10, 'ab': 20, 'ac': 30} That seems simple enough. Creating an instance of C with a = 10 will also give C the attributes of B(10) and A(10). This means our one instance of C has three attributes: cinst.ac, cinst.ab, cinst.a. The latter two were created by its parent classes (or superclasses) __init__ method. Note that A is also a new-style class. It subclasses the 'object' type. The actual calls to super pass the generic class 'C' and a handle to that class 'self', which is 'cinst' in our case. Super returns the literal parent of the class instance C since we passed it 'self'. It should be noted that A and B were created when we initialized cinst and are, therefore, 'bound' class objects (bound to cinst in memory through the actual instance of class C) and not referring to the class A and class B instructions defined at the interpreter (assuming you are typing along at the interpreter). Okay now let's define a few more classes to look briefly at multiple inheritance. class D(A): def __init__(self, a): self.ad = a*4 print 'executing D().__init__' # if super is commented out then __init__ chain ends #super(D,self).__init__(a) class E(D): def __init__(self, a): self.ae = a*5 print 'executing E().__init__' super(E,self).__init__(a) Note that the call to super in D is commented out. This breaks the __init__ chain. In [4]: einst = E(10) executing E().__init__ executing D().__init__ In [5]: vars(einst) Out[5]: {'ad': 40, 'ae': 50} If we uncomment the super in D, we get as we would expect In [6]: einst = E(10) executing E().__init__ executing D().__init__ executing A().__init__ In [7]: vars(einst) Out[7]: {'a': 10, 'ad': 40, 'ae': 50} Ok that's pretty straightforward. In this way super is used to pass off something to its parent class. For instance, say we have a little more realistic example and the instance of C takes some timeseries data that exhibits serial correlation. Then we can have C correct for the covariance structure of the data and "pass it up" to B where B can then perform OLS on our data now that it meets the assumptions of OLS. Further B can pass this data to A and return some descriptive statistics for our data. But remember these are 'bound' class objects, so they're all attributes to our original instance of C. Neat huh? Okay, now let's look at a pretty simple example of multiple inheritance. class F(C,E): def __init__(self, a): self.af = a*6 print 'executing F().__init__' super(F,self).__init__(a) For this example we are using the class of D, that has super commented out. In [8]: finst = F(10) executing F().__init__ executing C().__init__ executing B().__init__ executing E().__init__ executing D().__init__ In [8]: vars(finst) Out[8]: {'ab': 20, 'ac': 30, 'ad': 40, 'ae': 50, 'af': 60} The first time I saw this gave me pause. Why isn't there an finst.a? I was expecting the MRO to go F -> C -> B -> A -> E -> D -> A. Let's take a closer look. The F class has multiple inheritance. It inherits from both C and E. We can see F's method resolution order by doing In [9]: F.__mro__ Out[9]: (, , , , , , ) Okay, so we can see that for F A is a subclass of D but not B. But why? In [10]: A.__subclasses__() Out[10]: [, ] The reason is that A does not have a call to super, so the chain doesn't exist here. When you instantiate F, the hierarchy goes F -> C -> B -> E -> D -> A. The reason that it goes from B -> E is because A does not have a call to super, so it can't pass anything to E (It couldn't pass anything to E because the object.__init__ doesn't take a parameter "a" and because you cannot have a MRO F -> C -> B -> A -> E -> D -> A as this is inconsistent and will give an error!), so A does not cause a problem and the chain ends after D (remember that D's super is commented out, but if it were not then there would be finst.a = 10 as expected). Whew. I'm sure you're thinking "Oh that's (relatively) easy. I'm ready to go crazy with super." But there are a number of things must keep in mind when using super, which makes it necessary for the users of super to proceed carefully. 1. super() only works with new-style classes. You can read more about classic/old-style vs new-style classes here. From there you can click through or just go here for more information on new-style classes. Therefore, you must know that the base classes are new-style. This isn't a problem for our project right now, because I have access to all of the base classes. 2. Subclasses must use super if their superclasses do. This is why the user of super must be well-documented. If we have to classes A and B that both use super and a class C that inherits from them, but does not know about super then we will have a problem. Consider the slightly different case class A(object): def __init__(self): print "executing A().__init__" super(A, self).__init__() class B(object): def __init__(self): print "executing B().__init__" super(B, self).__init__() class C(A,B): def __init__(self): print "executing C().__init__" A.__init__(self) B.__init__(self) # super(C, self).__init__() Say class C was defined by someone who couldn't see class A and B, then they wouldn't know about super. Now if we do In [11]: C.__mro__ Out[11]: (, , , ) In [12]: c = C() executing C().__init__ executing A().__init__ executing B().__init__ executing B().__init__ B got called twice, but by now this should be expected. A's super calls __init__ on the next object in the MRO which is B (it works this time unlike above because there is no parameter passed with __init__), then C explicitly calls B again. If we uncomment super and comment out the calls to the parent __init__ methods in C then this works as expected. 3. Superclasses probably should use super if their subclasses do. We saw this earlier with class D's super call commented out. Note also that A does not have a call to super. The last class in the MRO does not need super *if* there is only one such class at the end. 4. Classes must have the exact same call signature. This should be obvious but is important for people to be able to subclass. It is possible however for subclasses to add additional arguments so *args and **kwargs should be probably always be included in the methods that are accessible to subclasses. 5. Because of these last three points, the use of super must be explicitly documented, as it has become a part of the interface to our classes. From alan.gauld at btinternet.com Sun Jun 14 17:52:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Jun 2009 16:52:41 +0100 Subject: [Tutor] Best Python Editor Message-ID: "Alan Gauld" wrote > Some of this might just be what we are used to too. Remember that > IDEs as such didn't really come into existence till about 12-15 years Sigh! I'm getting old.... In fact the first thing I would call an IDE in the modern sense was probably Turbo Pascal v4 (previous versions didn't include a debugger) which came out in 1987 according to Wikipedia. So in fact IDEs have been around on PCs for about 22 years! But they certainly weren't common on *nix until about the mid 90's (Galaxy, Object/CodeCenter and HP Softbench being very expensive exceptions!) [ And of course Smalltalk80 had a very complete IDE in 1980, (See Squeek screenshots for some idea of how it differs from modern GUIs!) but Smalltalk has always been an exception to the rules! ] Apologies for the misinformation. Alan G From carlos.zun at gmail.com Sun Jun 14 18:26:19 2009 From: carlos.zun at gmail.com (Carlos Zuniga) Date: Sun, 14 Jun 2009 11:26:19 -0500 Subject: [Tutor] Best Python Editor In-Reply-To: <333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com> References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> <87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com> <333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com> Message-ID: On Sat, Jun 13, 2009 at 7:57 PM, Wayne wrote: > On Sat, Jun 13, 2009 at 7:40 PM, Mike Hoy wrote: >> >> Try out Vim. It may take you a week to get used to it. Best thing I ever >> did was finally get started on Vim. Once I got used to it I was very happy. >> Google around for Vim tutorials. There is a #VIM channel on freenode I >> believe. There is also a VIM mailing list that is very helpful. You won't >> need these for long. Once you get used to it and think you've learned all >> you can you find out there's even more stuff you can do with it. >> >> >> So it's something that you use for life once you get that feeling of >> enlightenment that comes from never having to remove your hands from the >> keyboard. > > I'm another viim fanatic; > > I use two terminals - one with vim and one with ipython (I write most of my > code on linux). When I'm on windows I have a cmd window open with Ipython > and I have a gVim window open. I'm sure I barely scratch the surface of > things I can do and I know I've stopped using some things that I'm sure I'll > start using the more I code. > > I really like using F5 to run my code, so you can put in your .vimrc so you > don't have to type it, or just type it every time: > > map :!python % > > and every time you hit it will run your current script. > > Of course I also write code in c++ for school, so I have a few different > keys that will change the F5 bindings. You can map it directly to the filename extension so it uses the correct bindings automatically au BufNewFile,BufRead *.py map :!python % Cheers -- Linux Registered User # 386081 A menudo unas pocas horas de "Prueba y error" podr?n ahorrarte minutos de leer manuales. From alan.gauld at btinternet.com Sun Jun 14 19:35:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Jun 2009 18:35:32 +0100 Subject: [Tutor] Best Python Editor References: Message-ID: "Alan Gauld" wrote > [ And of course Smalltalk80 had a very complete IDE in 1980, > (See Squeek screenshots for some idea of how it differs from > modern GUIs!) but Smalltalk has always been an exception to > the rules! ] I'm not doing well today. Since I last looked Squeak has obviously changed course big style! It was originally trying to recreate the original parcPlace Smalltalk80 environment but the latest screenshots are something altogether more modern looking. Once more I apologise. Alan G. From kurt at tool.net Sun Jun 14 21:03:36 2009 From: kurt at tool.net (Kurt Bendl) Date: Sun, 14 Jun 2009 15:03:36 -0400 Subject: [Tutor] Best Python Editor In-Reply-To: References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> <87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com> <333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com> Message-ID: <53B3AFCC-698E-4C61-BDF9-71B865F08783@tool.net> I've been pretty happy with WingIDE from wingware and have been impressed with the give-away version of Komodo from ActiveState. My fall back editor when I'm in a hurry on mac is still TextMate. Knowing my way around vim is essential, but I just can't commit to it as my primary editor. (I guess I'm just not hard core enough.) I like Kate on Ubuntu as well. Kurt -- http://tool.net On Jun 14, 2009, at 12:26 PM, Carlos Zuniga wrote: > On Sat, Jun 13, 2009 at 7:57 PM, Wayne wrote: >> On Sat, Jun 13, 2009 at 7:40 PM, Mike Hoy wrote: >>> >>> Try out Vim. It may take you a week to get used to it. Best thing >>> I ever >>> did was finally get started on Vim. Once I got used to it I was >>> very happy. >>> Google around for Vim tutorials. There is a #VIM channel on >>> freenode I >>> believe. There is also a VIM mailing list that is very helpful. >>> You won't >>> need these for long. Once you get used to it and think you've >>> learned all >>> you can you find out there's even more stuff you can do with it. >>> >>> >>> So it's something that you use for life once you get that feeling of >>> enlightenment that comes from never having to remove your hands >>> from the >>> keyboard. >> >> I'm another viim fanatic; >> >> I use two terminals - one with vim and one with ipython (I write >> most of my >> code on linux). When I'm on windows I have a cmd window open with >> Ipython >> and I have a gVim window open. I'm sure I barely scratch the >> surface of >> things I can do and I know I've stopped using some things that I'm >> sure I'll >> start using the more I code. >> >> I really like using F5 to run my code, so you can put in >> your .vimrc so you >> don't have to type it, or just type it every time: >> >> map :!python % >> >> and every time you hit it will run your current script. >> >> Of course I also write code in c++ for school, so I have a few >> different >> keys that will change the F5 bindings. > > You can map it directly to the filename extension so it uses the > correct bindings automatically > > au BufNewFile,BufRead *.py map :!python % > > Cheers > > -- > Linux Registered User # 386081 > A menudo unas pocas horas de "Prueba y error" podr?n ahorrarte minut > os > de leer manuales. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From emile at fenx.com Sun Jun 14 21:53:19 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 14 Jun 2009 12:53:19 -0700 Subject: [Tutor] Best Python Editor In-Reply-To: References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net><1244910171.3938.1320224125@webmail.messagingengine.com><87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com><333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com><87d8ca690906131802o4802abb1r186bdb4989e8e9f3@mail.gmail.com> Message-ID: On 6/14/2009 8:04 AM Alan Gauld said... > "Tom Green" wrote > >> Since VIM seems to be the editor of choice and I have been programming in >> Python for many years using Pyscripter and Eclipse I was wondering how I >> could transition away from the IDE world to VIM. > > With great difficulty and to be honest I wouyldn't bother. > If you are used to eclipse then there is little to be gained from moving > to vim. Seconded. Editors are a personal choice and often the loss of productivity while learning a new environment isn't worth it. My introduction to coding Turbo Pascal was eased owing to the WordStar compatible/modeled editor it used. Nowadays, any editor with configurable syntax capability is sufficient. It's all personal preference after that. > Some of this might just be what we are used to too. Remember that > IDEs as such didn't really come into existence till about 12-15 years > ago. Those of us who have notched up more than 2 or 3 decades of > coding have probably just not got used to the new concepts yet! Full screen editing with WordStar spoiled me after having only the primitive form of edlin I'd been working with. vi on the *nix boxen was (and still is) a necessary tool because it was/is available everywhere, but I never quite got it and only cautiously use it when I do. Somewhere along the line I heard that "vi has two modes -- one that beeps at you; and another that destroys your file." Since then I've had fewer problems with it. :) My editor for the past ten years or so has been TextPad on windows with a variety of syntax plugins. (php,perl,python,pro5,postscript) Emile From michael at trollope.org Mon Jun 15 04:31:53 2009 From: michael at trollope.org (Michael Powe) Date: Sun, 14 Jun 2009 19:31:53 -0700 Subject: [Tutor] Best Python Editor In-Reply-To: References: Message-ID: <20090615023153.GA23272@titan.spiretech.com> On Sun, Jun 14, 2009 at 12:53:19PM -0700, Emile van Sebille wrote: > On 6/14/2009 8:04 AM Alan Gauld said... > >"Tom Green" wrote > >>Since VIM seems to be the editor of choice and I have been programming in > >>Python for many years using Pyscripter and Eclipse I was wondering how I > >>could transition away from the IDE world to VIM. > >With great difficulty and to be honest I wouyldn't bother. > >If you are used to eclipse then there is little to be gained from moving > >to vim. > Seconded. Editors are a personal choice and often the loss of > productivity while learning a new environment isn't worth it. My > introduction to coding Turbo Pascal was eased owing to the WordStar > compatible/modeled editor it used. Nowadays, any editor with > configurable syntax capability is sufficient. It's all personal > preference after that. It's good to see so much common sense prevailing on this topic. An IDE such as eclipse or VS really only becomes a necessity for productivity when (a) you are dealing with multiple code files and proper compilation and linking and so forth becomes complicated; or (b) you are working in a language with which you are not as familiar as you should like to be, and autocompletion because a real asset. However, I will say that while following this thread, it occurred to me that the one feature that VS and even the VBA editor in MS Office has, is the ability to pop you into the debugger on error. This feature is so useful that it surprises me nobody else seems to do it. Most often, simply the ability to jump to the error line is provided and I suppose that must be generally acceptable. Thanks. mp From lie.1296 at gmail.com Mon Jun 15 08:00:20 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 15 Jun 2009 16:00:20 +1000 Subject: [Tutor] Best Python Editor In-Reply-To: <20090615023153.GA23272@titan.spiretech.com> References: <20090615023153.GA23272@titan.spiretech.com> Message-ID: Michael Powe wrote: > It's good to see so much common sense prevailing on this topic. It's good that this newsgroup is not as prevalent to being flamed. In certain other newsgroup, even (an honest and naive) mentioning of preferred editor would turn the thread into World War E. > An > IDE such as eclipse or VS really only becomes a necessity for > productivity when (a) you are dealing with multiple code files and > proper compilation and linking and so forth becomes complicated; or People that write in text editors often uses makefiles to handle that. However, in python, there is nothing much to be done with multiple file handling. Python's import mechanism just works like magic... > Most often, simply the ability to jump to the error line is provided > and I suppose that must be generally acceptable. vim does. From denis.spir at free.fr Mon Jun 15 10:23:51 2009 From: denis.spir at free.fr (spir) Date: Mon, 15 Jun 2009 10:23:51 +0200 Subject: [Tutor] Need a solution. In-Reply-To: References: <801768.57354.qm@web43401.mail.sp1.yahoo.com> <4A31D33D.30400@abbottdavid.com> <4A330AAA.6040807@abbottdavid.com> <20090613120914.62ceea2a@o> Message-ID: <20090615102351.5bff6715@o> Le Sat, 13 Jun 2009 13:55:58 +0100, "Alan Gauld" s'exprima ainsi: > I think that you have a valid point but that "pure value" objects > occur far less often than you might think. I always treat a value > object as a sign that I've probably put some processing code > in the wrong place! Only when I've checked and convinced > myself I'm wrong would I proceed. > > For example, what do we do with the values? > Do we print them? Then maybe we should have a __str__ method? > Do we save them in a file? Then maybe we need a save() method? > Do we do some calculations? Maybe we should have a calculate() method? > Do we draw them... well, I'm sure you get the idea :-) Yes, I guess I understand what you mean.?This is indeed a valid question as far as you consider these 'values' as top-level objects. What are there for, then, if obviously one cannot do much with them? Actually, it seems that only in the scientific field values are everywhere top-level things. Values _are_ the kind of things maths manipulate. Right? But in all other programming things, values are: attributes of higher level objects. Usually, top-level objects are "real" objects. Values determine, or specify them. Among the so-called 'data' attribute, there are values on one side that tell us information about the object, and sub-objects (think: components) on the other side. This is my point of view. It works for me; I don't mean it's better than any other one. Below, V means value, C means component. point position V color V console screen C keyboard C mouse C machine speed V power v engine C mandrill C Well, artificial examples are just this... still, "I'm sure you get the idea :-)" Denis ------ la vita e estrany From alan.gauld at btinternet.com Mon Jun 15 11:10:54 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Jun 2009 10:10:54 +0100 Subject: [Tutor] Need a solution. References: <801768.57354.qm@web43401.mail.sp1.yahoo.com><4A31D33D.30400@abbottdavid.com> <4A330AAA.6040807@abbottdavid.com> <20090613120914.62ceea2a@o> <20090615102351.5bff6715@o> Message-ID: "spir" wrote > Actually, it seems that only in the scientific field values are > everywhere top-level things. Values _are_ the kind of > things maths manipulate. Right? Thats an interesting observation that had not occured to me but I think you are right. What is interesting to me is that when I'm doing "pure" science/math type programmes I tend to adopt a functional style rather than an OO style. Functional programming just seems to suit the nature of math/science type problems for me. Alan G. From xchimeras at gmail.com Mon Jun 15 11:49:20 2009 From: xchimeras at gmail.com (Tom Green) Date: Mon, 15 Jun 2009 05:49:20 -0400 Subject: [Tutor] Best Python Editor In-Reply-To: References: <20090615023153.GA23272@titan.spiretech.com> Message-ID: This has been a great discussion and when I first entered college I was required to take Pascal. At that time we used Turbo Pascal IDE--if you want to call it an IDE. As with anything technology advances and we have new tools for the job and I became spoiled once Visual Studio hit the market. I really can't see doing any large project without a full blown IDE. Yes, vim or any text editor is suitable for Python, but I prefer having a nice GUI interface while coding. I mean the automobile replaced the horse and buggy, while they both get you to your destination I would still rather travel in a car. Regards, T.Green On Mon, Jun 15, 2009 at 2:00 AM, Lie Ryan wrote: > Michael Powe wrote: > > > It's good to see so much common sense prevailing on this topic. > > It's good that this newsgroup is not as prevalent to being flamed. In > certain other newsgroup, even (an honest and naive) mentioning of > preferred editor would turn the thread into World War E. > > > An > > IDE such as eclipse or VS really only becomes a necessity for > > productivity when (a) you are dealing with multiple code files and > > proper compilation and linking and so forth becomes complicated; or > > People that write in text editors often uses makefiles to handle that. > However, in python, there is nothing much to be done with multiple file > handling. Python's import mechanism just works like magic... > > > Most often, simply the ability to jump to the error line is provided > > and I suppose that must be generally acceptable. > > vim does. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tanderse at iastate.edu Sun Jun 14 22:04:39 2009 From: tanderse at iastate.edu (Tycho Andersen) Date: Sun, 14 Jun 2009 15:04:39 -0500 Subject: [Tutor] Audio Framework for Python Message-ID: <49b3a7400906141304w386cad6o7f0bf2d1031e9d0a@mail.gmail.com> All: I'm interested in writing a simple media player in python. I've been poking around on the internet for a framework that can play the common audio formats (mp3, flac, ogg, etc.), but I haven't found one that I liked a whole lot. PyMedia looks promising, but I've been struggling to build it on an x64 architecture. Does anyone have any suggestions? TIA! Tycho From kent37 at tds.net Mon Jun 15 13:53:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Jun 2009 07:53:16 -0400 Subject: [Tutor] Audio Framework for Python In-Reply-To: <49b3a7400906141304w386cad6o7f0bf2d1031e9d0a@mail.gmail.com> References: <49b3a7400906141304w386cad6o7f0bf2d1031e9d0a@mail.gmail.com> Message-ID: <1c2a2c590906150453i6499df6j98a4e1a1b3e34ee8@mail.gmail.com> On Sun, Jun 14, 2009 at 4:04 PM, Tycho Andersen wrote: > All: > > I'm interested in writing a simple media player in python. I've been > poking around on the internet for a framework that can play the common > audio formats (mp3, flac, ogg, etc.), but I haven't found one that I > liked a whole lot. > > PyMedia looks promising, but I've been struggling to build it on an > x64 architecture. Does anyone have any suggestions? Is there a PyMedia mailing list? You will probably get better answers there for build problems. You might also look at http://www.moovida.com/ Kent From zebra05 at gmail.com Mon Jun 15 14:45:08 2009 From: zebra05 at gmail.com (OkaMthembo) Date: Mon, 15 Jun 2009 14:45:08 +0200 Subject: [Tutor] Best Python Editor In-Reply-To: References: <4A3384D1.5030606@ieee.org> Message-ID: I second Tom Green, when i started off with Python i mainly used Pyscripter on Windows and its excellent. On Sat, Jun 13, 2009 at 1:48 PM, Tom Green wrote: > For Windows check out PyScripter. Its IDE is similar to Borland Delphi and > I find it very easy to use. Whatever works for you would be "best" for > you. PyScripter is FREE and I would highly recommend it for people who are > new to Python or people with programming experience that are used to > programming in a IDE. > > Regards, > T. Green > > > > On Sat, Jun 13, 2009 at 6:52 AM, Dave Angel wrote: > >> Eddie wrote: >> >> Hi guys, >>> >>> What would you regard as the best free Python editor to use on Windows >>> for a new guy? Searching Google i see that there is quite a few out >>> there and is "VIM" the best one to go with? >>> >>> Regards >>> Eddie >>> >>> >>> >> This is such a common question on the python forums it ought to be in a >> FAQ, and maybe it is. >> >> VI and EMACS are the two "standard" Unix editors, going back decades. >> Somebody used to the flexibility of either of those two, who is now stuck >> on Windows, would naturally not want to give up any of the "customizability" >> of these. And people have posted macros for each to automate some of the >> things you'd like for Python, such as auto-indent. VIM is an editor in that >> heritage. >> >> Somebody who's used Windows for 20 years, however, might expect that >> Ctrl-S, Ctrl-F4, Alt-F4, etc. have standard meanings. So they might be more >> comfortable in an editor that starts with the Windows interface, and builds >> on it. I use metapad for many things, though not for Python. Others use >> Notepad++. >> >> Next question is whether you want an IDE. The ability to single-step in >> the debugger, locate and fix a problem in source, and start again, in a >> single environment is appealing. When I have a stack trace showing in the >> debugger, I can use the debugger to locate the source at any level of that >> stack without having to explicitly load the file and jump to the specified >> line number. And no risk that the same file is already loaded into some >> other editor and I'm going to lose changes if some are made one place and >> some another. And of course, it's nice to have a locals window, a globals >> window, a watch window, ... >> >> People that do not like an IDE cite the advantage of using a single editor >> for several programming languages, for word processing, and for web design. >> If such an editor is highly programmable, that would seem very good as >> well. >> >> So then it comes down to opinion. I use the (not-free) Komodo IDE. There >> is a free Komodo-Edit with most of the same features, but I really don't >> know what subset it includes. It is programmable with many canned add-ins, >> or you can customize it yourself with recorded macros and with scripts in >> Python or (I think) Javascript. Its addin technology is related somehow to >> Firefox, and I think it used a lot of the Mozilla code in its engine. The >> default UI is very familiar to people with Windows experience, though I >> don't know how it works on Mac and Linux >> >> http://www.activestate.com/komodo/ Komodo IDE >> http://www.activestate.com/komodo_edit/ opensource Komodo Edit >> http://www.activestate.com/komodo_edit/comparison/ comparison between >> the two >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From connorsml at gmail.com Mon Jun 15 14:55:55 2009 From: connorsml at gmail.com (Michael Connors) Date: Mon, 15 Jun 2009 14:55:55 +0200 Subject: [Tutor] Best Python Editor In-Reply-To: References: <4A3384D1.5030606@ieee.org> Message-ID: Back when I used Windows I used this: http://www.crimsoneditor.com/ I think its not being developed anymore, but it is a great editor/IDE that supports many languages. -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: From jfabiani at yolo.com Mon Jun 15 15:30:50 2009 From: jfabiani at yolo.com (johnf) Date: Mon, 15 Jun 2009 06:30:50 -0700 Subject: [Tutor] Best Python Editor In-Reply-To: <20090615023153.GA23272@titan.spiretech.com> References: <20090615023153.GA23272@titan.spiretech.com> Message-ID: <200906150630.50573.jfabiani@yolo.com> On Sunday 14 June 2009 07:31:53 pm Michael Powe wrote: > > However, I will say that while following this thread, it occurred to > me that the one feature that VS and even the VBA editor in MS Office > has, is the ability to pop you into the debugger on error. This > feature is so useful that it surprises me nobody else seems to do it. > Most often, simply the ability to jump to the error line is provided > and I suppose that must be generally acceptable. > > Thanks. Wing does. When error occurs it stops on the line and the programmer is working in the debugger. -- John Fabiani From emile at fenx.com Mon Jun 15 15:34:04 2009 From: emile at fenx.com (Emile van Sebille) Date: Mon, 15 Jun 2009 06:34:04 -0700 Subject: [Tutor] Best Python Editor In-Reply-To: References: <20090615023153.GA23272@titan.spiretech.com> Message-ID: On 6/15/2009 2:49 AM Tom Green said... > Yes, vim or any text editor is suitable for Python, but I > prefer having a nice GUI interface while coding. I mean the automobile > replaced the horse and buggy, while they both get you to your > destination I would still rather travel in a car. Anyone know of any studies comparing text based vs GUI IDE based code development? As I recall, programming productivity is measured in LOC/day and last time I noticed it seemed to be a very small number. I'm wondering if there might be documented benefits to migrating from my horse and buggy. :) Emile From worminater at gmail.com Mon Jun 15 18:22:31 2009 From: worminater at gmail.com (Chris Mueller) Date: Mon, 15 Jun 2009 12:22:31 -0400 Subject: [Tutor] Best Python Editor In-Reply-To: <333efb450906140716x2d5f97edy6b61c7ed63d89774@mail.gmail.com> References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> <87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com> <333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com> <87d8ca690906131802o4802abb1r186bdb4989e8e9f3@mail.gmail.com> <333efb450906140716x2d5f97edy6b61c7ed63d89774@mail.gmail.com> Message-ID: <940dc7890906150922m7a55b1d8ybe274a53f70e764@mail.gmail.com> for note; full tag completion and tag support can be used in vim via omnicompletion and taglists. Full class support/heiarchy + printing of the docscrint as you ctrl-n through each completion in the preview window. Extremly useful when using someone else's library or for remembering what to pass in; and mostly native to vim. I have never used a debugger (i usually use break points and prints, with a quick e to run and examine output); but I would assume it's there if you want it as I have seen GDB integration (as well as any VCS you would want, which suprises me that has not come up yet.) It just comes down to whether you want ot make the learning investment or not. After using it for awhile; your workflow just; well; flows. This to me is the biggest complement to an editor. Thanks, Chris On Sun, Jun 14, 2009 at 10:16 AM, Wayne wrote: > On Sun, Jun 14, 2009 at 5:55 AM, Tom Green wrote: > >> Since VIM seems to be the editor of choice and I have been programming in >> Python for many years using Pyscripter and Eclipse I was wondering how I >> could transition away from the IDE world to VIM. My main issue is how do I >> go about using VIM to debug my code? > > > I usually use print statements and/or raw_input's if you want break points. > > >> With Pyscripter and other IDES its as simple as placing a breakpoint and >> pressing F7 to step thru the code and you have the ability to see the >> variable values etc. > > > I know you can do some similar things with the python debugger but I've > honestly never used it that much (or worked on a project large enough I > needed to!) > > >> Also, with an IDE such as Pyscripter when calling a function a nice >> balloon hint appears showing you the number of parameters and their types. > > > It's not precisely the same thing, but you can fold multiple lines, which > allows you to have only the top line of a function showing. I find that > rather helpful, and ctrl-n autocompletes the function name. Then you can > mark the location with m then a-to-z (I use c as a mnemonic for 'current') > then move on top of the name and push * - that will find the next occurence > of the word, which is often the function declaration. I just hit "n" (next) > until I find it, if that's not the case. Then I type ` (the one over the > tilde) then c which takes me back to my 'current' location. If you really > wanted, though, you could also have horizontal split of the same file, and > you could probably write a macro that would move to that window/buffer and > find the function declaraition (so it would search for def under cursor>). I don't know precisely how the dropdown autocomplete menu > works but you could also probably edit your script to add parameters for the > function call just like an IDE. > > >> Coming from a Visual Studio background this is great, as I might be >> calling a function or method and I don't know off hand the values. Maybe >> someone could share how they go about programming a good size program with >> VIM as I would like to use it. Don't get me wrong for quick programs I will >> use VIM or notepad, but when it comes to building a OOP program I find >> Eclipse or Pyscripter much easier to use. > > > I suppose that's probably the case for a few people - and certainly the > reason those tools exist in the first place. If I were working on a quite > large program I might consider using an IDE, but in reality I'm probably > just as comfortable jumping around code to look for the information I need > as I would be using an IDE. > > HTH, > Wayne > > >> On Sun, Jun 14, 2009 at 12:54 AM, Eddie wrote: >> >>> I downloaded the previous version of PyScripter although couldn't get >>> it to work and after googling it, I downloaded Python Portable 1.1 >>> (Python 2.6.1 as most sites/books recommend this and not 3) which has >>> PySCripter included and this then works fine.Ii also downloaded Komod0 >>> 5.1 and after messing around with these, I think I prefer PyScripter >>> and will use that for the mean time. >>> >>> I'll also take a look at VIM as being able to use the same program for >>> PHP/CSS/HTML (and Basic if it supports it) as well as hopefully Python >>> (I've only just started learning it) would be an advantage. >>> >>> Thanks guys >>> Eddie >>> >>> 2009/6/14 Mike Hoy : >>> >> >>> >> >>> >> I really like using F5 to run my code, so you can put in your .vimrc >>> so >>> >> you don't have to type it, or just type it every time: >>> >> >>> >> map :!python % >>> >> >>> >> and every time you hit it will run your current script. >>> >> >>> > Thanks for that. It's even better than typing :!python % because it >>> doesn't >>> > spawn a shell separate from the Vim window. >>> > >>> > _______________________________________________ >>> > Tutor maillist - Tutor at python.org >>> > http://mail.python.org/mailman/listinfo/tutor >>> > >>> > >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > To be considered stupid and to be told so is more painful than being called > gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, > every vice, has found its defenders, its rhetoric, its ennoblement and > exaltation, but stupidity hasn?t. - Primo Levi > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 15 18:29:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Jun 2009 17:29:42 +0100 Subject: [Tutor] Best Python Editor References: <20090615023153.GA23272@titan.spiretech.com> Message-ID: "Emile van Sebille" wrote > Anyone know of any studies comparing text based vs GUI IDE based code > development? As I recall, programming productivity is measured in > LOC/day and last time I noticed it seemed to be a very small number. When I started in "software engineering" (c1985) the typical value was between 8-10 lines of working code per person per day. After PCs (and Unix workstations) became the norm the figure slowly rose to around 12-15. With the latest tools I suspect it might be getting close to breaking 20. (On small projects it will be much higher, this is an industry average remember) But i haven't seen a published figure for at least 5 years, if not more! > I'm wondering if there might be documented benefits to migrating from my > horse and buggy. :) Most improvements in productivity were down to things like seeing more than 24 lines of code at a time and faster navigation, as well as much faster compilatrion speeds (who remembers the days of limits on the number of compiles you could do per day - usually 3 or 4 - or the days when a full build was measured in hours, sometimes days (I worked on one project where we could only do a full build on a Friday night because it didn't finish until late Sunday afternoon...). The IDE doesn't add a huge amount of improvement, and the real issues holding down the figures are those that Fred Brooks called the "essential problems" - like understanding the requirements, defining an architecture etc - as well as regression testing etc. Even with test automation it still takes us 6 weeks to run a full regression test of some of our bigger projects. (Down from 16 though! :-) As for tests comparing text based editing v mouse driven those are very inconclusive and, I suspect, reflect the bias of the tester. Back when the Mac first came out(1984?) Apple showed that WYSIWYG word processors were much faster than older text styles(Wordstar etc) but then Wordstar showed that text based documents had fewer errors and gained students higher marks... I've certainly seen comparisons going both ways for programmer's editors. The one constant is that for pure text editing vi is usually fastest in the hands of an expert(*) even compared to emacs. But programmers do so much more than simply editing text! (*)The old DOS editor Brief ran it a very close second. Brief morphed into an Opensource GUI editor after Windows 3 came out (and Borland bought Brief) but I've forgotten the name and haven't heard of it for years. ....Wikipedia to the rescue - CrisP was the name and it was Unix only apparently. Then did the very unusual thing of going from Opensource to commercial! Its still going with a release in 2008. Ahh, nostalgia :-) Alan G. From vincent at vincentdavis.net Mon Jun 15 19:55:18 2009 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 15 Jun 2009 11:55:18 -0600 Subject: [Tutor] 3.0 on Mac In-Reply-To: <4A31D160.3000409@ieee.org> References: <4A31D160.3000409@ieee.org> Message-ID: <77e831100906151055p5ab46ad0t199c0795ab945649@mail.gmail.com> Here is what my .bash_profile looks like, This is in my user directory " # Setting PATH for EPD_Py25 v4.3.0 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:${PATH}" export PATH PYTHONPATH="/Volumes/iDisk/match/python" export PYTHONPATH " Note that the file "/Library/Frameworks/Python.framework/Versions/Current" is a symbolic link to the actual python. You could change the smbolic link or pint the Bash_profile directly to the python you want. I also found it difficult to understand the PYTHONPATH, As yu see it above Python will look in my idisk for modules to import. So if I have a file names mymod.py in /Volumes/iDisk/match/python and I "import mymod" it will find it. Hope this helps, When I was learning abut python I found it difficult to find spisific instructins for this. Part of the problem Is that it seems that most instruction assume some understanding of terminal than I had. I know little more that what allows me to follow clear instructions. Thanks Vincent Davis 720-301-3003 On Thu, Jun 11, 2009 at 9:54 PM, Dave Angel wrote: > acfleck wrote: > > I'm a Python nubie and having trouble with 3.0.1 on Mac (10.4.11). I did a >> default install of MacPython 3.0.1. The IDLE.app works fine, but from a >> Terminal window, the 'python' command still gets me V2.5.3 (the original >> Apple installed version). A 'python3' command is not recognized. I'd like to >> know what I need to change to access V3.0.1 from a Terminal window. >> >> > Use the 'which' command to see what versions of python are on your PATH. > Then, since you have two different versions of Python you want available, > create one or more scripts (on your path), to explicitly run the other > installed versions. Probably, those scripts can be one line each, though > you also might conceivably want to set an environment variable or two (such > as pythonpath) > > > As far as I know, the install will not create a script called python3, or > anything else like it. That's up to you. And it's generally not good form > to hide the system-installed version, since many utilities and scripts might > depend on that particular version. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at trollope.org Mon Jun 15 20:50:33 2009 From: michael at trollope.org (Michael Powe) Date: Mon, 15 Jun 2009 11:50:33 -0700 Subject: [Tutor] Best Python Editor In-Reply-To: <200906150630.50573.jfabiani@yolo.com> References: <20090615023153.GA23272@titan.spiretech.com> <200906150630.50573.jfabiani@yolo.com> Message-ID: <20090615185033.GB23272@titan.spiretech.com> On Mon, Jun 15, 2009 at 06:30:50AM -0700, johnf wrote: > On Sunday 14 June 2009 07:31:53 pm Michael Powe wrote: > > However, I will say that while following this thread, it occurred to > > me that the one feature that VS and even the VBA editor in MS Office > > has, is the ability to pop you into the debugger on error. This > > feature is so useful that it surprises me nobody else seems to do it. > > Most often, simply the ability to jump to the error line is provided > > and I suppose that must be generally acceptable. > Wing does. When error occurs it stops on the line and the programmer is > working in the debugger. Hello, I'll have to look at that. I have a kind of collection of editors -- the way I collect books, I guess. TextPad, vbsEdit, UltraEdit, SciTE, XmlCopyEditor, EditPlus, emacs. I never do anything with vi except munge conf files. For actual "projects" I use VS and NetBeans. When I get on a "back to basics" kick, I re-enter emacs. It used to be a joke about emacs not being an editor but an operating system. There is nothing on the linux side that even comes close, IMO. I don't like GUI-based stuff, though, so right off, any editor built on the assumption that I'm a mouse-oriented user is right out. Thanks. mp From michael at trollope.org Mon Jun 15 21:14:57 2009 From: michael at trollope.org (Michael Powe) Date: Mon, 15 Jun 2009 12:14:57 -0700 Subject: [Tutor] Best Python Editor In-Reply-To: References: <20090615023153.GA23272@titan.spiretech.com> Message-ID: <20090615191457.GC23272@titan.spiretech.com> On Mon, Jun 15, 2009 at 06:34:04AM -0700, Emile van Sebille wrote: > On 6/15/2009 2:49 AM Tom Green said... > >Yes, vim or any text editor is suitable for Python, but I > >prefer having a nice GUI interface while coding. I mean the automobile > >replaced the horse and buggy, while they both get you to your > >destination I would still rather travel in a car. > Anyone know of any studies comparing text based vs GUI IDE based code > development? As I recall, programming productivity is measured in > LOC/day and last time I noticed it seemed to be a very small number. > I'm wondering if there might be documented benefits to migrating from my > horse and buggy. :) Are you in a hurry to get somewhere? ;-) I recently worked on a module for a large existing Java application. The module I wrote had to be plugged in to the existing code base. So of course, I had to have all kinds of tie-ins to existing libraries and classes. First, I couldn't run the full application, so I had to rely on unit testing to verify my functionality. Second, I had to connect to hundreds of classes inside the application. I'm not that smart -- I could not have done it without NetBeans, which has fantastic introspection and can tell me most of the ways I'm violating protocol while I'm working. I stubbed out a lot of stuff and prototyped in jEdit. But when it was game on, I had to go to NB. It probably comes down to, How much stuff can you carry in your head? Thanks. mp From cosmicsand27 at yahoo.com Mon Jun 15 22:00:27 2009 From: cosmicsand27 at yahoo.com (Raj Medhekar) Date: Mon, 15 Jun 2009 13:00:27 -0700 (PDT) Subject: [Tutor] Help Needed Message-ID: <379876.64326.qm@web43411.mail.sp1.yahoo.com> I am looking to build a program that gets a message from the user and then prints it backward. I 've been at it for hours now but I can't seem to figure it out. I've been having trouble trying to index the message so I can print it out backwards. I would've posted my code but I really haven't gotten past the 'raw_input("Enter a message: ")' command line. Any help is gladly appreciated. Thanks! -Raj -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Mon Jun 15 22:11:43 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Mon, 15 Jun 2009 16:11:43 -0400 Subject: [Tutor] Help Needed In-Reply-To: <379876.64326.qm@web43411.mail.sp1.yahoo.com> References: <379876.64326.qm@web43411.mail.sp1.yahoo.com> Message-ID: Hi Raj, It might be easier if you create a simple test string inside the python interpreter and then tinker with it there. once you've found the solution, you can graft it onto the broader program that accepts user input. For example, you might create the following variable message = "This is a message" And then try splitting that message based on spaces and then using the "reverse" list method to switch the order. Or you could iterate through each character in the string and add it to a list, then apply the reverse method. Not sure precisely what you're getting at, but a little experimentation in the interpreter will probably lead you to a solution. HTH, Serdar From srilyk at gmail.com Mon Jun 15 23:28:11 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 15 Jun 2009 16:28:11 -0500 Subject: [Tutor] Help Needed In-Reply-To: <379876.64326.qm@web43411.mail.sp1.yahoo.com> References: <379876.64326.qm@web43411.mail.sp1.yahoo.com> Message-ID: <333efb450906151428q7fa86d6dha35fc573d87e1b9e@mail.gmail.com> On Mon, Jun 15, 2009 at 3:00 PM, Raj Medhekar wrote: > I am looking to build a program that gets a message from the user and then > prints it backward. I 've been at it for hours now but I can't seem to > figure it out. I've been having trouble trying to index the message so I can > print it out backwards. I would've posted my code but I really haven't > gotten past the 'raw_input("Enter a message: ")' command line. Any help is > gladly appreciated. Thanks! > Python treats a string like a list/array. In [1]: mystr = "I'm not a witch!" In [2]: mystr[0] Out[2]: 'I' Same goes for one that's defined with raw_input: In [4]: mystr = raw_input("She turned you into a newt? ") She turned you into a newt? I got better! In [5]: mystr[0] + mystr[1:] Out[5]: 'I got better!' Python has a slice operator the colon, so mystr[0] gives me the character at 0, and mystr[1:] gives me everything from the first character to the end (if you add something after the colon it will only return whatever is up to that point: In [10]: mystr[2:5] Out[10]: 'got' If you know what a loop is, you should be able to figure out how to get the result you're looking for. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Mon Jun 15 23:42:35 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 15 Jun 2009 16:42:35 -0500 Subject: [Tutor] Best Python Editor In-Reply-To: <20090615185033.GB23272@titan.spiretech.com> References: <20090615023153.GA23272@titan.spiretech.com> <200906150630.50573.jfabiani@yolo.com> <20090615185033.GB23272@titan.spiretech.com> Message-ID: <333efb450906151442n75bf461bk10ce3dc44dfaed8c@mail.gmail.com> On Mon, Jun 15, 2009 at 1:50 PM, Michael Powe wrote: > I don't like GUI-based stuff, > though, so right off, any editor built on the assumption that I'm a > mouse-oriented user is right out. That's why I'm a solid vim user. I can't stand touching the mouse when I'm coding. It just breaks up the flow of typing. I heard it mentioned before and I feel the same way - I have to switch to a different mindset to move around instead of push buttons. Of course, now that I have one of those eraser mouses in the middle of my laptop it's really hard to use a real mouse for anything except graphics editing. The mouse wins there, and gaming, and that's really it for me. -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 16 01:57:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Jun 2009 00:57:00 +0100 Subject: [Tutor] Help Needed References: <379876.64326.qm@web43411.mail.sp1.yahoo.com> Message-ID: "Raj Medhekar" wrote >I am looking to build a program that gets a message from > the user and then prints it backward. I 've been at it for > hours now but I can't seem to figure it out. So tell us what you re thinking? How would you solve it manually? > I've been having trouble trying to index the message > so I can print it out backwards. You can index the characters of a string in Python exactly as you do a list. > I would've posted my code but I really haven't gotten > past the 'raw_input("Enter a message: ")' command line. Its always better to try something even if its wrong, it lets us see where your thinking is going adrift. Or at least describe what you'd like to do conceptually. Alan G. From gilcosson_2000 at yahoo.com Tue Jun 16 08:53:03 2009 From: gilcosson_2000 at yahoo.com (Gil Cosson) Date: Mon, 15 Jun 2009 23:53:03 -0700 (PDT) Subject: [Tutor] Help Needed Message-ID: <689147.52804.qm@web35602.mail.mud.yahoo.com> I just stumbled on this Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> s="hello world" >>> s=s[::-1] >>> print s dlrow olleh >>> --- Gil Cosson Bremerton, Washington 360 620 0431 --- On Mon, 6/15/09, Wayne wrote: From: Wayne Subject: Re: [Tutor] Help Needed To: "Raj Medhekar" Cc: "Python Tutor" Date: Monday, June 15, 2009, 5:28 PM On Mon, Jun 15, 2009 at 3:00 PM, Raj Medhekar wrote: I am looking to build a program that gets a message from the user and then prints it backward. I 've been at it for hours now but I can't seem to figure it out. I've been having trouble trying to index the message so I can print it out backwards. I would've posted my code but I really haven't gotten past the? 'raw_input("Enter a message: ")' command line.? Any help is gladly appreciated. Thanks! Python treats a string like a list/array. In [1]: mystr = "I'm not a witch!" In [2]: mystr[0] Out[2]: 'I' Same goes for one that's defined with raw_input: In [4]: mystr = raw_input("She turned you into a newt? ") She turned you into a newt? I got better! In [5]: mystr[0] + mystr[1:] Out[5]: 'I got better!' Python has a slice operator the colon, so mystr[0] gives me the character at 0, and mystr[1:] gives me everything from the first character to the end (if you add something after the colon it will only return whatever is up to that point: In [10]: mystr[2:5] Out[10]: 'got' If you know what a loop is, you should be able to figure out how to get the result you're looking for. HTH, Wayne -----Inline Attachment Follows----- _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From fe78bi at yahoo.com Tue Jun 16 13:19:16 2009 From: fe78bi at yahoo.com (Febin Ameer Ahsen) Date: Tue, 16 Jun 2009 16:49:16 +0530 (IST) Subject: [Tutor] (no subject) Message-ID: <374794.51680.qm@web94812.mail.in2.yahoo.com> how to link two files in python Bollywood news, movie reviews, film trailers and more! Go to http://in.movies.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Tue Jun 16 14:04:42 2009 From: fomcl at yahoo.com (Albert-jan Roskam) Date: Tue, 16 Jun 2009 05:04:42 -0700 (PDT) Subject: [Tutor] Help Needed Message-ID: <131819.68867.qm@web110715.mail.gq1.yahoo.com> Hi, This is how I would do it, although there might be more readable solutions: s = raw_input("Enter a message: ") print "".join([s[-letter] for letter in range(len(s)+1)]) Cheers!! Albert-Jan --- On Tue, 6/16/09, Alan Gauld wrote: > From: Alan Gauld > Subject: Re: [Tutor] Help Needed > To: tutor at python.org > Date: Tuesday, June 16, 2009, 1:57 AM > > "Raj Medhekar" > wrote > > > I am looking to build a program that gets a message > from the user and then prints it backward. I 've been at it > for hours now but I can't seem to figure it out. > > So tell us what you re thinking? How would you solve it > manually? > > > I've been having trouble trying to index the message > so I can print it out backwards. > > You can index the characters of a string in Python exactly > as you do a list. > > > I would've posted my code but I really haven't gotten > past the? 'raw_input("Enter a message: ")' command > line.? > > Its always better to try something even if its wrong, it > lets us see where your thinking is going adrift. Or at least > describe what you'd like to do conceptually. > > Alan G. > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From srilyk at gmail.com Tue Jun 16 14:08:24 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 16 Jun 2009 07:08:24 -0500 Subject: [Tutor] (no subject) In-Reply-To: <374794.51680.qm@web94812.mail.in2.yahoo.com> References: <374794.51680.qm@web94812.mail.in2.yahoo.com> Message-ID: <333efb450906160508y68278a9dr24362f90b7838570@mail.gmail.com> On Tue, Jun 16, 2009 at 6:19 AM, Febin Ameer Ahsen wrote: > how to link two files in python A few tips on getting good replies: 1) Start with a descriptive subject, such as "importing a file" or "appending one file to another" 2) Actually ask a question and describe what you're trying to do. Without a question mark '?' all you are doing is making a statement. Even if you're asking a question in a non-native language, you should still be able to use somewhat proper punctuation! When you describe what you're trying to do, try to be as accurate as possible. When you say "link two files", that's very open ended. What type of files are you trying to link? How are you trying to link them? Do you have two text files that need to be embedded somehow? Do you have two python files, and you want to include the code from one in the other? Do you have an audio file you want to link with a video file? If you can give us a good idea about what you want, you will likely get a helpful response. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From tiwariabhishekin at gmail.com Tue Jun 16 15:52:04 2009 From: tiwariabhishekin at gmail.com (Abhishek Tiwari) Date: Tue, 16 Jun 2009 19:22:04 +0530 Subject: [Tutor] which is better solution of the question In-Reply-To: <50d982690906160650u5f55781dted45a6478644c40@mail.gmail.com> References: <50d982690906160650u5f55781dted45a6478644c40@mail.gmail.com> Message-ID: <50d982690906160652s35c7c3ccq90b408953509fe37@mail.gmail.com> *Question :* The first list contains some items, and the second list contains their value (higher is better). items = [apple, car, town, phone] values = [5, 2, 7, 1] Show how to sort the 'items' list based on the 'values' list so that you end up with the following two lists: items = [town, apple, car, phone] values = [7, 5, 2, 1] *Ans. 1* values, items = list(zip(*sorted(zip(values,items), reverse=True))) *Ans. 2* new_values = sorted(values, reverse=True) new_items = [items[x] for x in map(values.index,new_values)] I would like to know which method is better and why? -- With Regards, Abhishek Tiwari -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.serrato at gmail.com Tue Jun 16 16:15:29 2009 From: benjamin.serrato at gmail.com (Benjamin Serrato) Date: Tue, 16 Jun 2009 09:15:29 -0500 Subject: [Tutor] Tutor Digest, Vol 64, Issue 80 In-Reply-To: References: Message-ID: Wayne already explained slicing but I would like to point out the digit after the second colon changes the default step of the slice. Usually it defaults to 1, here because no values were given it takes the entire string and steps backward. You could set it to 2. First digit, beginning of slice, second digit end of slice, third digit is the jump to the next item in the sequence. HTH, Ben S. > Message: 2 > Date: Mon, 15 Jun 2009 23:53:03 -0700 (PDT) > From: Gil Cosson > To: Raj Medhekar , Wayne > Cc: Python Tutor > Subject: Re: [Tutor] Help Needed > Message-ID: <689147.52804.qm at web35602.mail.mud.yahoo.com> > Content-Type: text/plain; charset="iso-8859-1" > > I just stumbled on this > > Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> s="hello world" > >>> s=s[::-1] > >>> print s > dlrow olleh > >>> > > --- > > Gil Cosson > > Bremerton, Washington > > 360 620 0431 > From srilyk at gmail.com Tue Jun 16 16:23:14 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 16 Jun 2009 09:23:14 -0500 Subject: [Tutor] which is better solution of the question In-Reply-To: <50d982690906160652s35c7c3ccq90b408953509fe37@mail.gmail.com> References: <50d982690906160650u5f55781dted45a6478644c40@mail.gmail.com> <50d982690906160652s35c7c3ccq90b408953509fe37@mail.gmail.com> Message-ID: <333efb450906160723k793126fek31255397fdb9c891@mail.gmail.com> On Tue, Jun 16, 2009 at 8:52 AM, Abhishek Tiwari wrote: > *Question :* > The first list contains some items, and the second list contains their > value (higher is better). > > items = [apple, car, town, phone] > values = [5, 2, 7, 1] > > Show how to sort the 'items' list based on the 'values' list so that you > end up with the following two lists: > > items = [town, apple, car, phone] > values = [7, 5, 2, 1] > > *Ans. 1* > > values, items = list(zip(*sorted(zip(values,items), reverse=True))) > > *Ans. 2* > new_values = sorted(values, reverse=True) > new_items = [items[x] for x in map(values.index,new_values)] > > I would use a dict to store the values: {1:'phone', 5:'apple', 2:'car', 7:'town'} - then you just use sorted(mydict.keys(), reverse=True) to access them in a big-endian (most important) first, or without reverse if I wanted the least important value. This assumes that you can't have two values of the same weight, of course. If you're looking for speed, I'd look at timeit: http://docs.python.org/library/timeit.html I don't know which is considered more pythonic, though, so I'm afraid I can't be of much more help than that. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 16 16:32:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Jun 2009 15:32:41 +0100 Subject: [Tutor] which is better solution of the question References: <50d982690906160650u5f55781dted45a6478644c40@mail.gmail.com> <50d982690906160652s35c7c3ccq90b408953509fe37@mail.gmail.com> Message-ID: "Abhishek Tiwari" wrote > *Ans. 1* > > values, items = list(zip(*sorted(zip(values,items), reverse=True))) Personally I find that just a bit too dense so I'd break it out to: s = sorted(zip(values,items), reverse=True) values = [v for v,i in s] items = [i for v,i in s] > *Ans. 2* > new_values = sorted(values, reverse=True) > new_items = [items[x] for x in map(values.index,new_values)] I prefer this to the one-liner but don't like the map inside the comprehension. But as the old Irish saying goes: "If I was going there I wouldn't start from here!" >From a purely readability point of view, and if I had any control over the data formats I'd personally convert it to a dictionary of value,item pairs and not bother with two lists. Sorting then becomes a unified operation. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Tue Jun 16 16:49:40 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Jun 2009 10:49:40 -0400 Subject: [Tutor] which is better solution of the question In-Reply-To: <50d982690906160652s35c7c3ccq90b408953509fe37@mail.gmail.com> References: <50d982690906160650u5f55781dted45a6478644c40@mail.gmail.com> <50d982690906160652s35c7c3ccq90b408953509fe37@mail.gmail.com> Message-ID: <1c2a2c590906160749h69f76548hdf71662a88959c03@mail.gmail.com> On Tue, Jun 16, 2009 at 9:52 AM, Abhishek Tiwari wrote: > Question : > The first list contains some items, and the second list contains their value > (higher is better). > > items = [apple, car, town, phone] > values = [5, 2, 7, 1] > > Show how to sort the 'items' list based on the 'values' list so that you end > up with the following two lists: > > items = [town, apple, car, phone] > values = [7, 5, 2, 1] > > Ans. 1 > > values, items = list(zip(*sorted(zip(values,items), reverse=True))) I like this one though the list() is not needed. > Ans. 2 > new_values = sorted(values, reverse=True) > new_items = [items[x] for x in map(values.index,new_values)] This will become slow (O(n*n)) if the lists are large because it has to scan the values list for each entry in new_values. If you don't really need the sorted values list, you can use dictionary lookup to get keys: In [5]: ranks = dict(zip(items, values)) In [6]: ranks Out[6]: {'apple': 5, 'car': 2, 'phone': 1, 'town': 7} In [8]: sorted(items, key=ranks.__getitem__, reverse=True) Out[8]: ['town', 'apple', 'car', 'phone'] You could pull the sorted ranks from the dict or just sort values independently: In [9]: new_values = [ ranks[item] for item in _8] In [10]: new_values Out[10]: [7, 5, 2, 1] My guess is that the overhead of creating the dict and doing the lookups will make this slower than your first version but that is just a guess. timeit is your friend if speed is your metric. How do you measure "better"? Speed, clarity, ...? Kent From emile at fenx.com Tue Jun 16 17:32:33 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 16 Jun 2009 08:32:33 -0700 Subject: [Tutor] which is better solution of the question In-Reply-To: <1c2a2c590906160749h69f76548hdf71662a88959c03@mail.gmail.com> References: <50d982690906160650u5f55781dted45a6478644c40@mail.gmail.com> <50d982690906160652s35c7c3ccq90b408953509fe37@mail.gmail.com> <1c2a2c590906160749h69f76548hdf71662a88959c03@mail.gmail.com> Message-ID: On 6/16/2009 7:49 AM Kent Johnson said... > How do you measure "better"? Speed, clarity, ...? ... or the first method you think of that gives the right result. Where else would you find your keys once you've found them? Emile From ricaraoz at gmail.com Tue Jun 16 17:32:59 2009 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 16 Jun 2009 12:32:59 -0300 Subject: [Tutor] Best Python Editor In-Reply-To: References: <14097103.1244904031275.JavaMail.root@mswamui-valley.atl.sa.earthlink.net> <1244910171.3938.1320224125@webmail.messagingengine.com> <87d8ca690906131740p2787d3f3h11485b9976a32569@mail.gmail.com> <333efb450906131757n324fbe6ci430b212574b123db@mail.gmail.com> <87d8ca690906131802o4802abb1r186bdb4989e8e9f3@mail.gmail.com> Message-ID: <4A37BB2B.9030400@gmail.com> Eddie wrote: > I downloaded the previous version of PyScripter although couldn't get > it to work and after googling it, I downloaded Python Portable 1.1 > (Python 2.6.1 as most sites/books recommend this and not 3) which has > PySCripter included and this then works fine.Ii also downloaded Komod0 > 5.1 and after messing around with these, I think I prefer PyScripter > and will use that for the mean time. > > I'll also take a look at VIM as being able to use the same program for > PHP/CSS/HTML (and Basic if it supports it) as well as hopefully Python > (I've only just started learning it) would be an advantage. > > Thanks guys > Eddie > You might also check SPE (Stani's Python Editor), it's good. From lie.1296 at gmail.com Tue Jun 16 19:40:25 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 17 Jun 2009 03:40:25 +1000 Subject: [Tutor] which is better solution of the question In-Reply-To: <50d982690906160652s35c7c3ccq90b408953509fe37@mail.gmail.com> References: <50d982690906160650u5f55781dted45a6478644c40@mail.gmail.com> <50d982690906160652s35c7c3ccq90b408953509fe37@mail.gmail.com> Message-ID: Abhishek Tiwari wrote: > *Question :* > The first list contains some items, and the second list contains their > value (higher is better). > > items = [apple, car, town, phone] > values = [5, 2, 7, 1] > > Show how to sort the 'items' list based on the 'values' list so that you > end up with the following two lists: > > items = [town, apple, car, phone] > values = [7, 5, 2, 1] > > *Ans. 1* > > values, items = list(zip(*sorted(zip(values,items), reverse=True))) > > *Ans. 2* > new_values = sorted(values, reverse=True) > new_items = [items[x] for x in map(values.index,new_values)] > > > I would like to know which method is better and why? Don't know about being better, but this is another alternative: >>> keygen = iter(values) >>> sorted(items, key=lambda x: next(keygen), reverse=True) I'm thinking that maybe sorted/sort should accept a keylist= argument that takes a list/tuple/iterable of keys, so we can write it like this: >>> sorted(items, keylist=values, reverse=True) what do you think? From xchimeras at gmail.com Tue Jun 16 19:46:23 2009 From: xchimeras at gmail.com (xchimeras at gmail.com) Date: Tue, 16 Jun 2009 17:46:23 +0000 Subject: [Tutor] Conversion question Message-ID: <1644742819-1245174188-cardhu_decombobulator_blackberry.rim.net-1031235909-@bxe1291.bisx.prod.on.blackberry> Quick question. Say I have a string a="Man" and I want to print the string in base2. Is there a python function like there is in perl to do this? Thanks in advance for any input Sent from my Verizon Wireless BlackBerry From srilyk at gmail.com Tue Jun 16 20:13:58 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 16 Jun 2009 13:13:58 -0500 Subject: [Tutor] Conversion question In-Reply-To: <1644742819-1245174188-cardhu_decombobulator_blackberry.rim.net-1031235909-@bxe1291.bisx.prod.on.blackberry> References: <1644742819-1245174188-cardhu_decombobulator_blackberry.rim.net-1031235909-@bxe1291.bisx.prod.on.blackberry> Message-ID: <333efb450906161113t3dd60a84g5d1987fd6a4747c7@mail.gmail.com> On Tue, Jun 16, 2009 at 12:46 PM, wrote: > Quick question. Say I have a string a="Man" and I want to print the string > in base2. Is there a python function like there is in perl to do this? > Thanks in advance for any input do you mean like this: In [23]: int('Man', 2) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/wayne/ in () ValueError: invalid literal for int() with base 2: 'Man' Or do you mean this? In [24]: mystr = 'some string' In [25]: mystr.encode('hex') Out[25]: '736f6d6520737472696e67' HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From xchimeras at gmail.com Tue Jun 16 20:21:10 2009 From: xchimeras at gmail.com (xchimeras at gmail.com) Date: Tue, 16 Jun 2009 18:21:10 +0000 Subject: [Tutor] Conversion question In-Reply-To: <333efb450906161113t3dd60a84g5d1987fd6a4747c7@mail.gmail.com> References: <1644742819-1245174188-cardhu_decombobulator_blackberry.rim.net-1031235909-@bxe1291.bisx.prod.on.blackberry><333efb450906161113t3dd60a84g5d1987fd6a4747c7@mail.gmail.com> Message-ID: <1289589405-1245176270-cardhu_decombobulator_blackberry.rim.net-93337559-@bxe1291.bisx.prod.on.blackberry> Thanks for the reply I would like to print the string in binary Man=010011010110000101101110 Sent from my Verizon Wireless BlackBerry -----Original Message----- From: Wayne Date: Tue, 16 Jun 2009 13:13:58 To: Cc: Subject: Re: [Tutor] Conversion question On Tue, Jun 16, 2009 at 12:46 PM, wrote: > Quick question. Say I have a string a="Man" and I want to print the string > in base2. Is there a python function like there is in perl to do this? > Thanks in advance for any input do you mean like this: In [23]: int('Man', 2) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/wayne/ in () ValueError: invalid literal for int() with base 2: 'Man' Or do you mean this? In [24]: mystr = 'some string' In [25]: mystr.encode('hex') Out[25]: '736f6d6520737472696e67' HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Jun 16 21:05:27 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 17 Jun 2009 05:05:27 +1000 Subject: [Tutor] Conversion question In-Reply-To: <1289589405-1245176270-cardhu_decombobulator_blackberry.rim.net-93337559-@bxe1291.bisx.prod.on.blackberry> References: <1644742819-1245174188-cardhu_decombobulator_blackberry.rim.net-1031235909-@bxe1291.bisx.prod.on.blackberry><333efb450906161113t3dd60a84g5d1987fd6a4747c7@mail.gmail.com> <1289589405-1245176270-cardhu_decombobulator_blackberry.rim.net-93337559-@bxe1291.bisx.prod.on.blackberry> Message-ID: xchimeras at gmail.com wrote: > Thanks for the reply I would like to print the string in binary > Man=010011010110000101101110 > What's M in binary? Nobody knows... What's M in encoded in 8-bit ASCII string: '0b1001101' Source: bin(ord('M')) From xchimeras at gmail.com Tue Jun 16 21:25:58 2009 From: xchimeras at gmail.com (Tom Green) Date: Tue, 16 Jun 2009 15:25:58 -0400 Subject: [Tutor] Conversion question In-Reply-To: References: <1644742819-1245174188-cardhu_decombobulator_blackberry.rim.net-1031235909-@bxe1291.bisx.prod.on.blackberry> <333efb450906161113t3dd60a84g5d1987fd6a4747c7@mail.gmail.com> <1289589405-1245176270-cardhu_decombobulator_blackberry.rim.net-93337559-@bxe1291.bisx.prod.on.blackberry> Message-ID: Correct 8-bit ASCII. Sorry about that. I am using Python 2.5.2, which doesn't support bin. If I upgraded how would I go about converting the entire string to 8-bit ASCII? I appreciate your help. On Tue, Jun 16, 2009 at 3:05 PM, Lie Ryan wrote: > xchimeras at gmail.com wrote: > > Thanks for the reply I would like to print the string in binary > > Man=010011010110000101101110 > > > > What's M in binary? > Nobody knows... > > What's M in encoded in 8-bit ASCII string: > '0b1001101' > Source: bin(ord('M')) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Jun 16 21:37:56 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 16 Jun 2009 14:37:56 -0500 Subject: [Tutor] Conversion question In-Reply-To: References: <1644742819-1245174188-cardhu_decombobulator_blackberry.rim.net-1031235909-@bxe1291.bisx.prod.on.blackberry> <333efb450906161113t3dd60a84g5d1987fd6a4747c7@mail.gmail.com> <1289589405-1245176270-cardhu_decombobulator_blackberry.rim.net-93337559-@bxe1291.bisx.prod.on.blackberry> Message-ID: <333efb450906161237y12bb3f19wd81bd0cc459ff32f@mail.gmail.com> On Tue, Jun 16, 2009 at 2:25 PM, Tom Green wrote: > Correct 8-bit ASCII. Sorry about that. I am using Python 2.5.2, which > doesn't support bin. If I upgraded how would I go about converting the > entire string to 8-bit ASCII? > > I appreciate your help. you write the conversion yourself. 1. # convert a decimal (denary, base 10) integer to a binary string (base 2) 2. # tested with Python24 vegaseat 6/1/2005 3. 4. def Denary2Binary(n): 5. '''convert denary integer n to binary string bStr''' 6. bStr = '' 7. if n < 0: raise ValueError, "must be a positive integer" 8. if n == 0: return '0' 9. while n > 0: 10. bStr = str(n % 2) + bStr 11. n = n >> 1 12. return bStr 13. 14. def int2bin(n, count=24): 15. """returns the binary of integer n, using count number of digits""" 16. return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) 17. 18. # this test runs when used as a standalone program, but not as an imported module 19. # let's say you save this module as den2bin.py and use it in another program 20. # when you import den2bin the __name__ namespace would now be den2bin and the 21. # test would be ignored 22. if __name__ == '__main__': 23. print Denary2Binary(255) # 11111111 24. 25. # convert back to test it 26. print int(Denary2Binary(255), 2) # 255 27. 28. print 29. 30. # this version formats the binary 31. print int2bin(255, 12) # 000011111111 32. # test it 33. print int("000011111111", 2) # 255 34. 35. print 36. 37. # check the exceptions 38. print Denary2Binary(0) 39. print Denary2Binary(-5) # should give a ValueError from http://www.daniweb.com/code/snippet285.html# HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From xchimeras at gmail.com Tue Jun 16 21:51:00 2009 From: xchimeras at gmail.com (Tom Green) Date: Tue, 16 Jun 2009 15:51:00 -0400 Subject: [Tutor] Conversion question In-Reply-To: <333efb450906161237y12bb3f19wd81bd0cc459ff32f@mail.gmail.com> References: <1644742819-1245174188-cardhu_decombobulator_blackberry.rim.net-1031235909-@bxe1291.bisx.prod.on.blackberry> <333efb450906161113t3dd60a84g5d1987fd6a4747c7@mail.gmail.com> <1289589405-1245176270-cardhu_decombobulator_blackberry.rim.net-93337559-@bxe1291.bisx.prod.on.blackberry> <333efb450906161237y12bb3f19wd81bd0cc459ff32f@mail.gmail.com> Message-ID: Thanks I just happened to find the site myself. I guess I have to pass each character to the function and build the 8-bit ASCII string or is there a better way to do it? On Tue, Jun 16, 2009 at 3:37 PM, Wayne wrote: > On Tue, Jun 16, 2009 at 2:25 PM, Tom Green wrote: > >> Correct 8-bit ASCII. Sorry about that. I am using Python 2.5.2, which >> doesn't support bin. If I upgraded how would I go about converting the >> entire string to 8-bit ASCII? >> >> I appreciate your help. > > > you write the conversion yourself. anks > > > > > 1. # convert a decimal (denary, base 10) integer to a binary string (base 2) > > 2. # tested with Python24 vegaseat 6/1/2005 > 3. > 4. def Denary2Binary(n): > > 5. '''convert denary integer n to binary string bStr''' > 6. > bStr = '' > 7. if n < 0: raise ValueError, "must be a positive integer" > > 8. if n == 0: return '0' > 9. while n > 0: > > 10. bStr = str(n % 2) + bStr > 11. n = n >> 1 > > 12. return bStr > 13. > 14. def int2bin(n, count=24): > > 15. """returns the binary of integer n, using count number of digits""" > 16. return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) > > 17. > 18. # this test runs when used as a standalone program, but not as an imported module > 19. > # let's say you save this module as den2bin.py and use it in another program > 20. # when you import den2bin the __name__ namespace would now be den2bin and the > > 21. # test would be ignored > 22. if __name__ == '__main__': > 23. print Denary2Binary(255) # 11111111 > 24. > > 25. # convert back to test it > 26. print int(Denary2Binary(255), 2) # 255 > > 27. > 28. print > 29. > 30. # this version formats the binary > > 31. print int2bin(255, 12) # 000011111111 > > 32. # test it > 33. print int("000011111111", 2) # 255 > > 34. > 35. print > 36. > 37. # check the exceptions > > 38. print Denary2Binary(0) > 39. print Denary2Binary(-5) # should give a ValueError > > > from http://www.daniweb.com/code/snippet285.html# > > HTH, > Wayne > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Jun 16 22:09:01 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 17 Jun 2009 06:09:01 +1000 Subject: [Tutor] Conversion question In-Reply-To: References: <1644742819-1245174188-cardhu_decombobulator_blackberry.rim.net-1031235909-@bxe1291.bisx.prod.on.blackberry> <333efb450906161113t3dd60a84g5d1987fd6a4747c7@mail.gmail.com> <1289589405-1245176270-cardhu_decombobulator_blackberry.rim.net-93337559-@bxe1291.bisx.prod.on.blackberry> Message-ID: <4A37FBDD.10202@gmail.com> Tom Green wrote: > Correct 8-bit ASCII. Sorry about that. I am using Python 2.5.2, which > doesn't support bin. If I upgraded how would I go about converting the > entire string to 8-bit ASCII? > AFAIK, earlier versions of python does not have a function/module that converts a number to its binary representation; so you might have to build your own function there. The concept of base-2 conversion is simple, the modulus for powers of 2. >>> def bin(n): ... if n == 0: return '0' ... if n == 1: return '1' ... return mybin(n // 2) + str(n % 2) (that function is simple, but might be slow if you had to concatenate large strings) or generally: def rebase(n, base=2): ''' Convert a positive integer to number string with base `base` ''' if 0 <= n < base: return str(n) return rebase(n // base, base) + str(n % base) than you simply map your string to ord and the bin function, ''.join, and done. From denis.spir at free.fr Tue Jun 16 22:59:24 2009 From: denis.spir at free.fr (spir) Date: Tue, 16 Jun 2009 22:59:24 +0200 Subject: [Tutor] distutils MANIFEST.in Message-ID: <20090616225924.4e2e3ebc@o> Hello, a question for people who know how to write MANIFEST.in: How to tell to simply include all files in the package (and subdirs)? I tried: recursive-include *.* ==> warning: sdist: MANIFEST.in, line 1: 'recursive-include' expects ... recursive-include . *.* ==> warning: no files found matching '*.*' under directory '.' recursive-include pijnu *.* (pijnu is the name of the package) ==> warning: no files found matching '*.*' under directory 'pijnu' As a consequence, MANIFEST only includes: README setup.py and install installs nothing else the egg_info file. Denis ------ la vita e estrany From benshafat at gmail.com Tue Jun 16 23:00:59 2009 From: benshafat at gmail.com (Elisha Rosensweig) Date: Tue, 16 Jun 2009 17:00:59 -0400 Subject: [Tutor] How to change the working directory in IDLE Message-ID: <7fd42f290906161400k6d723b97pdb1829c5ecd6c3ef@mail.gmail.com> Hi Tutors, I"m using Python 2.6.2 and the IDLE tool (also v. 2.6.2). However, when I open the editor I cannot seem to change the directory so as to allow for easy access to my modules. So, for example, the following occurs: >>> os.chdir('/Users/elisha/Documents/workspace/CacheNetFramework/src/Tests') >>> os.getcwd() '/Users/elisha/Documents/workspace/CacheNetFramework/src/Tests' >>> import CSITest Traceback (most recent call last): File "", line 1, in import CSITest ImportError: No module named CSITest What am I doing wrong? Thanks Elisha -------------- next part -------------- An HTML attachment was scrubbed... URL: From cosmicsand27 at yahoo.com Tue Jun 16 23:25:00 2009 From: cosmicsand27 at yahoo.com (Raj Medhekar) Date: Tue, 16 Jun 2009 14:25:00 -0700 (PDT) Subject: [Tutor] Help Needed Message-ID: <461593.11084.qm@web43410.mail.sp1.yahoo.com> I had previously emailed y'all regarding inverting a message input by the user of the program backwards. After much contemplation on your earlier replies I came up with the code I have included in this email. The problem I am having with this code is that the the first character of the message that is reversed does not come up. Is there a solution to this? For my message that I input I used "take this" to test it, use the same message when the program prompts you to enter the message and run it, you'll see what I mean. Also is there a way to say reverse the string in a way so the reversed string would result to "this take" if you use my example? And is there a way to stop the loop without the use of break? Thanks for the help! Peace, Raj My Code: # Backward message # program gets message from user then prints it out backwards message = raw_input("Enter your message: ") print message high = len(message) low = -len(message) begin=None while begin != "": begin = int(high) if begin: end = int(low) print "Your message backwards is", print message[begin:end:-1] break raw_input("\n\nPress the enter key to exit") -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Tue Jun 16 23:33:16 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Tue, 16 Jun 2009 17:33:16 -0400 Subject: [Tutor] Help Needed In-Reply-To: <461593.11084.qm@web43410.mail.sp1.yahoo.com> References: <461593.11084.qm@web43410.mail.sp1.yahoo.com> Message-ID: <1245187996.5889.31.camel@bermanrl-desktop> You are putting far too much work into the solution. Look up slicing on the python web page. Then, as an example, In [1]: s1 = 'hello world' In [2]: s1[::-1] Out[2]: 'dlrow olleh' Hope this helps, Robert On Tue, 2009-06-16 at 14:25 -0700, Raj Medhekar wrote: > I had previously emailed y'all regarding inverting a message input by > the user of the program backwards. After much contemplation on your > earlier replies I came up with the code I have included in this email. > The problem I am having with this code is that the the first character > of the message that is reversed does not come up. Is there a solution > to this? For my message that I input I used "take this" to test it, > use the same message when the program prompts you to enter the message > and run it, you'll see what I mean. Also is there a way to say reverse > the string in a way so the reversed string would result to "this take" > if you use my example? And is there a way to stop the loop without the > use of break? Thanks for the help! > > Peace, > Raj > > My Code: > > # Backward message > # program gets message from user then prints it out backwards > > message = raw_input("Enter your message: ") > > print message > > high = len(message) > low = -len(message) > > begin=None > while begin != "": > begin = int(high) > > if begin: > end = int(low) > > print "Your message backwards is", > print message[begin:end:-1] > break > > > raw_input("\n\nPress the enter key to exit") > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From cosmicsand27 at yahoo.com Tue Jun 16 23:46:04 2009 From: cosmicsand27 at yahoo.com (Raj Medhekar) Date: Tue, 16 Jun 2009 14:46:04 -0700 (PDT) Subject: [Tutor] Help needed Message-ID: <18097.66470.qm@web43414.mail.sp1.yahoo.com> So I figured out the solution to the missing letter and I will post my code here. But I still need help figuring out the other stuff (please see my original message included in this email)! Thanks for putting up with me. Python is slowly but surely coming to me! I am psyched since this is the first programming language that I am learning! Thanks all for the assistance! -Raj New Code: # Backward message # program gets message from user then prints it out backwards message = raw_input("Enter your message: ") print message high = len(message) low = -len(message) begin=None while begin != "": begin = int(high) if begin: end = int(low) print "Your message backwards is", print message[::-1] break raw_input("\n\nPress the enter key to exit") My Original message: I had previously emailed y'all regarding inverting a message input by the user of the program backwards. After much contemplation on your earlier replies I came up with the code I have included in this email. The problem I am having with this code is that the the first character of the message that is reversed does not come up. Is there a solution to this? For my message that I input I used "take this" to test it, use the same message when the program prompts you to enter the message and run it, you'll see what I mean. Also is there a way to say reverse the string in a way so the reversed string would result to "this take" if you use my example? And is there a way to stop the loop without the use of break? Thanks for the help! Peace, Raj My Code: # Backward message # program gets message from user then prints it out backwards message = raw_input("Enter your message: ") print message high = len(message) low = -len(message) begin=None while begin != "": begin = int(high) if begin: end = int(low) print "Your message backwards is", print message[begin:end:-1] break raw_input("\n\nPress the enter key to exit") -------------- next part -------------- An HTML attachment was scrubbed... URL: From e_mitges at hotmail.com Tue Jun 16 23:27:50 2009 From: e_mitges at hotmail.com (Essah Mitges) Date: Tue, 16 Jun 2009 17:27:50 -0400 Subject: [Tutor] printing a list to a window Message-ID: What I am trying to do is print a high score text file to a pygame window it kinda works...I don't know how to go about doing this... _________________________________________________________________ Internet explorer 8 lets you browse the web faster. http://go.microsoft.com/?linkid=9655582 -------------- next part -------------- A non-text attachment was scrubbed... Name: greenberet.png Type: image/png Size: 142512 bytes Desc: not available URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: scoresys.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: high_score.txt URL: From lie.1296 at gmail.com Tue Jun 16 23:58:14 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 17 Jun 2009 07:58:14 +1000 Subject: [Tutor] Help needed In-Reply-To: <18097.66470.qm@web43414.mail.sp1.yahoo.com> References: <18097.66470.qm@web43414.mail.sp1.yahoo.com> Message-ID: Raj Medhekar wrote: > So I figured out the solution to the missing letter and I will post my > code here. But I still need help figuring out the other stuff (please > see my original message included in this email)! Thanks for putting up > with me. Python is slowly but surely coming to me! I am psyched since > this is the first programming language that I am learning! Thanks all > for the assistance! > > -Raj > > New Code: > # Backward message > # program gets message from user then prints it out backwards > > message = raw_input("Enter your message: ") > > print message > > high = len(message) > low = -len(message) > > begin=None > while begin != "": > begin = int(high) > > if begin: > end = int(low) > > print "Your message backwards is", > print message[::-1] > break > > > raw_input("\n\nPress the enter key to exit") > All that can be simplified to two lines: message = raw_input("Enter your message: ") print "Your message backwards is", message[::-1] From mwalsh at mwalsh.org Wed Jun 17 00:04:20 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 16 Jun 2009 17:04:20 -0500 Subject: [Tutor] How to change the working directory in IDLE In-Reply-To: <7fd42f290906161400k6d723b97pdb1829c5ecd6c3ef@mail.gmail.com> References: <7fd42f290906161400k6d723b97pdb1829c5ecd6c3ef@mail.gmail.com> Message-ID: <4A3816E4.20802@mwalsh.org> Elisha Rosensweig wrote: > Hi Tutors, > > I"m using Python 2.6.2 and the IDLE tool (also v. 2.6.2). However, when > I open the editor I cannot seem to change the directory so as to allow > for easy access to my modules. So, for example, the following occurs: > >>>> > os.chdir('/Users/elisha/Documents/workspace/CacheNetFramework/src/Tests') >>>> os.getcwd() > '/Users/elisha/Documents/workspace/CacheNetFramework/src/Tests' >>>> import CSITest > > Traceback (most recent call last): > File "", line 1, in > import CSITest > ImportError: No module named CSITest > > > What am I doing wrong? http://docs.python.org/tutorial/modules.html#the-module-search-path You probably want to append to sys.path in your script, or to the PYTHONPATH environment variable, instead of using os.chdir. import sys sys.path.append('/Users/elisha/Documents/workspace/CacheNetFramework/src/Tests') import CSITest HTH, Marty From mwalsh at mwalsh.org Wed Jun 17 00:08:37 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 16 Jun 2009 17:08:37 -0500 Subject: [Tutor] How to change the working directory in IDLE In-Reply-To: <4A3816E4.20802@mwalsh.org> References: <7fd42f290906161400k6d723b97pdb1829c5ecd6c3ef@mail.gmail.com> <4A3816E4.20802@mwalsh.org> Message-ID: <4A3817E5.7040905@mwalsh.org> Martin Walsh wrote: > Elisha Rosensweig wrote: >> Hi Tutors, >> >> I"m using Python 2.6.2 and the IDLE tool (also v. 2.6.2). However, when >> I open the editor I cannot seem to change the directory so as to allow >> for easy access to my modules. So, for example, the following occurs: >> >> os.chdir('/Users/elisha/Documents/workspace/CacheNetFramework/src/Tests') >>>>> os.getcwd() >> '/Users/elisha/Documents/workspace/CacheNetFramework/src/Tests' >>>>> import CSITest >> Traceback (most recent call last): >> File "", line 1, in >> import CSITest >> ImportError: No module named CSITest >> >> >> What am I doing wrong? > > http://docs.python.org/tutorial/modules.html#the-module-search-path > > You probably want to append to sys.path in your script, or to the > PYTHONPATH environment variable, instead of using os.chdir. Sorry, 'in your script' should read something like 'in Idle'. Here's another doc reference. http://docs.python.org/tutorial/modules.html#tut-standardmodules > > import sys > sys.path.append('/Users/elisha/Documents/workspace/CacheNetFramework/src/Tests') > > import CSITest > > HTH, > Marty From christopher.henk at allisontransmission.com Wed Jun 17 00:42:04 2009 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Tue, 16 Jun 2009 18:42:04 -0400 Subject: [Tutor] Help needed In-Reply-To: <18097.66470.qm@web43414.mail.sp1.yahoo.com> Message-ID: > My Original message: > > I had previously emailed y'all regarding inverting a message input by the user of the program backwards. After much > contemplation on your earlier replies I came up with the code I have included in this email. The problem I am having > with this code is that the the first character of the message that is reversed does not come up. Is there a solution > to this? For my message that I input I used "take this" to test it, use the same message when the program prompts you > to enter the message and run it, you'll see what I mean. Also is there a way to say reverse the string in a way so the > reversed string would result to "this take" if you use my example? And is there a way to stop the loop without the use > of break? Thanks for the help! > As to your second part of your request you can use the function split. http://www.python.org/doc/2.4.4/lib/string-methods.html >>> mystring="Mary had a little lamb." >>> mystring.split() ['Mary', 'had', 'a', 'little', 'lamb.'] >>> And then you can use slicing to reverse the created list the same way you did with the full string. Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Jun 17 01:46:16 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 16 Jun 2009 16:46:16 -0700 Subject: [Tutor] Best Python Editor In-Reply-To: <20090615191457.GC23272@titan.spiretech.com> References: <20090615023153.GA23272@titan.spiretech.com> <20090615191457.GC23272@titan.spiretech.com> Message-ID: On 6/15/2009 12:14 PM Michael Powe said... > On Mon, Jun 15, 2009 at 06:34:04AM -0700, Emile van Sebille wrote: >> I'm wondering if there might be documented benefits to migrating from my >> horse and buggy. :) > > Are you in a hurry to get somewhere? ;-) If 20 LOC/day is average nowadays, how fast do you need to be going? > > I recently worked on a module for a large existing Java application. > The module I wrote had to be plugged in to the existing code base. So > of course, I had to have all kinds of tie-ins to existing libraries > and classes. First, I couldn't run the full application, so I had to > rely on unit testing to verify my functionality. Second, I had to > connect to hundreds of classes inside the application. I'm not that > smart -- I could not have done it without NetBeans, which has > fantastic introspection and can tell me most of the ways I'm violating > protocol while I'm working. This is a good use case. Unfortunately, I'm still supporting several 30-35 year old 250k line basic applications and associated glue apps that don't play nice with modern tools. And each time I've considered switching (for the glue bits), the time to become productive with a new tool was taking as long as the project estimated time to implement and so it just hasn't happened. > > I stubbed out a lot of stuff and prototyped in jEdit. But when it was > game on, I had to go to NB. It probably comes down to, How much stuff > can you carry in your head? several 35 year old 250k line basic applications and associated glue apps :) Also the names of my kids, but not always in the proper one-to-one association. :)) Emile From srilyk at gmail.com Wed Jun 17 02:11:55 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 16 Jun 2009 19:11:55 -0500 Subject: [Tutor] printing a list to a window In-Reply-To: References: Message-ID: <333efb450906161711y9fd7608p74eddca8b618103a@mail.gmail.com> On Tue, Jun 16, 2009 at 4:27 PM, Essah Mitges wrote: > > What I am trying to do is print a high score text file to a pygame window > it kinda works...I don't know how to go about doing this... > Do you know how to print text to a window? to read a file, just in a terminal window: f = open('somefile.txt', 'r') for line in f.readlines(): print line Just translate that. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jun 17 02:32:50 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Jun 2009 01:32:50 +0100 Subject: [Tutor] Help Needed References: <461593.11084.qm@web43410.mail.sp1.yahoo.com> Message-ID: "Raj Medhekar" wrote > ... I came up with the code I have included in this email. Waaaay to complicated! > message = raw_input("Enter your message: ") > > print message > > high = len(message) > low = -len(message) > > begin=None > while begin != "": > begin = int(high) > > if begin: > end = int(low) you don't need the int calls because lebn returns an int. But you don't even need begin and end since they are just aliases to high and low! And since you never change begin after assigning to high you don't need the loop or the if statement! All thats left is what is below: > print "Your message backwards is", > print message[high:low:-1] But there is a bug because you tried to be too clever and got confused with the -len() for end. So for 'hello' you are calling print 'hello'[5:-5:-1] but you really needed print 'hello'[-1:-6:-1] Look at the description of slicing to see why... However all you really need to do is print message[::-1] and let Python figure out the boundaries itself. Keep it simple... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jun 17 02:40:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Jun 2009 01:40:04 +0100 Subject: [Tutor] printing a list to a window References: Message-ID: "Essah Mitges" wrote > What I am trying to do is print a high score text file > to a pygame window it kinda works... How do you define kinda? It doesn't look like it works to me. The function main defined as def main(): high_file = open_file("high_score.txt", "r") score = next_block(high_file) global score high_file.close() score is a local variable and has a value assigned Then you use gloobal which will have no affect so far as I can tell. Finally this function is being replaced by the second function main you defined. You might like to try getting it to work by printing on a console first! Then worry about the GUI bits. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jun 17 02:41:50 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Jun 2009 01:41:50 +0100 Subject: [Tutor] Help needed References: <18097.66470.qm@web43414.mail.sp1.yahoo.com> Message-ID: wrote >>>> mystring="Mary had a little lamb." >>>> mystring.split() > ['Mary', 'had', 'a', 'little', 'lamb.'] >>>> > > And then you can use slicing to reverse the created list the same way you > did with the full string. Or use the reverse() method of the list... Alan G From ayyaz84 at gmail.com Wed Jun 17 03:59:13 2009 From: ayyaz84 at gmail.com (ayyaz) Date: Tue, 16 Jun 2009 21:59:13 -0400 Subject: [Tutor] Help needed In-Reply-To: <18097.66470.qm@web43414.mail.sp1.yahoo.com> References: <18097.66470.qm@web43414.mail.sp1.yahoo.com> Message-ID: Raj Medhekar wrote: > So I figured out the solution to the missing letter and I will post my > code here. But I still need help figuring out the other stuff (please > see my original message included in this email)! Thanks for putting up > with me. Python is slowly but surely coming to me! I am psyched since > this is the first programming language that I am learning! Thanks all > for the assistance! > > -Raj > > New Code: > # Backward message > # program gets message from user then prints it out backwards > > message = raw_input("Enter your message: ") > > print message > > high = len(message) > low = -len(message) > > begin=None > while begin != "": > begin = int(high) > > if begin: > end = int(low) > > print "Your message backwards is", > print message[::-1] > break > > > raw_input("\n\nPress the enter key to exit") > > > My Original message: > > I had previously emailed y'all regarding inverting a message input by > the user of the program backwards. After much contemplation on your > earlier replies I came up with the code I have included in this email. > The problem I am having with this code is that the the first character > of the message that is reversed does not come up. Is there a solution to > this? For my message that I input I used "take this" to test it, use the > same message when the program prompts you to enter the message and run > it, you'll see what I mean. Also is there a way to say reverse the > string in a way so the reversed string would result to "this take" if > you use my example? And is there a way to stop the loop without the use > of break? Thanks for the help! > > Peace, > Raj > > My Code: > > # Backward message > # program gets message from user then prints it out backwards > > message = raw_input("Enter your message: ") > > print message > > high = len(message) > low = -len(message) > > begin=None > while begin != "": > begin = int(high) > > if begin: > end = int(low) > > print "Your message backwards is", > print message[begin:end:-1] > break > > > raw_input("\n\nPress the enter key to exit") > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Hello, The following works also. msg = raw_input("\nPlease enter a message to print backwards: ") x = range(0,len(msg)) x.reverse() for i in x: print msg[i], --ayyaz From srilyk at gmail.com Wed Jun 17 04:31:29 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 16 Jun 2009 21:31:29 -0500 Subject: [Tutor] Help needed In-Reply-To: References: <18097.66470.qm@web43414.mail.sp1.yahoo.com> Message-ID: <333efb450906161931j6a1decd2w848e7591ed88d9d@mail.gmail.com> On Tue, Jun 16, 2009 at 8:59 PM, ayyaz wrote: > The following works also. > > msg = raw_input("\nPlease enter a message to print backwards: ") > x = range(0,len(msg)) > x.reverse() > for i in x: print msg[i], or even simpler, allow range to generate the reverse: range(len(msg)-1, -1, -1) Some explanation: len will actually give you a value that is out of range, so you need len-1. So you'll start at the end, and go until you hit -1, and your step is -1. If you did -2 at the end, you'll get every other letter in reverse. And simpler still, just add that (or substitute xrange) to the loop: for i in xrange(len(msg)-1, -1,-1): print msg[i] HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From benshafat at gmail.com Wed Jun 17 06:35:24 2009 From: benshafat at gmail.com (Elisha Rosensweig) Date: Wed, 17 Jun 2009 00:35:24 -0400 Subject: [Tutor] Help Needed In-Reply-To: <461593.11084.qm@web43410.mail.sp1.yahoo.com> References: <461593.11084.qm@web43410.mail.sp1.yahoo.com> Message-ID: <7fd42f290906162135k46767ccfgd01746c57589f6f4@mail.gmail.com> > Also is there a way to say reverse the string in a way so the reversed > string would result to "this take" if you use my example? And is there a way > to stop the loop without the use of break? Thanks for the help! > Sure. First take your string S and use S.split() to get a list of the individual words in the string. Then you can use similar techniques to those previously proposed for the first problem to reverse the order. Elisha -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Wed Jun 17 14:30:42 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 17 Jun 2009 08:30:42 -0400 Subject: [Tutor] converting encoded symbols from rss feed? Message-ID: Hi everyone, I just tried my hand at parsing an RSS 2.0 feed using Universal Feed Parser and it worked beautifully. My one point of confusion -- I'm not sure how to convert encoded characters back to their human-readable ascii/unicode. Not sure if it matters, but the feed I'm dealing with is using xml version 1.0 and "windows-1252" encoding. Here are some examples of the encoded characters I'm trying to convert: &#150; (symbol as it appears in the original xml file) – (symbol as it appears in ipython shell after using Universal Feed Parser) What I'd like to do is process all of these xml items, convert the encoded characters to readable text, and then pop the items in a database. So to my question -- can anyone point me to documentation on how to perform this conversion? I didn't find anything explicit in the Universal Feed Parser docs, but I figured Python might have a library that handles this kind of thing. Any help is greatly appreciated. Regards, Serdar From srilyk at gmail.com Wed Jun 17 14:58:00 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 17 Jun 2009 07:58:00 -0500 Subject: [Tutor] converting encoded symbols from rss feed? In-Reply-To: References: Message-ID: <333efb450906170558m5111d0f6pdadc6a3d52ebad67@mail.gmail.com> On Wed, Jun 17, 2009 at 7:30 AM, Serdar Tumgoren wrote: > Here are some examples of the encoded characters I'm trying to > convert: > > &#150; (symbol as it appears in the original xml file) > – (symbol as it appears in ipython shell after > using Universal Feed Parser) > I've never played around much, but & is the HTML code for an &. So if you have &#150 it will show up as –. I have no clue if the latter is any type of special character or something, though. Upon searching for – in google, I came up with this: http://www.siber-sonic.com/mac/charsetstuff/Soniccharset.html HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Wed Jun 17 16:19:44 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 17 Jun 2009 10:19:44 -0400 Subject: [Tutor] converting encoded symbols from rss feed? In-Reply-To: <333efb450906170558m5111d0f6pdadc6a3d52ebad67@mail.gmail.com> References: <333efb450906170558m5111d0f6pdadc6a3d52ebad67@mail.gmail.com> Message-ID: > Upon searching for – in google, I came up with this: > http://www.siber-sonic.com/mac/charsetstuff/Soniccharset.html The character table definitely helps. Thanks. Some additional googling suggests that I need to unescape HTML entities. I'm planning to try the below approach from Frederik Lundh. It relies on the "re" and "htmlentitydefs" modules. http://effbot.org/zone/re-sub.htm#unescape-html I'll report back with my results. Meantime, I welcome any other suggestions. Thanks! From denis.spir at free.fr Wed Jun 17 18:53:17 2009 From: denis.spir at free.fr (spir) Date: Wed, 17 Jun 2009 18:53:17 +0200 Subject: [Tutor] distutils MANIFEST.in In-Reply-To: <20090616225924.4e2e3ebc@o> References: <20090616225924.4e2e3ebc@o> Message-ID: <20090617185317.4f671b2a@o> No one has a clue about this? Le Tue, 16 Jun 2009 22:59:24 +0200, spir s'exprima ainsi: > Hello, > > a question for people who know how to write MANIFEST.in: > How to tell to simply include all files in the package (and subdirs)? I > tried: > > recursive-include *.* > ==> warning: sdist: MANIFEST.in, line 1: 'recursive-include' expects > ... > > recursive-include . *.* > ==> warning: no files found matching '*.*' under directory '.' > > recursive-include pijnu *.* > (pijnu is the name of the package) > ==> warning: no files found matching '*.*' under directory 'pijnu' > > As a consequence, MANIFEST only includes: > README > setup.py > and install installs nothing else the egg_info file. > > Denis > ------ > la vita e estrany > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------ la vita e estrany From cfuller084 at thinkingplanet.net Wed Jun 17 19:51:09 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 17 Jun 2009 12:51:09 -0500 Subject: [Tutor] distutils MANIFEST.in In-Reply-To: <20090617185317.4f671b2a@o> References: <20090616225924.4e2e3ebc@o> <20090617185317.4f671b2a@o> Message-ID: <200906171251.10308.cfuller084@thinkingplanet.net> Use os.path.walk or similar to build the file before you call setup(). Cheers From denis.spir at free.fr Wed Jun 17 21:17:08 2009 From: denis.spir at free.fr (spir) Date: Wed, 17 Jun 2009 21:17:08 +0200 Subject: [Tutor] distutils MANIFEST.in In-Reply-To: <200906171251.10308.cfuller084@thinkingplanet.net> References: <20090616225924.4e2e3ebc@o> <20090617185317.4f671b2a@o> <200906171251.10308.cfuller084@thinkingplanet.net> Message-ID: <20090617211708.1de0d513@o> Le Wed, 17 Jun 2009 12:51:09 -0500, Chris Fuller s'exprima ainsi: > > Use os.path.walk or similar to build the file before you call setup(). > > Cheers Thanks, that's what I thought I would end up doing... Denis ------ la vita e estrany From skellem2003 at hotmail.com Wed Jun 17 22:46:00 2009 From: skellem2003 at hotmail.com (matthew andriani) Date: Wed, 17 Jun 2009 20:46:00 +0000 Subject: [Tutor] New to programming and python first minimilistic program (Bottles of beer), , please comment! Message-ID: Hi Guys, I wrote this program for some practice to get into python..I'm trying to find fun ways to learn the language so if anyone has a challenge on this basic level using loops that sounds exciting please let me know.. If you think this program can be improved please let me know too :) b = "bottles of beer" w = "on the wall" a = 100 while a != 0: a = a-1 print a,b,w,a,b,"if one of those bottles should happen to fall there'll be",a-1,b,w Thanks for the feedback.. Cheers, Skellem. _________________________________________________________________ Drag n? drop?Get easy photo sharing with Windows Live? Photos. http://www.microsoft.com/windows/windowslive/products/photos.aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Wed Jun 17 23:01:45 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 17 Jun 2009 15:01:45 -0600 Subject: [Tutor] New to programming and python first minimilistic program (Bottles of beer), , please comment! In-Reply-To: References: Message-ID: <1e53c510906171401j7e40d399v6903977ee48d02e6@mail.gmail.com> Like in any language there any number for ways, heres another b = "bottles of beer" w = "on the wall" bottles = range(1, 101) bottles.reverse() for bottle in bottles: print " %s %s %s if one of those bottles should happen to fall there'll be %s %s %s" % (bottle, b,w, bottle-1, b,w) Vince 2009/6/17 matthew andriani > Hi Guys, > > I wrote this program for some practice to get into python..I'm trying to > find fun ways to learn the language so if anyone has a challenge on this > basic level using loops that sounds exciting please let me know.. If you > think this program can be improved please let me know too :) > > b = "bottles of beer" > w = "on the wall" > a = 100 > while a != 0: > a = a-1 > print a,b,w,a,b,"if one of those bottles should happen to fall there'll > be",a-1,b,w > > > Thanks for the feedback.. > > Cheers, > Skellem. > > > > ------------------------------ > What can you do with the new Windows Live? Find out > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregor.lingl at aon.at Wed Jun 17 23:47:01 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 17 Jun 2009 23:47:01 +0200 Subject: [Tutor] New to programming and python first minimilistic program (Bottles of beer), , please comment! Message-ID: <4A396455.5090202@aon.at> matthew andriani schrieb: > Hi Guys, > > I wrote this program for some practice to get into python..I'm trying > to find fun ways to learn the language so if anyone has a challenge on > this basic level using loops that sounds exciting please let me know.. > If you think this program can be improved please let me know too :) > > b = "bottles of beer" > w = "on the wall" > a = 100 > while a != 0: > a = a-1 > print a,b,w,a,b,"if one of those bottles should happen to fall > there'll be",a-1,b,w > > If you don't want the output of your program to be considered as a somewhat strange joke, you should better write: b = "bottles of beer" w = "on the wall" a = 100 while a != 0: print a,b,w,a,b,"if one of those bottles should happen to fall there'll be",a-1,b,w a = a-1 That means: determine carefully the order of statements in the body of a loop. Regards, Gregor > Thanks for the feedback.. > > Cheers, > Skellem. > > > > ------------------------------------------------------------------------ > What can you do with the new Windows Live? Find out > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From emile at fenx.com Wed Jun 17 23:46:36 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 17 Jun 2009 14:46:36 -0700 Subject: [Tutor] New to programming and python first minimilistic program (Bottles of beer), , please comment! In-Reply-To: References: Message-ID: On 6/17/2009 1:46 PM matthew andriani said... > Hi Guys, > > I wrote this program for some practice to get into python..I'm trying to > find fun ways to learn the language so if anyone has a challenge on this > basic level using loops that sounds exciting please let me know.. Exciting? How about writing a sort utility? I know there are easy ways in python, but as an exercise, put the words from the second quoted line above in alpha order by examining each word. Or how about enumerating the possible outcomes of throwing three dice? Once that's done, leverage python's capabilities and see how short a program will give the same results. Emile From zstumgoren at gmail.com Thu Jun 18 00:00:02 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 17 Jun 2009 18:00:02 -0400 Subject: [Tutor] converting encoded symbols from rss feed? In-Reply-To: References: <333efb450906170558m5111d0f6pdadc6a3d52ebad67@mail.gmail.com> Message-ID: Hey everyone, For the moment, I opted to use string replacement as my "solution." So for the below string containing the HTML decimal represenation for en dash: >>>x = "The event takes place June 17 – 19" >>>x.replace('–', '-') 'The event takes place June 17 - 19' It works in my case since this seems to be the only code that Universal Feed Parser didn't properly translate, but of course not an ideal solution. I assume this path will require me to build a character reference dictionary as I encounter more character codes. I also tried wrestling with character conversion: >>>unichr(150) u'\x96' Not sure where to go from there... From bermanrl at cfl.rr.com Thu Jun 18 00:03:05 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 17 Jun 2009 18:03:05 -0400 Subject: [Tutor] List Splicing Message-ID: <1245276185.22050.39.camel@bermanrl-desktop> Greetings, I am working on a 'simple' algorithm to solve the problem called PRIME1 explained at http://www.spoj.pl/problems/PRIME1/. I do have an algorithm based on the Sieve of Eratosthenes and it does work as I am failing the project not because of a computational error but because of the dreaded TLE (time limit exceeded) designator. I have determined there are at least 3 areas for improvement. The first is within my code where I am creating a list of the first million primes. The code is as follows: def BuildSieve(itemsin): TheSieve=list() TheSieve = range(0,itemsin+1) TheSieve[1]=0 for i in range(2,itemsin+1): if (TheSieve[i] > 0): j = i + i while (j <= itemsin): TheSieve[j] = 0 j+=i return TheSieve It is called with PrimaryList = BuildSieve(1000000) I have read that list splicing rather than looping to set a range of items to zero is the best approach. Given an example list of In [53]: l1 Out[53]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] Since 3 is a prime, we can eliminate all multiples of 3. Within l1, these are expressed as In [52]: l1[n+n:len(l1):n] Out[52]: [6, 9, 12] when n = 3. ( do know 12 would have been eliminated by the prime number 2) It would be great if I could say l1[n+n:len(l1):n] = 0 but obviously that will fail for obvious reasons. I am looking for the right hand side of the statement to set a list within the list to all zeros. Also, if anyone had a relatively simple explanation why in Python this is faster than a loop, I would really like to understand it. Thanks for the input. Robert From emile at fenx.com Thu Jun 18 00:25:11 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 17 Jun 2009 15:25:11 -0700 Subject: [Tutor] List Splicing In-Reply-To: <1245276185.22050.39.camel@bermanrl-desktop> References: <1245276185.22050.39.camel@bermanrl-desktop> Message-ID: On 6/17/2009 3:03 PM Robert Berman said... > Greetings, > > I am working on a 'simple' algorithm to solve the problem called PRIME1 > explained at http://www.spoj.pl/problems/PRIME1/. > > I do have an algorithm based on the Sieve of Eratosthenes and it does > work as I am failing the project not because of a computational error > but because of the dreaded TLE (time limit exceeded) designator. I have > determined there are at least 3 areas for improvement. The first is > within my code where I am creating a list of the first million primes. It looks more like it creates a list 1000001 in length where the non-zero numbers in that list are primes. I'd try BuildSieve(100) until BuildSieve was returning just primes. Or, are you trying to create a list of the primes under 1000000? Optimization should proceed once you've got it working. Emie From bermanrl at cfl.rr.com Thu Jun 18 01:48:46 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 17 Jun 2009 19:48:46 -0400 Subject: [Tutor] List Splicing In-Reply-To: References: <1245276185.22050.39.camel@bermanrl-desktop> Message-ID: <1245282526.22050.59.camel@bermanrl-desktop> Emile, Thank your for your comments. I do have a list running from 0-1000001. Yes, it is true, I only needed 0 - 100000 and yes I will change it. However, if you use primearray as a sieve of all primes 2-1000000 you will see it works quite well. Printing a range, say primearray[21] through primearray[50] will give you all prime numbers between 21 and 50. 23 29 31 37 41 43 47 73000 to 99,123 works nicely, too. I did, in the beginning use a list of 100 (actually (101) and that worked well so thank you for corroborating the approach. Another question I will ask after this one is resolved involves the methodology I use to find primes well over one million. However, for the time being, can you perhaps share some suggestions on list splicing? Thank you for your assistance. Robert On Wed, 2009-06-17 at 15:25 -0700, Emile van Sebille wrote: > On 6/17/2009 3:03 PM Robert Berman said... > > Greetings, > > > > I am working on a 'simple' algorithm to solve the problem called PRIME1 > > explained at http://www.spoj.pl/problems/PRIME1/. > > > > I do have an algorithm based on the Sieve of Eratosthenes and it does > > work as I am failing the project not because of a computational error > > but because of the dreaded TLE (time limit exceeded) designator. I have > > determined there are at least 3 areas for improvement. The first is > > within my code where I am creating a list of the first million primes. > > It looks more like it creates a list 1000001 in length where the > non-zero numbers in that list are primes. I'd try BuildSieve(100) until > BuildSieve was returning just primes. > > Or, are you trying to create a list of the primes under 1000000? > > Optimization should proceed once you've got it working. > > Emie > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From emile at fenx.com Thu Jun 18 02:01:44 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 17 Jun 2009 17:01:44 -0700 Subject: [Tutor] List Splicing In-Reply-To: <1245282526.22050.59.camel@bermanrl-desktop> References: <1245276185.22050.39.camel@bermanrl-desktop> <1245282526.22050.59.camel@bermanrl-desktop> Message-ID: On 6/17/2009 4:48 PM Robert Berman said... > Emile, > > Thank your for your comments. I do have a list running from 0-1000001. > Yes, it is true, I only needed 0 - 100000 and yes I will change it. > However, if you use primearray you haven't posted the primearray code... > > However, for the time being, can you perhaps share some suggestions on > list splicing? So, this part of your original post-- > Out[53]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > Since 3 is a prime, we can eliminate all multiples of 3. Within l1, > these are expressed as > > In [52]: l1[n+n:len(l1):n] > Out[52]: [6, 9, 12] > > when n = 3. ( do know 12 would have been eliminated by the prime > number 2) > > It would be great if I could say l1[n+n:len(l1):n] = 0 but you can say: for ii in l1[n+n:len(l1):n]: l1[ii] = 0 Is something like that what you're after? Emile > but obviously > > that will fail for obvious reasons. I am looking for the right hand > side of the statement to set a list within the list to all zeros. --- From bermanrl at cfl.rr.com Thu Jun 18 02:11:18 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 17 Jun 2009 20:11:18 -0400 Subject: [Tutor] List Splicing In-Reply-To: References: <1245276185.22050.39.camel@bermanrl-desktop> <1245282526.22050.59.camel@bermanrl-desktop> Message-ID: <1245283878.22050.65.camel@bermanrl-desktop> Emille, Thank you for the example of list splicing. Do you know if this is faster than a more conventional loop statement as in my code for primearray which is in my original post (reprinted here) The code is as follows: def BuildSieve(itemsin): TheSieve=list() TheSieve = range(0,itemsin+1) TheSieve[1]=0 for i in range(2,itemsin+1): if (TheSieve[i] > 0): j = i + i while (j <= itemsin): TheSieve[j] = 0 j+=i return TheSieve It is called with PrimaryList = BuildSieve(1000000) Again, thank you for your help. Robert On Wed, 2009-06-17 at 17:01 -0700, Emile van Sebille wrote: > On 6/17/2009 4:48 PM Robert Berman said... > > Emile, > > > > Thank your for your comments. I do have a list running from 0-1000001. > > Yes, it is true, I only needed 0 - 100000 and yes I will change it. > > However, if you use primearray > > you haven't posted the primearray code... > > > > > > However, for the time being, can you perhaps share some suggestions on > > list splicing? > > So, this part of your original post-- > > Out[53]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > > > Since 3 is a prime, we can eliminate all multiples of 3. Within l1, > > these are expressed as > > > > In [52]: l1[n+n:len(l1):n] > > Out[52]: [6, 9, 12] > > > > when n = 3. ( do know 12 would have been eliminated by the prime > > number 2) > > > > It would be great if I could say l1[n+n:len(l1):n] = 0 > > but you can say: > > for ii in l1[n+n:len(l1):n]: l1[ii] = 0 > > Is something like that what you're after? > > Emile > > > > > but obviously > > > > that will fail for obvious reasons. I am looking for the right hand > > side of the statement to set a list within the list to all zeros. > --- > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Thu Jun 18 02:26:30 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 17 Jun 2009 19:26:30 -0500 Subject: [Tutor] List Splicing In-Reply-To: <1245283878.22050.65.camel@bermanrl-desktop> References: <1245276185.22050.39.camel@bermanrl-desktop> <1245282526.22050.59.camel@bermanrl-desktop> <1245283878.22050.65.camel@bermanrl-desktop> Message-ID: <333efb450906171726s5d125e96l6eb3ad5b3677f03f@mail.gmail.com> On Wed, Jun 17, 2009 at 7:11 PM, Robert Berman wrote: > Emille, > > Thank you for the example of list splicing. Do you know if this is faster > than a more conventional loop statement as in my code for primearray which > is in my original post (reprinted here) > > The code is as follows: > > def BuildSieve(itemsin): > TheSieve=list() > TheSieve = range(0,itemsin+1) > TheSieve[1]=0 > for i in range(2,itemsin+1): > if (TheSieve[i] > 0): > j = i + i > while (j <= itemsin): > TheSieve[j] = 0 > j+=i > return TheSieve > > It is called with PrimaryList = BuildSieve(1000000) > I'm curious if it wouldn't be faster to use xrange. I know for certain instead of range(0, itemsin+1) you could use TheSieve = [1, 2] TheSieve.extend(range(3, itemsin+1,2)) Which would save you at least half the time in your generation. Since your first step should be removing multiples of two, that should be a big help. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Jun 18 02:30:39 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 17 Jun 2009 17:30:39 -0700 Subject: [Tutor] List Splicing In-Reply-To: <1245283878.22050.65.camel@bermanrl-desktop> References: <1245276185.22050.39.camel@bermanrl-desktop> <1245282526.22050.59.camel@bermanrl-desktop> <1245283878.22050.65.camel@bermanrl-desktop> Message-ID: On 6/17/2009 5:11 PM Robert Berman said... > Emille, > > Thank you for the example of list splicing. Do you know if this is > faster than a more conventional loop statement Faster can be exactly determined using timeit. (for some definition of exact -- the one we use mostly around here anyway) So, for the bits you want to know faster about, you'd do something like: >>> from timeit import Timer >>> t = Timer("aa = range(0,100,2)") >>> t.timeit() 1.6688069739620928 >>> t = Timer("aa = range(100)[::2]") >>> t.timeit() 3.3360306112492282 >>> I'm not sure this applies specifically to what you're doing, and crafting what you are timing is important, but read up on timeit and try it out. > as in my code for > primearray which is in my original post (reprinted here) Well, there's the confusion. This is the code for something called BuildSieve. In your prior post you show: ----- Printing a range, say primearray[21] through primearray[50] will give you all prime numbers between 21 and 50. 23 29 31 37 41 43 47 ----- ... but this isn't what BuildSieve yields: >>> BuildSieve(20) [0, 0, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11, 0, 13, 0, 0, 0, 17, 0, 19, 0] So I still don't know what primearray is/does. Emile > > The code is as follows: > > def BuildSieve(itemsin): > TheSieve=list() > TheSieve = range(0,itemsin+1) > TheSieve[1]=0 > for i in range(2,itemsin+1): > if (TheSieve[i] > 0): > j = i + i > while (j <= itemsin): > TheSieve[j] = 0 > j+=i > return TheSieve > > It is called with PrimaryList = BuildSieve(1000000) > > Again, thank you for your help. > > Robert > > > On Wed, 2009-06-17 at 17:01 -0700, Emile van Sebille wrote: >> On 6/17/2009 4:48 PM Robert Berman said... >> > Emile, >> > >> > Thank your for your comments. I do have a list running from 0-1000001. >> > Yes, it is true, I only needed 0 - 100000 and yes I will change it. >> > However, if you use primearray >> >> you haven't posted the primearray code... >> >> >> > >> > However, for the time being, can you perhaps share some suggestions on >> > list splicing? >> >> So, this part of your original post-- >> > Out[53]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >> > >> > Since 3 is a prime, we can eliminate all multiples of 3. Within l1, >> > these are expressed as >> > >> > In [52]: l1[n+n:len(l1):n] >> > Out[52]: [6, 9, 12] >> > >> > when n = 3. ( do know 12 would have been eliminated by the prime >> > number 2) >> > >> > It would be great if I could say l1[n+n:len(l1):n] = 0 >> >> but you can say: >> >> for ii in l1[n+n:len(l1):n]: l1[ii] = 0 >> >> Is something like that what you're after? >> >> Emile >> >> >> >> > but obviously >> > >> > that will fail for obvious reasons. I am looking for the right hand >> > side of the statement to set a list within the list to all zeros. >> --- >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bermanrl at cfl.rr.com Thu Jun 18 02:33:07 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 17 Jun 2009 20:33:07 -0400 Subject: [Tutor] List Splicing In-Reply-To: <333efb450906171726s5d125e96l6eb3ad5b3677f03f@mail.gmail.com> References: <1245276185.22050.39.camel@bermanrl-desktop> <1245282526.22050.59.camel@bermanrl-desktop> <1245283878.22050.65.camel@bermanrl-desktop> <333efb450906171726s5d125e96l6eb3ad5b3677f03f@mail.gmail.com> Message-ID: <1245285187.22050.69.camel@bermanrl-desktop> Wayne, Thank you for the suggestion. I will let you know how well this plays out. Robert On Wed, 2009-06-17 at 19:26 -0500, Wayne wrote: > On Wed, Jun 17, 2009 at 7:11 PM, Robert Berman > wrote: > Emille, > > Thank you for the example of list splicing. Do you know if > this is faster than a more conventional loop statement as in > my code for primearray which is in my original post (reprinted > here) > > > The code is as follows: > > def BuildSieve(itemsin): > TheSieve=list() > TheSieve = range(0,itemsin+1) > TheSieve[1]=0 > for i in range(2,itemsin+1): > if (TheSieve[i] > 0): > j = i + i > while (j <= itemsin): > TheSieve[j] = 0 > j+=i > return TheSieve > > It is called with PrimaryList = BuildSieve(1000000) > > > I'm curious if it wouldn't be faster to use xrange. I know for certain > instead of range(0, itemsin+1) you could use TheSieve = [1, 2] > TheSieve.extend(range(3, itemsin+1,2)) > > Which would save you at least half the time in your generation. Since > your first step should be removing multiples of two, that should be a > big help. > > HTH, > Wayne > > From bermanrl at cfl.rr.com Thu Jun 18 02:49:54 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 17 Jun 2009 20:49:54 -0400 Subject: [Tutor] List Splicing In-Reply-To: References: <1245276185.22050.39.camel@bermanrl-desktop> <1245282526.22050.59.camel@bermanrl-desktop> <1245283878.22050.65.camel@bermanrl-desktop> Message-ID: <1245286194.22050.83.camel@bermanrl-desktop> Emille, Thank you very much for the information on timeit. I will investigate and use it. >>... but this isn't what BuildSieve yields: >>> BuildSieve(20) >>[0, 0, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11, 0, 13, 0, 0, 0, 17, 0, 19, 0] >>So I still don't know what primearray is/does. If you look at or print all non zero numbers you have the primes between 2 and 20. Robert On Wed, 2009-06-17 at 17:30 -0700, Emile van Sebille wrote: > On 6/17/2009 5:11 PM Robert Berman said... > > Emille, > > > > Thank you for the example of list splicing. Do you know if this is > > faster than a more conventional loop statement > > Faster can be exactly determined using timeit. (for some definition of > exact -- the one we use mostly around here anyway) > > So, for the bits you want to know faster about, you'd do something like: > > >>> from timeit import Timer > >>> t = Timer("aa = range(0,100,2)") > >>> t.timeit() > 1.6688069739620928 > >>> t = Timer("aa = range(100)[::2]") > >>> t.timeit() > 3.3360306112492282 > >>> > > I'm not sure this applies specifically to what you're doing, and > crafting what you are timing is important, but read up on timeit and try > it out. > > > > as in my code for > > primearray which is in my original post (reprinted here) > > Well, there's the confusion. This is the code for something called > BuildSieve. In your prior post you show: > > ----- > Printing a range, say primearray[21] > through primearray[50] will give you all prime numbers between 21 and > 50. > > 23 > 29 > 31 > 37 > 41 > 43 > 47 > ----- > > ... but this isn't what BuildSieve yields: > > >>> BuildSieve(20) > [0, 0, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11, 0, 13, 0, 0, 0, 17, 0, 19, 0] > > So I still don't know what primearray is/does. > > Emile > > > > > The code is as follows: > > > > def BuildSieve(itemsin): > > TheSieve=list() > > TheSieve = range(0,itemsin+1) > > TheSieve[1]=0 > > for i in range(2,itemsin+1): > > if (TheSieve[i] > 0): > > j = i + i > > while (j <= itemsin): > > TheSieve[j] = 0 > > j+=i > > return TheSieve > > > > It is called with PrimaryList = BuildSieve(1000000) > > > > Again, thank you for your help. > > > > Robert > > > > > > On Wed, 2009-06-17 at 17:01 -0700, Emile van Sebille wrote: > >> On 6/17/2009 4:48 PM Robert Berman said... > >> > Emile, > >> > > >> > Thank your for your comments. I do have a list running from 0-1000001. > >> > Yes, it is true, I only needed 0 - 100000 and yes I will change it. > >> > However, if you use primearray > >> > >> you haven't posted the primearray code... > >> > >> > >> > > >> > However, for the time being, can you perhaps share some suggestions on > >> > list splicing? > >> > >> So, this part of your original post-- > >> > Out[53]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > >> > > >> > Since 3 is a prime, we can eliminate all multiples of 3. Within l1, > >> > these are expressed as > >> > > >> > In [52]: l1[n+n:len(l1):n] > >> > Out[52]: [6, 9, 12] > >> > > >> > when n = 3. ( do know 12 would have been eliminated by the prime > >> > number 2) > >> > > >> > It would be great if I could say l1[n+n:len(l1):n] = 0 > >> > >> but you can say: > >> > >> for ii in l1[n+n:len(l1):n]: l1[ii] = 0 > >> > >> Is something like that what you're after? > >> > >> Emile > >> > >> > >> > >> > but obviously > >> > > >> > that will fail for obvious reasons. I am looking for the right hand > >> > side of the statement to set a list within the list to all zeros. > >> --- > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From benshafat at gmail.com Thu Jun 18 02:39:39 2009 From: benshafat at gmail.com (Elisha Rosensweig) Date: Wed, 17 Jun 2009 20:39:39 -0400 Subject: [Tutor] Fast way to access items in a dictionary Message-ID: <7fd42f290906171739i11f34c78r59f1fb25c6badb4d@mail.gmail.com> Hi, Till now, when I receive a dictionary that I'm not sure contains a certain key, I would use the following template to access a given key: if 'someKey' in dict.keys(): someData = dict['someKey'] is there a faster way to do this? accessing a key that does not exist will through an exception, which is just as tiresome... Thanks Elisha -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jun 18 03:30:17 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 17 Jun 2009 21:30:17 -0400 Subject: [Tutor] List Splicing In-Reply-To: <1245276185.22050.39.camel@bermanrl-desktop> References: <1245276185.22050.39.camel@bermanrl-desktop> Message-ID: <4A3998A9.1040000@gmail.com> Robert Berman wrote: > Greetings, > > I am working on a 'simple' algorithm to solve the problem called PRIME1 > explained at http://www.spoj.pl/problems/PRIME1/. > > I do have an algorithm based on the Sieve of Eratosthenes and it does > work as I am failing the project not because of a computational error > but because of the dreaded TLE (time limit exceeded) designator. I have > determined there are at least 3 areas for improvement. The first is > within my code where I am creating a list of the first million primes. > The code is as follows: > > def BuildSieve(itemsin): > TheSieve=list() > TheSieve = range(0,itemsin+1) > TheSieve[1]=0 > for i in range(2,itemsin+1): > if (TheSieve[i] > 0): > j = i + i > while (j <= itemsin): > TheSieve[j] = 0 > j+=i > return TheSieve > Observations: By convention we like to use names beginning with CAPS for class names and names beginning with lower for variable names. Not a requirement, but it makes it easier for us to read the code. There is no need for TheSieve=list() as the next statement overrides that. There is no need to store the actual numbers in the list, as the list index can serve that purpose. You could instead build a list of 2 0s followed by all 1s: The Sieve = [0,0] + [1]*(itemsin-2). > It is called with PrimaryList = BuildSieve(1000000) > > I have read that list splicing rather than looping to set a range of > items to zero is the best approach. Given an example list of > > In [53]: l1 > Out[53]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > Since 3 is a prime, we can eliminate all multiples of 3. Within l1, > these are expressed as > > In [52]: l1[n+n:len(l1):n] > Out[52]: [6, 9, 12] > > when n = 3. ( do know 12 would have been eliminated by the prime number > 2) > > It would be great if I could say l1[n+n:len(l1):n] = 0 but obviously > that will fail for obvious reasons. I am looking for the right hand side > of the statement to set a list within the list to all zeros. Also, if > anyone had a relatively simple explanation why in Python this is faster > than a loop, I would really like to understand it. > > Thanks for the input. > > Robert > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer Chapel Hill NC 919-636-4239 From srilyk at gmail.com Thu Jun 18 03:33:02 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 17 Jun 2009 20:33:02 -0500 Subject: [Tutor] Fast way to access items in a dictionary In-Reply-To: <7fd42f290906171739i11f34c78r59f1fb25c6badb4d@mail.gmail.com> References: <7fd42f290906171739i11f34c78r59f1fb25c6badb4d@mail.gmail.com> Message-ID: <333efb450906171833o2df8d31ev7afe993a54ea002d@mail.gmail.com> On Wed, Jun 17, 2009 at 7:39 PM, Elisha Rosensweig wrote: > Hi, > > Till now, when I receive a dictionary that I'm not sure contains a certain > key, I would use the following template to access a given key: > > if 'someKey' in dict.keys(): > someData = dict['someKey'] > > is there a faster way to do this? accessing a key that does not exist will > through an exception, which is just as tiresome... sure is: In [97]: mydict = {'knights':'say ni', 'death':'pointy teeth'} In [98]: mydict.get('spam') In [99]: mydict.get('knights') Out[99]: 'say ni' In [100]: if mydict.get(3): .....: print 'Hi' .....: .....: In [101]: if mydict.get('death'): .....: print mydict['death'] .....: .....: pointy teeth HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Jun 18 05:33:11 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 17 Jun 2009 20:33:11 -0700 Subject: [Tutor] Fast way to access items in a dictionary In-Reply-To: <7fd42f290906171739i11f34c78r59f1fb25c6badb4d@mail.gmail.com> References: <7fd42f290906171739i11f34c78r59f1fb25c6badb4d@mail.gmail.com> Message-ID: On 6/17/2009 5:39 PM Elisha Rosensweig said... > Hi, > > Till now, when I receive a dictionary that I'm not sure contains a > certain key, I would use the following template to access a given key: > > if 'someKey' in dict.keys(): > someData = dict['someKey'] > > is there a faster way to do this? Looks like a simple 'in' is faster both when it's there... >>> Timer("'D' in {'D':123}.keys()").timeit() 0.93669924584355613 >>> Timer("'D' in {'D':123}").timeit() 0.34678047105990117 ... and when it isn't... >>> Timer("'E' in {'D':123}.keys()").timeit() 0.99194670371434768 >>> Timer("'E' in {'D':123}").timeit() 0.34795386410769424 >>> Emile > accessing a key that does not exist > will through an exception, which is just as tiresome... > > Thanks > > Elisha > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Thu Jun 18 07:34:19 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 18 Jun 2009 00:34:19 -0500 Subject: [Tutor] List Splicing In-Reply-To: <1245283878.22050.65.camel@bermanrl-desktop> References: <1245276185.22050.39.camel@bermanrl-desktop> <1245282526.22050.59.camel@bermanrl-desktop> <1245283878.22050.65.camel@bermanrl-desktop> Message-ID: <4A39D1DB.1050006@gmail.com> Robert Berman wrote: > Emille, > > Thank you for the example of list splicing. Do you know if this is > faster than a more conventional loop statement as in my code for > primearray which is in my original post (reprinted here) As has been mentioned, you will want to profile your code to know what is truly faster. however, the main idea in speeding up your code is to move as much of the actual operations to C functions as possible. For example, x = [] for i in range(10000): x.append(0) is going to be quite a bit slower than x = [0] * 10000 >>> t = Timer("""x = [0] * 1000""") >>> t.timeit() 6.623384202829115 >>> t = Timer("""x = [] for i in range(1000): x.append(0)""") >>> t.timeit() 141.14222554321785 As you can see, the for loop version is about 20 times slower than the other version. But they both accomplish the same thing. The key here is that the first one, using the "[] * var" syntax, does not iterate over items individually. This is a gross oversimplification, but think of the python interpreter like this: you take your code to a copy shop (a la Kinkos). however, they do not have any copy machines... instead they will rewrite it by hand, line by line. and say they're going to charge you 20 cents per line. Therefore you'd want to minimize the lines of code to save money, right? However, in Python, the interpreter isn't executing just line-by-line (otherwise we'd have no loops) so what it's essentially seeing in the two examples are, first: x = [0] * 1000 and for the second example: x = [] x.append(0) x.append(0) x.append(0) x.append(0) x.append(0) ..... about 992 more times ... x.append(0) x.append(0) x.append(0) So you are getting charged to "copy" each of these lines. So what originally looked like only 2 or 3 more lines of code is in fact many hundreds more instructions. This analogy refers to the overhead of the interpreter - just to call functions and do other basic things, the overhead is much higher than it would be in a compiled language such as C. Now you may be thinking "but behind the scenes, x = [0] * 1000 is a lot of instructions as well!" and you're correct. However, here's where the key of Python comes in: that "behind the scenes" stuff is written over a period of years by very experienced coders, and has been optimized to heck. Also, it's typically going to be written in C and compiled to native code, which is *a lot* faster than interpreted Python is. So basically when you're trying to optimize Python, remember that the cost of executing each individual line is not that high, for the most part (of course there are exceptions). What you want to do is minimize the amount of lines that are interpreted and maximize the amount of code that is executed by the interpreter's libraries, which are highly efficient C code. While in another language you may think "I can do this faster if I do it myself, because the language's libraries are probably too generic to be faster than a custom implementation" but if you want to write fast Python, you have to think "I want to try to do as little as possible most of the time, so I can transfer most of the computational load over to the libraries and away from my code." Just some generic speculation on making stuff more efficient... From rabidpoobear at gmail.com Thu Jun 18 07:42:24 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 18 Jun 2009 00:42:24 -0500 Subject: [Tutor] Fast way to access items in a dictionary In-Reply-To: References: <7fd42f290906171739i11f34c78r59f1fb25c6badb4d@mail.gmail.com> Message-ID: <4A39D3C0.8080304@gmail.com> > Looks like a simple 'in' is faster both when it's there... > > >>> Timer("'D' in {'D':123}.keys()").timeit() > 0.93669924584355613 > >>> Timer("'D' in {'D':123}").timeit() > 0.34678047105990117 > > ... and when it isn't... > > >>> Timer("'E' in {'D':123}.keys()").timeit() > 0.99194670371434768 > >>> Timer("'E' in {'D':123}").timeit() > 0.34795386410769424 > >>> That's because dictionaries are iterable by default, so if you're calling keys() you're just adding the overhead of another function call, and (I think) also generating a whole list as well (but keys() may return an iterable as well.) From karen_palen at yahoo.com Thu Jun 18 07:53:19 2009 From: karen_palen at yahoo.com (Karen Palen) Date: Wed, 17 Jun 2009 22:53:19 -0700 (PDT) Subject: [Tutor] Apparent incosistency with Python interperter in IDLE Message-ID: <710503.22343.qm@web63103.mail.re1.yahoo.com> I am an experienced C/C++/C# programmer who is just starting out with Python. My first attempt at IDLE worked great with the tutorial, but seems to have a problem with my first real app! I am trying to get the Python subprocess/Popen module working with the example from the Python 3 documentation page: >>> import subprocess >>> subprocess.call('ls') Archive Firefox_wallpaper.png result.txt ... which is what I expect. However this same input to the IDLE "Python Shell" yields: Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22) [GCC 4.3.3] on linux2 Type "copyright", "credits" or "license()" for more information. ==== No Subprocess ==== >>> import subprocess >>> subprocess.call('ls') 0 >>> Which appears to be merely the return code, not the stdout! It looks like I need to set some variable in IDLE, but I can't figure out exactly what is needed here. Can anyone point me to an answer? Karen From rabidpoobear at gmail.com Thu Jun 18 08:16:48 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 18 Jun 2009 01:16:48 -0500 Subject: [Tutor] Apparent incosistency with Python interperter in IDLE In-Reply-To: <710503.22343.qm@web63103.mail.re1.yahoo.com> References: <710503.22343.qm@web63103.mail.re1.yahoo.com> Message-ID: <4A39DBD0.30902@gmail.com> Karen Palen wrote: > > Which appears to be merely the return code, not the stdout! > > It looks like I need to set some variable in IDLE, but I can't figure out exactly what is needed here. > > Can anyone point me to an answer? > Well, Karen, according to my IDLE (admittedly it's 2.6 not 3.0 so it may not agree), call only returns the return code. You can check on your system by doing the following: IDLE 2.6.2 >>> import subprocess >>> help(subprocess.call) which will print out the docstring for the method: Help on function call in module subprocess: call(*popenargs, **kwargs) Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) I believe what's happening is that you are confused about the presence of STDOUT in IDLE. In a normal console window, when you call a program (such as "ls"), stdout is directed at the screen (the console window.) So what's happening in the first example (the non-idle one) is: open subprocess and execute an "ls" call - the subprocess prints out the result of the "ls" call -subprocess finishes process finishes Now the key here is that in this case, both of these have the same stdout (the screen), which is the default stdout. However, when you run from an IDLE prompt, your stdout is not going to be the default. check it out if you want: >>> import sys >>> print sys.stdout Notice that this is not a standard stdout. In a normal Python window, >>> import sys >>> print sys.stdout ', mode 'w' at 0x00A43070> it's not the same stdout as IDLE has. So what's happening when you run the command from IDLE: open subprocess and execute an "ls" call -subprocess starts, executes "ls", prints result to _its_ stdout (which is not IDLE's stdout, remember!) -subprocess executes, output goes bye bye your process ends as well So the problem is that the stdout of the "ls" command is appearing in some location that you cannot see. As for ways to remedy this - I don't know. The idea here, though, is that even though the regular Python version has the side-effect that it outputs it in the console, that's not necessarily what you want it to do. The reason is that you have no way to access that data. Also you mentioned that IDLE prints out a 0. This is only something that IDLE's interpreter does. For example >>> x = "hello" >>> x 'hello' IDLE echoes the value of x. However, if you had the code x = "hello" x and you ran it (not in IDLE's interpreter) you would not get any output. What you should learn from this is 1- IDLE is weird in many ways 2 - that subprocess.call() is not meant to get data back from a call (look at subprocess.Popen and its communicate() method for that) 3 - sometimes things that appear to be outputs are side-effects/artifacts of the environment you're running them in and can't be depended upon. HTH, -Luke From alan.gauld at btinternet.com Thu Jun 18 10:08:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Jun 2009 09:08:46 +0100 Subject: [Tutor] Fast way to access items in a dictionary References: <7fd42f290906171739i11f34c78r59f1fb25c6badb4d@mail.gmail.com> Message-ID: "Elisha Rosensweig" wrote > if 'someKey' in dict.keys(): > someData = dict['someKey'] > > is there a faster way to do this? Faster in terms of execution speed? Sure just miss out the test... > accessing a key that does not exist will > through an exception, which is just as tiresome... Tiresome means more code? but its a lot faster in execution time since it only affects the result when you have an error. (Assuming you hit more often than you miss!) But you can also use get() which will not throw an exception and you can provide a default return value for the times you miss >>> d = {1:7,2:9,3:12} >>> d.get(2,-1) 9 >>> d.get(12,-1) -1 >>> HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dorjetarap at googlemail.com Thu Jun 18 12:21:24 2009 From: dorjetarap at googlemail.com (karma) Date: Thu, 18 Jun 2009 12:21:24 +0200 Subject: [Tutor] variable within function retains value Message-ID: Hi All, I'm trying to write a function that flattens a list. However after I call the function more than once, it appends the result (a list) from the second call with the first. I can get around it by either setting the list to an empty one before calling the function, but I would like to keep it in the function, another alternative I found was to pass an empty list as an argument. Can someone explain how python keeps track of variables within functions (I was expecting the variable to be destroyed after a value was returned). Also what is a better way to handle this? Thanks >>> def flatten(myList,start=[]): """ Flatten nested lists >>> flatten([1,[2,[3,4],5]],[]) [1, 2, 3, 4, 5] """ for i in myList: if type(i) != list: start.append(i) else: flatten(i,start) return start >>> flatten([1,[2,[3,4],5]]) [1, 2, 3, 4, 5] >>> flatten([1,[2,[3,4],5]]) [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] >>> flatten([1,[2,[3,4],5]],[]) [1, 2, 3, 4, 5] 2009/6/18 Luke Paireepinart : > Karen Palen wrote: >> >> Which appears to be merely the return code, not the stdout! >> >> It looks like I need to set some variable in IDLE, but I can't figure out >> exactly what is needed here. >> >> Can anyone point me to an answer? >> > > Well, Karen, according to my IDLE (admittedly it's 2.6 not 3.0 so it may not > agree), call only returns the return code. > You can check on your system by doing the following: > > IDLE 2.6.2 ? ? >>> import subprocess >>>> help(subprocess.call) > > which will print out the docstring for the method: > > Help on function call in module subprocess: > > call(*popenargs, **kwargs) > ? Run command with arguments. ?Wait for command to complete, then > ? return the returncode attribute. > ? ? The arguments are the same as for the Popen constructor. ?Example: > ? ? retcode = call(["ls", "-l"]) > > I believe what's happening is that you are confused about the presence of > STDOUT in IDLE. > > In a normal console window, when you call a program (such as "ls"), stdout > is directed at the screen (the console window.) > So what's happening in the first example (the non-idle one) is: > > open subprocess and execute an "ls" call > ? - the subprocess prints out the result of the "ls" call > ? -subprocess finishes > process finishes > > Now the key here is that in this case, both of these have the same stdout > (the screen), which is the default stdout. > > However, when you run from an IDLE prompt, your stdout is not going to be > the default. > check it out if you want: > >>>> import sys >>>> print sys.stdout > > > Notice that this is not a standard stdout. > In a normal Python window, > >>>> import sys >>>> print sys.stdout > ', mode 'w' at 0x00A43070> > > it's not the same stdout as IDLE has. > > So what's happening when you run the command from IDLE: > open subprocess and execute an "ls" call > ? -subprocess starts, executes "ls", prints result to _its_ stdout (which is > not IDLE's stdout, remember!) > ? -subprocess executes, output goes bye bye > your process ends as well > > So the problem is that the stdout of the "ls" command is appearing in some > location that you cannot see. > As for ways to remedy this - I don't know. ?The idea here, though, is that > even though the regular Python version has the side-effect that it outputs > it in the console, that's not necessarily what you want it to do. ?The > reason is that you have no way to access that data. > > Also you mentioned that IDLE prints out a 0. ?This is only something that > IDLE's interpreter does. > For example >>>> x = "hello" >>>> x > 'hello' > > IDLE echoes the value of x. ?However, if you had the code > x = "hello" > x > > and you ran it (not in IDLE's interpreter) you would not get any output. > > What you should learn from this is > 1- IDLE is weird in many ways > 2 - that subprocess.call() is not meant to get data back from a call (look > at subprocess.Popen and its communicate() method for that) > 3 - sometimes things that appear to be outputs are side-effects/artifacts of > the environment you're running them in and can't be depended upon. > > HTH, > -Luke > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From suzee87_aa at yahoo.com Thu Jun 18 10:30:02 2009 From: suzee87_aa at yahoo.com (suzee Eslam) Date: Thu, 18 Jun 2009 01:30:02 -0700 (PDT) Subject: [Tutor] please help me Message-ID: <15092.14341.qm@web62505.mail.re1.yahoo.com> to every one help me please .. i need the code to do chatting by python in mobiles over bluetooth technology .. i need it please if any one know it send it to me as soon as possible.. thanks for all. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Jun 18 13:02:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Jun 2009 07:02:26 -0400 Subject: [Tutor] variable within function retains value In-Reply-To: References: Message-ID: <1c2a2c590906180402u52fec64dnf555f8d65123ba7f@mail.gmail.com> On Thu, Jun 18, 2009 at 6:21 AM, karma wrote: > Hi All, > > I'm trying to write a function that flattens a list. However after I > call the function more than once, it appends the result (a list) from > the second call with the first. I can get around it by either setting > the list to an empty one before calling the function, but I would like > to keep it in the function, another alternative I found was to pass an > empty list as an argument. > > Can someone explain how python keeps track of variables within > functions (I was expecting the variable to be destroyed after a value > was returned). Also what is a better way to handle this? Default arguments are only evaluated once, when the function is compiled, so the start list is shared between invocations of flatten. This is a FAQ: http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm Another solution - it's easy to rewrite flatten() so it doesnt' need a default argument: In [1]: def flatten(myList): ...: start = [] ...: for i in myList: ...: if type(i) != list: ...: start.append(i) ...: else: ...: start.extend(flatten(i)) ...: return start Kent PS Please don't quote unrelated questions when posting. > Thanks > > >>>> def flatten(myList,start=[]): > ? ?""" Flatten nested lists > ? ?>>> flatten([1,[2,[3,4],5]],[]) > ? ?[1, 2, 3, 4, 5] > ? ?""" > ? ?for i in myList: > ? ? ? ?if type(i) != list: > ? ? ? ? ? ?start.append(i) > ? ? ? ?else: flatten(i,start) > ? ?return start > > >>>> flatten([1,[2,[3,4],5]]) > [1, 2, 3, 4, 5] > >>>> flatten([1,[2,[3,4],5]]) > [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] > >>>> flatten([1,[2,[3,4],5]],[]) > [1, 2, 3, 4, 5] From dorjetarap at googlemail.com Thu Jun 18 13:40:56 2009 From: dorjetarap at googlemail.com (karma) Date: Thu, 18 Jun 2009 13:40:56 +0200 Subject: [Tutor] variable within function retains value In-Reply-To: <1c2a2c590906180402u52fec64dnf555f8d65123ba7f@mail.gmail.com> References: <1c2a2c590906180402u52fec64dnf555f8d65123ba7f@mail.gmail.com> Message-ID: Excellent, thanks for that answer Kent. Also thanks for the link 2009/6/18 Kent Johnson : > On Thu, Jun 18, 2009 at 6:21 AM, karma wrote: >> Hi All, >> >> I'm trying to write a function that flattens a list. However after I >> call the function more than once, it appends the result (a list) from >> the second call with the first. I can get around it by either setting >> the list to an empty one before calling the function, but I would like >> to keep it in the function, another alternative I found was to pass an >> empty list as an argument. >> >> Can someone explain how python keeps track of variables within >> functions (I was expecting the variable to be destroyed after a value >> was returned). Also what is a better way to handle this? > > Default arguments are only evaluated once, when the function is > compiled, so the start list is shared between invocations of flatten. > This is a FAQ: > http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm > > Another solution - it's easy to rewrite flatten() so it doesnt' need a > default argument: > > In [1]: def flatten(myList): > ? ...: ? ? start = [] > ? ...: ? ? for i in myList: > ? ...: ? ? ? ? if type(i) != list: > ? ...: ? ? ? ? ? ? start.append(i) > ? ...: ? ? ? ? else: > ? ...: ? ? ? ? ? ? start.extend(flatten(i)) > ? ...: ? ? return start > > Kent > > PS Please don't quote unrelated questions when posting. > >> Thanks From zstumgoren at gmail.com Thu Jun 18 14:48:27 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 18 Jun 2009 08:48:27 -0400 Subject: [Tutor] converting encoded symbols from rss feed? In-Reply-To: <333efb450906171756v5fdd0764q9eab83b896c1d25@mail.gmail.com> References: <333efb450906170558m5111d0f6pdadc6a3d52ebad67@mail.gmail.com> <333efb450906171756v5fdd0764q9eab83b896c1d25@mail.gmail.com> Message-ID: > Some further searching reveals this: > (yay archives ;)) > http://mail.python.org/pipermail/python-list/2008-April/658644.html > Aha! I noticed that 150 was missing from the ISO encoding table and the source xml is indeed using windows-1252 encoding. That explains why this appears to be the only character in the xml source that doesn't seem to get translated by Universal Feed Parser. But I'm now wondering if the feed parser is using windows-1252 rather than some other encoding. The below page provides details on how UFP handles character encodings. http://www.feedparser.org/docs/character-encoding.html I'm wondering if there's a way to figure out which encoding UFP uses when it parses the file. I didn't have the Universal Encoding Detector (http://chardet.feedparser.org/) installed when I parsed the xml file. It's not clear to me whether UFP requires that library to detect the encoding or if it's an optional part of it's broader routine for determining encoding. From dorjetarap at googlemail.com Thu Jun 18 15:15:04 2009 From: dorjetarap at googlemail.com (karma) Date: Thu, 18 Jun 2009 15:15:04 +0200 Subject: [Tutor] Eliminating consecutive duplicates in a list Message-ID: I was playing around with eliminating duplicates in a list not using groupby. From the two solutions below, which is more "pythonic". Alternative solutions would be welcome. Thanks x=[1,1,1,3,2,2,2,2,4,4] [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] output: [1, 3, 2, 4] From bermanrl at cfl.rr.com Thu Jun 18 15:22:49 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 18 Jun 2009 09:22:49 -0400 Subject: [Tutor] Eliminating consecutive duplicates in a list In-Reply-To: References: Message-ID: <1245331369.7422.3.camel@bermanrl-desktop> This might help: http://code.activestate.com/recipes/52560/ Robert On Thu, 2009-06-18 at 15:15 +0200, karma wrote: > I was playing around with eliminating duplicates in a list not using > groupby. From the two solutions below, which is more "pythonic". > Alternative solutions would be welcome. > > Thanks > > x=[1,1,1,3,2,2,2,2,4,4] > > [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] > > [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] > > output: > [1, 3, 2, 4] > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dorjetarap at googlemail.com Thu Jun 18 16:23:28 2009 From: dorjetarap at googlemail.com (karma) Date: Thu, 18 Jun 2009 16:23:28 +0200 Subject: [Tutor] Eliminating consecutive duplicates in a list In-Reply-To: <1245331369.7422.3.camel@bermanrl-desktop> References: <1245331369.7422.3.camel@bermanrl-desktop> Message-ID: Hi Robert, Thanks for the link. However, I am looking for eliminating consecutive duplicates rather than all duplicates - my example wasn't clear, apologies for that. x=[1,1,1,3,2,2,2,4,4,2,2] [1 ,3 ,2 ,4 ,2 ] 2009/6/18 Robert Berman : > This might help: http://code.activestate.com/recipes/52560/ > > Robert > > > On Thu, 2009-06-18 at 15:15 +0200, karma wrote: >> I was playing around with eliminating duplicates in a list not using >> groupby. From the two solutions below, which is more "pythonic". >> Alternative solutions would be welcome. >> >> Thanks >> >> x=[1,1,1,3,2,2,2,2,4,4] >> >> [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] >> >> [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] >> >> output: >> [1, 3, 2, 4] >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > From jojo.mwebaze at gmail.com Thu Jun 18 16:37:27 2009 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Thu, 18 Jun 2009 16:37:27 +0200 Subject: [Tutor] Program Slicing / Trace Message-ID: <3124be320906180737x4e64553p7fa3636c179be597@mail.gmail.com> Hi Tutor The problem i have is to see which statements modify my data at execution time without referring to the code. Referring to the code is difficult esp because of branching. You can never tell before hand which branch execution will follow. e.g in the example below, statements 1, 2, 5,7 and 10 modify my data and are the ones i would like to trace during run time. However the other statements do not change my data so am not interested in them. How can this be achieved during execution? Not sure if the traceback module can be helpful here! Cheers Jojo. =========================== def myfunction(): 1. num1= 20 #statement 1 2. num2 = 30 #statement 2 3. somelist= [ ] #statement 3 4. if (num1 < num2): 5. num2 = num2 * 20 #statement 3 6. else: 7 num2 = num1 + num2 #statement 3 8. mylist = [num1, num2] #statement 4 9. for items in mylist: 10. somelist.append( math.sqrt(item) + math.log(item)) #statement 5 11. return somelist -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Jun 18 16:51:00 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 18 Jun 2009 07:51:00 -0700 Subject: [Tutor] please help me In-Reply-To: <15092.14341.qm@web62505.mail.re1.yahoo.com> References: <15092.14341.qm@web62505.mail.re1.yahoo.com> Message-ID: On 6/18/2009 1:30 AM suzee Eslam said... > to every one help me please .. > i need the code to do chatting by python in mobiles over bluetooth > technology .. i need it please if any one know it send it to me as soon > as possible.. > thanks for all. Maybe this will get you started... http://www.mobilenin.com/mobilepythonbook/examples/057-btchat.html Emile From benshafat at gmail.com Thu Jun 18 16:53:44 2009 From: benshafat at gmail.com (Elisha Rosensweig) Date: Thu, 18 Jun 2009 10:53:44 -0400 Subject: [Tutor] Program Slicing / Trace In-Reply-To: <3124be320906180737x4e64553p7fa3636c179be597@mail.gmail.com> References: <3124be320906180737x4e64553p7fa3636c179be597@mail.gmail.com> Message-ID: <7fd42f290906180753x37c86f0q7d1904436b21738b@mail.gmail.com> It is not clear to me in what way line 3 is different than line 2 - both are assignments... Please clarify Elisha On Thu, Jun 18, 2009 at 10:37 AM, Jojo Mwebaze wrote: > Hi Tutor > > The problem i have is to see which statements modify my data at execution > time without referring to the code. Referring to the code is difficult esp > because of branching. You can never tell before hand which branch execution > will follow. > > e.g in the example below, statements 1, 2, 5,7 and 10 modify my data and > are the ones i would like to trace during run time. However the other > statements do not change my data so am not interested in them. > > How can this be achieved during execution? Not sure if the traceback module > can be helpful here! > > Cheers > > Jojo. > > =========================== > > def myfunction(): > 1. num1= 20 #statement 1 > 2. num2 = 30 #statement 2 > 3. somelist= [ ] #statement 3 > 4. if (num1 < num2): > 5. num2 = num2 * 20 #statement 3 > 6. else: > 7 num2 = num1 + num2 #statement 3 > 8. mylist = [num1, num2] #statement 4 > 9. for items in mylist: > 10. somelist.append( math.sqrt(item) + math.log(item)) #statement 5 > 11. return somelist > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Jun 18 16:54:13 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 18 Jun 2009 07:54:13 -0700 Subject: [Tutor] Program Slicing / Trace In-Reply-To: <3124be320906180737x4e64553p7fa3636c179be597@mail.gmail.com> References: <3124be320906180737x4e64553p7fa3636c179be597@mail.gmail.com> Message-ID: On 6/18/2009 7:37 AM Jojo Mwebaze said... > Hi Tutor > > The problem i have is to see which statements modify my data at > execution time without referring to the code. Referring to the code is > difficult esp because of branching. You can never tell before hand which > branch execution will follow. > > e.g in the example below, statements 1, 2, 5,7 and 10 modify my data and > are the ones i would like to trace during run time. However the other > statements do not change my data so am not interested in them. > > How can this be achieved during execution? I think most of us will litter print statements through the code to track where something changes, then remove them once we're done. Sometimes I'll set a DEBUG variable or dict. I also use pdb as needed, eg import pdb; pdb.set_trace() Emile > Not sure if the traceback > module can be helpful here! > > Cheers > > Jojo. > > =========================== > > def myfunction(): > 1. num1= 20 #statement 1 > 2. num2 = 30 #statement 2 > 3. somelist= [ ] #statement 3 > 4. if (num1 < num2): > 5. num2 = num2 * 20 #statement 3 > 6. else: > 7 num2 = num1 + num2 #statement 3 > 8. mylist = [num1, num2] #statement 4 > 9. for items in mylist: > 10. somelist.append( math.sqrt(item) + math.log(item)) #statement 5 > 11. return somelist > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From emile at fenx.com Thu Jun 18 17:02:07 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 18 Jun 2009 08:02:07 -0700 Subject: [Tutor] Eliminating consecutive duplicates in a list In-Reply-To: References: <1245331369.7422.3.camel@bermanrl-desktop> Message-ID: On 6/18/2009 7:23 AM karma said... > Hi Robert, > > Thanks for the link. However, I am looking for eliminating consecutive > duplicates rather than all duplicates - my example wasn't clear, > apologies for that. > > x=[1,1,1,3,2,2,2,4,4,2,2] > > [1 ,3 ,2 ,4 ,2 ] Something like [ ii for ii,jj in zip(x,x[1:]+[-1]) if jj != ii] Emile From bermanrl at cfl.rr.com Thu Jun 18 17:08:01 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 18 Jun 2009 11:08:01 -0400 Subject: [Tutor] Eliminating consecutive duplicates in a list In-Reply-To: References: <1245331369.7422.3.camel@bermanrl-desktop> Message-ID: <1245337681.7422.9.camel@bermanrl-desktop> Whoops. That's called assuming what I read is really what I see. A good lesson in reading questions twice. I remember this from a post some time back and I remember having been intrigued by it. I used Google, and since I tend to keep extensive notes, the solution I found is not uniquely mine, but it does work. http://wasstock.com/?p=12 Robert On Thu, 2009-06-18 at 16:23 +0200, karma wrote: > Hi Robert, > > Thanks for the link. However, I am looking for eliminating consecutive > duplicates rather than all duplicates - my example wasn't clear, > apologies for that. > > x=[1,1,1,3,2,2,2,4,4,2,2] > > [1 ,3 ,2 ,4 ,2 ] > > > 2009/6/18 Robert Berman : > > This might help: http://code.activestate.com/recipes/52560/ > > > > Robert > > > > > > On Thu, 2009-06-18 at 15:15 +0200, karma wrote: > >> I was playing around with eliminating duplicates in a list not using > >> groupby. From the two solutions below, which is more "pythonic". > >> Alternative solutions would be welcome. > >> > >> Thanks > >> > >> x=[1,1,1,3,2,2,2,2,4,4] > >> > >> [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] > >> > >> [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] > >> > >> output: > >> [1, 3, 2, 4] > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > > > > From globophobe at gmail.com Thu Jun 18 17:27:58 2009 From: globophobe at gmail.com (Luis N) Date: Fri, 19 Jun 2009 00:27:58 +0900 Subject: [Tutor] Subclassing list Message-ID: I get an error "TypeError: 'rounding' is an invalid keyword argument for this function" on my list subclass. How might I subclass list without this error? This is the code: class SeriesList(list): def __new__(cls, *args, **kwargs): series_list = list.__new__(cls, *args) series_list.rounding = kwargs.get('rounding', None) return series_list def moving_average(self, function, period=10): index = 0 window = [] ma = [] for i in self.__iter__(): i = float(i) if is_not_nan(i): window.insert(0, i) if len(window) == period: ma.append(function(window)) window.pop() else: ma.append(float('nan')) return round(ma, self.rounding) --- Regards, Luis From jojo.mwebaze at gmail.com Thu Jun 18 17:33:23 2009 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Thu, 18 Jun 2009 17:33:23 +0200 Subject: [Tutor] Program Slicing / Trace In-Reply-To: <7fd42f290906180753x37c86f0q7d1904436b21738b@mail.gmail.com> References: <3124be320906180737x4e64553p7fa3636c179be597@mail.gmail.com> <7fd42f290906180753x37c86f0q7d1904436b21738b@mail.gmail.com> Message-ID: <3124be320906180833l2a6574cfiec6cbeeb28668b5b@mail.gmail.com> True both are assignments, L3, does change a value of any variable. Johnson On Thu, Jun 18, 2009 at 4:53 PM, Elisha Rosensweig wrote: > It is not clear to me in what way line 3 is different than line 2 - both > are assignments... Please clarify > > Elisha > > On Thu, Jun 18, 2009 at 10:37 AM, Jojo Mwebaze wrote: > >> Hi Tutor >> >> The problem i have is to see which statements modify my data at execution >> time without referring to the code. Referring to the code is difficult esp >> because of branching. You can never tell before hand which branch execution >> will follow. >> >> e.g in the example below, statements 1, 2, 5,7 and 10 modify my data and >> are the ones i would like to trace during run time. However the other >> statements do not change my data so am not interested in them. >> >> How can this be achieved during execution? Not sure if the traceback >> module can be helpful here! >> >> Cheers >> >> Jojo. >> >> =========================== >> >> def myfunction(): >> 1. num1= 20 #statement 1 >> 2. num2 = 30 #statement 2 >> 3. somelist= [ ] #statement 3 >> 4. if (num1 < num2): >> 5. num2 = num2 * 20 #statement 3 >> 6. else: >> 7 num2 = num1 + num2 #statement 3 >> 8. mylist = [num1, num2] #statement 4 >> 9. for items in mylist: >> 10. somelist.append( math.sqrt(item) + math.log(item)) #statement 5 >> 11. return somelist >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jun 18 17:56:00 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 18 Jun 2009 11:56:00 -0400 Subject: [Tutor] Subclassing list In-Reply-To: References: Message-ID: <4A3A6390.2090208@gmail.com> Luis N wrote: > I get an error "TypeError: 'rounding' is an invalid keyword argument > for this function" on my list subclass. > > How might I subclass list without this error? > > This is the code: > > class SeriesList(list): > def __new__(cls, *args, **kwargs): > series_list = list.__new__(cls, *args) > series_list.rounding = kwargs.get('rounding', None) > return series_list > > def moving_average(self, function, period=10): > index = 0 > window = [] > ma = [] > for i in self.__iter__(): > i = float(i) > if is_not_nan(i): > window.insert(0, i) > if len(window) == period: > ma.append(function(window)) > window.pop() > else: > ma.append(float('nan')) > return round(ma, self.rounding) > --- > I copied and ran the above. It gives me no errors. Of course all it is is a class definition. Is there more to the code? And please post the traceback so we have more information! -- Bob Gailer Chapel Hill NC 919-636-4239 From benshafat at gmail.com Thu Jun 18 18:17:56 2009 From: benshafat at gmail.com (Elisha Rosensweig) Date: Thu, 18 Jun 2009 12:17:56 -0400 Subject: [Tutor] reference to directory a module is located at Message-ID: <7fd42f290906180917s5038ce9cuf37fa150c5a003b9@mail.gmail.com> Hi, How can I determine the directory in which a module is located, from within that module? Elisha -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jun 18 18:29:12 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 18 Jun 2009 12:29:12 -0400 Subject: [Tutor] reference to directory a module is located at In-Reply-To: <7fd42f290906180917s5038ce9cuf37fa150c5a003b9@mail.gmail.com> References: <7fd42f290906180917s5038ce9cuf37fa150c5a003b9@mail.gmail.com> Message-ID: <4A3A6B58.9020507@gmail.com> Elisha Rosensweig wrote: > Hi, > > How can I determine the directory in which a module is located, from > within that module? sys.modules[__name__].__file__ -- Bob Gailer Chapel Hill NC 919-636-4239 From davea at ieee.org Thu Jun 18 18:34:17 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 18 Jun 2009 12:34:17 -0400 Subject: [Tutor] Eliminating consecutive duplicates in a list In-Reply-To: References: Message-ID: <4A3A6C89.5030401@ieee.org> karma wrote: > > I was playing around with eliminating duplicates in a list not using > groupby. From the two solutions below, which is more "pythonic". > Alternative solutions would be welcome. > > Thanks > > x=[1,1,1,3,2,2,2,2,4,4] > > [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] > > [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] > > output: > [1, 3, 2, 4] > > I'd vote for the first form, though I might make a generator out of it. gen = (v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0) print list(gen) Of course, that depends on the lifetime of the various objects. Interestingly, if you modify x after defining gen, but before using it, gen will use the new contents of x. From davea at ieee.org Thu Jun 18 18:48:40 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 18 Jun 2009 12:48:40 -0400 Subject: [Tutor] reference to directory a module is located at In-Reply-To: References: Message-ID: <4A3A6FE8.2040205@ieee.org> bob gailer wrote: > Elisha Rosensweig wrote: >> > Hi, >> > >> > How can I determine the directory in which a module is located, from >> > within that module? >> > sys.modules[__name__].__file__ > -- Bob Gailer Or more simply, __file__ But the OP wanted the directory, which can be extracted with method dirname: import os print __file__ print os.path.dirname(__file__) From matthew.strax-haber at nasa.gov Thu Jun 18 18:35:13 2009 From: matthew.strax-haber at nasa.gov (Strax-Haber, Matthew (LARC-D320)) Date: Thu, 18 Jun 2009 11:35:13 -0500 Subject: [Tutor] reference to directory a module is located at In-Reply-To: <7fd42f290906180917s5038ce9cuf37fa150c5a003b9@mail.gmail.com> Message-ID: Try the following: import os.path os.path.abspath(__file__) This won't work in an interactive shell since it is not being executed from within a module. -- ~ Matthew Strax-Haber National Aeronautics and Space Administration Langley Research Center (LaRC) Co-op, Safety-Critical Avionics Systems Branch Student, Northeastern University W: 757-864-7378; C: 561-704-0029 Matthew.Strax-Haber at nasa.gov ________________________________ From: Elisha Rosensweig Reply-To: Date: Thu, 18 Jun 2009 11:17:56 -0500 To: Python Tutor Subject: [Tutor] reference to directory a module is located at Hi, How can I determine the directory in which a module is located, from within that module? Elisha -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Jun 18 19:20:48 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 19 Jun 2009 03:20:48 +1000 Subject: [Tutor] Apparent incosistency with Python interperter in IDLE In-Reply-To: <4A39DBD0.30902@gmail.com> References: <710503.22343.qm@web63103.mail.re1.yahoo.com> <4A39DBD0.30902@gmail.com> Message-ID: Luke Paireepinart wrote: > So the problem is that the stdout of the "ls" command is appearing in > some location that you cannot see. > As for ways to remedy this - I don't know. The idea here, though, is > that even though the regular Python version has the side-effect that it > outputs it in the console, that's not necessarily what you want it to > do. The reason is that you have no way to access that data. You have to explicitly redirect the stdout from subprocess subprocess.Popen(['ls'], stdout=...) What you're seeing is a side effect of the nature of the interactive console and IDLE. The defined behavior of python is when it is being run from a script. From lie.1296 at gmail.com Thu Jun 18 20:39:03 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 19 Jun 2009 04:39:03 +1000 Subject: [Tutor] List Splicing In-Reply-To: <4A39D1DB.1050006@gmail.com> References: <1245276185.22050.39.camel@bermanrl-desktop> <1245282526.22050.59.camel@bermanrl-desktop> <1245283878.22050.65.camel@bermanrl-desktop> <4A39D1DB.1050006@gmail.com> Message-ID: Luke Paireepinart wrote: > Robert Berman wrote: >> Emille, >> >> Thank you for the example of list splicing. Do you know if this is >> faster than a more conventional loop statement as in my code for >> primearray which is in my original post (reprinted here) > As has been mentioned, you will want to profile your code to know what > is truly faster. > however, the main idea in speeding up your code is to move as much of > the actual operations to C functions as possible. > For example, > x = [] > for i in range(10000): > x.append(0) > > is going to be quite a bit slower than > x = [0] * 10000 > > >>>> t = Timer("""x = [0] * 1000""") >>>> t.timeit() > 6.623384202829115 >>>> t = Timer("""x = [] > for i in range(1000): > x.append(0)""") >>>> t.timeit() > 141.14222554321785 > > As you can see, the for loop version is about 20 times slower than the > other version. > But they both accomplish the same thing. > The key here is that the first one, using the "[] * var" syntax, does > not iterate over items individually. > This is a gross oversimplification, but think of the python interpreter > like this: > you take your code to a copy shop (a la Kinkos). however, they do not > have any copy machines... instead they will rewrite it by hand, line by > line. > and say they're going to charge you 20 cents per line. > Therefore you'd want to minimize the lines of code to save money, right? > Also, it's a matter of memory allocation. With an .append loop, there is no way python would know how much memory to allocate in advance; therefore it has to repeatedly reallocate memory as the list grows. Reallocating is an expensive stuff as the interpreter has to copy the whole list everytime. With [0] * 100, the interpreter knows to allocate a memory for 100 objects, in advance. It can allocate once and does not need to copy the list. But remember that all these are low level stuffs we should not need to worry about unless we have problems with performance. As for the original question (l1[n+n:len(l1):n] = 0), I usually use this: l1[start:stop:step] = [value] * len(ll[start:stop:step]) Since the len(ll[start:stop:step]) part will only generate a slice object, it would be fast. However, note that [value] * int does generate a list. Maybe an even faster version could be made using itertools.repeat(0, len(a[2::2])), we'll need to ask timeit's opinion about it. From matthew.strax-haber at nasa.gov Thu Jun 18 21:43:08 2009 From: matthew.strax-haber at nasa.gov (Strax-Haber, Matthew (LARC-D320)) Date: Thu, 18 Jun 2009 14:43:08 -0500 Subject: [Tutor] reference to directory a module is located at In-Reply-To: <4A3A6FE8.2040205@ieee.org> Message-ID: Whoops. I should read more carefully. I thought he said the path to the module itself. Yes, os.path.dirname(__file__) works. If you want an absolute path (rather than a relative path), use: os.path.abspath(os.path.dirname(__file__)) I would find this more useful if the path will be passed around. -- ~ Matthew Strax-Haber National Aeronautics and Space Administration Langley Research Center (LaRC) Co-op, Safety-Critical Avionics Systems Branch Student, Northeastern University W: 757-864-7378; C: 561-704-0029 Matthew.Strax-Haber at nasa.gov ________________________________ From: Dave Angel Date: Thu, 18 Jun 2009 11:48:40 -0500 To: Python Tutor Subject: Re: [Tutor] reference to directory a module is located at bob gailer wrote: > Elisha Rosensweig wrote: >> > Hi, >> > >> > How can I determine the directory in which a module is located, from >> > within that module? >> > sys.modules[__name__].__file__ > -- Bob Gailer Or more simply, __file__ But the OP wanted the directory, which can be extracted with method dirname: import os print __file__ print os.path.dirname(__file__) _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Jun 18 21:45:33 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Jun 2009 15:45:33 -0400 Subject: [Tutor] Eliminating consecutive duplicates in a list In-Reply-To: References: Message-ID: <1c2a2c590906181245s54bee408jed2e0d05f8531b87@mail.gmail.com> On Thu, Jun 18, 2009 at 9:15 AM, karma wrote: > I was playing around with eliminating duplicates in a list not using > groupby. From the two solutions below, which is more "pythonic". > Alternative solutions would be welcome. But why not use groupby()? That seems much clearer to me: In [1]: from itertools import groupby In [3]: x=[1,1,1,3,2,2,2,2,4,4] In [4]: [ k for k, v in groupby(x) ] Out[4]: [1, 3, 2, 4] In [5]: x=[1,1,1,3,2,2,2,4,4,2,2] In [6]: [ k for k, v in groupby(x) ] Out[6]: [1, 3, 2, 4, 2] Kent From kevinfpearson at gmail.com Thu Jun 18 21:55:15 2009 From: kevinfpearson at gmail.com (Kevin Pearson) Date: Thu, 18 Jun 2009 15:55:15 -0400 Subject: [Tutor] Checking Syntax Message-ID: I am teaching myslef Python from a GIS tutorial 'Writing_Geoprocessing_Scripts.pdf'. I have typed everything exactly like it is in the tutorial and when I go to run a check on the sytax (before I try running the program) it places a cursor like so: outFeatureClas|s = outWorkspace + "/" + GP.ValidateTableName(fc,outWorkspace) I have checked the tutorial and I can't see what is wrong. I can't get past this until it is corrected. I have attached the script. Any advice would be greatly appreciated. Thanks, Kevin #Import standard library modules #imports system, operating system & Windows 32 modules #sys refers to Python system, os refers to acess to operating system import win32com.client, sys, os #Create the Geoprocessor object GP = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") #Set the input workspace #argv = argument value #argv[1] is the name of the script GP.workspace = sys.argv[1] #Set the clip featureclass clipFeatures = sys.argv[2] #Set the output workspace outWorkspace = sys.argv[3] #Set the cluster tolerance clusterTolerance = sys.argv[4] #try statement defines the beginning of a block of code that will be #handled by its associated exception handler, or except statement #try/except statements are used to handle unexpected errors #this defines that the program should do when an exception happens try: #Get a list of the featureclasses in the input folder fcs = GP.ListFeatureClasses() #Loop through the list of feature classes #always reset a list so the first item is extracted #so you can be sure you get the first item in the list fcs.Reset() fc = fcs.Next() while fc: #Validate the new feature class name for the output workspace. #ValidateTableName ensures output name is valid for output #workspace, it returns unique name so no existing data is overwritten. outFeatureClass = outWorkspace + "/" + GP.ValidateTableName(fc, outWorkspace) #Clip each feature class in list with the clip feature class. #Do not clip the clipFeatures, it may be in the same workspace. if str(fc) != str(os.path.split(clipFeatures)[1]): GP.Clip(fc, clipFeatures, outFeatureClass, clusterTolerance) fc = fcs.Next() except: #except statement is required by the earlier try statement #if an error occurs during execution the code in the except #block will run GP.AddMessage(GP.GetMessages(2)) print GP.GetMessages(2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From benshafat at gmail.com Thu Jun 18 22:29:41 2009 From: benshafat at gmail.com (Elisha Rosensweig) Date: Thu, 18 Jun 2009 16:29:41 -0400 Subject: [Tutor] reference to directory a module is located at In-Reply-To: <4A3A6FE8.2040205@ieee.org> References: <4A3A6FE8.2040205@ieee.org> Message-ID: <7fd42f290906181329x38926b4dn92fe91bcb96d0bbc@mail.gmail.com> Thanks - just what I needed (and thanks to all the others too) Elisha On Thu, Jun 18, 2009 at 12:48 PM, Dave Angel wrote: > bob gailer wrote: > > Elisha Rosensweig wrote: >> >>> > Hi, >>> > >>> > How can I determine the directory in which a module is located, from > >>> within that module? >>> >>> >> sys.modules[__name__].__file__ >> -- Bob Gailer >> > Or more simply, > __file__ > > But the OP wanted the directory, which can be extracted with method > dirname: > > import os > print __file__ > print os.path.dirname(__file__) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Thu Jun 18 22:37:28 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 18 Jun 2009 16:37:28 -0400 Subject: [Tutor] converting encoded symbols from rss feed? In-Reply-To: References: <333efb450906170558m5111d0f6pdadc6a3d52ebad67@mail.gmail.com> <333efb450906171756v5fdd0764q9eab83b896c1d25@mail.gmail.com> Message-ID: Hey everyone, I'm trying to get down to basics with this handy intro on Python encodings: http://eric.themoritzfamily.com/2008/11/21/python-encodings-and-unicode/ But I'm running into some VERY strange results. On the above link, the section on "Encoding Unicode Byte Streams" has the following example: >>> u = u"abc\u2013" >>> print u Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3: ordinal not in range(128) >>> print u.encode("utf-8") abc? But when I try the same example on my Windows XP machine (with Python 2.5.4), I can't get the same results. Instead, it spits out the below (hopefully it renders properly and we don't have encoding issues!!!): $ python Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x = u"abc\u2013" >>> print x Traceback (most recent call last): File "", line 1, in File "C:\Program Files\Python25\lib\encodings\cp437.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position 3: character maps to >>> x.encode("utf-8") 'abc\xe2\x80\x93' >>> print x.encode("utf-8") abc??? I get the above results in python interpreters invoked from both the Windows command line and in a cygwin shell. HOWEVER -- the test code works properly (i.e. I get the expected "abc-" when I run the code in WingIDE 10.1 (version 3.1.8-1). In a related test, I was unable change the default character encoding for the python interpreter from ascii to utf-8. In all cases (cygwin, Wing IDE, windows command line), the interpreter reported that I my "sys" module does not contain the "setdefaultencoding" method (even though this should be part of the module from versions 2.x and above). Can anyone help me untangle this mess? I'd be indebted! From emile at fenx.com Thu Jun 18 22:47:21 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 18 Jun 2009 13:47:21 -0700 Subject: [Tutor] Checking Syntax In-Reply-To: References: Message-ID: On 6/18/2009 12:55 PM Kevin Pearson said... > I am teaching myslef Python from a GIS tutorial > 'Writing_Geoprocessing_Scripts.pdf'. > I have typed everything exactly like it is in the tutorial and when I go > to run a check on the sytax (before I try running the program) it places > a cursor like so: > outFeatureClas|s = outWorkspace + "/" + > GP.ValidateTableName(fc,outWorkspace) > I have checked the tutorial and I can't see what is wrong. I can't get > past this until it is corrected. > I have attached the script. > Any advice would be greatly appreciated. > Thanks, > Kevin > > #Import standard library modules > #imports system, operating system & Windows 32 modules > #sys refers to Python system, os refers to acess to operating system > import win32com.client, sys, os > #Create the Geoprocessor object > GP = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") > #Set the input workspace > #argv = argument value > #argv[1] is the name of the script > GP.workspace = sys.argv[1] > #Set the clip featureclass > clipFeatures = sys.argv[2] > #Set the output workspace > outWorkspace = sys.argv[3] > #Set the cluster tolerance > clusterTolerance = sys.argv[4] > #try statement defines the beginning of a block of code that will be > #handled by its associated exception handler, or except statement > #try/except statements are used to handle unexpected errors > #this defines that the program should do when an exception happens > try: > #Get a list of the featureclasses in the input folder > fcs = GP.ListFeatureClasses() > #Loop through the list of feature classes > #always reset a list so the first item is extracted > #so you can be sure you get the first item in the list > fcs.Reset() > fc = fcs.Next() > while fc: I don/t know if this is the only case, but certainly you'll need to increase indentation level after any lines ending in a colon that indicate the start of a block. This type of error can cause cryptic messages to the thrown up that don't always point to the actual problem. HTH, Emile > #Validate the new feature class name for the output workspace. > #ValidateTableName ensures output name is valid for output > #workspace, it returns unique name so no existing data is overwritten. > outFeatureClass = outWorkspace + "/" + GP.ValidateTableName(fc, > outWorkspace) > #Clip each feature class in list with the clip feature class. > #Do not clip the clipFeatures, it may be in the same workspace. > if str(fc) != str(os.path.split(clipFeatures)[1]): > GP.Clip(fc, clipFeatures, outFeatureClass, > clusterTolerance) > fc = fcs.Next() > except: > #except statement is required by the earlier try statement > #if an error occurs during execution the code in the except > #block will run > GP.AddMessage(GP.GetMessages(2)) > print GP.GetMessages(2) > > > > > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Thu Jun 18 23:23:33 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 18 Jun 2009 16:23:33 -0500 Subject: [Tutor] Apparent incosistency with Python interperter in IDLE In-Reply-To: <554256.42021.qm@web63102.mail.re1.yahoo.com> References: <554256.42021.qm@web63102.mail.re1.yahoo.com> Message-ID: <4A3AB055.3000207@gmail.com> Karen Palen wrote: > WOW! Thanks for the detailed explanation! > Sure thing, putting off doing homework so... > This was about what I had expected so it is no surprise. > > My conclusion (so far) is that there is not much to gain from an IDE in this situation and a lot of complexity to deal with. > You'd be surprised how many people write Python without an IDE at all. I end up doing most of my work just in an editor with syntax highlighting (such as Notepad ++) and setting my f5 to run my Python program in a new window. That circumvents all the issues IDEs have with their stdout, as well as some other issues IDLE has (namely, if IDLE can't create a subprocess (which it is the default behavior on windows not to) and you run a program, all variables and imports will hang around for the next program run. therefore you can have the line "import os" then run your program, remove the line, and run it again, and even if you use methods from the "os" module, your code will still work fine... that is, until you restart IDLE.) > Clearly I will have to deal with stdin and stdout as part of any real app however. > Python makes it really easy to deal with stdin and stdout - they are just generic File objects. Since Python does Duck Typing (anything that walks like a duck and quacks like a duck may as well be a duck), you can place any class into stdin and stdout that has the common File methods (write, writeline, read, readline, etc.) You don't even have to inherit the class from File. You can make an entirely new class, so long as it implements the common methods. That's one of the beauties of Python. so you can do something like class GUIStdOut(object): def write(self, data): #draw data in your GUI self.stdout = GUIStdOut() and then you can print "Hello, World!" and it will show up in your GUI. > The intended app is to run a mono based subprocess (yes I know, but it is too big to change) and then control it through a pipe with stdin and stdout. > > > It looks as I I will just have to write something in C#/mono to echo my commands for testing then go from there. > > At the moment it looks like the straight Python interpreter plus Gedit/PDB will be the tools of choice. > Yes, those are perfectly suitable tools. You may find an IDE that you like later, but just using editors are fine. One thing I do miss about IDEs is the printing of the method docstrings while you're typing, but you can get plugins to do that for most editors, I believe. > I am using Python 301 because this is a brand new project and I don't want to have to convert 6 months or so down the road. > > Can you suggest a better strategy? > No, Python 3 is probably a better bet in the long run. Just be wary of it in regard to other libraries - most 3rd party libraries do not work on Python 3 yet (Python 3 broke backward compatibility). So if you have to use any of those libraries, you're going to end up having to use 2.6. I'm personally not moving to Python 3 until all the libraries I use support it, even if I'm not using one of said libraries for a specific program. From kent37 at tds.net Thu Jun 18 23:32:09 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Jun 2009 17:32:09 -0400 Subject: [Tutor] converting encoded symbols from rss feed? In-Reply-To: References: <333efb450906170558m5111d0f6pdadc6a3d52ebad67@mail.gmail.com> <333efb450906171756v5fdd0764q9eab83b896c1d25@mail.gmail.com> Message-ID: <1c2a2c590906181432k160b8d3bj68c489d946f73e5a@mail.gmail.com> On Thu, Jun 18, 2009 at 4:37 PM, Serdar Tumgoren wrote: > On the above link, the section on "Encoding Unicode Byte Streams" has > the following example: > >>>> u = u"abc\u2013" >>>> print u > Traceback (most recent call last): > ?File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in > position 3: ordinal not in range(128) >>>> print u.encode("utf-8") > abc? > > But when I try the same example on my Windows XP machine (with Python > 2.5.4), I can't get the same results. Instead, it spits out the below > (hopefully it renders properly and we don't have encoding issues!!!): > > $ python > Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = u"abc\u2013" >>>> print x > Traceback (most recent call last): > ?File "", line 1, in > ?File "C:\Program Files\Python25\lib\encodings\cp437.py", line 12, in encode > ? ?return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position > ?3: character maps to >>>> x.encode("utf-8") > 'abc\xe2\x80\x93' >>>> print x.encode("utf-8") > abc??? The example is written assuming the console encoding is utf-8. Yours seems to be cp437. Try this: C:\Project\Mango> py Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. In [1]: import sys In [2]: sys.stdout.encoding Out[2]: 'cp437' But there is another problem - \u2013 is an em dash which does not appear in cp437, so even giving the correct encoding doesn't work. Try this: In [6]: x = u"abc\u2591" In [7]: print x.encode('cp437') ------> print(x.encode('cp437')) abc? > In a related test, I was unable change the default character encoding > for the python interpreter from ascii to utf-8. In all cases (cygwin, > Wing IDE, windows command line), the interpreter reported that I my > "sys" module does not contain the "setdefaultencoding" method (even > though this should be part of the module from versions 2.x and above). sys.defaultencoding is deleted by site.py on python startup.You have to set the default encoding from within a sitecustomize.py module. But it's usually better to get a correct understanding of what is going on and to leave the default encoding alone. Kent From zstumgoren at gmail.com Fri Jun 19 00:33:18 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 18 Jun 2009 18:33:18 -0400 Subject: [Tutor] converting encoded symbols from rss feed? In-Reply-To: <1c2a2c590906181432k160b8d3bj68c489d946f73e5a@mail.gmail.com> References: <333efb450906170558m5111d0f6pdadc6a3d52ebad67@mail.gmail.com> <333efb450906171756v5fdd0764q9eab83b896c1d25@mail.gmail.com> <1c2a2c590906181432k160b8d3bj68c489d946f73e5a@mail.gmail.com> Message-ID: > The example is written assuming the console encoding is utf-8. Yours > seems to be cp437. Try this: > In [1]: import sys > > In [2]: sys.stdout.encoding > Out[2]: 'cp437' That is indeed the result that I get as well. > But there is another problem - \u2013 is an em dash which does not > appear in cp437, so even giving the correct encoding doesn't work. Try > this: > In [6]: x = u"abc\u2591" > > In [7]: print x.encode('cp437') > ------> print(x.encode('cp437')) > abc? > So does this mean that my python install is incapable of encoding the en/em dash? For the time being, I've gone with treating the symptom rather than the root problem and created a translate function. def translate_code(text): text = text.replace("‘","'") text = text.replace("’","'") text = text.replace("“",'"') text = text.replace("”",'"') text = text.replace("–","-") text = text.replace("—","--") return text Which of course has led to a new problem. I'm first using Fredrik Lundh's code to extract random html gobbledygook, then running my translate function over the file to replace the windows-1252 encoded characters. But for some reason, I can't seem to get my translate_code function to work inside the same loop as Mr. Lundh's html cleanup code. Below is the problem code: infile = open('test.txt','rb') outfile = open('test_cleaned.txt','wb') for line in infile: try: newline = strip_html(line) cleanline = translate_code(newline) outfile.write(cleanline) except: newline = "NOT CLEANED: %s" % line outfile.write(newline) infile.close() outfile.close() The strip_html function, documented here (http://effbot.org/zone/re-sub.htm#unescape-html ), returns a text string as far as I can tell. I'm confused why I wouldn't be able to further manipulate the string with the "translate_code" function and store the result in the "cleanline" variable. When I try this approach, none of the translations succeed and I'm left with the same HTML gook in the "outfile". Is there some way to combine these functions so I can perform all the processing in one pass? From alan.gauld at btinternet.com Fri Jun 19 01:26:38 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Jun 2009 00:26:38 +0100 Subject: [Tutor] Checking Syntax References: Message-ID: "Kevin Pearson" wrote > run a check on the sytax (before I try running the program) it places a > cursor like so: > outFeatureClas|s = outWorkspace + "/" + > GP.ValidateTableName(fc,outWorkspace) You should try running it, the error message may be more helpful than the syntax checker... However, it will also help make your code more readable is you insert some blank lines to break it into logical groups See below... Also most of the comments are really bad stylistically since they simply describe what the code is doing which is in most cases self evident even to a beginner. Comments should describe *why* the code is as it is, not what it is. I've removed the worst cases. > #Import standard library modules > import win32com.client, sys, os > #Create the Geoprocessor object > GP = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") > #argv[1] is the name of the script > GP.workspace = sys.argv[1] > clipFeatures = sys.argv[2] > outWorkspace = sys.argv[3] > clusterTolerance = sys.argv[4] > try: > fcs = GP.ListFeatureClasses() > #always reset a list so the first item is extracted > #so you can be sure you get the first item in the list > fcs.Reset() > fc = fcs.Next() > while fc: > # returns unique name so no existing data is overwritten. > outFeatureClass = outWorkspace + "/" + GP.ValidateTableName(fc, > outWorkspace) Notice that this line is supposerd to be inside the body of a while loop. That means it should be indented. Because it isn't the syntax checker thinks there is a missing body to the loop. Your line is the first line after Python detects the error so thats where the cursor stops. > #Do not clip the clipFeatures, it may be in the same workspace. > if str(fc) != str(os.path.split(clipFeatures)[1]): > GP.Clip(fc, clipFeatures, outFeatureClass, > clusterTolerance) > fc = fcs.Next() I suspect all of these lines should be indented too... > except: > GP.AddMessage(GP.GetMessages(2)) > print GP.GetMessages(2) > HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From vincent at vincentdavis.net Fri Jun 19 01:32:22 2009 From: vincent at vincentdavis.net (Vincent Davis) Date: Thu, 18 Jun 2009 17:32:22 -0600 Subject: [Tutor] list of instance objects, access attribute Message-ID: <77e831100906181632s6043ddb0p34a30be6698183d7@mail.gmail.com> given a class like class B(): def __init__(self, b1, b2): ??? self.fooa = fooa ??? self.foob = foob Ok now I have several instances in a list b1 = B(1, 2) b2 = B(3, 4) b3 = B(9, 10) alist = [b1, b2, b3] Lets say for each instance of the class I want to print the value of fooa if it is greater than 5. How do I do this, what I am unclear about is how I iterate over the values of fooa. As I write this I am thinking of trying For x in alist: if x.fooa > 5 : print(x.fooa) Is that the right way or is there a better? will this work for methods? Thanks Vincent Davis From kent37 at tds.net Fri Jun 19 02:09:22 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Jun 2009 20:09:22 -0400 Subject: [Tutor] list of instance objects, access attribute In-Reply-To: <77e831100906181632s6043ddb0p34a30be6698183d7@mail.gmail.com> References: <77e831100906181632s6043ddb0p34a30be6698183d7@mail.gmail.com> Message-ID: <1c2a2c590906181709l1ec614fcsd88d6676b461b5ba@mail.gmail.com> On Thu, Jun 18, 2009 at 7:32 PM, Vincent Davis wrote: > given a class like > class B(): > def __init__(self, b1, b2): > ??? self.fooa = fooa > ??? self.foob = foob > > Ok now I have several instances in a list > b1 = B(1, 2) > b2 = B(3, 4) > b3 = B(9, 10) > alist = [b1, b2, b3] > > Lets say for each instance of the class I want to print the value of > fooa if it is greater than 5. How do I do this, what I am unclear > about is how I iterate over the values of fooa. As I write this I am > thinking of trying > For x in alist: > ? ?if x.fooa > 5 : print(x.fooa) > > Is that the right way or is there a better? What you have is fine. > will this work for methods? Sure. Try it! Kent From kent37 at tds.net Fri Jun 19 02:07:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Jun 2009 20:07:24 -0400 Subject: [Tutor] converting encoded symbols from rss feed? In-Reply-To: References: <333efb450906170558m5111d0f6pdadc6a3d52ebad67@mail.gmail.com> <333efb450906171756v5fdd0764q9eab83b896c1d25@mail.gmail.com> <1c2a2c590906181432k160b8d3bj68c489d946f73e5a@mail.gmail.com> Message-ID: <1c2a2c590906181707h371eb2bercfe65a142243d3ee@mail.gmail.com> 2009/6/18 Serdar Tumgoren : >> In [7]: print x.encode('cp437') >> ------> print(x.encode('cp437')) >> abc? >> > So does this mean that my python install is incapable of encoding the > en/em dash? No, the problem is with the print, not the encoding. Your console, as configured, is incapable of displaying the em dash. > But for some reason, I can't seem to get my translate_code function to > work inside the same loop as Mr. Lundh's html cleanup code. Below is > the problem code: > > infile = open('test.txt','rb') > outfile = open('test_cleaned.txt','wb') > > for line in infile: > ? ?try: > ? ? ? ?newline = strip_html(line) > ? ? ? ?cleanline = translate_code(newline) > ? ? ? ?outfile.write(cleanline) > ? ?except: > ? ? ? ?newline = "NOT CLEANED: %s" % line > ? ? ? ?outfile.write(newline) > > infile.close() > outfile.close() > > The strip_html function, documented here > (http://effbot.org/zone/re-sub.htm#unescape-html ), returns a text > string as far as I can tell. I'm confused why I wouldn't be able to > further manipulate the string with the "translate_code" function and > store the result in the "cleanline" variable. When I try this > approach, none of the translations succeed and I'm left with the same > HTML gook in the "outfile". Your try/except is hiding the problem. What happens if you take it out? what error do you get? My guess is that strip_html() is returning unicode and translate_code() is expecting strings but I'm not sure without seeing the error. Kent From zstumgoren at gmail.com Fri Jun 19 03:03:26 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 18 Jun 2009 21:03:26 -0400 Subject: [Tutor] converting encoded symbols from rss feed? In-Reply-To: <1c2a2c590906181707h371eb2bercfe65a142243d3ee@mail.gmail.com> References: <333efb450906170558m5111d0f6pdadc6a3d52ebad67@mail.gmail.com> <333efb450906171756v5fdd0764q9eab83b896c1d25@mail.gmail.com> <1c2a2c590906181432k160b8d3bj68c489d946f73e5a@mail.gmail.com> <1c2a2c590906181707h371eb2bercfe65a142243d3ee@mail.gmail.com> Message-ID: Ok, I should say that I managed to "solve" the problem by first reading and translating the data, and then applying Mr. Lundh's strip_html function to the resulting lines. For future reference (and of course any additional feedback), the working code is here: http://pastebin.com/f309bf607 But of course that's a Band-Aid approach and I'm still interested in understanding the root of the problem. To that end, I've attached the Exception below from the problematic code. > Your try/except is hiding the problem. What happens if you take it > out? what error do you get? > > My guess is that strip_html() is returning unicode and > translate_code() is expecting strings but I'm not sure without seeing > the error. > When I run this code: <<< snip >>> for line in infile: cleanline = translate_code(line) newline = strip_html(cleanline) outfile.write(newline) <<< snip >>> ...I receive the below traceback: Traceback (most recent call last): File "htmlcleanup.py", line 112, in outfile.write(newline) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 21: ordinal not in range(128) From davea at ieee.org Fri Jun 19 03:16:21 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 18 Jun 2009 21:16:21 -0400 Subject: [Tutor] list of instance objects, access attribute In-Reply-To: References: Message-ID: <4A3AE6E5.2000001@ieee.org> Vincent Davis wrote: > given a class like > class B(): > def __init__(self, b1, b2): > ??? self.fooa = fooa > ??? self.foob = foob > > Ok now I have several instances in a list > b1 = B(1, 2) > b2 = B(3, 4) > b3 = B(9, 10) > alist = [b1, b2, b3] > > Lets say for each instance of the class I want to print the value of > fooa if it is greater than 5. How do I do this, what I am unclear > about is how I iterate over the values of fooa. As I write this I am > thinking of trying > For x in alist: > if x.fooa > 5 : print(x.fooa) > > Is that the right way or is there a better? > will this work for methods? > > Thanks > Vincent Davis > Did you actually try to run this code? There are at least three syntax problems. 1) you need to indent the body of the class 2) you need to match the formal parameters of __init__() with their usage. 3) you need to change 'For' to 'for' class B(): def __init__(self, b1, b2): self.fooa = b1 self.foob = b2 #Ok now I have several instances in a list b1 = B(1, 2) b2 = B(3, 4) b3 = B(9, 10) alist = [b1, b2, b3] for x in alist: if x.fooa > 5 : print(x.fooa) And then the answer is yes, that's a reasonable way to iterate over the objects, displaying the ones with an attribute of specified value. However, as a style issue, I'd split the print on its own line. Another change I'd make is to explicitly specify object as the base class for class B. From globophobe at gmail.com Fri Jun 19 03:48:03 2009 From: globophobe at gmail.com (Luis N) Date: Fri, 19 Jun 2009 10:48:03 +0900 Subject: [Tutor] Subclassing list In-Reply-To: <4A3A6390.2090208@gmail.com> References: <4A3A6390.2090208@gmail.com> Message-ID: On Fri, Jun 19, 2009 at 12:56 AM, bob gailer wrote: > > Luis N wrote: >> >> I get an error "TypeError: 'rounding' is an invalid keyword argument >> for this function" on my list subclass. >> >> How might I subclass list without this error? >> >> This is the code: >> >> class SeriesList(list): >> ? ?def __new__(cls, *args, **kwargs): >> ? ? ? ?series_list = list.__new__(cls, *args) >> ? ? ? ?series_list.rounding = kwargs.get('rounding', None) >> ? ? ? ?return series_list >> >> ? ?def moving_average(self, function, period=10): >> ? ? ? ?index = 0 >> ? ? ? ?window = [] >> ? ? ? ?ma = [] >> ? ? ? ?for i in self.__iter__(): >> ? ? ? ? ? ?i = float(i) >> ? ? ? ? ? ?if is_not_nan(i): >> ? ? ? ? ? ? ? ?window.insert(0, i) >> ? ? ? ? ? ? ? ?if len(window) == period: >> ? ? ? ? ? ? ? ? ? ?ma.append(function(window)) >> ? ? ? ? ? ? ? ? ? ?window.pop() >> ? ? ? ? ? ?else: >> ? ? ? ? ? ? ? ?ma.append(float('nan')) >> ? ? ? ?return round(ma, self.rounding) >> --- >> > > I copied and ran the above. It gives me no errors. > > Of course all it is is a class definition. > > Is there more to the code? > > And please post the traceback so we have more information! > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 This is the traceback. I want to let SeriesList know how to round moving average series derived from itself. In [121]: s = SeriesList(rounding=1) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/Luis/Documents/Programming/speculation/ in () TypeError: 'rounding' is an invalid keyword argument for this function Thank you for your help, Luis From djbags275 at yahoo.com Fri Jun 19 03:48:35 2009 From: djbags275 at yahoo.com (dave chachi) Date: Thu, 18 Jun 2009 18:48:35 -0700 (PDT) Subject: [Tutor] home directory usage script Message-ID: <630673.38348.qm@web110702.mail.gq1.yahoo.com> I was wondering if I can get some incite on how to create a python that will accomplish the following tasks: issue: /home partition is partitioned to 80 or so G of space 24 G's is used ??? ??? A. What is taking up this amount of space ??? B. Not alot of packages are installed and shouldnt take up much space ??? Script to perform: ??? A. Create a script that monitors the /home partition ??? B. have it write to a log file in /var/log ??? C. have crontab run it daily -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jun 19 04:53:03 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Jun 2009 22:53:03 -0400 Subject: [Tutor] converting encoded symbols from rss feed? In-Reply-To: References: <333efb450906171756v5fdd0764q9eab83b896c1d25@mail.gmail.com> <1c2a2c590906181432k160b8d3bj68c489d946f73e5a@mail.gmail.com> <1c2a2c590906181707h371eb2bercfe65a142243d3ee@mail.gmail.com> Message-ID: <1c2a2c590906181953y427a10etfbeb5da6185666f0@mail.gmail.com> On Thu, Jun 18, 2009 at 9:03 PM, Serdar Tumgoren wrote: > When I run this code: > > <<< snip >>> > for line in infile: > ? ?cleanline = translate_code(line) > ? ?newline = strip_html(cleanline) > ? ?outfile.write(newline) > <<< snip >>> > > ...I receive the below traceback: > > ? Traceback (most recent call last): > ? ? ?File "htmlcleanup.py", line 112, in > ? ? ?outfile.write(newline) > ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in > position 21: ordinal not in range(128) OK, so newline is unicode, outfile.write() wants a plain string. What encoding do you want outfile to be in? Try something like outfile.write(newline.encode('utf-8')) or use the codecs module to create an output that knows how to encode. Kent From kent37 at tds.net Fri Jun 19 04:56:53 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Jun 2009 22:56:53 -0400 Subject: [Tutor] Subclassing list In-Reply-To: References: <4A3A6390.2090208@gmail.com> Message-ID: <1c2a2c590906181956q4f330cd7ydd40f5d5b8bd8f52@mail.gmail.com> On Thu, Jun 18, 2009 at 9:48 PM, Luis N wrote: >>> I get an error "TypeError: 'rounding' is an invalid keyword argument >>> for this function" on my list subclass. >>> >>> How might I subclass list without this error? >>> >>> This is the code: >>> >>> class SeriesList(list): >>> ? ?def __new__(cls, *args, **kwargs): >>> ? ? ? ?series_list = list.__new__(cls, *args) >>> ? ? ? ?series_list.rounding = kwargs.get('rounding', None) >>> ? ? ? ?return series_list > This is the traceback. I want to let SeriesList know how to round > moving average series derived from itself. > > In [121]: s = SeriesList(rounding=1) > --------------------------------------------------------------------------- > TypeError ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Traceback (most recent call last) > > /Users/Luis/Documents/Programming/speculation/ in () > > TypeError: 'rounding' is an invalid keyword argument for this function I think you need to define SeriesList.__init__(self, rounding=None). This function should assign self.round, then __new__() can be just def __new__(cls, *args, **kwargs): series_list = list.__new__(cls, *args) return series_list Kent From kent37 at tds.net Fri Jun 19 04:58:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Jun 2009 22:58:10 -0400 Subject: [Tutor] home directory usage script In-Reply-To: <630673.38348.qm@web110702.mail.gq1.yahoo.com> References: <630673.38348.qm@web110702.mail.gq1.yahoo.com> Message-ID: <1c2a2c590906181958g114fc79jeb6d082090e8fe48@mail.gmail.com> On Thu, Jun 18, 2009 at 9:48 PM, dave chachi wrote: > ??? A. Create a script that monitors the /home partition > ??? B. have it write to a log file in /var/log > ??? C. have crontab run it daily What do you want it to write? Kent From karen_palen at yahoo.com Fri Jun 19 04:52:17 2009 From: karen_palen at yahoo.com (Karen Palen) Date: Thu, 18 Jun 2009 19:52:17 -0700 (PDT) Subject: [Tutor] Apparent incosistency with Python interperter in IDLE Message-ID: <280560.16193.qm@web63106.mail.re1.yahoo.com> Yes I see. Based on other feedback I am leaning towards not using any IDE for the moment. Python seems well adapted to that kind of workflow, as well as an impressive portability - every bit as good a Java from my tests so far. Karen --- On Thu, 6/18/09, Lie Ryan wrote: > From: Lie Ryan > Subject: Re: [Tutor] Apparent incosistency with Python interperter in IDLE > To: tutor at python.org > Date: Thursday, June 18, 2009, 10:20 AM > Luke Paireepinart wrote: > > So the problem is that the stdout of the "ls" command > is appearing in > > some location that you cannot see. > > As for ways to remedy this - I don't know.? The > idea here, though, is > > that even though the regular Python version has the > side-effect that it > > outputs it in the console, that's not necessarily what > you want it to > > do.? The reason is that you have no way to access > that data. > > You have to explicitly redirect the stdout from subprocess > > subprocess.Popen(['ls'], stdout=...) > > What you're seeing is a side effect of the nature of the > interactive > console and IDLE. The defined behavior of python is when it > is being run > from a script. > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Jun 19 10:21:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Jun 2009 09:21:02 +0100 Subject: [Tutor] list of instance objects, access attribute References: <77e831100906181632s6043ddb0p34a30be6698183d7@mail.gmail.com> Message-ID: "Vincent Davis" wrote class B(): def __init__(self, b1, b2): self.fooa = b1 self.foob = b2 I assume thats what you really meant! Ok now I have several instances in a list b1 = B(1, 2) b2 = B(3, 4) b3 = B(9, 10) alist = [b1, b2, b3] > Lets say for each instance of the class I want to print the value of > fooa if it is greater than 5. How do I do this, define a method of the class, say bigprint() def bigprint(self, limit=5): if self.fooa > limit: print self.fooa > about is how I iterate over the values of fooa. Iterate over the objects and call the method. Make the object do the work, your code should not need to know about the internal attributes of the object. For x in alist: x.bigprint() > Is that the right way or is there a better? > will this work for methods? Methods are how you should do it. Direct access other than for simple reading of values is a suspicious design smell. Any processing of or rules about the data should be in a method. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 19 10:24:29 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Jun 2009 09:24:29 +0100 Subject: [Tutor] home directory usage script References: <630673.38348.qm@web110702.mail.gq1.yahoo.com> Message-ID: "dave chachi" wrote > create a python that will accomplish the following tasks: > > issue: /home partition is partitioned to 80 or so G of space 24 G's is > used > > A. What is taking up this amount of space > B. Not alot of packages are installed and shouldnt take up much space While a Python script could this for you... Why not use du? Thats what it's designed for... Alan G From denis.spir at free.fr Fri Jun 19 10:58:02 2009 From: denis.spir at free.fr (spir) Date: Fri, 19 Jun 2009 10:58:02 +0200 Subject: [Tutor] distutils archive creation blocked Message-ID: <20090619105802.002f9ee1@o> Hello, when trying to create an archive with python setup.py sdist --formats=gztar,zip all works fine (archives are created) except temp dir deletion. Program blocks on removing 'foobar-1.0' (and everything under it) Actually, don't know how to check further for don't where this temp dir is supposed to be -- or not (exploring distutils in the mean time). Denis ------ la vita e estrany From denis.spir at free.fr Fri Jun 19 12:24:58 2009 From: denis.spir at free.fr (spir) Date: Fri, 19 Jun 2009 12:24:58 +0200 Subject: [Tutor] distutils archive creation blocked In-Reply-To: <20090619105802.002f9ee1@o> References: <20090619105802.002f9ee1@o> Message-ID: <20090619122458.29271065@o> Solved -- actually it was an error of mine in a wrapping subprocess.Popen() call. Le Fri, 19 Jun 2009 10:58:02 +0200, spir s'exprima ainsi: > Hello, > > when trying to create an archive with > > python setup.py sdist --formats=gztar,zip > > all works fine (archives are created) except temp dir deletion. Program > blocks on > > removing 'foobar-1.0' (and everything under it) > > Actually, don't know how to check further for don't where this temp dir is > supposed to be -- or not (exploring distutils in the mean time). > > Denis > ------ > la vita e estrany > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------ la vita e estrany From amit.pureenergy at gmail.com Fri Jun 19 13:21:03 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Fri, 19 Jun 2009 16:51:03 +0530 Subject: [Tutor] taking image of gtk.drawing area Message-ID: Hi , I am trying to take image of a gst video playing in the gtk.drawingarea i am using following code for it : def snap_shot(self,widget,data=None): global file_loc ,pixbuf self.pipeline.set_state(gst.STATE_PAUSED) pixbuf = gtk.gdk.Pixbuf( gtk.gdk.COLORSPACE_RGB, False, 8, 640, 480) pixbuf.get_from_drawable( self.movie_window.window, self.movie_window.get_colormap(), 0, 0, 0, 0, 640, 480) file_loc="/tmp/bar%d"%time.time() pixbuf.save(file_loc,'jpeg', {'quality':'100'}) self.pipeline.set_state(gst.STATE_PLAYING) but the movie seems to momentarily stop and i am left with a dark image where i might be going wrong?? -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Fri Jun 19 15:29:50 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 19 Jun 2009 09:29:50 -0400 Subject: [Tutor] converting encoded symbols from rss feed? In-Reply-To: <1c2a2c590906181953y427a10etfbeb5da6185666f0@mail.gmail.com> References: <333efb450906171756v5fdd0764q9eab83b896c1d25@mail.gmail.com> <1c2a2c590906181432k160b8d3bj68c489d946f73e5a@mail.gmail.com> <1c2a2c590906181707h371eb2bercfe65a142243d3ee@mail.gmail.com> <1c2a2c590906181953y427a10etfbeb5da6185666f0@mail.gmail.com> Message-ID: > OK, so newline is unicode, outfile.write() wants a plain string. What > encoding do you want outfile to be in? Try something like > outfile.write(newline.encode('utf-8')) > or use the codecs module to create an output that knows how to encode. Aha!! The second of the two options above did the trick! It appears I needed to open my "outfile" with utf-8 encoding. After that, I was able to write out cleaned lines without any hitches. Below is the working code. And of course, many thanks for the help!! infile = open('test.txt','rb') #infile = codecs.open('test.txt','rb','utf-8') outfile = codecs.open('test_cleaned.txt','wb','utf-8') for line in infile: cleanline = strip_html(translate_code(line)).strip() if cleanline: outline = cleanline + '\n' outfile.write(outline) else: continue From timomlists at gmail.com Fri Jun 19 16:23:10 2009 From: timomlists at gmail.com (Timo List) Date: Fri, 19 Jun 2009 16:23:10 +0200 Subject: [Tutor] Python and SQL recommendation Message-ID: Hello all, At the moment I'm using 3 files as datastorage for my program. One file using ConfigParser and two use the Pickle module. File one contains for example: [ID] option1 = string1 option2 = string2 option3 = string3 And is connected to one of the Pickle files which is like this: {ID : [{key1 : value1, key2 : value2}, {key1 : value3, key2 : value4}], ID2 : [{key1 : value5, key2 : value6}, {key1 : value7, key2 : value8}]} The second Pickle file is data not related to an ID or anything... I was thinking of putting this all in SQL. How would this be done? And what SQL module for Python should I use? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jopython at gmail.com Fri Jun 19 16:55:51 2009 From: jopython at gmail.com (Joe Python) Date: Fri, 19 Jun 2009 10:55:51 -0400 Subject: [Tutor] Handling Generator exceptions in Python 2.5 Message-ID: I have a generator as follows to do list calculations. *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))]* The above generator, throws '*ZeroDivisionError*' exception if ListA[i] = 0. Is there a way to say 'Don't divide by ListA[i] if its equal to 0 (within that statement)'. Sorry if this question sounds too stupid. TIA Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Fri Jun 19 17:09:08 2009 From: vinces1979 at gmail.com (vince spicer) Date: Fri, 19 Jun 2009 09:09:08 -0600 Subject: [Tutor] Handling Generator exceptions in Python 2.5 In-Reply-To: References: Message-ID: <1e53c510906190809n4e8cf9e9ic1e62adf7db7e0d1@mail.gmail.com> Well* *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))*if not ListA[i] == 0*] will exclude any results where listA[i] is 0, if you still want these in the result you may want to use good'ol for statement instead of list comprehension results = [] for x in range(len(listA)): y = ListA[i] - ListB[i-1] if not ListA[i] == 0: y = y / ListA[i] results.append(y) print results Vince On Fri, Jun 19, 2009 at 8:55 AM, Joe Python wrote: > I have a generator as follows to do list calculations. > > *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))]* > > The above generator, throws '*ZeroDivisionError*' exception if ListA[i] = > 0. > Is there a way to say 'Don't divide by ListA[i] if its equal to 0 (within > that statement)'. > > Sorry if this question sounds too stupid. > > TIA > Joe > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jopython at gmail.com Fri Jun 19 17:28:17 2009 From: jopython at gmail.com (Joe Python) Date: Fri, 19 Jun 2009 11:28:17 -0400 Subject: [Tutor] Handling Generator exceptions in Python 2.5 In-Reply-To: <1e53c510906190809n4e8cf9e9ic1e62adf7db7e0d1@mail.gmail.com> References: <1e53c510906190809n4e8cf9e9ic1e62adf7db7e0d1@mail.gmail.com> Message-ID: Thanks everyone for the responses. - Joe On Fri, Jun 19, 2009 at 11:09 AM, vince spicer wrote: > Well* > > *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))*if > not ListA[i] == 0*] > > will exclude any results where listA[i] is 0, if you still want these in > the result > you may want to use good'ol for statement instead of list comprehension > > > results = [] > for x in range(len(listA)): > y = ListA[i] - ListB[i-1] > if not ListA[i] == 0: > y = y / ListA[i] > results.append(y) > > print results > > Vince > > > On Fri, Jun 19, 2009 at 8:55 AM, Joe Python wrote: > >> I have a generator as follows to do list calculations. >> >> *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))]* >> >> The above generator, throws '*ZeroDivisionError*' exception if ListA[i] >> = 0. >> Is there a way to say 'Don't divide by ListA[i] if its equal to 0 (within >> that statement)'. >> >> Sorry if this question sounds too stupid. >> >> TIA >> Joe >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 19 18:20:45 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Jun 2009 17:20:45 +0100 Subject: [Tutor] Handling Generator exceptions in Python 2.5 References: Message-ID: "Joe Python" wrote > *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))]* > > The above generator, throws '*ZeroDivisionError*' exception if ListA[i] > = > 0. > Is there a way to say 'Don't divide by ListA[i] if its equal to 0 (within > that statement)'. You could use an 'or' sideffect result = [(ListA[i] - ListB[i-1])/(ListA[i] or 1) for i in range(len(ListA))] But whether dividing by 1 as a default makes any sense will be a choice depending on the application and data. Alan G From davea at ieee.org Fri Jun 19 20:34:04 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 19 Jun 2009 14:34:04 -0400 Subject: [Tutor] Handling Generator exceptions in Python 2.5 In-Reply-To: References: Message-ID: <4A3BDA1C.1080606@ieee.org> Joe Python wrote: > I have a generator as follows to do list calculations. > > *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))]* > > The above generator, throws '*ZeroDivisionError*' exception if ListA[i] = > 0. > Is there a way to say 'Don't divide by ListA[i] if its equal to 0 (within > that statement)'. > > Sorry if this question sounds too stupid. > > TIA > Joe > Doesn't sound stupid to me at all. Short answer is a conditional expression. Replace (ListA[i] - ListB[i-1])/ListA[i] with (ListA[i] - ListB[i-1])/ListA[i] if ListA[i] else 1.0 and you'll see 1.0 whenever ListA[i] == 0, and your original value otherwise. But I see a couple of other things. You're calling this a generator when it's a list comprehension. For short lists, that frequently doesn't matter, but in case it does, you could start by replacing the braces on the outside with parentheses. Next question is the two lists are the same length. And final one is whether you really meant the offset of one when accessing ListB. If the lists are both of length 4, you're doing something like (a0 - b3)/a0 (a1-b0)/a1 (a2-b1)/a2 (a3-b2)/a3 In other words, you're using the last item of ListB for the first division. If that's really what you want, consider the following generator: gen = ((a-b)/a if a!=0.0 else 1.0 for a,b in zip(ListA, ListB[-1:]+ListB)) From saeed.gnu at gmail.com Fri Jun 19 22:13:01 2009 From: saeed.gnu at gmail.com (saeed) Date: Sat, 20 Jun 2009 00:43:01 +0430 Subject: [Tutor] [pygtk] taking image of gtk.drawing area In-Reply-To: References: Message-ID: <6aba7fa70906191313m42c1ec9eqe2525c71b8eba3ff@mail.gmail.com> JPEG doesn't support alpha (transparency), try with PNG or GIF. On 6/19/09, Amit Sethi wrote: > Hi , > I am trying to take image of a gst video playing in the gtk.drawingarea i am > using following code for it : > > def snap_shot(self,widget,data=None): > global file_loc ,pixbuf > self.pipeline.set_state(gst.STATE_PAUSED) > pixbuf = gtk.gdk.Pixbuf( gtk.gdk.COLORSPACE_RGB, False, 8, 640, 480) > pixbuf.get_from_drawable( self.movie_window.window, > self.movie_window.get_colormap(), 0, 0, 0, 0, 640, 480) > file_loc="/tmp/bar%d"%time.time() > pixbuf.save(file_loc,'jpeg', {'quality':'100'}) > self.pipeline.set_state(gst.STATE_PLAYING) > > but the movie seems to momentarily stop and i am left with a dark image > where i might be going wrong?? > > -- > A-M-I-T S|S > From cosmicsand27 at yahoo.com Fri Jun 19 22:42:56 2009 From: cosmicsand27 at yahoo.com (Raj Medhekar) Date: Fri, 19 Jun 2009 13:42:56 -0700 (PDT) Subject: [Tutor] Need help with code. Message-ID: <532371.85169.qm@web43405.mail.sp1.yahoo.com> Hi, I need help with the code below. I am trying to pair the list in the hint with the list of words. However, the list is not matching up correctly. Also when the correct guess is entered the program just continues without acknowledging the right answer. Please could y'all test this out and let me know where I am going wrong. I also want to add a scoring system where the computer rewards the person that guesses without getting a hint. Any suggestions as to how I might go about incorporating that into my code. Thanks for the help! Peace, Raj # Word Jumble V2 # Computer jumbles a randomly selected word then asks the player to guess it # If player cant guess the word he can ask for a hint # Scoring system that rewards players for solving jumble without a hint (not included in this code) import random WORDS = ("sweep","difficult", "python", "america") HINTS = ("remove dirt","not easy","computer language and a snake", "land of the free") word = random.choice(WORDS) correct = word jumble = "" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position+1):] for word in WORDS: HINTS[position] == WORDS[position] print\ """ Welcome to Word Jumble Unscramble the letters to make a word Remember Hints lower your score (Press the enter key at the prompt to exit) """ print "The jumble is: ",jumble guess = raw_input("Guess the word: ") guess = guess.lower() tries = 1 while guess != word and word !="" and tries <5: print "Sorry! That's not it!" guess = raw_input("Guess the word: ") guess = guess.lower() tries +=1 if guess == correct: print "You're right, the word is", word else: print "Maybe you need a hint:" print HINTS[position] guess = raw_input("Guess the word: ") guess = guess.lower() raw_input("\n\nPress the enter key to exit:") -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Fri Jun 19 23:41:27 2009 From: srilyk at gmail.com (Wayne) Date: Fri, 19 Jun 2009 16:41:27 -0500 Subject: [Tutor] Tkinter idiosyncracies? Message-ID: <333efb450906191441h289fbbd6u6349b054df3218a9@mail.gmail.com> Hi, I'm having some problems with Tkinter doing its own thing (or not) when I try to time events. for instance: import time import Tkinter as tk def funky(): lbl.config(text='Foo') time.sleep(4) lbl.config(text='Bar') root = tk.Tk() lbl = tk.Label(text = "Click the button to see weirdness") btn = tk.Button(text='Click me', command=funky) lbl.pack() btn.pack() root.mainloop() I'd expect that upon clicking the button the text of the label would change to 'Foo', then it would wait for 4 seconds, and then the text would change to 'Bar'. It doesn't do this - instead, it waits for 4 seconds, and then the text changes to foo, then bar, almost too fast to see. A similar thing happens (or the exact same) if you replace funky with this definition: def funky(): lbl.config(text='Foo') lbl.after(4000, lbl.config(text='Bar')) Am I missing something essential here? Or is this a bug that nobody has encountered yet? I appreciate any help! TIA, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sat Jun 20 00:12:17 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 20 Jun 2009 08:12:17 +1000 Subject: [Tutor] Tkinter idiosyncracies? In-Reply-To: <333efb450906191441h289fbbd6u6349b054df3218a9@mail.gmail.com> References: <333efb450906191441h289fbbd6u6349b054df3218a9@mail.gmail.com> Message-ID: Wayne wrote: > I'd expect that upon clicking the button the text of the label would > change to 'Foo', then it would wait for 4 seconds, and then the text > would change to 'Bar'. It doesn't do this - instead, it waits for 4 > seconds, and then the text changes to foo, then bar, almost too fast to > see. A similar thing happens (or the exact same) if you replace funky > with this definition: after and sleep is a blocking operation. That means after you called them, the program execution does not have the chance to return to the main loop and tk does not have the chance to update the screen. From alan.gauld at btinternet.com Sat Jun 20 00:13:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Jun 2009 23:13:51 +0100 Subject: [Tutor] Tkinter idiosyncracies? References: <333efb450906191441h289fbbd6u6349b054df3218a9@mail.gmail.com> Message-ID: "Wayne" wrote > Am I missing something essential here? > Or is this a bug that nobody has encountered yet? Its not a bug its the way GUIs and event driven programs work. You need to buuld the time delay as an event so the after() approach is nearly right. But you need the first event to make it say Foo then the after event to change it to Bar. You can use a single event handler with a parameter then use a lambda to pass the value in. Something like: import Tkinter as tk def funky(value=None): if value: lbl.config(text=value) else: lbl['text'] = 'Foo' lbl.after(3000, lambda : funky('Bar') ) root = tk.Tk() lbl = tk.Label(text = "Click the button to see weirdness") btn = tk.Button(text='Click me', command=funky) lbl.pack() btn.pack() root.mainloop() Otherwise the GUI doesn;t get redrawn until after the handler exits which means both updates get done at the same time. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lie.1296 at gmail.com Sat Jun 20 00:30:07 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 20 Jun 2009 08:30:07 +1000 Subject: [Tutor] list of instance objects, access attribute In-Reply-To: References: <77e831100906181632s6043ddb0p34a30be6698183d7@mail.gmail.com> Message-ID: Alan Gauld wrote: > > "Vincent Davis" wrote > > class B(): > def __init__(self, b1, b2): > self.fooa = b1 > self.foob = b2 > > I assume thats what you really meant! > > Ok now I have several instances in a list > b1 = B(1, 2) > b2 = B(3, 4) > b3 = B(9, 10) > alist = [b1, b2, b3] > >> Lets say for each instance of the class I want to print the value of >> fooa if it is greater than 5. How do I do this, > > define a method of the class, say bigprint() > > def bigprint(self, limit=5): > if self.fooa > limit: print self.fooa > >> about is how I iterate over the values of fooa. > > Iterate over the objects and call the method. Make the object do the > work, your code should not need to know about the internal attributes of > the object. > > For x in alist: > x.bigprint() > >> Is that the right way or is there a better? >> will this work for methods? > > Methods are how you should do it. Direct access other than for simple > reading of values is a suspicious design smell. Any processing of or > rules about the data should be in a method. > > Personally, I often thought input/output inside an object is a design smell (except for debugging), preferring something like this: class B(object): def __init__(...): ... def big(self, limit=5): return (self.fooa > limit) alist = [...] for y in (x for x in alist if x.big()): print y.fooa although admittably often it could make certain codes more difficult to write; and in some cases the practical approach would be warranted. This is especially true as the codebase gets larger. From robert.lummis at gmail.com Sat Jun 20 00:23:49 2009 From: robert.lummis at gmail.com (Robert Lummis) Date: Fri, 19 Jun 2009 18:23:49 -0400 Subject: [Tutor] how to manage an encrypted file? Message-ID: <71d330f00906191523y1f4c0bcdy45f9c8c30a8e0fd3@mail.gmail.com> Could you recommend a module or methods I should use to manage an encrypted text file? I want to store passwords and associated contact information in a file and feel confident that if the file is stolen the information couldn't be read. -- Robert Lummis From bgailer at gmail.com Sat Jun 20 02:25:42 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 19 Jun 2009 20:25:42 -0400 Subject: [Tutor] Need help with code. In-Reply-To: <532371.85169.qm@web43405.mail.sp1.yahoo.com> References: <532371.85169.qm@web43405.mail.sp1.yahoo.com> Message-ID: <4A3C2C86.6090009@gmail.com> Raj Medhekar wrote: > Hi, I need help with the code below. I am trying to pair the list in > the hint with the list of words. However, the list is not matching up > correctly. Also when the correct guess is entered the program just > continues without acknowledging the right answer. Please could y'all > test this out and let me know where I am going wrong. I also want to > add a scoring system where the computer rewards the person that > guesses without getting a hint. Any suggestions as to how I might go > about incorporating that into my code. Thanks for the help! > > Peace, > Raj I will throw out a few hints below. I suggest you familiarize yourself with "desk checking" - walking through the program by hand , writing down the values of variables at each step, and tracking the loops and conditions carefully. > > # Word Jumble V2 > # Computer jumbles a randomly selected word then asks the player to > guess it > # If player cant guess the word he can ask for a hint Note you don't offer a way to ask for a hint, you just give it. > # Scoring system that rewards players for solving jumble without a > hint (not included in this code) > Get the rest working first. > import random > > WORDS = ("sweep","difficult", "python", "america") > HINTS = ("remove dirt","not easy","computer language and a snake", > "land of the free") > > word = random.choice(WORDS) > correct = word > jumble = "" > > while word: > position = random.randrange(len(word)) > jumble += word[position] > word = word[:position] + word[(position+1):] OK so far. The next loop does not make sense - it uses word to iterate thru WORDS but does nothing with word! Position is a constant (0) so all it does is compare "remove dirt" with "sweeps" 4 times. > for word in WORDS: > HINTS[position] == WORDS[position] > > print\ > """ > Welcome to Word Jumble > Unscramble the letters to make a word > Remember Hints lower your score > (Press the enter key at the prompt to exit) > """ > print "The jumble is: ",jumble > guess = raw_input("Guess the word: ") > guess = guess.lower() > tries = 1 OK again. The while condition below does not make sense. word will always be "america" (can you see why?) > while guess != word and word !="" and tries <5: > print "Sorry! That's not it!" > guess = raw_input("Guess the word: ") > guess = guess.lower() > tries +=1 > if guess == correct: > print "You're right, the word is", word > else: > print "Maybe you need a hint:" > print HINTS[position] > guess = raw_input("Guess the word: ") > guess = guess.lower() > The program at this point is not in any loop so it terminates. > > raw_input("\n\nPress the enter key to exit:") -- Bob Gailer Chapel Hill NC 919-636-4239 From davea at ieee.org Sat Jun 20 02:27:42 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 19 Jun 2009 20:27:42 -0400 Subject: [Tutor] Need help with code. In-Reply-To: References: Message-ID: <4A3C2CFE.1020006@ieee.org> Raj Medhekar wrote: > Hi, I need help with the code below. I am trying to pair the list in the hint with the list of words. However, the list is not matching up correctly. Also when the correct guess is entered the program just continues without acknowledging the right answer. Please could y'all test this out and let me know where I am going wrong. I also want to add a scoring system where the computer rewards the person that guesses without getting a hint. Any suggestions as to how I might go about incorporating that into my code. Thanks for the help! > > Peace, > Raj > > # Word Jumble V2 > # Computer jumbles a randomly selected word then asks the player to guess it > # If player cant guess the word he can ask for a hint > # Scoring system that rewards players for solving jumble without a hint (not included in this code) > > import random > > WORDS = ("sweep","difficult", "python", "america") > HINTS = ("remove dirt","not easy","computer language and a snake", > "land of the free") > > word = random.choice(WORDS) > correct = word > jumble = "" > > while word: > position = random.randrange(len(word)) > jumble += word[position] > word = word[:position] + word[(position+1):] > for word in WORDS: > HINTS[position] == WORDS[position] > > print\ > """ > Welcome to Word Jumble > Unscramble the letters to make a word > Remember Hints lower your score > (Press the enter key at the prompt to exit) > """ > print "The jumble is: ",jumble > guess = raw_input("Guess the word: ") > guess = guess.lower() > tries = 1 > while guess != word and word !="" and tries <5: > print "Sorry! That's not it!" > guess = raw_input("Guess the word: ") > guess = guess.lower() > tries +=1 > if guess == correct: > print "You're right, the word is", word > else: > print "Maybe you need a hint:" > print HINTS[position] > guess = raw_input("Guess the word: ") > guess = guess.lower() > > > raw_input("\n\nPress the enter key to exit:") > > > To start with, what did you possibly hope to do with: for word in WORDS: HINTS[position] == WORDS[position] The body of that loop does nothing at all. What you really wanted was: position = WORDS.index(correct) Next, examine the phrase: while guess != word and word !="" and tries <5: print "Sorry! That's not it!" Why would you be comparing 'guess' against the highest word in the list? Shouldn't you be comparing it to 'correct' ? From cfuller084 at thinkingplanet.net Sat Jun 20 06:45:34 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 19 Jun 2009 23:45:34 -0500 Subject: [Tutor] how to manage an encrypted file? In-Reply-To: <71d330f00906191523y1f4c0bcdy45f9c8c30a8e0fd3@mail.gmail.com> References: <71d330f00906191523y1f4c0bcdy45f9c8c30a8e0fd3@mail.gmail.com> Message-ID: <200906192345.34930.cfuller084@thinkingplanet.net> On Friday 19 June 2009 17:23, Robert Lummis wrote: > Could you recommend a module or methods I should use to manage an > encrypted text file? I want to store passwords and associated contact > information in a file and feel confident that if the file is stolen > the information couldn't be read. Use the PyCrypto module. It (not so) recently changed maintainers, there isn't a release yet at the main site: http://www.dlitz.net/software/pycrypto/, so use the old site for now, http://www.amk.ca/python/code/pycrypto.html. If you're using Linux, check to see if there's already a package for your distribution. There are windoze binaries at http://www.voidspace.org.uk/modules.shtml#pycrypto. Cheers From vincent at vincentdavis.net Sat Jun 20 07:04:13 2009 From: vincent at vincentdavis.net (Vincent Davis) Date: Fri, 19 Jun 2009 23:04:13 -0600 Subject: [Tutor] list of instance objects, access attribute In-Reply-To: References: <77e831100906181632s6043ddb0p34a30be6698183d7@mail.gmail.com> Message-ID: <77e831100906192204s44deccdfn9d89e37e34d1a411@mail.gmail.com> Thanks to all for the comments, It was much more than I expected. Vincent On Fri, Jun 19, 2009 at 4:30 PM, Lie Ryan wrote: > Alan Gauld wrote: >> >> "Vincent Davis" wrote >> >> class B(): >> ?def __init__(self, b1, b2): >> ? ? self.fooa = b1 >> ? ? self.foob = b2 >> >> I assume thats what you really meant! >> >> Ok now I have several instances in a list >> b1 = B(1, 2) >> b2 = B(3, 4) >> b3 = B(9, 10) >> alist = [b1, b2, b3] >> >>> Lets say for each instance of the class I want to print the value of >>> fooa if it is greater than 5. How do I do this, >> >> define a method of the class, say bigprint() >> >> def bigprint(self, limit=5): >> ? ? if self.fooa > limit: print self.fooa >> >>> about is how I iterate over the values of fooa. >> >> Iterate over the objects and call the method. Make the object do the >> work, your code should not need to know about the internal attributes of >> the object. >> >> For x in alist: >> ? ? ?x.bigprint() >> >>> Is that the right way or is there a better? >>> will this work for methods? >> >> Methods are how you should do it. Direct access other than for simple >> reading of values is a suspicious design smell. Any processing of or >> rules about the data should be in a method. >> >> > > Personally, I often thought input/output inside an object is a design > smell (except for debugging), preferring something like this: > > class B(object): > ? ?def __init__(...): > ? ? ? ?... > ? ?def big(self, limit=5): > ? ? ? ?return (self.fooa > limit) > > alist = [...] > > for y in (x for x in alist if x.big()): > ? ?print y.fooa > > although admittably often it could make certain codes more difficult to > write; and in some cases the practical approach would be warranted. This > is especially true as the codebase gets larger. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From john_re at fastmail.us Sat Jun 20 09:39:53 2009 From: john_re at fastmail.us (john_re) Date: Sat, 20 Jun 2009 00:39:53 -0700 Subject: [Tutor] Join Python Global Meeting Sunday June 21 using VOIP - BerkeleyTIP Message-ID: <1245483593.28275.1321307343@webmail.messagingengine.com> Join the friendly Python Global [& ALL FREE SW HW & CULTURE] community Meeting: this Sunday, June 21, using VOIP, 10A - 6P Pacific USA time [GMT - 8? 7? hours] = 1P - 9P Eastern USA = 6P - 2A??? GMT - Daylight savings correction? +7 hours? at the BerkeleyTIP Global Free SW HW & Culture meeting http://sites.google.com/site/berkeleytip/ CONNECT VIA VOIP (& IRC): Join IRC channel #berkeleytip on freenode.net, & we'll help get you connected on VOIP. Have a VOIP headset. http://sites.google.com/site/berkeleytip/remote-attendance LOCAL MEETING NEW LOCATION: Free speech cafe closed Sundays in summer. Watch the BTIP local list for final in person UCB meeting location details: http://groups.google.com/group/BerkTIP GENERIC HOURLY SCHEDULE, & MARK YOUR CALENDAR - NEXT 3 MEETINGS: Sun June 21, Sat July 4, Sun July 19 http://sites.google.com/site/berkeleytip/schedule Join the mailing list, introduce yourself, tell us what projects you are interested in, invite others to join your project: BTIP-Global http://groups.google.com/group/BerkTIPGlobal ===== HOT TOPICs: Oracle owns OpenOffice & MySQL - What help is needed? KDE 4 aps need work - especially Calendar?! Open Hardware - Robotics? POLL: ** How about 2x per month Weekday Evening BTIP-Global Meetings? ** 1) The Wednesday & Thursday _after_ the BTIP weekend meetings? 2) The Monday & Tuesday _before_ the BTIP weekend meetings? 3) Other? Your suggestions? - Join the mailing list & send in your opinions/thoughts/suggestions. GROUP PROJECT - Asterisk VOIP conference server: We've now got our own Asterisk VOIP conference server. [Thanks, Windsor & Jack! :) ] Help: - get a user channel members status page working - get SIP & Skype ability? http://sites.google.com/site/berkeleytip/remote-attendance YOUR PROJECT - LET US KNOW, GET SOME VOLUNTEER HELP: http://groups.google.com/group/BerkTIPGlobal VIDEOS - OPPORTUNITY - FINDER VOLUNTEER NEEDED No videos this month, cause David & I are too busy. Do you want to find some for us all to watch? Check out this link, email the list & let us know you'd like to volunteer. :) http://sites.google.com/site/berkeleytip/talk-videos See the mailing lists for the latest info/changes: http://sites.google.com/site/berkeleytip/mailing-lists JOIN THE ANNOUNCEMENT LIST - 1 or 2 announcements per month: http://groups.google.com/group/BerkTIPAnc FOR FORWARDING: You are invited to forward this message to anywhere appropriate. From gdoghomes at gmail.com Sat Jun 20 09:49:13 2009 From: gdoghomes at gmail.com (Michael Morrissey) Date: Sat, 20 Jun 2009 14:49:13 +0700 Subject: [Tutor] Generating Deck Combinations Message-ID: I need to generate all possible deck combinations given two different lists as input. The Input: List 1 has Card names listed inside it. List 2 has Maximum Quantities for each Card name. For example: List1[0] would be: "Aether Vial" List2[0] would be: "4" List1[1] would be: "Mountain" List2[1] would be: "10" List1[2] would be: "Gempalm Incinerator" List2[2] would be: "3" etc. A deck is 60 cards total (no more, no less). I need to loop over these lists to generate all possible combinations of 60 card decks which use up to the maximum quantity for each card. So, from the example, I need to generate decks with '1' Aether Vial' and 59 other cards in all possible combinations (still within the maximum cap for each card), and then I'd need to generate decks with '2' Aether Vial' and 58 other cards in all possible combinations It is vital that I create all combinations and that the maximum quantities are never breached. I am hoping that the each deck could be output as two lists: ListA = ['Cardname1', 'Cardname2', ...] ListB = ['1', '2', ...] These lists will have exactly 60 members. If you have an idea of how to do this, please share it! =) I would be most appreciative. I'll be testing all methods for speed because I have very large amount of computing to do. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Sat Jun 20 10:34:31 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 20 Jun 2009 09:34:31 +0100 Subject: [Tutor] how to manage an encrypted file? In-Reply-To: <71d330f00906191523y1f4c0bcdy45f9c8c30a8e0fd3@mail.gmail.com> References: <71d330f00906191523y1f4c0bcdy45f9c8c30a8e0fd3@mail.gmail.com> Message-ID: <4A3C9F17.4040301@timgolden.me.uk> Robert Lummis wrote: > Could you recommend a module or methods I should use to manage an > encrypted text file? I want to store passwords and associated contact > information in a file and feel confident that if the file is stolen > the information couldn't be read. If you're on Windows, just encrypt the file under Explorer. TJG From andreengels at gmail.com Sat Jun 20 12:09:58 2009 From: andreengels at gmail.com (Andre Engels) Date: Sat, 20 Jun 2009 12:09:58 +0200 Subject: [Tutor] Generating Deck Combinations In-Reply-To: References: Message-ID: <6faf39c90906200309n60780a0cwa0e8e984b77b07a4@mail.gmail.com> On Sat, Jun 20, 2009 at 9:49 AM, Michael Morrissey wrote: > I need to generate all possible deck combinations given two different lists > as input. > The Input: > List 1 has Card names listed inside it. > List 2 has Maximum Quantities for each Card name. > > For example: > > List1[0] would be: "Aether Vial" > List2[0] would be: "4" > > List1[1] would be: "Mountain" > List2[1] would be: "10" > > List1[2] would be: "Gempalm Incinerator" > List2[2] would be: "3" > > etc. In my opinion, that's a very unpythonic way of specifying data - I would use a dictionary for this kind of information: maximalQuantity = {"Aether Vial": 4, "Mountain": 10, "Gempalm Incinerator": 3 ...} > A deck is 60 cards total (no more, no less).?I need to loop over these lists > to generate all possible combinations of 60 card decks which use up to the > maximum quantity for each card. > So, from the example, I need to generate decks with '1' Aether Vial' and 59 > other cards in all possible combinations (still within the maximum cap for > each card), and then I'd need to generate decks with '2' Aether Vial' and 58 > other cards in all possible combinations > It is vital that I create all combinations and that the maximum quantities > are never breached. > I am hoping that the each deck could be output as two lists: > ListA = ['Cardname1', 'Cardname2', ...] > ListB = ['1', '2', ...] > These lists will have exactly 60 members. > If you have an idea of how to do this, please share it! =) I would be most > appreciative. I'll be testing all methods for speed because I have very > large amount of computing to do. Given that ListB will _always_ be ['1', '2', '3', ..., '60'], I do not see what its use is... For this problem I would use recursion. I define a function possible_decks(listA, listB, number) its input are the lists listA and listB and the number of cards in the deck, its output is a list of lists, each of which is ListA (it is confusing to have the same name for two different objects in your description...) for some legal deck. The code would be (untested): def possible_decks(listA, listB, number): if number < 0: return [] # trying to put more than 60 cards in the deck if number == 0: return [[]] # there's exactly one deck of size 0 - the empty deck if not listA: return [] # out of cards, but the deck is not yet full thiselement = listA[0] thismaximum = int(listB[0]) returnvalue = [] for i in xrange(thismaximum): possible_rests_of_deck = possible_decks(listA[1:], listB[1:], number - i) returnvalue += [i*[thiselement] + deck for deck in possible_rests_of_deck] return returnvalue -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Sat Jun 20 13:17:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Jun 2009 12:17:32 +0100 Subject: [Tutor] how to manage an encrypted file? References: <71d330f00906191523y1f4c0bcdy45f9c8c30a8e0fd3@mail.gmail.com> <4A3C9F17.4040301@timgolden.me.uk> Message-ID: "Tim Golden" wrote >> encrypted text file? I want to store passwords and associated contact >> information in a file and feel confident that if the file is stolen >> the information couldn't be read. > > If you're on Windows, just encrypt the file under Explorer. Although that's not very secure: if you copy it to a non NTFS filesystem since Windows will, by default, helpfully unencrypt it for you... There is some stuff on MSDN that tells how to make Windows encryption work sensibly but the defaults make it kind of pointless. (Actually, I haven't tried this on XP, but certainly on Win2000 the default encryption was a joke. If anyone can confirm that XP fixes it I might start using it again.) Alan G. From kent37 at tds.net Sat Jun 20 13:40:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 20 Jun 2009 07:40:05 -0400 Subject: [Tutor] Generating Deck Combinations In-Reply-To: References: Message-ID: <1c2a2c590906200440s2e086666k41632aceb9d78227@mail.gmail.com> On Sat, Jun 20, 2009 at 3:49 AM, Michael Morrissey wrote: > I need to generate all possible deck combinations given two different lists > as input. > The Input: > List 1 has Card names listed inside it. > List 2 has Maximum Quantities for each Card name. I generally prefer a list of pairs to paired list. In this case I would use a single list containing tuples of (card name, max quantitiy). > A deck is 60 cards total (no more, no less).?I need to loop over these lists > to generate all possible combinations of 60 card decks which use up to the > maximum quantity for each card. This cries out for a recursive solution - pick a number of the first card, then create all possible decks containing the remaining cards. Here is one solution. It uses a generator function, so rather than returning a list of all solutions, it creates an iterator that yields solutions. limits = [('A', 3), ('B', 2), ('C', 4)] def deck(limits, size): # Check for end condition if size == 0 or not limits: yield [] return # The current card and its limit card, cardMax = limits[0] # The remaining cards rest = limits[1:] # For each possible number of the current card for i in range(0, min(size, cardMax)+1): cards = [card] * i # Create all possible decks from the remaining cards for remainder in deck(rest, size-i): if size-i == len(remainder): yield cards + remainder for d in deck(limits, 5): print d There are probably faster ways but this is straightforward. One inefficiency in this one is that it generates a lot of short solutions that are screened out by the "if size-i == len(remainder)" conditional. This conditional isn't hit until the full recursion is completed. This could be optimized by creating a list of (card name, max quantity, max quantity following). I.e. the third element is the most cards that could be added from the remaining cards. If this is less than size-i, then there is no need to continue, the deck can't be completed. Kent From davea at ieee.org Sat Jun 20 15:27:59 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 20 Jun 2009 09:27:59 -0400 Subject: [Tutor] Generating Deck Combinations In-Reply-To: References: Message-ID: <4A3CE3DF.4030803@ieee.org> Michael Morrissey wrote: > I need to generate all possible deck combinations given two different lists > as input. > > The Input: > > List 1 has Card names listed inside it. > List 2 has Maximum Quantities for each Card name. > > For example: > > List1[0] would be: "Aether Vial" > List2[0] would be: "4" > > List1[1] would be: "Mountain" > List2[1] would be: "10" > > List1[2] would be: "Gempalm Incinerator" > List2[2] would be: "3" > > etc. > > > A deck is 60 cards total (no more, no less). I need to loop over these lists > to generate all possible combinations of 60 card decks which use up to the > maximum quantity for each card. > > So, from the example, I need to generate decks with '1' Aether Vial' and 59 > other cards in all possible combinations (still within the maximum cap for > each card), and then I'd need to generate decks with '2' Aether Vial' and 58 > other cards in all possible combinations > > It is vital that I create all combinations and that the maximum quantities > are never breached. > > I am hoping that the each deck could be output as two lists: > > ListA = ['Cardname1', 'Cardname2', ...] > ListB = ['1', '2', ...] > > These lists will have exactly 60 members. > > If you have an idea of how to do this, please share it! =) I would be most > appreciative. I'll be testing all methods for speed because I have very > large amount of computing to do. > It isn't considered polite to submit questions without even attempting your own solutions. And classroom assignments should be solved by the student. But I can give you some general hints. Since you're doing combinations, not permutations, the usual approach of making a complete deck (containing all possible duplicates of cards), and doing selection without replacement won't run in practical time. Consider writing a generator function (look up yield) that uses recursion to list all the cases. Worst case recursion would be 59, of course. Consider returning the results front loaded: Aether Vial-4, Mountain-10, ... .... Aether Vial-4, Mountain-9, ... .... Aether Vial-4, Mountain-8, ... .... ......... Aether Vial-3, Mountain-10, ... That way, the funny edge-cases are at the end, and you can just return the first time your recursion gets beyond the end of the ListA While initial testing, pick a much smaller number than 60, like 6. And of course use smaller numbers for ListB From srilyk at gmail.com Sat Jun 20 16:26:21 2009 From: srilyk at gmail.com (Wayne) Date: Sat, 20 Jun 2009 09:26:21 -0500 Subject: [Tutor] how to manage an encrypted file? In-Reply-To: References: <71d330f00906191523y1f4c0bcdy45f9c8c30a8e0fd3@mail.gmail.com> <4A3C9F17.4040301@timgolden.me.uk> Message-ID: <333efb450906200726x228463e7obf0d6dc2ba9477ff@mail.gmail.com> On Sat, Jun 20, 2009 at 6:17 AM, Alan Gauld wrote: > "Tim Golden" wrote > >> encrypted text file? I want to store passwords and associated contact >>> information in a file and feel confident that if the file is stolen >>> the information couldn't be read. >>> >> >> If you're on Windows, just encrypt the file under Explorer. >> > > Although that's not very secure: if you copy it to a non NTFS filesystem > since Windows will, by default, helpfully unencrypt it for you... > > There is some stuff on MSDN that tells how to make Windows encryption work > sensibly but the defaults make it kind of pointless. > (Actually, I haven't tried this on XP, but certainly on Win2000 the default > encryption was a joke. If anyone can confirm that XP fixes it I might start > using it again.) I used a program called AxCrypt ( http://www.axantum.com/AxCrypt/ ) that seemed to work alright. If you want the most basic encryption you could simply XOR the file. It's fairly easy to break, though, because the same character patterns will be present as with your original file. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From jopython at gmail.com Sat Jun 20 18:50:35 2009 From: jopython at gmail.com (Joe) Date: Sat, 20 Jun 2009 12:50:35 -0400 Subject: [Tutor] Handling Generator exceptions in Python 2.5 In-Reply-To: <4A3BDA1C.1080606@ieee.org> References: <4A3BDA1C.1080606@ieee.org> Message-ID: <4A3D135B.1090302@gmail.com> Dave, Thanks for enlightening me and providing a solution. I am a recent Python convert (from Perl). Hence the confusion about generators.(Coroutines are not a standard part of Perl anyway) - Joe Dave Angel wrote: > Joe Python wrote: > >> I have a generator as follows to do list calculations. >> >> *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))]* >> >> The above generator, throws '*ZeroDivisionError*' exception if >> ListA[i] = >> 0. >> Is there a way to say 'Don't divide by ListA[i] if its equal to 0 >> (within >> that statement)'. >> >> Sorry if this question sounds too stupid. >> >> TIA >> Joe > Doesn't sound stupid to me at all. > > Short answer is a conditional expression. Replace > (ListA[i] - ListB[i-1])/ListA[i] > with > (ListA[i] - ListB[i-1])/ListA[i] if ListA[i] else 1.0 > > and you'll see 1.0 whenever ListA[i] == 0, and your original value > otherwise. > > > But I see a couple of other things. You're calling this a generator > when it's a list comprehension. For short lists, that frequently > doesn't matter, but in case it does, you could start by replacing the > braces on the outside with parentheses. > > Next question is the two lists are the same length. And final one is > whether you really meant the offset of one when accessing ListB. If > the lists are both of length 4, you're doing something like > (a0 - b3)/a0 (a1-b0)/a1 (a2-b1)/a2 (a3-b2)/a3 > > In other words, you're using the last item of ListB for the first > division. > > If that's really what you want, consider the following generator: > gen = ((a-b)/a if a!=0.0 else 1.0 for a,b in zip(ListA, > ListB[-1:]+ListB)) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ptmcg at austin.rr.com Sat Jun 20 19:01:56 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 20 Jun 2009 12:01:56 -0500 Subject: [Tutor] Generating deck combinations In-Reply-To: References: Message-ID: <9433B4DEA55E4E7C940D663CB0FCA337@AWA2> If you are looking for all possible 60-card deals of this deck, then you also probably want to filter out duplicate deals caused by equivalent cards exchanging places. That is, say you had a deck of 3 cards: 2 Mountain, and 1 Vial, and you want to deal out al 3 in various order of cards. Using the recursive solutions, you will get: (hmm, couldn't get either of the previous submissions to work..., well something like this) ['Mountain', 'Mountain', 'Vial'] ['Mountain', 'Vial', 'Mountain'] ['Mountain', 'Mountain', 'Vial'] ['Mountain', 'Vial', 'Mountain'] ['Vial', 'Mountain', 'Mountain'] ['Vial', 'Mountain', 'Mountain'] That is, because you have 2 Mountain cards, recursively shuffling this list *looks* like you have two different list elements to process, but in fact, they are equivalent so you will get duplicate deals. Now imagine you have up to 150 different types of cards, in quantities of 1-10 of each, and this problem magnifies considerably. Try this version (mildly tested): def deal(cards, size): if size > len(cards): raise ValueError, "cannot deal more cards than are in the deck" if size == 1: for cd in cards: yield [cd] else: for i,cd in enumerate(cards): remainder = cards[:i] + cards[i+1:] for d in deal(remainder,size-1): yield [cd]+d cardlist = [('Mountain', 2), ('Vial', 6), ] allcards = sum(([card,]*qty for card,qty in cardlist), []) # generate all unique deals of 'n' cards from allcards # use the seenalready set to avoid reporting duplicate deals n = 4 seenalready = set() for d in deal(allcards,n): newdeck = tuple(d) if newdeck not in seenalready: print d seenalready.add(newdeck) Here are all the 4-card deals from this pack of 8 cards: ['Mountain', 'Mountain', 'Vial', 'Vial'] ['Mountain', 'Vial', 'Mountain', 'Vial'] ['Mountain', 'Vial', 'Vial', 'Mountain'] ['Mountain', 'Vial', 'Vial', 'Vial'] ['Vial', 'Mountain', 'Mountain', 'Vial'] ['Vial', 'Mountain', 'Vial', 'Mountain'] ['Vial', 'Mountain', 'Vial', 'Vial'] ['Vial', 'Vial', 'Mountain', 'Mountain'] ['Vial', 'Vial', 'Mountain', 'Vial'] ['Vial', 'Vial', 'Vial', 'Mountain'] ['Vial', 'Vial', 'Vial', 'Vial'] (If order is not significant, then you could simplify this algorithm accordingly, and you would get these results: ['Mountain', 'Mountain', 'Vial', 'Vial'] ['Mountain', 'Vial', 'Vial', 'Vial'] ['Vial', 'Vial', 'Vial', 'Vial'] ) This is definitely a brute-force approach (brute-force is actually my favorite first approach), generating all possible deals and then filtering duplicates using a set of "already been seen" deals. A smarter algorithm would generate only the unique deals. If someone were paying me to be that smart, maybe I'd work on it. I'm guessing this is an attempt to optimize a deck for playing a card game like Magic or Pokemon, etc. Your plan is, given a set of 'n' cards in your collection (presumbaly n>60, or there would be no problem to solve), to compute all possible decks of 60 cards. Then you have some function to evaluate this deck, or perhaps simulate playing it against another deck. You will then exhaustively run this simulation function against each deck to find which deck from your collection of 100's of cards is the "best". By the time your program has finished running, I suspect the sun will be a cold, dark cinder. But have fun with it. -- Paul From kent37 at tds.net Sat Jun 20 23:21:37 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 20 Jun 2009 17:21:37 -0400 Subject: [Tutor] Generating deck combinations In-Reply-To: <9433B4DEA55E4E7C940D663CB0FCA337@AWA2> References: <9433B4DEA55E4E7C940D663CB0FCA337@AWA2> Message-ID: <1c2a2c590906201421w1174ec21oc2329326963c4c01@mail.gmail.com> On Sat, Jun 20, 2009 at 1:01 PM, Paul McGuire wrote: > If you are looking for all possible 60-card deals of this deck, then you > also probably want to filter out duplicate deals caused by equivalent cards > exchanging places. ?That is, say you had a deck of 3 cards: 2 Mountain, and > 1 Vial, and you want to deal out al 3 in various order of cards. ?Using the > recursive solutions, you will get: > > (hmm, couldn't get either of the previous submissions to work..., well > something like this) > > ['Mountain', 'Mountain', 'Vial'] > ['Mountain', 'Vial', 'Mountain'] > ['Mountain', 'Mountain', 'Vial'] > ['Mountain', 'Vial', 'Mountain'] > ['Vial', 'Mountain', 'Mountain'] > ['Vial', 'Mountain', 'Mountain'] No, my solution does not generate that list. It generates ['Vial', 'Vial', 'Vial'] ['Mountain', 'Vial', 'Vial'] ['Mountain', 'Mountain', 'Vial'] > That is, because you have 2 Mountain cards, recursively shuffling this list > *looks* like you have two different list elements to process, but in fact, > they are equivalent so you will get duplicate deals. My solution does not shuffle. It picks each possible number of the first card, then recursively constructs all possible decks from the remaining card . Kent From froslie at gmail.com Sun Jun 21 00:03:36 2009 From: froslie at gmail.com (Pete Froslie) Date: Sat, 20 Jun 2009 18:03:36 -0400 Subject: [Tutor] filling in web forms Message-ID: <41fcacc90906201503k4fc77e3fxbb299d200b678267@mail.gmail.com> I would to access web forms and fill them out. I am feeling that the 'ClientForm' module makes sense as a starting place, but am concerned that maybe it is dated and that there might be a better starting option.. can anyone help start me along the correct path as I am pretty new to python and not the most experienced programmer? thanks so much! -- P Froslie http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at Safe-mail.net Sat Jun 20 21:34:36 2009 From: python.list at Safe-mail.net (python.list at Safe-mail.net) Date: Sat, 20 Jun 2009 15:34:36 -0400 Subject: [Tutor] reading and processing xml files with python Message-ID: Hi, I am a total python XML noob and wanted some clarification on using python with reading remote XML data. All examples I have found assumes the data is stored localy or have I misunderstood this? If I browse to: 'user:password at domain.com/external/xmlinterface.jsp?cid=xxx&resType=hotel200631&intfc=ws&xml=' This request returns a page like: ? 134388 Milford Plaza at Times Square 700 8th Avenue New York NY US 10036 NYC 155.4 259.0 USD 40.75905 -73.98844 + <b>Location.</b><br> <UL><LI>The Milford Plaza is located in New York, N.Y. /hotels/thumbs/NYC_MILF-exter-1-thumb.jpg H TIMES SQUARE/THEATER DISTRICT 2.5 1 1 true true 3.9202964 MI + N 72 Hour Sale - Don't miss this great deal! 17A828141014136319 -1 25033 true false Standard room 108606 252427 ? USD ? 259.0 259.0 575.76 575.76 57.76 USD ? 259.0 259.0 575.76 B ? USD ? 155.4 155.4 368.56 368.56 57.76 USD ? 155.4 155.4 368.56 B I got this so far: >>> import urllib2 >>> request = urllib2.Request('user:password at domain.com/external/xmlinterface.jsp?cid=xxx&resType=hotel200631&intfc=ws&xml=') >>> opener = urllib2.build_opener() >>> firstdatastream = opener.open(request) >>> firstdata = firstdatastream.read() >>> print firstdata 134388 Milford Plaza at Times Square 700 8th Avenue New York NY US 10036 ... >>> I would like to understand how to manipulate the data further and extract for example all the hotel names in a list? Thank you Marti From norman at khine.net Sun Jun 21 06:35:18 2009 From: norman at khine.net (Norman Khine) Date: Sun, 21 Jun 2009 06:35:18 +0200 Subject: [Tutor] filling in web forms In-Reply-To: <41fcacc90906201503k4fc77e3fxbb299d200b678267@mail.gmail.com> References: <41fcacc90906201503k4fc77e3fxbb299d200b678267@mail.gmail.com> Message-ID: <9c2c8ffb0906202135k33428c0bh45b3524273dbe12d@mail.gmail.com> On Sun, Jun 21, 2009 at 12:03 AM, Pete Froslie wrote: > I would to access web forms and fill them out. > > I am feeling that the 'ClientForm' module makes sense as a starting place, > but am concerned that maybe it is dated and that there might be a better > starting option.. can anyone help start me along the correct path as I am > pretty new to python and not the most experienced programmer? You could try using twill http://twill.idyll.org/ The first example shows you how to fill out a login form. http://twill.idyll.org/examples.html > > thanks so much! > > -- > P Froslie > http://www.froslie.net > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From zstumgoren at gmail.com Sun Jun 21 07:03:13 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Sun, 21 Jun 2009 01:03:13 -0400 Subject: [Tutor] filling in web forms In-Reply-To: <9c2c8ffb0906202135k33428c0bh45b3524273dbe12d@mail.gmail.com> References: <41fcacc90906201503k4fc77e3fxbb299d200b678267@mail.gmail.com> <9c2c8ffb0906202135k33428c0bh45b3524273dbe12d@mail.gmail.com> Message-ID: You might want to read up on Python Mechanize as well: http://wwwsearch.sourceforge.net/mechanize/ From froslie at gmail.com Sun Jun 21 07:25:21 2009 From: froslie at gmail.com (Pete Froslie) Date: Sun, 21 Jun 2009 01:25:21 -0400 Subject: [Tutor] filling in web forms In-Reply-To: References: <41fcacc90906201503k4fc77e3fxbb299d200b678267@mail.gmail.com> <9c2c8ffb0906202135k33428c0bh45b3524273dbe12d@mail.gmail.com> Message-ID: <41fcacc90906202225j53f69a50g938aea63a98f5ff4@mail.gmail.com> Thank you so much.. I will start looking into twill and I just finished installing Mechanize. FYI: I use Netbeans as my IDE and encountered an error that took some time to resolve, as follows: A java.lang.NoClassDefFoundError exception has occurred the resolution can be found here if you run into it: http://forums.netbeans.org/post-38386.html it seems to have been an issue with mac OS X : java 10.5 update 6. with that fixed I'll be able to try these options out.. On Sun, Jun 21, 2009 at 1:03 AM, Serdar Tumgoren wrote: > You might want to read up on Python Mechanize as well: > > http://wwwsearch.sourceforge.net/mechanize/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Sun Jun 21 08:17:44 2009 From: norman at khine.net (Norman Khine) Date: Sun, 21 Jun 2009 08:17:44 +0200 Subject: [Tutor] reading and processing xml files with python In-Reply-To: References: Message-ID: <9c2c8ffb0906202317q1b1c7a2ewf8cc673bb9b6ac85@mail.gmail.com> you can use something like http://docs.hforge.org/itools/xml.html to process your xml request or some other python xml parser such as BeautifulStoneSoup. to return a list of the tag value, you could , perhaps: >>> firstdata = ' 134388 Milford Plaza at Times Square 700 8th Avenue New York NY US 10036 ' >>> >>> from itools.xml import (XMLParser, START_ELEMENT, ... END_ELEMENT, TEXT) >>> names = [] >>> for type, value, line in XMLParser(firstdata): ... if type == TEXT: ... names.append(value) >>> names [' ', '134388', ' ', 'Milford Plaza at Times Square', ' ', '700 8th Avenue', ' ', ' ', ' ', 'New York', ' ', 'NY', ' ', 'US', ' ', '10036', ' '] Here is a another version, using BeautifulStoneSoup: >>> from BeautifulSoup import BeautifulStoneSoup >>> soup = BeautifulStoneSoup(firstdata) >>> names = soup.findAll('name') >>> names [Milford Plaza at Times Square] >>> On Sat, Jun 20, 2009 at 9:34 PM, wrote: > Hi, > I am a total python XML noob and wanted some clarification on using python with reading remote XML data. > > All examples I have found assumes the data is stored localy or have I misunderstood this? > > If I browse to: > 'user:password at domain.com/external/xmlinterface.jsp?cid=xxx&resType=hotel200631&intfc=ws&xml=' > > This request returns a page like: > > > - > > 134388 > Milford Plaza at Times Square > 700 8th Avenue > > > New York > NY > US > 10036 > NYC > 155.4 > 259.0 > USD > 40.75905 > -73.98844 > + > > <b>Location.</b><br> <UL><LI>The Milford Plaza is located in New York, N.Y. > > /hotels/thumbs/NYC_MILF-exter-1-thumb.jpg > H > TIMES SQUARE/THEATER DISTRICT > 2.5 > 1 > 1 > true > true > 3.9202964 > MI > + > > N > 72 Hour Sale - Don't miss this great deal! > > > 17A828141014136319 > -1 > 25033 > true > false > Standard room > 108606 > 252427 > - > > USD > - > > 259.0 > 259.0 > > 575.76 > 575.76 > 57.76 > USD > - > > 259.0 > 259.0 > > 575.76 > B > > - > > USD > - > > 155.4 > 155.4 > > 368.56 > 368.56 > 57.76 > USD > - > > 155.4 > 155.4 > > 368.56 > B > > > > > > I got this so far: > >>>> import urllib2 >>>> request = urllib2.Request('user:password at domain.com/external/xmlinterface.jsp?cid=xxx&resType=hotel200631&intfc=ws&xml=') >>>> opener = urllib2.build_opener() >>>> firstdatastream = opener.open(request) >>>> firstdata = firstdatastream.read() >>>> print firstdata > > > > > 134388 > Milford Plaza at Times Square > 700 8th Avenue > > > New York > NY > US > 10036 > > ... > >>>> > > I would like to understand how to manipulate the data further and extract for example all the hotel names in a list? > > Thank you > Marti > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From wescpy at gmail.com Sun Jun 21 08:30:17 2009 From: wescpy at gmail.com (wesley chun) Date: Sat, 20 Jun 2009 23:30:17 -0700 Subject: [Tutor] filling in web forms In-Reply-To: <41fcacc90906202225j53f69a50g938aea63a98f5ff4@mail.gmail.com> References: <41fcacc90906201503k4fc77e3fxbb299d200b678267@mail.gmail.com> <9c2c8ffb0906202135k33428c0bh45b3524273dbe12d@mail.gmail.com> <41fcacc90906202225j53f69a50g938aea63a98f5ff4@mail.gmail.com> Message-ID: <78b3a9580906202330y45015d26m25a4ae858316ff85@mail.gmail.com> On Sat, Jun 20, 2009 at 10:25 PM, Pete Froslie wrote: > Thank you so much.. I will start looking into twill and I just finished > installing Mechanize. those are very well-known individual tools that will meet your needs. for larger web testing frameworks, you may also consider Windmill and Selenium. best regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From stefan_ml at behnel.de Sun Jun 21 09:30:14 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 21 Jun 2009 09:30:14 +0200 Subject: [Tutor] reading and processing xml files with python In-Reply-To: References: Message-ID: Hi, python.list at Safe-mail.net wrote: > I am a total python XML noob and wanted some clarification on using python with reading remote XML data. For XML in general, there's xml.etree.ElementTree in the stdlib. For remote data (and for various other features), you should also try lxml.etree, which is an advanced re-implementation. http://codespeak.net/lxml/ > All examples I have found assumes the data is stored localy or have I misunderstood this? Likely a misunderstanding. Any XML library I know of can parse from a string or a file-like object (which a socket is, for example). > If I browse to: > 'user:password at domain.com/external/xmlinterface.jsp?cid=xxx&resType=hotel200631&intfc=ws&xml=' > > This request returns a page like: > > > ? > > 134388 > Milford Plaza at Times Square > 700 8th Avenue > > > New York > NY > US > 10036 > NYC > 155.4 > 259.0 > USD > 40.75905 > -73.98844 [...] > B > > > > > > I got this so far: > >>>> import urllib2 >>>> request = urllib2.Request('user:password at domain.com/external/xmlinterface.jsp?cid=xxx&resType=hotel200631&intfc=ws&xml=') >>>> opener = urllib2.build_opener() >>>> firstdatastream = opener.open(request) >>>> firstdata = firstdatastream.read() >>>> print firstdata I never used HTTP authentication with lxml (ElementTree doesn't support parsing from remote URLs at all), so I'm not sure if this works: url = 'user:password at domain.com/external/...' from lxml import etree document = etree.parse(url) If it doesn't, you can use your above code (BTW, isn't urlopen() enough here?) up to the .open() call and do this afterwards: document = etree.parse( firstdatastream ) > > > 134388 > Milford Plaza at Times Square > 700 8th Avenue > > > New York > NY > US > 10036 > > ... > > I would like to understand how to manipulate the data further and extract for example all the hotel names in a list? Read the tutorials on ElementTree and/or lxml. To get a list of hotel names, I'd expect this to work: print [ name.text for name in document.find('//Hotel/name') ] Stefan From d.conca at gmail.com Mon Jun 22 09:46:38 2009 From: d.conca at gmail.com (Daniele) Date: Mon, 22 Jun 2009 09:46:38 +0200 Subject: [Tutor] how to manage an encrypted file? Message-ID: <537341c70906220046w5b54d04el5a0095a67f7295ca@mail.gmail.com> > From:?Wayne > If you want the most basic encryption you could simply XOR the file. It's fairly easy to break, though, because the same character patterns will be present as with your original file. Actually if you do it properly this kind of encryption is unbreakable, but you'd have to: 1. generate a random key long enough to cover your data 2. keep the key secure and in a separate place 3. DON'T use the key twice there must be a Security Now episode that explains the thing pretty well (could be this one http://www.grc.com/sn/sn-011.htm). Some arguments may rise against the randomness of the key, but I don't think its the case to go into that. You could also use TrueCrypt which is an extremely powerful cryptographic software (open source), I found this article that can help you linking it with python: http://blog.bjrn.se/2008/01/truecrypt-explained.html From alan.gauld at btinternet.com Mon Jun 22 15:15:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Jun 2009 14:15:55 +0100 Subject: [Tutor] how to manage an encrypted file? References: <537341c70906220046w5b54d04el5a0095a67f7295ca@mail.gmail.com> Message-ID: > there must be a Security Now episode that explains the thing pretty > well (could be this one http://www.grc.com/sn/sn-011.htm). Eek! I tried to read that but it was so garbled and basically illiterate that I gave up! It's the nearest thing I've seen to plain text encryption! Sample: """ We don't, you know, they're all - the rules - nobody's really codified how this whole stuff works and who's liable for what, so I guess it makes sense""" I'm glad it makes sense to him, it sure didn't to me! :-) Alan G. From robert.lummis at gmail.com Mon Jun 22 20:48:19 2009 From: robert.lummis at gmail.com (Robert Lummis) Date: Mon, 22 Jun 2009 14:48:19 -0400 Subject: [Tutor] how to manage an encrypted file? In-Reply-To: <537341c70906220046w5b54d04el5a0095a67f7295ca@mail.gmail.com> References: <537341c70906220046w5b54d04el5a0095a67f7295ca@mail.gmail.com> Message-ID: <71d330f00906221148v6408eb3cjc36445d743238c97@mail.gmail.com> Very good suggestion! Thanks! I knew about TrueCrypt before (it's really excellent) but I didn't think of it for this purpose because it didn't show up when I did a Synaptic search. I'll see if I can get it installed on ubuntu and used with Python. Actually, the URL you give doesn't work (at least for me). But I found the following by googling the URL: http://blog.bjrn.se/2008/02/truecrypt-explained-truecrypt-5-update.html On Mon, Jun 22, 2009 at 3:46 AM, Daniele wrote: >> From:?Wayne > >> If you want the most basic encryption you could simply XOR the file. It's fairly easy to break, though, because the same character patterns will be present as with your original file. > > Actually if you do it properly this kind of encryption is unbreakable, > but you'd have to: > 1. generate a random key long enough to cover your data > 2. keep the key secure and in a separate place > 3. DON'T use the key twice > > there must be a Security Now episode that explains the thing pretty > well (could be this one http://www.grc.com/sn/sn-011.htm). > Some arguments may rise against the randomness of the key, but I don't > think its the case to go into that. > > You could also use TrueCrypt which is an extremely powerful > cryptographic software (open source), I found this article that can > help you linking it with python: > http://blog.bjrn.se/2008/01/truecrypt-explained.html > -- Robert Lummis From eike.welk at gmx.net Mon Jun 22 21:02:36 2009 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 22 Jun 2009 21:02:36 +0200 Subject: [Tutor] how to manage an encrypted file? In-Reply-To: References: <537341c70906220046w5b54d04el5a0095a67f7295ca@mail.gmail.com> Message-ID: <200906222102.36505.eike.welk@gmx.net> The method that Daniele describes is called encryption with a "One Time Pad". A somewhat readable description is in Wikipedia: http://en.wikipedia.org/wiki/One_time_pad This encryption method is a theoretically perfectly secure, but there are big organizational problems connected to its use. It interestingly does not require any technology. The Taliban could use it if they had someone with good handwriting, much patience, and a passion for throwing dices. Kind regards, Eike. From benshafat at gmail.com Mon Jun 22 22:15:13 2009 From: benshafat at gmail.com (Elisha Rosensweig) Date: Mon, 22 Jun 2009 16:15:13 -0400 Subject: [Tutor] filtering NaN values Message-ID: <7fd42f290906221315m63ae8733oa0abf973c4937a80@mail.gmail.com> Hi, I have a list with some values being NaN (after division-by-zero). How can I check and remove all the NaN values? Thanks Elisha -------------- next part -------------- An HTML attachment was scrubbed... URL: From bryan.fodness at gmail.com Mon Jun 22 22:16:38 2009 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Mon, 22 Jun 2009 16:16:38 -0400 Subject: [Tutor] extracting lines in large file Message-ID: I am trying to output all the lines that start with a specific word. It is a large output file (~14 Mb), but nothing that I thought would be a problem. for line in open('output.new'): i_line = line.split() if i_line: if i_line[0] == "intrinsic": print i_line It does not get all of the lines, it stops at line 130323. There are ~260000 line. Is there a limit to the number of lines you can read in this way, or am I overlooking something else. Bryan From vinces1979 at gmail.com Mon Jun 22 22:21:57 2009 From: vinces1979 at gmail.com (vince spicer) Date: Mon, 22 Jun 2009 14:21:57 -0600 Subject: [Tutor] extracting lines in large file In-Reply-To: References: Message-ID: <1e53c510906221321u5b7dfe50m4555f312bee4e234@mail.gmail.com> 14mb file shouldn't be an issue, unless you very little ram, is there any errors being outputted? a cleaner way for reading the file: for line in open("output.new"): if line.startswith("intrinsic"): print line On Mon, Jun 22, 2009 at 2:16 PM, Bryan Fodness wrote: > I am trying to output all the lines that start with a specific word. > It is a large output file (~14 Mb), but nothing that I thought would > be a problem. > > for line in open('output.new'): > i_line = line.split() > if i_line: > if i_line[0] == "intrinsic": > print i_line > > It does not get all of the lines, it stops at line 130323. There are > ~260000 line. Is there a limit to the number of lines you can read in > this way, or am I overlooking something else. > > Bryan > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eduardo.susan at gmail.com Mon Jun 22 23:04:30 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 22 Jun 2009 15:04:30 -0600 Subject: [Tutor] Writing a csv from a dictionary Message-ID: <9356b9f30906221404o7a7c5e5dt3d59e7b6d40accd0@mail.gmail.com> Hello, I have a dictionary similar to this: dyc = { 'a50' : ['textfield', 50, 40], 'k77' : ['othertext', 60, 10] } I was trying to write a csv with the csv module, by doing this: import csv myfile = open('c:/myscripts/csv-test.csv', 'wb') mywriter = csv.writer(myfile, dialect='excel') for item in dyc: mywriter.write(item) myfile.close() this gives me this result: a50,"['textfield', 50, 40]" k77,"['othertext', 60, 10]" I would like this, instead: a50,"textfield", 50, 40 k77,"othertext", 60, 10 I also could manage to transform that dictionary in a list like this: [ [a50,"textfield", 50, 40], [k77,"othertext", 60, 10] Thanks in advance for your advice -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 23 00:37:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Jun 2009 23:37:13 +0100 Subject: [Tutor] filtering NaN values References: <7fd42f290906221315m63ae8733oa0abf973c4937a80@mail.gmail.com> Message-ID: "Elisha Rosensweig" wrote > I have a list with some values being NaN (after division-by-zero). How > can I > check and remove all the NaN values? NaN is, so far as I know, a JavaScript only feature. The equivalent thing in Python would be to avoid having those 'values' in your list in the first place by trapping the divide by zero error while creating your list, or by not dividing by zero in the first place: mylist = [] for item in biglist: try: value = item/divisor except ZeroDivisionError: continue # ignore if divide by zero mylist.append(value) OR mylist = [item/divisor for item in biglist if divisor != 0] # avoids the division If you can't do either of those then we need a bit more information about how the "NaN"s come about. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Jun 23 00:40:38 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Jun 2009 23:40:38 +0100 Subject: [Tutor] extracting lines in large file References: Message-ID: "Bryan Fodness" wrote >I am trying to output all the lines that start with a specific word. > It is a large output file (~14 Mb), but nothing that I thought would > be a problem. Shouldn't be, you are processing one line at a time! > for line in open('output.new'): > i_line = line.split() > if i_line: > if i_line[0] == "intrinsic": > print i_line > > It does not get all of the lines, it stops at line 130323. There are Sounds like it has an EOF character in it, try opening in binary mode and see what happens... It could cause other problems if there really is binary data in there but it might just work... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From srilyk at gmail.com Tue Jun 23 01:25:57 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 22 Jun 2009 18:25:57 -0500 Subject: [Tutor] variable length precision Message-ID: <333efb450906221625x59aa13euf4650623359f7acd@mail.gmail.com> Well, I was going to ask the question, but some experimentation has led me to the answer which I will share. Mainly because I'm sure someone out there may come across the need. I'm writing a function that will generate me a filename such as "file0001.jpg" but I want to be able to specify the minimum length - so it could be "file01.jpg" or "file00000001.jpg" With string formatting I know you can easily specify precision a la 'file%.2d.jpg' % 1 which would give me 'file01.jpg' but then I discovered you can indeed chain together formatting (or use variables in place of string constants... of course some of us know that string objects really are references to constant strings...) - you just have to add %% where you want the final one: In [45]: 'some numbers %%.%sd' % 8 % 4 Out[45]: 'some numbers 00000004' Hope this helps someone! -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jun 23 02:43:55 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 22 Jun 2009 20:43:55 -0400 Subject: [Tutor] filtering NaN values In-Reply-To: <7fd42f290906221315m63ae8733oa0abf973c4937a80@mail.gmail.com> References: <7fd42f290906221315m63ae8733oa0abf973c4937a80@mail.gmail.com> Message-ID: <1c2a2c590906221743g14cad5c5wc4941e075a9d242b@mail.gmail.com> On Mon, Jun 22, 2009 at 4:15 PM, Elisha Rosensweig wrote: > Hi, > > I have a list with some values being NaN (after division-by-zero). How can I > check and remove all the NaN values? In Python 2.6 you can use math.isnan() to check for NaN, so you can filter your list by newList = [ x for x in oldList if not math.isnan(x) ] In older versions of Python I don't know how to do this. Kent From kent37 at tds.net Tue Jun 23 02:48:48 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 22 Jun 2009 20:48:48 -0400 Subject: [Tutor] variable length precision In-Reply-To: <333efb450906221625x59aa13euf4650623359f7acd@mail.gmail.com> References: <333efb450906221625x59aa13euf4650623359f7acd@mail.gmail.com> Message-ID: <1c2a2c590906221748t6bb046c0u527bff7372019903@mail.gmail.com> On Mon, Jun 22, 2009 at 7:25 PM, Wayne wrote: > With string formatting I know you can easily specify precision a la > 'file%.2d.jpg' % 1 which would give me 'file01.jpg' but then I discovered > you can indeed chain together formatting (or use variables in place of > string constants... of course some of us know that string objects really are > references to constant strings...) - you just have to add %% where you want > the final one: > > In [45]: 'some numbers %%.%sd' % 8 % 4 > Out[45]: 'some numbers 00000004' Even simpler - you can use a * for the field width or precision, which means, take the width or precision from the argument list: In [12]: 'some numbers %.*d' % (8, 4) Out[12]: 'some numbers 00000004' In [13]: 'some numbers %*.*d' % (12, 8, 4) Out[13]: 'some numbers 00000004' Kent From bryan.fodness at gmail.com Tue Jun 23 04:14:00 2009 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Mon, 22 Jun 2009 22:14:00 -0400 Subject: [Tutor] extracting lines in large file In-Reply-To: <1e53c510906221321u5b7dfe50m4555f312bee4e234@mail.gmail.com> References: <1e53c510906221321u5b7dfe50m4555f312bee4e234@mail.gmail.com> Message-ID: tried both again, they both return the same 9 lines, when i expect 492. it dies on a blank line, but the if i_line takes care of the previous ones. On Mon, Jun 22, 2009 at 4:21 PM, vince spicer wrote: > 14mb file shouldn't be an issue, unless you very little ram, is there any > errors being outputted? > > a cleaner way for reading the file: > > for line in open("output.new"): > ??? if line.startswith("intrinsic"): > ??????? print line > > > On Mon, Jun 22, 2009 at 2:16 PM, Bryan Fodness > wrote: >> >> I am trying to output all the lines that start with a specific word. >> It is a large output file (~14 Mb), but nothing that I thought would >> be a problem. >> >> for line in open('output.new'): >> ? ?i_line = line.split() >> ? ?if i_line: >> ? ? ? ?if i_line[0] == "intrinsic": >> ? ? ? ? ? ?print i_line >> >> It does not get all of the lines, it stops at line 130323. ?There are >> ~260000 line. ?Is there a limit to the number of lines you can read in >> this way, or am I overlooking something else. >> >> Bryan >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > -- ?The game of science can accurately be described as a never-ending insult to human intelligence.? - Jo?o Magueijo "Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. " -Albert Einstein From vinces1979 at gmail.com Tue Jun 23 04:18:21 2009 From: vinces1979 at gmail.com (Vince Spicer) Date: Mon, 22 Jun 2009 20:18:21 -0600 Subject: [Tutor] extracting lines in large file In-Reply-To: References: <1e53c510906221321u5b7dfe50m4555f312bee4e234@mail.gmail.com> Message-ID: <200906222018.21883.vinces1979@gmail.com> are there any extra spaces of characters " intrinsic" !== "intrinsic" On Monday 22 June 2009 8:14:00 pm Bryan Fodness wrote: > tried both again, they both return the same 9 lines, when i expect > 492. it dies on a blank line, but the if i_line takes care of the > previous ones. > > On Mon, Jun 22, 2009 at 4:21 PM, vince spicer wrote: > > 14mb file shouldn't be an issue, unless you very little ram, is there any > > errors being outputted? > > > > a cleaner way for reading the file: > > > > for line in open("output.new"): > > if line.startswith("intrinsic"): > > print line > > > > > > On Mon, Jun 22, 2009 at 2:16 PM, Bryan Fodness > > > > wrote: > >> I am trying to output all the lines that start with a specific word. > >> It is a large output file (~14 Mb), but nothing that I thought would > >> be a problem. > >> > >> for line in open('output.new'): > >> i_line = line.split() > >> if i_line: > >> if i_line[0] == "intrinsic": > >> print i_line > >> > >> It does not get all of the lines, it stops at line 130323. There are > >> ~260000 line. Is there a limit to the number of lines you can read in > >> this way, or am I overlooking something else. > >> > >> Bryan > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor From metolone+gmane at gmail.com Tue Jun 23 07:08:52 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 22 Jun 2009 22:08:52 -0700 Subject: [Tutor] Writing a csv from a dictionary References: <9356b9f30906221404o7a7c5e5dt3d59e7b6d40accd0@mail.gmail.com> Message-ID: "Eduardo Vieira" wrote in message news:9356b9f30906221404o7a7c5e5dt3d59e7b6d40accd0 at mail.gmail.com... > Hello, I have a dictionary similar to this: > dyc = { > 'a50' : ['textfield', 50, 40], > 'k77' : ['othertext', 60, 10] > } > > I was trying to write a csv with the csv module, by doing this: > import csv > myfile = open('c:/myscripts/csv-test.csv', 'wb') > mywriter = csv.writer(myfile, dialect='excel') > > for item in dyc: > mywriter.write(item) > > myfile.close() > > this gives me this result: > a50,"['textfield', 50, 40]" > k77,"['othertext', 60, 10]" > > I would like this, instead: > a50,"textfield", 50, 40 > k77,"othertext", 60, 10 It's a good idea to cut-and-paste actual code and actual output. Your above code doesn't work. "writerow" is the correct method and "for item in dyc.items():" is needed to iterate over keys and values correctly. import csv dyc = { 'a50' : ['textfield', 50, 40], 'k77' : ['othertext', 60, 10] } myfile = open('csv-test.csv', 'w') mywriter = csv.writer(myfile, dialect='excel') for k,[a,b,c] in dyc.items(): mywriter.writerow([k,a,b,c]) myfile.close() OUTPUT: a50,textfield,50,40 k77,othertext,60,10 If you want quoted text fields use: mywriter = csv.writer(myfile, dialect='excel',quoting=csv.QUOTE_NONNUMERIC) -Mark From alan.gauld at btinternet.com Tue Jun 23 07:53:59 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Jun 2009 06:53:59 +0100 Subject: [Tutor] filtering NaN values References: <7fd42f290906221315m63ae8733oa0abf973c4937a80@mail.gmail.com> <1c2a2c590906221743g14cad5c5wc4941e075a9d242b@mail.gmail.com> Message-ID: "Kent Johnson" wrote >> I have a list with some values being NaN (after division-by-zero). How >> can I >> check and remove all the NaN values? > > In Python 2.6 you can use math.isnan() to check for NaN, so you can > filter your list by > newList = [ x for x in oldList if not math.isnan(x) ] Interesting! How is a NaN stored in Python? ie. How do you get to the point of having one in the first place? Python continues is symbiosis with JavaScript... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From john at fouhy.net Tue Jun 23 08:20:25 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 23 Jun 2009 18:20:25 +1200 Subject: [Tutor] filtering NaN values In-Reply-To: References: <7fd42f290906221315m63ae8733oa0abf973c4937a80@mail.gmail.com> <1c2a2c590906221743g14cad5c5wc4941e075a9d242b@mail.gmail.com> Message-ID: <5e58f2e40906222320u5ab7df03w8cbd45c1564e0bc6@mail.gmail.com> 2009/6/23 Alan Gauld : > Interesting! How is a NaN stored in Python? > ie. How do you get to the point of having one in the first place? Well, you can do this: >>> float('nan') nan (try float('inf') too) -- John. From d.conca at gmail.com Tue Jun 23 08:58:39 2009 From: d.conca at gmail.com (Daniele) Date: Tue, 23 Jun 2009 08:58:39 +0200 Subject: [Tutor] how to manage an encrypted file? Message-ID: <537341c70906222358o4efa88cle4317b2e89d2d3bf@mail.gmail.com> > From:?"Alan Gauld" > To:?tutor at python.org > Date:?Mon, 22 Jun 2009 14:15:55 +0100 > Subject:?Re: [Tutor] how to manage an encrypted file? >> >> there must be a Security Now episode that explains the thing pretty >> well (could be this one http://www.grc.com/sn/sn-011.htm). > > Eek! I tried to read that but it was so garbled and basically illiterate > that I gave up! It's the nearest thing I've seen to plain text encryption! eheh Alan try the audio version, it's far better ;P From kent37 at tds.net Tue Jun 23 13:15:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 Jun 2009 07:15:05 -0400 Subject: [Tutor] Writing a csv from a dictionary In-Reply-To: References: <9356b9f30906221404o7a7c5e5dt3d59e7b6d40accd0@mail.gmail.com> Message-ID: <1c2a2c590906230415q351c7c74kebc591907ce0e9c9@mail.gmail.com> On Tue, Jun 23, 2009 at 1:08 AM, Mark Tolonen wrote: > import csv > > dyc = { > 'a50' : ['textfield', 50, 40], > 'k77' : ['othertext', 60, 10] > } > > myfile = open('csv-test.csv', 'w') > mywriter = csv.writer(myfile, dialect='excel') > > for k,[a,b,c] in dyc.items(): > ? mywriter.writerow([k,a,b,c]) I think I would write this as for k, v in dyc.items(): # or iteritems() mywriter.writerow([k] + v) That way it doesn't depend on the actual size of the value list. Kent From kent37 at tds.net Tue Jun 23 13:16:38 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 Jun 2009 07:16:38 -0400 Subject: [Tutor] filtering NaN values In-Reply-To: References: <7fd42f290906221315m63ae8733oa0abf973c4937a80@mail.gmail.com> <1c2a2c590906221743g14cad5c5wc4941e075a9d242b@mail.gmail.com> Message-ID: <1c2a2c590906230416n2371e3f2n739ab77e85641656@mail.gmail.com> On Tue, Jun 23, 2009 at 1:53 AM, Alan Gauld wrote: > Interesting! How is a NaN stored in Python? > ie. How do you get to the point of having one in the first place? Google 'python nan' for lots of interesting discussion... Kent From metolone+gmane at gmail.com Tue Jun 23 16:31:39 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 23 Jun 2009 07:31:39 -0700 Subject: [Tutor] Writing a csv from a dictionary References: <9356b9f30906221404o7a7c5e5dt3d59e7b6d40accd0@mail.gmail.com> <1c2a2c590906230415q351c7c74kebc591907ce0e9c9@mail.gmail.com> Message-ID: "Kent Johnson" wrote in message news:1c2a2c590906230415q351c7c74kebc591907ce0e9c9 at mail.gmail.com... On Tue, Jun 23, 2009 at 1:08 AM, Mark Tolonen wrote: >> import csv >> >> dyc = { >> 'a50' : ['textfield', 50, 40], >> 'k77' : ['othertext', 60, 10] >> } >> >> myfile = open('csv-test.csv', 'w') >> mywriter = csv.writer(myfile, dialect='excel') >> >> for k,[a,b,c] in dyc.items(): >> mywriter.writerow([k,a,b,c]) > >I think I would write this as >for k, v in dyc.items(): # or iteritems() > mywriter.writerow([k] + v) > >That way it doesn't depend on the actual size of the value list. I knew there was a more straightforward way, it just wouldn't come to me at 1am. ;^) -Mark From lie.1296 at gmail.com Tue Jun 23 20:45:04 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 24 Jun 2009 04:45:04 +1000 Subject: [Tutor] Writing a csv from a dictionary In-Reply-To: References: <9356b9f30906221404o7a7c5e5dt3d59e7b6d40accd0@mail.gmail.com> Message-ID: Mark Tolonen wrote: > It's a good idea to cut-and-paste actual code and actual output. Your > above code doesn't work. I'd just like to clarify, in case someone misunderstood, it isn't a really good idea to simply cut-and-paste actual code and actual output for 2 reasons: 1) cut-and-paste means you lost your own copy of the code :) 2) you should simplify your own code before copy-and-paste to a mailing list. The simplified code should: 1) run when copy-and-pasted to the interpreter[1], 2) still generates the error/unexpected result[2], 3) demonstrate the intent of the code. In many cases, trying to simplify the code would reveal the error to yourself, and in other cases it makes it easier for others to spot the errors. [1] except when the question is why a code works in an interpreter but not the other or vice versa; or when the code doesn't even run at all [2] it is easier to debug a wrong code than debug a correct code From lie.1296 at gmail.com Tue Jun 23 21:03:48 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 24 Jun 2009 05:03:48 +1000 Subject: [Tutor] extracting lines in large file In-Reply-To: References: <1e53c510906221321u5b7dfe50m4555f312bee4e234@mail.gmail.com> Message-ID: Bryan Fodness wrote: > tried both again, they both return the same 9 lines, when i expect > 492. it dies on a blank line, but the if i_line takes care of the > previous ones. > Can you give a sample input that should, but not passed by the code? Unrelated Tips: You can rely on python's short-circuiting logical operator and write the `if i_line` like this: if i_line and i_line[0] == "intrinsic": ... From charlie.reddington at gmail.com Tue Jun 23 22:01:46 2009 From: charlie.reddington at gmail.com (Charlie Reddington) Date: Tue, 23 Jun 2009 15:01:46 -0500 Subject: [Tutor] Trouble with passing commands / variables to os.system() Message-ID: <5D94F894-8EE5-43EC-B1B0-9A0C286940CD@gmail.com> Hi, I'm very very green when it comes to python. I know bash better than python, so I figured a good way to learn things was covert my bash stuff to python. So here goes... Here's a quick example of the code I have that is broken. import os username = 'charlie' private_key = '/path/to/key' ssh = '/usr/bin/ssh' command = 'hostname && df -h && exit' servers = ['172.16.1.1', '172.16.12.2', '172.16.1.3'] for host in servers: print(os.system(ssh -l username -i private_key host command)) What I'm trying to do is is, is use ssh with a private key. That way I can quickly run some remote commands on a few hundred servers in a quick way to do stuff (disk usage, top, etc). When I run this, I get errors like this for every host in my list. Warning: Identity file private_key not accessible: No such file or directory. ssh: Could not resolve hostname i: nodename nor servname provided, or not known 65280 My first thoughts are, it's not passing my variables to the function the way I'd expect. So my questions are... 1.) Is it nessacary to put my IP's in quotes? 2.) When I call a variable in a function (like os.system() or print()) I don't use $'s right? 3.) Am I putting variables in my functions properly? Can I put variables like this in there? Thanks for any help. Charlie From vinces1979 at gmail.com Tue Jun 23 22:06:35 2009 From: vinces1979 at gmail.com (vince spicer) Date: Tue, 23 Jun 2009 14:06:35 -0600 Subject: [Tutor] Trouble with passing commands / variables to os.system() In-Reply-To: <5D94F894-8EE5-43EC-B1B0-9A0C286940CD@gmail.com> References: <5D94F894-8EE5-43EC-B1B0-9A0C286940CD@gmail.com> Message-ID: <1e53c510906231306x73f283c6l6f01cd44f70fc0c2@mail.gmail.com> os.system is not the best way to handle this you may want to look into the subprocess module however: import os username = 'charlie' private_key = '/path/to/key' ssh = '/usr/bin/ssh' command = 'hostname && df -h && exit' servers = ['172.16.1.1', '172.16.12.2', '172.16.1.3'] for host in servers: os.system("ssh %s@%s -i %s %s" %(username, host, private_key, command) On Tue, Jun 23, 2009 at 2:01 PM, Charlie Reddington < charlie.reddington at gmail.com> wrote: > Hi, > > I'm very very green when it comes to python. I know bash better than > python, so I figured a good way to learn things was covert my bash stuff to > python. So here goes... > > Here's a quick example of the code I have that is broken. > > import os > > username = 'charlie' > private_key = '/path/to/key' > ssh = '/usr/bin/ssh' > command = 'hostname && df -h && exit' > > servers = ['172.16.1.1', '172.16.12.2', '172.16.1.3'] > > for host in servers: > print(os.system(ssh -l username -i private_key host command)) > > What I'm trying to do is is, is use ssh with a private key. That way I can > quickly run some remote commands on a few hundred servers in a quick way to > do stuff (disk usage, top, etc). > > When I run this, I get errors like this for every host in my list. > > Warning: Identity file private_key not accessible: No such file or > directory. > ssh: Could not resolve hostname i: nodename nor servname provided, or not > known > 65280 > > My first thoughts are, it's not passing my variables to the function the > way I'd expect. > > So my questions are... > > 1.) Is it nessacary to put my IP's in quotes? > 2.) When I call a variable in a function (like os.system() or print()) I > don't use $'s right? > 3.) Am I putting variables in my functions properly? Can I put variables > like this in there? > > Thanks for any help. > > Charlie > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From charlie.reddington at gmail.com Tue Jun 23 22:19:16 2009 From: charlie.reddington at gmail.com (Charlie Reddington) Date: Tue, 23 Jun 2009 15:19:16 -0500 Subject: [Tutor] Trouble with passing commands / variables to os.system() In-Reply-To: <1e53c510906231306x73f283c6l6f01cd44f70fc0c2@mail.gmail.com> References: <5D94F894-8EE5-43EC-B1B0-9A0C286940CD@gmail.com> <1e53c510906231306x73f283c6l6f01cd44f70fc0c2@mail.gmail.com> Message-ID: Thanks, Your code works as expected! Can you tell me what your code is doing different than mine? Charlie On Jun 23, 2009, at 3:06 PM, vince spicer wrote: > os.system is not the best way to handle this you may want to look into > the subprocess module > > however: > > import os > > username = 'charlie' > private_key = '/path/to/key' > ssh = '/usr/bin/ssh' > command = 'hostname && df -h && exit' > > servers = ['172.16.1.1', '172.16.12.2', '172.16.1.3'] > > for host in servers: > os.system("ssh %s@%s -i %s %s" %(username, host, private_key, > command) > > > > On Tue, Jun 23, 2009 at 2:01 PM, Charlie Reddington > wrote: > Hi, > > I'm very very green when it comes to python. I know bash better than > python, so I figured a good way to learn things was covert my bash > stuff to python. So here goes... > > Here's a quick example of the code I have that is broken. > > import os > > username = 'charlie' > private_key = '/path/to/key' > ssh = '/usr/bin/ssh' > command = 'hostname && df -h && exit' > > servers = ['172.16.1.1', '172.16.12.2', '172.16.1.3'] > > for host in servers: > print(os.system(ssh -l username -i private_key host command)) > > What I'm trying to do is is, is use ssh with a private key. That way > I can quickly run some remote commands on a few hundred servers in a > quick way to do stuff (disk usage, top, etc). > > When I run this, I get errors like this for every host in my list. > > Warning: Identity file private_key not accessible: No such file or > directory. > ssh: Could not resolve hostname i: nodename nor servname provided, > or not known > 65280 > > My first thoughts are, it's not passing my variables to the function > the way I'd expect. > > So my questions are... > > 1.) Is it nessacary to put my IP's in quotes? > 2.) When I call a variable in a function (like os.system() or > print()) I don't use $'s right? > 3.) Am I putting variables in my functions properly? Can I put > variables like this in there? > > Thanks for any help. > > Charlie > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 23 23:50:30 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Jun 2009 22:50:30 +0100 Subject: [Tutor] Trouble with passing commands / variables to os.system() References: <5D94F894-8EE5-43EC-B1B0-9A0C286940CD@gmail.com><1e53c510906231306x73f283c6l6f01cd44f70fc0c2@mail.gmail.com> Message-ID: "Charlie Reddington" wrote > Your code works as expected! Can you tell me what your code is doing > different than mine? os.system needs the command to be a string so you have to build up the string by passing in your variables using the string format operator(%) or building it bit by bit outside the call to system. Beware that the return value from system is just the exit code which is not very useful, hencehthe recommendation to oook at subprocess... >> for host in servers: >> os.system("ssh %s@%s -i %s %s" %(username, host, private_key, >> command) Also while this might seem a good approach to start you will likely find that most of the things you are doing via sysyem will be possible directly from Python which will be more efficient in resources. Take a look at the Using the OS topic in my tutorioal for just a few examples of the kinds of things you can do directly - as well as how to use subprocess. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From charlie.reddington at gmail.com Wed Jun 24 01:24:47 2009 From: charlie.reddington at gmail.com (Charlie Reddington) Date: Tue, 23 Jun 2009 18:24:47 -0500 Subject: [Tutor] Trouble with passing commands / variables to os.system() In-Reply-To: References: <5D94F894-8EE5-43EC-B1B0-9A0C286940CD@gmail.com><1e53c510906231306x73f283c6l6f01cd44f70fc0c2@mail.gmail.com> Message-ID: <03EF6852-A2FC-481F-BB87-5E866E4FFE51@gmail.com> On Jun 23, 2009, at 4:50 PM, Alan Gauld wrote: > > "Charlie Reddington" wrote > >> Your code works as expected! Can you tell me what your code is doing >> different than mine? > > os.system needs the command to be a string so you have to build > up the string by passing in your variables using the string format > operator(%) > or building it bit by bit outside the call to system. > > Beware that the return value from system is just the exit code which > is not > very useful, hencehthe recommendation to oook at subprocess... > >>> for host in servers: >>> os.system("ssh %s@%s -i %s %s" %(username, host, private_key, >>> command) > > Also while this might seem a good approach to start you will likely > find that > most of the things you are doing via sysyem will be possible directly > from Python which will be more efficient in resources. > > Take a look at the Using the OS topic in my tutorioal for just a > few examples of the kinds of things you can do directly - as well > as how to use subprocess. > > HTH, > Thanks for all the replies, I'll definitely look into it all. Charlie > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From david at pythontoo.com Wed Jun 24 02:13:33 2009 From: david at pythontoo.com (David) Date: Tue, 23 Jun 2009 20:13:33 -0400 Subject: [Tutor] Trouble with passing commands / variables to os.system() In-Reply-To: <03EF6852-A2FC-481F-BB87-5E866E4FFE51@gmail.com> References: <5D94F894-8EE5-43EC-B1B0-9A0C286940CD@gmail.com><1e53c510906231306x73f283c6l6f01cd44f70fc0c2@mail.gmail.com> <03EF6852-A2FC-481F-BB87-5E866E4FFE51@gmail.com> Message-ID: <4A416FAD.4080108@pythontoo.com> Charlie Reddington wrote: > > Thanks for all the replies, I'll definitely look into it all. > > Charlie > > Something else for your consideration; http://commandline.org.uk/python/sftp-python-really-simple-ssh/ -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From david at pythontoo.com Wed Jun 24 02:42:33 2009 From: david at pythontoo.com (David) Date: Tue, 23 Jun 2009 20:42:33 -0400 Subject: [Tutor] Trouble with passing commands / variables to os.system() In-Reply-To: <4A416FAD.4080108@pythontoo.com> References: <5D94F894-8EE5-43EC-B1B0-9A0C286940CD@gmail.com><1e53c510906231306x73f283c6l6f01cd44f70fc0c2@mail.gmail.com> <03EF6852-A2FC-481F-BB87-5E866E4FFE51@gmail.com> <4A416FAD.4080108@pythontoo.com> Message-ID: <4A417679.4090308@pythontoo.com> David wrote: > Charlie Reddington wrote: > >> >> Thanks for all the replies, I'll definitely look into it all. >> >> Charlie >> >> > Something else for your consideration; > http://commandline.org.uk/python/sftp-python-really-simple-ssh/ > almost forgot pexpect #!/usr/bin/python import pexpect child = pexpect.spawn ('ssh root at localhost') child.expect ('Password:') child.sendline ('mypassword') child.expect ('') child.sendline ('ls -a') print child.before child.interact() -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From yashkochar at gmail.com Wed Jun 24 08:11:25 2009 From: yashkochar at gmail.com (Yash) Date: Wed, 24 Jun 2009 02:11:25 -0400 Subject: [Tutor] puzzling for-loop behavior Message-ID: Hello, I am a newbie to python. I am trying to practice writing a code in python and am trying to write a function to generate prime numbers using sieve of Eratosthenes. (code follows at the end of mail) The way it is coded, if I change the for loop over "j" from for j in range( (2*i*(i + 1)), np, (2*i +1)): to for j in range( (2*i*(i + 1)), np, 2*(2*i +1)): I should get the same output for the two (which I do). The second for loop has to make roughly half the iterations compared to the first, because I increased the step-size by factor 2. However when I time the code for the two different for loops, I observe that the code takes longer to run as compared the first for loop. This seems to be counter intuitive. Can someone explain this behavior ? Also if I replace the for loop by while loop, it takes longer to run, which I guess could be because in case of for loop it kind of knows how many iterations to make, but in while loop it has to keep checking every time. Thank you, Yash def primes(Nmax): """ primes(Nmax) -> list of prime numbers between 1 to Nmax Generates a list of primes numbers between 1 and Nmax, including Nmax, using Sieve of Eratosthenes. """ # Author -Yash Kochar # Last modified -23rd June 2009 #--------------------------------------------------------------------------- # Check input : try : Nmax = int(Nmax); except ValueError : print('Unable to convert input to integer.'); except TypeError : print('Input value should be a number or string.'); except : print('Something unexcepted happen while trying to convert input to '\ 'int-type.'); # Set flags for odd prime numbers : if ( Nmax < 2 ) : plst = []; else : plst = [True]*( (Nmax +1)//2 ); # start with True for [1, 3, 5, 7, ...] plst[0] = False; # 1 is not prime np = len(plst); # Number of odd numbers to be considered for i in range(1, int(((2*np +1) **0.5) +1)): if plst[i]: # Number is a prime for j in range( (2*i*(i + 1)), np, (2*i +1)): plst[j] = False; # Filter out the required values (all odd primes) : plst = [(2*n +1) for n in range(0, np) if plst[n]]; plst.insert(0, 2); # Append "2" at the beginning. return plst; From cyberjacob at googlemail.com Sun Jun 21 16:59:02 2009 From: cyberjacob at googlemail.com (Jacob Mansfield) Date: Sun, 21 Jun 2009 15:59:02 +0100 Subject: [Tutor] reading and processing xml files with python In-Reply-To: <9c2c8ffb0906202317q1b1c7a2ewf8cc673bb9b6ac85@mail.gmail.com> References: <9c2c8ffb0906202317q1b1c7a2ewf8cc673bb9b6ac85@mail.gmail.com> Message-ID: hello all, I am currently making a birthday prezzie for someone (deadline is Thursday night). the basic idea is a wall of photos that you can move about to view different ones using a joystick and press the joystick button to hear a roughly five second commentary that is individual for each photo. I currently have a wall of photos that you can navigate using the wasd keys. all help in creating the final product in time would be appreciated and you would be mentioned in the credits by a nickname (IE. cyberjacob). I am currently using the pygame library. any more detail can be supplied including full source code, thanks everyone, i need all the help I can get to finish this in time please reply ASAP thanks once again cyberjacob -------------- next part -------------- An HTML attachment was scrubbed... URL: From jdmccla at regence.com Wed Jun 24 13:01:22 2009 From: jdmccla at regence.com (James D Mcclatchey) Date: Wed, 24 Jun 2009 04:01:22 -0700 Subject: [Tutor] AUTO: James D Mcclatchey is out of the office. (returning 06/29/2009) Message-ID: I am out of the office until 06/29/2009. I will respond to your message when I return. Note: This is an automated response to your message "Tutor Digest, Vol 64, Issue 113" sent on 6/24/09 3:00:02. This is the only notification you will receive while this person is away. *IMPORTANT NOTICE: This communication, including any attachment, contains information that may be confidential or privileged, and is intended solely for the entity or individual to whom it is addressed. If you are not the intended recipient, you should delete this message and are hereby notified that any disclosure, copying, or distribution of this message is strictly prohibited. Nothing in this email, including any attachment, is intended to be a legally binding signature. * From rabidpoobear at gmail.com Wed Jun 24 14:16:52 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 24 Jun 2009 07:16:52 -0500 Subject: [Tutor] puzzling for-loop behavior In-Reply-To: References: Message-ID: <4A421934.1060905@gmail.com> Yash wrote: > Hello, > I am a newbie to python. I am trying to practice writing a code in > python and am trying to write a function to generate prime numbers > using sieve of Eratosthenes. (code follows at the end of mail) > > The way it is coded, if I change the for loop over "j" from > for j in range( (2*i*(i + 1)), np, (2*i +1)): > to > for j in range( (2*i*(i + 1)), np, 2*(2*i +1)): > I should get the same output for the two (which I do). > > The second for loop has to make roughly half the iterations compared > to the first, because I increased the step-size by factor 2. > However when I time the code for the two different for loops, I > observe that the code takes longer to run as compared the first for > loop. > How do you know it's taking longer to run? How are you profiling your code? I just ran your code through timeit, and you're correct, changing that line does make the code take longer to run. The reason for this is not extremely clear-cut and you'll have to do further analysis to confirm this (look into the "timeit" module among others) but here is my suspicion: try printing the return from primes print primes(1000) try the line the original way you had it, and then try it with the second line. You do NOT get the same output. In fact, it's significantly different. let's see exactly how many extra numbers we have with the second loop style (primes2 is the same function, but with your second loop definition.) x = set(primes(10000)) y = set(primes2(10000)) print len(y) print len(x) print len(y - x) this gives us the fact that there are 1881 incorrect results in "y"! Also, it claims there are 1229 primes less than 10,000 which seems unrealistically-high to me (though I very well may be incorrect.) so you may want to look into that. So what it comes down to is that the reason the second way is taking longer is because it's simply got a larger set that it's dealing with - when you iterate over the items to generate plst after your for loop, it's having to iterate over a larger set, and when returning the list, it's having to return a larger amount of data (although I don't think that would actually have any speed difference as it would just return the reference to the set...) The answer to your original question - why does it take longer to execute over a smaller range - it doesn't. It won't take longer to execute over a smaller range. When you suspect something like this, that is completely counter-intuitive, write a new program that tests JUST that feature, and compare based on that. As you've seen from this problem, there can be minor nuances in your program that effect runtime in very odd ways that you did not expect. Moral of the story: print your output, use various methods at your disposal to check that they're actually equal (use set subtraction / intersections and such, rather than relying on eyeballing it) when comparing data sets. Also a few style notes ( just helpful suggestions, not meant to be overly critical): 1) please, please! don't use semicolons at the end of your lines. It is NOT required syntax in Python and it therefore just looks cluttered / unnecessary. 2) you do not need to call print() as a function unless you're using Python 3.0, but it doesn't hurt to. you can just use print 'somestring' instead. 3) be consistent with your spacing. for example, in some cases you have lines ("else :") with an extra space before the colon, and sometimes you don't ("if plst[i]:"). I would suggest you use no space between the condition and the colon, but it doesn't really matter so long as you're consistent. Just don't be inconsistent. 4) don't put the condition of your "if" statement in parenthesis if it's not necessary (the line "if ( Nmax < 2 ) :" is functionally equivalent to "if Nmax < 2:") 5) you catch an exception if Nmax can't be coerced to an integer, output a "sorry, Nmax couldn't be converted" message, and then you go ahead and use Nmax later in the function. Except clauses do NOT terminate a function automatically. You need to either force a return of the function in your except clauses (after your "print" statements, put a "return []" or something of that sort), or not bother doing the type coercion in the first place, or just don't catch the exceptions yourself and let them bubble up to the next level of execution. > This seems to be counter intuitive. Can someone explain this behavior ? > I hope I have already done so. > Also if I replace the for loop by while loop, it takes longer to run, > which I guess could be because in case of for loop it kind of knows > how many iterations to make, but in while loop it has to keep checking > every time. > If you would like a detailed explanation of why one program takes longer to run than the other, reply to this thread with some code with both functions, the one with the "for" loop and the one with the "while" loop, and I'll try to explain why. It's not something inherent in while loops vs. for loops, it's something specific to your application, so we can't help you analyze it without actual code. HTH, -Luke From bgailer at gmail.com Wed Jun 24 14:24:34 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 24 Jun 2009 08:24:34 -0400 Subject: [Tutor] Help with photo wall Message-ID: <4A421B02.6050504@gmail.com> Please start a new thread with a relevant topic rather than adding to an existing thread. hello all, I am currently making a birthday prezzie for someone (deadline is Thursday night). the basic idea is a wall of photos that you can move about to view different ones using a joystick and press the joystick button to hear a roughly five second commentary that is individual for each photo. I currently have a wall of photos that you can navigate using the wasd keys. all help in creating the final product in time would be appreciated and you would be mentioned in the credits by a nickname (IE. cyberjacob). I am currently using the pygame library. any more detail can be supplied including full source code, thanks everyone, i need all the help I can get to finish this in time please reply ASAP thanks once again cyberjacob Personally I kinda doubt that anyone would tackle this for free. -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Wed Jun 24 14:40:00 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 24 Jun 2009 08:40:00 -0400 Subject: [Tutor] Help with photo wall In-Reply-To: References: <4A421B02.6050504@gmail.com> Message-ID: <4A421EA0.6070307@gmail.com> Please reply-all so a copy goes to the list. Jacob Mansfield wrote: > I've all ready got most of the code just need help with the sound and > joystick > > 2009/6/24 bob gailer > > > Please start a new thread with a relevant topic rather than adding > to an existing thread. > > hello all, > I am currently making a birthday prezzie for someone (deadline is > Thursday night). the basic idea is a wall of photos that you can > move about to view different ones using a joystick and press the > joystick button to hear a roughly five second commentary that is > individual for each photo. I currently have a wall of photos that > you can navigate using the wasd keys. all help in creating the > final product in time would be appreciated and you would be > mentioned in the credits by a nickname (IE. cyberjacob). I am > currently using the pygame library. any more detail can be > supplied including full source code, > thanks everyone, i need all the help I can get to finish this in time > please reply ASAP > thanks once again > cyberjacob > > Personally I kinda doubt that anyone would tackle this for free. > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > > -- Bob Gailer Chapel Hill NC 919-636-4239 From rabidpoobear at gmail.com Wed Jun 24 14:51:27 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 24 Jun 2009 07:51:27 -0500 Subject: [Tutor] Help with photo wall In-Reply-To: <4A421B02.6050504@gmail.com> References: <4A421B02.6050504@gmail.com> Message-ID: <4A42214F.8060901@gmail.com> bob gailer wrote: > Please start a new thread with a relevant topic rather than adding to > an existing thread. seconded > > hello all, > I am currently making a birthday prezzie for someone (deadline is > Thursday night). the basic idea is a wall of photos that you can move > about to view different ones using a joystick and press the joystick > button to hear a roughly five second commentary that is individual for > each photo. I currently have a wall of photos that you can navigate > using the wasd keys. all help in creating the final product in time > would be appreciated and you would be mentioned in the credits by a > nickname (IE. cyberjacob). I am currently using the pygame library. > any more detail can be supplied including full source code, > thanks everyone, i need all the help I can get to finish this in time > please reply ASAP > thanks once again > cyberjacob > > Personally I kinda doubt that anyone would tackle this for free. Why can't you do it yourself? This shouldn't be a very big stretch if you've already got it working for WASD. Just use the joystick module of Pygame, and get the X axis movement, if it's positive and larger than a certain threshold, move to the right, and if it's negative and larger than the threshold, move left. As for playing the sound, just use pygame.music() to stream it from disk, make a new folder called "commentary" where each item has the same name as the picture it's associated with. So root dir images foobar.jpg foobaz.bmp sounds foobar.mp3 foobaz.mp3 then it's simple to just go "ok i'm currently at image "foobar.jpg". I want to load a sound to play for it: import os soundfile = os.path.join("sounds", os.path.splitext(current_img)[0]+".mp3") pygame.music.load(soundfile) # may not be correct function names pygame.music.play() So your main program will look like this (pseudocode warning!) import os, pygame init screen #render wall motion = 0 # how fast (in pixels) we shift the wall each frame. speed = 2 # a multiplier for motion (i think joysticks report axis position as float from 0 to 1, this allows you to scroll faster.) thresh = 0.5 while 1: pygame.clock.tick(60) #lock your framerate #shift wall "motion" pixels in the x axis. refresh screen. for event in pygame.event.get(): if event.type == JOYSTICKDOWN and event.button == BUTTONIWANT: #obviously for this to work must know current image. should not be hard to do. soundfile = os.path.join("sounds", os.path.splitext(current_img)[0]+".mp3") pygame.music.stop() pygame.music.load(soundfile) # may not be correct function names pygame.music.play() elif event.type == JOYSTICKMOTION: x = get_x_axis_of_joystick() if abs(x) > thresh: motion = x * speed pygame.music.stop() # unless you want commentary to keep playing while they scroll. From cyberjacob at googlemail.com Wed Jun 24 15:07:29 2009 From: cyberjacob at googlemail.com (Jacob Mansfield) Date: Wed, 24 Jun 2009 14:07:29 +0100 Subject: [Tutor] Help with photo wall In-Reply-To: <4A42214F.8060901@gmail.com> References: <4A421B02.6050504@gmail.com> <4A42214F.8060901@gmail.com> Message-ID: thank you Luke, It's a bit more complicated than that, all the images are in one massive jpg file similar to those in http://cdn.nhl.com/ducks/images/upload/2008/06/FanPhotos3.jpg also the joystick is a usb module so I didn't think that would work. with regards to the wasd keys there is a glitch that you have to keep tapping them. I also might be able to get the usb adapter in tome so would like to use the arrow keys as a backup. btw do you have any info on the pygame.movie module as i would like to show a YouTube vid first then go immediately into the main program, but the system must wait until I am ready to start which I would signal with the space bar. sorry for being a pain. but thanks a bunch cyberjacob -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Wed Jun 24 19:17:16 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Wed, 24 Jun 2009 10:17:16 -0700 Subject: [Tutor] string pickling and sqlite blob'ing Message-ID: I want to pickle (very long) strings and save them in a sqlite db. The plan is to use pickle dumps() to turn a string into a pickle object and store it in sqlite. After reading the string back from the sqlite db, use pickle loads() to turn back into original string. - Is this a good approach for storing very long strings? - Are the pickle'd strings stored in the sqlite db as a STRING or BLOB? Cheers. Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Wed Jun 24 19:49:10 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 24 Jun 2009 11:49:10 -0600 Subject: [Tutor] string pickling and sqlite blob'ing In-Reply-To: References: Message-ID: <1e53c510906241049y51516f9ev912cb0e5820c728@mail.gmail.com> Pickle is more for storing complex objects (arrays, dict, etc). pickling a string makes it bigger. I have stored large text chunks in text and/or blob columns compressed with gzip.zlib.compress and extracted with gzip.zlib.decompress Comparison: import cPickle as Pickle import gzip x = "asdfasdfasdfasdfasdfasdfasdfasdfasdf" print len(x) >> 36 print len(Pickle.dumps(x)) >> 44 print len(gzip.zlib.compress(x)) >> 14 Vince On Wed, Jun 24, 2009 at 11:17 AM, Dinesh B Vadhia wrote: > I want to pickle (very long) strings and save them in a sqlite db. The > plan is to use pickle dumps() to turn a string into a pickle object and > store it in sqlite. After reading the string back from the sqlite db, use > pickle loads() to turn back into original string. > > - Is this a good approach for storing very long strings? > > - Are the pickle'd strings stored in the sqlite db as a STRING or BLOB? > > Cheers. > > Dinesh > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tiagosaboga at gmail.com Wed Jun 24 20:24:17 2009 From: tiagosaboga at gmail.com (Tiago Saboga) Date: Wed, 24 Jun 2009 15:24:17 -0300 Subject: [Tutor] re module / separator Message-ID: <87ljnhxzfy.fsf@sofocles.comuna.andre> Hi! I am trying to split some lists out of a single text file, and I am having a hard time. I have reduced the problem to the following one: text = "a2345b. f325. a45453b. a325643b. a435643b. g234324b." Of this line of text, I want to take out strings where all words start with a, end with "b.". But I don't want a list of words. I want that: ["a2345b.", "a45453b. a325643b. a435643b."] And I feel I still don't fully understand regular expression's logic. I do not understand the results below: In [33]: re.search("(a[^.]*?b\.\s?){2}", text).group(0) Out[33]: 'a45453b. a325643b. ' In [34]: re.findall("(a[^.]*?b\.\s?){2}", text) Out[34]: ['a325643b. '] In [35]: re.search("(a[^.]*?b\.\s?)+", text).group(0) Out[35]: 'a2345b. ' In [36]: re.findall("(a[^.]*?b\.\s?)+", text) Out[36]: ['a2345b. ', 'a435643b. '] What's the difference between search and findall in [33-34]? And why I cannot generalize [33] to [35]? Out[35] would make sense to me if I had put a non-greedy +, but why do re gets only one word? Thanks, Tiago Saboga. From yashkochar at gmail.com Wed Jun 24 19:38:30 2009 From: yashkochar at gmail.com (Yash) Date: Wed, 24 Jun 2009 13:38:30 -0400 Subject: [Tutor] puzzling for-loop behavior In-Reply-To: <4A421934.1060905@gmail.com> References: <4A421934.1060905@gmail.com> Message-ID: That helps a lot. It was stupid of me to not compare the output from the two functions. The second for loop is actually skiiping over some of the values and hence it takes longer to run when the "plst" is generated. On Wed, Jun 24, 2009 at 8:16 AM, Luke Paireepinart wrote: > Yash wrote: >> >> Hello, >> I am a newbie to python. I am trying to practice writing a code in >> python and am trying to write a function to generate prime numbers >> using sieve of Eratosthenes. (code follows at the end of mail) >> >> The way it is coded, if I change the for loop over "j" from >> for j in range( (2*i*(i + 1)), np, (2*i +1)): >> to >> for j in range( (2*i*(i + 1)), np, 2*(2*i +1)): >> I should get the same output for the two (which I do). >> >> The second for loop has to make roughly half the iterations compared >> to the first, because I increased the step-size by factor 2. >> However when I time the code for the two different for loops, I >> observe that the code takes longer to run as compared the first for >> loop. >> > > How do you know it's taking longer to run? ?How are you profiling your code? I use the clock() function from time module to measure the total run time. > > I just ran your code through timeit, and you're correct, changing that line > does make the code take longer to run. > The reason for this is not extremely clear-cut and you'll have to do further > analysis to confirm this (look into the "timeit" module among others) > but here is my suspicion: > try printing the return from primes > > print primes(1000) > > try the line the original way you had it, and then try it with the second > line. ?You do NOT get the same output. > In fact, it's significantly different. > let's see exactly how many extra numbers we have with the second loop style > (primes2 is the same function, but with your second loop definition.) > > x = set(primes(10000)) > y = set(primes2(10000)) > print len(y) > print len(x) > print len(y - x) > > this gives us the fact that there are 1881 incorrect results in "y"! > > Also, it claims there are 1229 primes less than 10,000 ?which seems > unrealistically-high to me (though I very well may be incorrect.) so you may > want to look into that. > > So what it comes down to is that the reason the second way is taking longer > is because it's simply got a larger set that it's dealing with - when you > iterate over the items to generate plst after your for loop, it's having to > iterate over a larger set, and when returning the list, it's having to > return a larger amount of data (although I don't think that would actually > have any speed difference as it would just return the reference to the > set...) > > The answer to your original question - why does it take longer to execute > over ?a smaller range - it doesn't. ?It won't take longer to execute over a > smaller range. > When you suspect something like this, that is completely counter-intuitive, > write a new program that tests JUST that feature, and compare based on that. > As you've seen from this problem, there can be minor nuances in your program > that effect runtime in very odd ways that you did not expect. > > Moral of the story: print your output, use various methods at your disposal > to check that they're actually equal (use set subtraction / intersections > and such, rather than relying on eyeballing it) when comparing data sets. > > > Also a few style notes ( just helpful suggestions, not meant to be overly > critical): > 1) please, please! don't use semicolons at the end of your lines. ?It is NOT > required syntax in Python and it therefore just looks cluttered / > unnecessary. > 2) you do not need to call print() as a function unless you're using Python > 3.0, but it doesn't hurt to. ?you can just use print 'somestring' instead. > 3) be consistent with your spacing. ?for example, in some cases you have > lines ("else :") with an extra space before the colon, and sometimes you > don't ("if plst[i]:"). ?I would suggest you use no space between the > condition and the colon, but it ?doesn't really matter so long as you're > consistent. ?Just don't be inconsistent. > 4) don't put the condition of your "if" statement in parenthesis if it's not > necessary (the line "if ( Nmax < 2 ) :" is functionally equivalent to "if > Nmax < 2:") > 5) you catch an exception if Nmax can't be coerced to an integer, output a > "sorry, Nmax couldn't be converted" message, and then you go ahead and use > Nmax later in the function. ?Except clauses do NOT terminate a function > automatically. ?You need to either force a return of the function in your > except clauses (after your "print" statements, put a "return []" or > something of that sort), or not bother doing the type coercion in the first > place, or just don't catch the exceptions yourself and let them bubble up to > the next level of execution. thank you. I will keep these in mind. > >> This seems to be counter intuitive. Can someone explain this behavior ? >> > > I hope I have already done so. >> >> Also if I replace the for loop by while loop, it takes longer to run, >> which I guess could be because in case of for loop it kind of knows >> how many iterations to make, but in while loop it has to keep checking >> every time. >> > > If you would like a detailed explanation of why one program takes longer to > run than the other, reply to this thread with > some code with both functions, the one with the "for" loop and the one with > the "while" loop, and I'll try to explain why. > It's not something inherent in while loops vs. for loops, it's something > specific to your application, so we can't help you analyze it without actual > code. I will try printing the output and test it. > > HTH, > -Luke > Thank you very much, Yash From kent37 at tds.net Wed Jun 24 20:40:37 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Jun 2009 14:40:37 -0400 Subject: [Tutor] string pickling and sqlite blob'ing In-Reply-To: References: Message-ID: <1c2a2c590906241140qc2e6312j5a2b4c7a503d10a8@mail.gmail.com> On Wed, Jun 24, 2009 at 1:17 PM, Dinesh B Vadhia wrote: > I want to pickle (very long) strings and save them in a sqlite db.? The plan > is to use pickle dumps() to turn a string into a pickle object and store it > in sqlite.? After reading the string back from the sqlite db, use pickle > loads() to turn back into original string. There is no such thing as a "pickle object", the result of pickle.dumps() is a string. Kent From zstumgoren at gmail.com Wed Jun 24 21:07:44 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 24 Jun 2009 15:07:44 -0400 Subject: [Tutor] re module / separator In-Reply-To: <87ljnhxzfy.fsf@sofocles.comuna.andre> References: <87ljnhxzfy.fsf@sofocles.comuna.andre> Message-ID: Hey Tiago, > text = "a2345b. f325. a45453b. a325643b. a435643b. g234324b." > > Of this line of text, I want to take out strings where all words start > with a, end with "b.". But I don't want a list of words. I want that: > > ["a2345b.", "a45453b. a325643b. a435643b."] > Are you saying you want a list of every item that starts with an "a" and ends with a "b"? If so, the above list is not what you're after. It only contains two items: a2345b. a45453b. a325643b. a435643b. You can verify this by trying len(["a2345b.", "a45453b. a325643b. a435643b."]). You can also see that each item is wrapped in double quotes and separated by a comma. > And I feel I still don't fully understand regular expression's logic. I > do not understand the results below: Try reading this: http://www.amk.ca/python/howto/regex/ I've found it to be a very gentle and useful introduction to regexes. It explains, among other things, what the search and findall methods do. If I'm understanding your problem correctly, you probably want the findall method: You should definitely take the time to read up on regexes. Your patterns grew too complex for this problem (again, if I'm understanding you right) which is probably why you're not understanding your results. In [9]: re.findall(r'a[a-z0-9]+b',text) Out[9]: ['a2345b', 'a45453b', 'a325643b', 'a435643b'] There are other ways to perform the above, for instance using the "\w" metacharacter to match any alphanumeric. In [20]: re.findall(r'a\w+b',text) Out[20]: ['a2345b', 'a45453b', 'a325643b', 'a435643b'] Or, to get even more (needlessly) complicated: In [21]: re.findall(r'\ba\w+b\b',text) Out[21]: ['a2345b', 'a45453b', 'a325643b', 'a435643b'] As you learned, regexes can get really complicated, really quickly if you don't understand the syntax. Others with more experience might offer more elegant solutions to your problem, but I'd still encourage you to read up on the basics and get comfortable with the re module. It's a great tool once you understand it. Best of luck, Serdar From zstumgoren at gmail.com Wed Jun 24 21:15:10 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 24 Jun 2009 15:15:10 -0400 Subject: [Tutor] re module / separator In-Reply-To: References: <87ljnhxzfy.fsf@sofocles.comuna.andre> Message-ID: apologies -- I just reread your post and appears you also want to capture the dot after each "b" ( "b." ) In that case, you need to update the pattern to match for the dot. But because the dot is itself a metacharacter, you have to escape it with a backslash: In [23]: re.findall(r'a\w+b\.',text) Out[23]: ['a2345b.', 'a45453b.', 'a325643b.', 'a435643b.'] Again, all of these features are explained nicely at http://www.amk.ca/python/howto/regex/ From eduardo.susan at gmail.com Wed Jun 24 21:30:58 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Wed, 24 Jun 2009 13:30:58 -0600 Subject: [Tutor] Problems with parameter queries Message-ID: <9356b9f30906241230n6a06b03ap7052259826e143ad@mail.gmail.com> Hello, I am accessing a Pervasive SQL data source using odbc and I'm having this trouble: import dbi import odbc # the first execute works pnumber = '09F153' wh = '00' qty = 3 myconn = odbc.odbc('DSN=MKPT01') mycursor = myconn.cursor() mycursor.execute(""" SELECT "INVENTORY"."CODE", "INVENTORY"."INV_DESCRIPTION" FROM "INVENTORY" WHERE "INVENTORY"."CODE" = ? AND WHSE = ? """, [pnumber, wh]) results = mycursor.fetchall() print results # this one below doesn't mycursor.execute("""UPDATE INVENTORY SET ONHAND = ? WHERE CODE = ? AND WHSE = '00' """, [pnumber, qty]) #mycursor.commit() mycursor.close() If I don't use parameter in the update code, it updates fine. Am I missing something? Is this a problem specific to the Pervasive SQL? For example, this works: mycursor.execute("""UPDATE INVENTORY SET ONHAND='0' WHERE CODE = '09F153' AND WHSE = '00' """) Thanks Eduardo From rabidpoobear at gmail.com Wed Jun 24 21:57:17 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 24 Jun 2009 14:57:17 -0500 Subject: [Tutor] Help with photo wall In-Reply-To: References: <4A421B02.6050504@gmail.com> <4A42214F.8060901@gmail.com> Message-ID: <4A42851D.9000007@gmail.com> Jacob Mansfield wrote: > thank you Luke, > It's a bit more complicated than that, all the images are in one > massive jpg file similar to those in > http://cdn.nhl.com/ducks/images/upload/2008/06/FanPhotos3.jpg So they're not lined up? they overlap? Do they have to be in one massive jpg? Do they have to overlap? Do you know exactly the location of every image? > also the joystick is a usb module so I didn't think that would work. pygame.joystick supports any kind of joystick. Did you try it? It works fine for me w/ a Microsoft Sidewinder 2 USB joystick. > with regards to the wasd keys there is a glitch that you have to keep > tapping them. Keep tapping them to do what? What is the specific glitch? > I also might be able to get the usb adapter in tome so would like to > use the arrow keys as a backup. This sentence doesn't make sense to me. What does tome mean? Did you mean you might not be able to get a USB adapter? Why would you need an adapter if the joystick is USB already? > btw do you have any info on the pygame.movie module as i would like to > show a YouTube vid first then go immediately into the main program, > but the system must wait until I am ready to start which I would > signal with the space bar. sorry for being a pain. but thanks a bunch I don't think the pygame.movie module supports flv's. I would rip the video off of youtube and recompress it as an mpeg. you can use VLC to do this. Then pygame.movie is simple, you just load it in and play it. However, it doesn't work very well on Windows in some cases. Someone just released an alpha version of their media player (they announced it on the pygame mailing list), that uses VLC as a back-end - that would probably even be able to play the original FLV. as for not progressing to the photo wall until after you press space... I feel like you could've figured that one out on your own. Just have a flag such as state="PLAYING" and put all your Wall code in an if statement such as 'if state == "WALL"', and then after you play the video, just wait until you get a "space" and then set state="WALL" and it will automatically switch states. There are a myriad of other ways you could solve this as well, that's just one possibility. I don't mean to be condescending but it looks like I'm the only one helping you so far, and you have a very tight schedule, and I don't have a whole lot of time to help, so you would be best served by only asking those questions you can't figure out on your own. So try more stuff and keep trying it until you run into severe roadblocks, and I'll provide a gentle nudging to get you over them. See http://catb.org/~esr/faqs/smart-questions.html for more information on why this style of asking questions benefits both you and me. From tiagosaboga at gmail.com Wed Jun 24 22:42:15 2009 From: tiagosaboga at gmail.com (Tiago Saboga) Date: Wed, 24 Jun 2009 17:42:15 -0300 Subject: [Tutor] re module / separator In-Reply-To: (Serdar Tumgoren's message of "Wed, 24 Jun 2009 15:07:44 -0400") References: <87ljnhxzfy.fsf@sofocles.comuna.andre> Message-ID: <87k531wehk.fsf@sofocles.comuna.andre> Serdar Tumgoren writes: > Hey Tiago, > >> text = "a2345b. f325. a45453b. a325643b. a435643b. g234324b." >> >> Of this line of text, I want to take out strings where all words start >> with a, end with "b.". But I don't want a list of words. I want that: >> >> ["a2345b.", "a45453b. a325643b. a435643b."] >> > > Are you saying you want a list of every item that starts with an "a" > and ends with a "b"? If so, the above list is not what you're after. > It only contains two items: > a2345b. > a45453b. a325643b. a435643b. Yes, I want to find only two items. I want every sequence of words where every word begins with an "a" and ends with "b.". > Try reading this: > http://www.amk.ca/python/howto/regex/ I have read several times, and I thought I understood it quite well ;) I have not the time right now to do it, but if it turns out to be useful, I can show why I came to the patterns I sent to the list. Thanks, Tiago. From dineshbvadhia at hotmail.com Wed Jun 24 22:42:54 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Wed, 24 Jun 2009 13:42:54 -0700 Subject: [Tutor] string pickling and sqlite blob'ing In-Reply-To: <1e53c510906241049y51516f9ev912cb0e5820c728@mail.gmail.com> References: <1e53c510906241049y51516f9ev912cb0e5820c728@mail.gmail.com> Message-ID: Hi Vince That's terrific! Once a string is compressed with gzip.zlib does it make a difference whether it is stored it in a TEXT or BLOB column? Dinesh From: vince spicer Sent: Wednesday, June 24, 2009 10:49 AM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] string pickling and sqlite blob'ing Pickle is more for storing complex objects (arrays, dict, etc). pickling a string makes it bigger. I have stored large text chunks in text and/or blob columns compressed with gzip.zlib.compress and extracted with gzip.zlib.decompress Comparison: import cPickle as Pickle import gzip x = "asdfasdfasdfasdfasdfasdfasdfasdfasdf" print len(x) >> 36 print len(Pickle.dumps(x)) >> 44 print len(gzip.zlib.compress(x)) >> 14 Vince On Wed, Jun 24, 2009 at 11:17 AM, Dinesh B Vadhia wrote: I want to pickle (very long) strings and save them in a sqlite db. The plan is to use pickle dumps() to turn a string into a pickle object and store it in sqlite. After reading the string back from the sqlite db, use pickle loads() to turn back into original string. - Is this a good approach for storing very long strings? - Are the pickle'd strings stored in the sqlite db as a STRING or BLOB? Cheers. Dinesh _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jun 24 23:22:03 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Jun 2009 17:22:03 -0400 Subject: [Tutor] re module / separator In-Reply-To: <87ljnhxzfy.fsf@sofocles.comuna.andre> References: <87ljnhxzfy.fsf@sofocles.comuna.andre> Message-ID: <1c2a2c590906241422r61cd387bk2cdcd12e4978c5b1@mail.gmail.com> On Wed, Jun 24, 2009 at 2:24 PM, Tiago Saboga wrote: > Hi! > > I am trying to split some lists out of a single text file, and I am > having a hard time. I have reduced the problem to the following one: > > text = "a2345b. f325. a45453b. a325643b. a435643b. g234324b." > > Of this line of text, I want to take out strings where all words start > with a, end with "b.". But I don't want a list of words. I want that: > > ["a2345b.", "a45453b. a325643b. a435643b."] > > And I feel I still don't fully understand regular expression's logic. I > do not understand the results below: > > In [33]: re.search("(a[^.]*?b\.\s?){2}", text).group(0) > Out[33]: 'a45453b. a325643b. ' group(0) is the entire match so this returns what you expect. But what is group(1)? In [6]: re.search("(a[^.]*?b\.\s?){2}", text).group(1) Out[6]: 'a325643b. ' Repeated groups are tricky; the returned value contains only the first match for the group, not the repeats. > In [34]: re.findall("(a[^.]*?b\.\s?){2}", text) > Out[34]: ['a325643b. '] When the re contains groups, re.findall() returns the groups. It doesn't return the whole match. So this is giving group(1), not group(0). You can get the whole match by explicitly grouping it: In [4]: re.findall("((a[^.]*?b\.\s?){2})", text) Out[4]: [('a45453b. a325643b. ', 'a325643b. ')] > In [35]: re.search("(a[^.]*?b\.\s?)+", text).group(0) > Out[35]: 'a2345b. ' You only get the first match, so this is correct. > In [36]: re.findall("(a[^.]*?b\.\s?)+", text) > Out[36]: ['a2345b. ', 'a435643b. '] This is finding both matches but the grouping has the same difficulty as the previous findall(). This is closer: In [7]: re.findall("((a[^.]*?b\.\s?)+)", text) Out[7]: [('a2345b. ', 'a2345b. '), ('a45453b. a325643b. a435643b. ', 'a435643b. ')] If you change the inner parentheses to be non-grouping then you get pretty much what you want: In [8]: re.findall("((?:a[^.]*?b\.\s?)+)", text) Out[8]: ['a2345b. ', 'a45453b. a325643b. a435643b. '] Kent From zstumgoren at gmail.com Wed Jun 24 23:57:59 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 24 Jun 2009 17:57:59 -0400 Subject: [Tutor] re module / separator In-Reply-To: <87k531wehk.fsf@sofocles.comuna.andre> References: <87ljnhxzfy.fsf@sofocles.comuna.andre> <87k531wehk.fsf@sofocles.comuna.andre> Message-ID: As usual, Kent Johnson has swooped in an untangled the mess with a clear explanation. By the time a regex gets this complicated, I typically start thinking of ways to simplify or avoid them altogether. Below is the code I came up with. It goes through some gymnastics and can surely stand improvement, but it seems to get the job done. Suggestions are welcome. In [83]: text Out[83]: 'a2345b. f325. a45453b. a325643b. a435643b. g234324b.' In [84]: textlist = text.split() In [85]: textlist Out[85]: ['a2345b.', 'f325.', 'a45453b.', 'a325643b.', 'a435643b.', 'g234324b.'] In [86]: newlist = [] In [87]: pat = re.compile(r'a\w+b\.') In [88]: for item in textlist: ....: if pat.match(item): ....: newlist.append(item) ....: else: ....: newlist.append("|") ....: ....: In [89]: newlist Out[89]: ['a2345b.', '|', 'a45453b.', 'a325643b.', 'a435643b.', '|'] In [90]: lastlist = ''.join(newlist) In [91]: lastlist Out[91]: 'a2345b.|a45453b.a325643b.a435643b.|' In [92]: lastlist.rstrip("|").split("|") Out[92]: ['a2345b.', 'a45453b.a325643b.a435643b.'] From zstumgoren at gmail.com Thu Jun 25 00:19:12 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 24 Jun 2009 18:19:12 -0400 Subject: [Tutor] re module / separator In-Reply-To: References: <87ljnhxzfy.fsf@sofocles.comuna.andre> <87k531wehk.fsf@sofocles.comuna.andre> Message-ID: Ok -- realized my "solution" incorrectly strips white space from multiword strings: > Out[92]: ['a2345b.', 'a45453b.a325643b.a435643b.'] > So here are some more gymnastics to get the correct result: In [105]: newlist Out[105]: ['a2345b.', '|', 'a45453b.', 'a325643b.', 'a435643b.', '|'] In [109]: lastlist2 = " ".join(newlist).rstrip("|").split("|") In [110]: lastlist3 = [item.strip() for item in lastlist2] In [111]: lastlist3 Out[111]: ['a2345b.', 'a45453b. a325643b. a435643b.'] From alan.gauld at btinternet.com Thu Jun 25 01:44:22 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Jun 2009 00:44:22 +0100 Subject: [Tutor] string pickling and sqlite blob'ing References: Message-ID: "Dinesh B Vadhia" wrote > I want to pickle (very long) strings and save them in a sqlite db. Why? Why not just store the string in the database? If that turns out to be a problem then think about other options - like splitting it into chunks say? But until you know you have a problem don't try to solve it! > - Is this a good approach for storing very long strings? Probably not. > - Are the pickle'd strings stored in the sqlite db as a STRING or BLOB? They could be stored either way, thats up to how you define your tables and write your SQL. In general I expect databases to handle very large quantities of data either as blobs or as references to a file. Is this a valid approach? Write the long string (assuming its many MB in size) into a text file and store that with a unique name. Then store the filename in the database. But first check that you can't store it in the database directly or in chunks. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From roadierich at googlemail.com Thu Jun 25 02:07:08 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Thu, 25 Jun 2009 01:07:08 +0100 Subject: [Tutor] string pickling and sqlite blob'ing In-Reply-To: References: <1e53c510906241049y51516f9ev912cb0e5820c728@mail.gmail.com> Message-ID: 2009/6/24 Dinesh B Vadhia : > Hi Vince > > That's terrific!? Once a string is compressed with gzip.zlib does it make a > difference whether it is stored it in a TEXT or BLOB column? > > Dinesh > > >From the MySQL language reference: """A BLOB is a binary large object that can hold a variable amount of data. The four BLOB types TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB differ only in the maximum length of the values they can hold. The four TEXT types TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT correspond to the four BLOB types and have the same maximum lengths and storage requirements. The only difference between BLOB and TEXT types is that sorting and comparison is performed in case-sensitive fashion for BLOB values and case-insensitive fashion for TEXT values. In other words, a TEXT is a case-insensitive BLOB.""" gzip.zlib outputs binary data, so you should use BLOB. Pickle, I believe, outputs an ascii string, so should use TEXT. Hope that makes it a bit clearer. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From roadierich at googlemail.com Thu Jun 25 02:16:12 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Thu, 25 Jun 2009 01:16:12 +0100 Subject: [Tutor] Fwd: Problems with parameter queries In-Reply-To: References: <9356b9f30906241230n6a06b03ap7052259826e143ad@mail.gmail.com> Message-ID: (oops... forgot to reply-all) ---------- Forwarded message ---------- From: Richard Lovely Date: 2009/6/25 Subject: Re: [Tutor] Problems with parameter queries To: Eduardo Vieira 2009/6/24 Eduardo Vieira : > Hello, I am accessing a Pervasive SQL data source using odbc and I'm > having this trouble: > > import dbi > import odbc > ?# the first execute works > pnumber = '09F153' > wh = '00' > qty = 3 > myconn = odbc.odbc('DSN=MKPT01') > mycursor = myconn.cursor() > mycursor.execute(""" > SELECT "INVENTORY"."CODE", "INVENTORY"."INV_DESCRIPTION" FROM "INVENTORY" > WHERE "INVENTORY"."CODE" = ? AND WHSE = ? > > """, [pnumber, wh]) > results = mycursor.fetchall() > > print results > > # this one below doesn't > > mycursor.execute("""UPDATE INVENTORY SET ONHAND = ? > WHERE CODE = ? AND WHSE = '00' > > """, [pnumber, qty]) > #mycursor.commit() > mycursor.close() > > If I don't use parameter in the update code, it updates fine. Am I > missing something? Is this a problem specific to the Pervasive SQL? > For example, this works: > mycursor.execute("""UPDATE INVENTORY SET ONHAND='0' > WHERE CODE = '09F153' AND WHSE = '00' > > """) > > Thanks > > Eduardo > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Isn't the arguement list to the non-working query back-to-front? -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From lie.1296 at gmail.com Thu Jun 25 07:43:27 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 25 Jun 2009 15:43:27 +1000 Subject: [Tutor] string pickling and sqlite blob'ing In-Reply-To: References: <1e53c510906241049y51516f9ev912cb0e5820c728@mail.gmail.com> Message-ID: Richard Lovely wrote: > 2009/6/24 Dinesh B Vadhia : >> Hi Vince >> >> That's terrific! Once a string is compressed with gzip.zlib does it make a >> difference whether it is stored it in a TEXT or BLOB column? >> >> Dinesh >> >> >>From the MySQL language reference: > """A BLOB is a binary large object that can hold a variable amount of > data. The four BLOB types TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB > differ only in the maximum length of the values they can hold. > > The four TEXT types TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT > correspond to the four BLOB types and have the same maximum lengths > and storage requirements. The only difference between BLOB and TEXT > types is that sorting and comparison is performed in case-sensitive > fashion for BLOB values and case-insensitive fashion for TEXT values. > In other words, a TEXT is a case-insensitive BLOB.""" > > gzip.zlib outputs binary data, so you should use BLOB. > Pickle, I believe, outputs an ascii string, so should use TEXT. Although pickle output only ascii string, it is not meant to be human readable at all. Basically there is no difference how it is stored as long as what goes in is equal with what goes out. I can't think of a need to sort or compare raw pickle data. From realtimethrill at googlemail.com Thu Jun 25 05:32:35 2009 From: realtimethrill at googlemail.com (Dave C) Date: Thu, 25 Jun 2009 04:32:35 +0100 Subject: [Tutor] short circuiting Message-ID: <970eb3ed0906242032l41df5705vfa78ab5de02fbfa@mail.gmail.com> Hi I've read that the builtin all() function stops evaluating as soon as it hits a false item, meaning that items after the first false one are not evaluated. I was wondering if someone could give an example of where all()'s short circuiting is of consequence, akin to: False and produces_side_effect() Many thanks From ericzhao at microsoft.com Thu Jun 25 05:49:56 2009 From: ericzhao at microsoft.com (Eric Zhao) Date: Thu, 25 Jun 2009 11:49:56 +0800 Subject: [Tutor] why PyObject_VAR_HEAD? Message-ID: <4ED28A1ED2237346A6B2A76952E3FCC024B039807E@AA-EXMSG-C421.southpacific.corp.microsoft.com> Hi, I'm studying the CPython source code. I don't quite understand why they're using PyObject_VAR_HEAD to define struct like PyListObject. To define such kind of struct, could I use _PyObject_HEAD_EXTRA as a header and add "items" pointer and "allocated" count explicity? Is there any difference? Thanks. Eric From kent37 at tds.net Thu Jun 25 12:52:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Jun 2009 06:52:50 -0400 Subject: [Tutor] Program Slicing / Trace In-Reply-To: <3124be320906180737x4e64553p7fa3636c179be597@mail.gmail.com> References: <3124be320906180737x4e64553p7fa3636c179be597@mail.gmail.com> Message-ID: <1c2a2c590906250352k127b6d83na6bcbdeff8245c0@mail.gmail.com> On Thu, Jun 18, 2009 at 10:37 AM, Jojo Mwebaze wrote: > Hi Tutor > > The problem i have is to see which statements modify my data at execution > time without referring to the code. Referring to the code is difficult esp > because of branching. You can never tell before hand which branch execution > will follow. Stepping through the code in a debugger can be very helpful, either pdb or winpdb. You also might look at CodeInvestigator: http://codeinvestigator.googlepages.com/main Kent From tiagosaboga at gmail.com Thu Jun 25 14:44:29 2009 From: tiagosaboga at gmail.com (Tiago Saboga) Date: Thu, 25 Jun 2009 09:44:29 -0300 Subject: [Tutor] re module / separator In-Reply-To: <1c2a2c590906241422r61cd387bk2cdcd12e4978c5b1@mail.gmail.com> (Kent Johnson's message of "Wed, 24 Jun 2009 17:22:03 -0400") References: <87ljnhxzfy.fsf@sofocles.comuna.andre> <1c2a2c590906241422r61cd387bk2cdcd12e4978c5b1@mail.gmail.com> Message-ID: <87bpocpjo2.fsf@sofocles.comuna.andre> Thanks Kent! Once more you go straight to the point! Kent Johnson writes: > On Wed, Jun 24, 2009 at 2:24 PM, Tiago Saboga wrote: >> In [33]: re.search("(a[^.]*?b\.\s?){2}", text).group(0) >> Out[33]: 'a45453b. a325643b. ' > > group(0) is the entire match so this returns what you expect. But what > is group(1)? > > In [6]: re.search("(a[^.]*?b\.\s?){2}", text).group(1) > Out[6]: 'a325643b. ' > > Repeated groups are tricky; the returned value contains only the first > match for the group, not the repeats. The problem was exactly that. I had seen that findall got the first group of the match, but not that this would not span repeats. But it makes sense, as the repeat count is after the parens. > If you change the inner parentheses to be non-grouping then you get > pretty much what you want: > > In [8]: re.findall("((?:a[^.]*?b\.\s?)+)", text) > Out[8]: ['a2345b. ', 'a45453b. a325643b. a435643b. '] And the trick of the non-grouping parens is great too. Thanks again! Tiago. From roadierich at googlemail.com Thu Jun 25 14:53:46 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Thu, 25 Jun 2009 13:53:46 +0100 Subject: [Tutor] string pickling and sqlite blob'ing In-Reply-To: References: <1e53c510906241049y51516f9ev912cb0e5820c728@mail.gmail.com> Message-ID: 2009/6/25 Lie Ryan : > > Although pickle output only ascii string, it is not meant to be human > readable at all. Basically there is no difference how it is stored as > long as what goes in is equal with what goes out. I can't think of a > need to sort or compare raw pickle data. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > But you never know, do you. I mean, it wouldn't be the first time SQL has been abused for something much easier to do in code... see http://thedailywtf.com/Articles/The-Int-Divide.aspx for one, and I'm sure there's many more out there. A couple of rough ideas for usage are already forming, but not to a sharable degree. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From dineshbvadhia at hotmail.com Thu Jun 25 16:25:41 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 25 Jun 2009 07:25:41 -0700 Subject: [Tutor] string pickling and sqlite blob'ing Message-ID: Alan On a machine with 6gb of ram, storing very long strings in sqlite caused a "sqlite3.OperationalError: Could not decode to UTF-8 column 'j' with text" which has been resolved. This fix then caused a memory error when reading some of the strings back from the db. Hence, I'm trying to work out what the problem is and looking for alternative solutions. It is strange that I can insert a long string into sqlite but a memory error is caused when selecting it. Splitting the strings into smaller chunks is the obvious solution but I need to sort out the above first since the post-processing after the select is on the entire string. Dinesh -------------------------------------------------------------------------------- Message: 3 Date: Thu, 25 Jun 2009 00:44:22 +0100 From: "Alan Gauld" To: tutor at python.org Subject: Re: [Tutor] string pickling and sqlite blob'ing Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Dinesh B Vadhia" wrote > I want to pickle (very long) strings and save them in a sqlite db. Why? Why not just store the string in the database? If that turns out to be a problem then think about other options - like splitting it into chunks say? But until you know you have a problem don't try to solve it! > - Is this a good approach for storing very long strings? Probably not. > - Are the pickle'd strings stored in the sqlite db as a STRING or BLOB? They could be stored either way, thats up to how you define your tables and write your SQL. In general I expect databases to handle very large quantities of data either as blobs or as references to a file. Is this a valid approach? Write the long string (assuming its many MB in size) into a text file and store that with a unique name. Then store the filename in the database. But first check that you can't store it in the database directly or in chunks. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From manufrhel at yahoo.com Thu Jun 25 14:21:05 2009 From: manufrhel at yahoo.com (Christopher Altieri) Date: Thu, 25 Jun 2009 05:21:05 -0700 (PDT) Subject: [Tutor] syntax error Message-ID: <254122.50865.qm@web57514.mail.re1.yahoo.com> loaded python 3 and 3.1 several times on vista. tried first command: print "hello world' but keep getting syntax error. what am I doing wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Jun 25 16:50:35 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 25 Jun 2009 16:50:35 +0200 Subject: [Tutor] syntax error In-Reply-To: <254122.50865.qm@web57514.mail.re1.yahoo.com> References: <254122.50865.qm@web57514.mail.re1.yahoo.com> Message-ID: <4A438EBB.9060304@compuscan.co.za> Christopher Altieri wrote: > loaded python 3 and 3.1 several times on vista. tried first command: > print "hello world' but keep getting syntax error. what am I doing wrong? > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Python 3.0+ print has been changed to a function so you need to do print("Hello World!") -- Kind Regards, Christian Witts From kent37 at tds.net Thu Jun 25 16:37:09 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Jun 2009 10:37:09 -0400 Subject: [Tutor] short circuiting In-Reply-To: <970eb3ed0906242032l41df5705vfa78ab5de02fbfa@mail.gmail.com> References: <970eb3ed0906242032l41df5705vfa78ab5de02fbfa@mail.gmail.com> Message-ID: <1c2a2c590906250737g69211d45p6cce5dc855e0ed2f@mail.gmail.com> On Wed, Jun 24, 2009 at 11:32 PM, Dave C wrote: > Hi > I've read that the builtin all() function stops evaluating as soon as > it hits a false item, meaning that items after the first false one are > not evaluated. > > I was wondering if someone could give an example of where all()'s > short circuiting is of consequence It can have a performance impact if the sequence under test is long or the comparison is expensive. Kent From vinces1979 at gmail.com Thu Jun 25 16:38:41 2009 From: vinces1979 at gmail.com (vince spicer) Date: Thu, 25 Jun 2009 08:38:41 -0600 Subject: [Tutor] string pickling and sqlite blob'ing In-Reply-To: References: <1e53c510906241049y51516f9ev912cb0e5820c728@mail.gmail.com> Message-ID: <1e53c510906250738n64841432w26f2320570017fac@mail.gmail.com> Dinesh In theory you can store in either type(i have done it), however you should store in the binary column, blob Vince On Wed, Jun 24, 2009 at 2:42 PM, Dinesh B Vadhia wrote: > Hi Vince > > That's terrific! Once a string is compressed with gzip.zlib does it make a > difference whether it is stored it in a TEXT or BLOB column? > > Dinesh > > > > *From:* vince spicer > *Sent:* Wednesday, June 24, 2009 10:49 AM > *To:* Dinesh B Vadhia > *Cc:* tutor at python.org > *Subject:* Re: [Tutor] string pickling and sqlite blob'ing > > Pickle is more for storing complex objects (arrays, dict, etc). pickling a > string makes it bigger. > > I have stored large text chunks in text and/or blob columns compressed with > gzip.zlib.compress and extracted with gzip.zlib.decompress > > Comparison: > > import cPickle as Pickle > import gzip > > x = "asdfasdfasdfasdfasdfasdfasdfasdfasdf" > > print len(x) > >> 36 > > print len(Pickle.dumps(x)) > >> 44 > > print len(gzip.zlib.compress(x)) > >> 14 > > > Vince > > On Wed, Jun 24, 2009 at 11:17 AM, Dinesh B Vadhia < > dineshbvadhia at hotmail.com> wrote: > I want to pickle (very long) strings and save them in a sqlite db. The > plan is to use pickle dumps() to turn a string into a pickle object and > store it in sqlite. After reading the string back from the sqlite db, use > pickle loads() to turn back into original string. > > - Is this a good approach for storing very long strings? > > - Are the pickle'd strings stored in the sqlite db as a STRING or BLOB? > > Cheers. > > Dinesh > > > >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eduardo.susan at gmail.com Thu Jun 25 17:13:21 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Thu, 25 Jun 2009 09:13:21 -0600 Subject: [Tutor] Fwd: Problems with parameter queries In-Reply-To: References: <9356b9f30906241230n6a06b03ap7052259826e143ad@mail.gmail.com> Message-ID: <9356b9f30906250813l3b9aae10mbaadf4dd85e5f53a@mail.gmail.com> On Wed, Jun 24, 2009 at 6:16 PM, Richard Lovely wrote: > (oops... forgot to reply-all) > > > ---------- Forwarded message ---------- > From: Richard Lovely > Date: 2009/6/25 > Subject: Re: [Tutor] Problems with parameter queries > To: Eduardo Vieira > > > 2009/6/24 Eduardo Vieira : >> Hello, I am accessing a Pervasive SQL data source using odbc and I'm >> having this trouble: >> >> import dbi >> import odbc >> ?# the first execute works >> pnumber = '09F153' >> wh = '00' >> qty = 3 >> myconn = odbc.odbc('DSN=MKPT01') >> mycursor = myconn.cursor() >> mycursor.execute(""" >> SELECT "INVENTORY"."CODE", "INVENTORY"."INV_DESCRIPTION" FROM "INVENTORY" >> WHERE "INVENTORY"."CODE" = ? AND WHSE = ? >> >> """, [pnumber, wh]) >> results = mycursor.fetchall() >> >> print results >> >> # this one below doesn't >> >> mycursor.execute("""UPDATE INVENTORY SET ONHAND = ? >> WHERE CODE = ? AND WHSE = '00' >> >> """, [pnumber, qty]) >> #mycursor.commit() >> mycursor.close() >> >> If I don't use parameter in the update code, it updates fine. Am I >> missing something? Is this a problem specific to the Pervasive SQL? >> For example, this works: >> mycursor.execute("""UPDATE INVENTORY SET ONHAND='0' >> WHERE CODE = '09F153' AND WHSE = '00' >> >> """) >> >> Thanks >> >> Eduardo >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > Isn't the arguement list to the non-working query back-to-front? > > -- > Richard "Roadie Rich" Lovely, part of the JNP|UK Famile > www.theJNP.com > > > Oops! My bad, I guess that was the problem. I'm going to test it soon. Thanks for spotting that! From bgailer at gmail.com Thu Jun 25 21:23:03 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 25 Jun 2009 15:23:03 -0400 Subject: [Tutor] short circuiting In-Reply-To: <1c2a2c590906250737g69211d45p6cce5dc855e0ed2f@mail.gmail.com> References: <970eb3ed0906242032l41df5705vfa78ab5de02fbfa@mail.gmail.com> <1c2a2c590906250737g69211d45p6cce5dc855e0ed2f@mail.gmail.com> Message-ID: <4A43CE97.4070507@gmail.com> Kent Johnson wrote: > On Wed, Jun 24, 2009 at 11:32 PM, Dave C wrote: > >> Hi >> I've read that the builtin all() function stops evaluating as soon as >> it hits a false item, meaning that items after the first false one are >> not evaluated. >> >> I was wondering if someone could give an example of where all()'s >> short circuiting is of consequence >> > > It can have a performance impact if the sequence under test is long or > the comparison is expensive. > Also an item could be a call to a callable object (function, method, ...?). That can have side effects. -- Bob Gailer Chapel Hill NC 919-636-4239 From fe78bi at yahoo.com Fri Jun 26 12:29:17 2009 From: fe78bi at yahoo.com (Febin Ameer Ahsen) Date: Fri, 26 Jun 2009 15:59:17 +0530 (IST) Subject: [Tutor] (no subject) Message-ID: <455436.36020.qm@web94812.mail.in2.yahoo.com> how to implement diff command showing? difference in box ICC World Twenty20 England '09 exclusively on YAHOO! CRICKET http://cricket.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Fri Jun 26 12:42:03 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 26 Jun 2009 12:42:03 +0200 Subject: [Tutor] difflib (was: (no subject)) In-Reply-To: <455436.36020.qm@web94812.mail.in2.yahoo.com> References: <455436.36020.qm@web94812.mail.in2.yahoo.com> Message-ID: <4A44A5FB.40500@tue.nl> Febin Ameer Ahsen wrote: > how to implement diff command showing difference in box Don't implement diff yourself, use the difflib module instead. Albert From kgotlelelok at galmail.co.za Fri Jun 26 12:54:21 2009 From: kgotlelelok at galmail.co.za (kgotlelelok at galmail.co.za) Date: Fri, 26 Jun 2009 12:54:21 +0200 (SAST) Subject: [Tutor] newton's method for system of nonlinear equations Message-ID: <2640.146.64.81.22.1246013661.squirrel@galmail.mig.wm.co.za> Hi, I am trying to write a program in python that solves a system of nonlinear equations using newton's method. I don't know what I am doing wrong. Please help from scipy import* x = array([0.0,0.0,0.0]) n=len(x) tol= 0.00001 N=30 k=1 while k <= N: def f(x): f= zeros((len(x)),float) f[0][k]= x[0][k]**2 + x[1][k]-37 f[1][k]=x[0][k]- x[1][k]**2- 5 f[2][k]= x[0][k] + x[1][k]+ x[2][k]- 3 return f[k] def J(x): J= zeros((n,n),float) for i in range(n): ei=zeros(n,float) ei[i]=1.0 J[:i]=(f(x[k]+tol*ei)-f(x[k]))/tol return J y[k] = -(J.I)*f[k] x[k+1]=x[k]+y[k] if sqrt(dot(f0,f0)/len(x)) < tol: print x else: k=k+1 print 'Too many iterations' ----------------------------------------- This email was sent using SquirrelMail. "Webmail for nuts!" http://squirrelmail.org/ From klegodi at csir.co.za Fri Jun 26 12:47:29 2009 From: klegodi at csir.co.za (Kgotlelelo Legodi) Date: Fri, 26 Jun 2009 12:47:29 +0200 Subject: [Tutor] Hi, Message-ID: <4A44C361.E1B3.0040.0@csir.co.za> Hi, I am trying to write a program in python that solves a system of nonlinear equations using newton's method. I don't know what I am doing wrong. Please help from scipy import* x = array([0.0,0.0,0.0]) n=len(x) tol= 0.00001 N=30 k=1 while k <= N: def f(x): f= zeros((len(x)),float) f[0][k]= x[0][k]**2 + x[1][k]-37 f[1][k]=x[0][k]- x[1][k]**2- 5 f[2][k]= x[0][k] + x[1][k]+ x[2][k]- 3 return f[k] def J(x): J= zeros((n,n),float) for i in range(n): ei=zeros(n,float) ei[i]=1.0 J[:i]=(f(x[k]+tol*ei)-f(x[k]))/tol return J y[k] = -(J.I)*f[k] x[k+1]=x[k]+y[k] if sqrt(dot(f0,f0)/len(x)) < tol: print x else: k=k+1 print 'Too many iterations' -- This message is subject to the CSIR's copyright terms and conditions, e-mail legal notice, and implemented Open Document Format (ODF) standard. The full disclaimer details can be found at http://www.csir.co.za/disclaimer.html. This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. MailScanner thanks Transtec Computers for their support. -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Fri Jun 26 13:49:43 2009 From: washakie at gmail.com (John [H2O]) Date: Fri, 26 Jun 2009 04:49:43 -0700 (PDT) Subject: [Tutor] creating a dict-like class - asigning variables... this one may take some thought ; ) In-Reply-To: <1c2a2c590905280752y74b8a360x3316ab4aff6f4816@mail.gmail.com> References: <23759398.post@talk.nabble.com> <1c2a2c590905280752y74b8a360x3316ab4aff6f4816@mail.gmail.com> Message-ID: <24218879.post@talk.nabble.com> Thanks everyone, all of this feedback is valuable! -- View this message in context: http://www.nabble.com/creating-a-dict-like-class---asigning-variables...-this-one-may-take-some-thought--%29-tp23759398p24218879.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Fri Jun 26 13:50:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 26 Jun 2009 07:50:14 -0400 Subject: [Tutor] (no subject) In-Reply-To: <455436.36020.qm@web94812.mail.in2.yahoo.com> References: <455436.36020.qm@web94812.mail.in2.yahoo.com> Message-ID: <1c2a2c590906260450p515ef491x86950bba06cc123d@mail.gmail.com> On Fri, Jun 26, 2009 at 6:29 AM, Febin Ameer Ahsen wrote: > how to implement diff command showing? difference in box Here are some examples of using difflib to list differences: http://blog.doughellmann.com/2007/10/pymotw-difflib.html http://personalpages.tds.net/~kent37/blog/arch_m1_2004_06.html#e47 What kind of box do you want to show them in? A window? For that you need to use a GUI framework such as Tkinter. Kent From bgailer at gmail.com Fri Jun 26 13:57:52 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 26 Jun 2009 07:57:52 -0400 Subject: [Tutor] Hi, In-Reply-To: <4A44C361.E1B3.0040.0@csir.co.za> References: <4A44C361.E1B3.0040.0@csir.co.za> Message-ID: <4A44B7C0.8080906@gmail.com> Kgotlelelo Legodi wrote: > Hi, > I am trying to write a program in python that solves a system of > nonlinear equations using newton's method. I don't know what I am > doing wrong. Please help Mostly what you are "doing wrong" is failing to tell us why you think there is a problem! What results are you expecting and what are you getting? > > from scipy import* > > x = array([0.0,0.0,0.0]) > n=len(x) > tol= 0.00001 > N=30 > > k=1 > while k <= N: > def f(x): > f= zeros((len(x)),float) > f[0][k]= x[0][k]**2 + x[1][k]-37 > f[1][k]=x[0][k]- x[1][k]**2- 5 > f[2][k]= x[0][k] + x[1][k]+ x[2][k]- 3 > return f[k] > def J(x): > J= zeros((n,n),float) > for i in range(n): > ei=zeros(n,float) > ei[i]=1.0 > J[:i]=(f(x[k]+tol*ei)-f(x[k]))/tol > return J > > y[k] = -(J.I)*f[k] > x[k+1]=x[k]+y[k] > > if sqrt(dot(f0,f0)/len(x)) < tol: print x > else: > k=k+1 > > print 'Too many iterations' > > -- Bob Gailer Chapel Hill NC 919-636-4239 From a.t.hofkamp at tue.nl Fri Jun 26 14:08:22 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 26 Jun 2009 14:08:22 +0200 Subject: [Tutor] newton's method for system of nonlinear equations In-Reply-To: <2640.146.64.81.22.1246013661.squirrel@galmail.mig.wm.co.za> References: <2640.146.64.81.22.1246013661.squirrel@galmail.mig.wm.co.za> Message-ID: <4A44BA36.2090408@tue.nl> kgotlelelok at galmail.co.za wrote: > Hi, > I am trying to write a program in python that solves a system of nonlinear > equations using newton's method. I don't know what I am doing wrong. > Please help In general, it helps for both you and us if you show what happens when you run the program, and how that is not according to your expectations. In this case, you just say "I don't know what I am doing wrong". We can look at the code and see what will happen when one executes it, but we don't know how that is wrong for you. > from scipy import* Many readers here (including self) don't know much about numerical stuff, so if that's your problem, maybe posting at a scipy related list may be more useful. > x = array([0.0,0.0,0.0]) > n=len(x) > tol= 0.00001 > N=30 > > k=1 > while k <= N: > def f(x): > f= zeros((len(x)),float) > f[0][k]= x[0][k]**2 + x[1][k]-37 > f[1][k]=x[0][k]- x[1][k]**2- 5 > f[2][k]= x[0][k] + x[1][k]+ x[2][k]- 3 > return f[k] > def J(x): > J= zeros((n,n),float) > for i in range(n): > ei=zeros(n,float) > ei[i]=1.0 > J[:i]=(f(x[k]+tol*ei)-f(x[k]))/tol > return J > > y[k] = -(J.I)*f[k] > x[k+1]=x[k]+y[k] You have a while loop, and inside the loop you define a function called 'f'. Can you explain what you think should happen here? > > if sqrt(dot(f0,f0)/len(x)) < tol: print x f0 is never defined above, so you will get an 'undefined identifier f0' error here. What is f0 supposed to be? (if you intended to call 'f' here, type 'f(0)' instead of 'f0') (Calling f probably makes sense only if the 'if' statement is inside the 'while' loop. See also below.) > else: > k=k+1 The 'if' statement is after the 'while' loop. Incrementing k here does not make much sense here. Maybe you meant the 'if' inside the 'while'? If so, indent the statement accordingly (same amount as the "def f(x):" line). Albert From davea at ieee.org Fri Jun 26 17:50:31 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 26 Jun 2009 11:50:31 -0400 Subject: [Tutor] newton's method for system of nonlinear equations In-Reply-To: References: Message-ID: <4A44EE47.7010706@ieee.org> kgotlelelok at galmail.co.za wrote: > > Hi, > I am trying to write a program in python that solves a system of nonlinear > equations using newton's method. I don't know what I am doing wrong. > Please help > > First thing wrong is posting two messages in the mailing list in rapid succession (7 minutes) with same content and different titles. Not the best way to get sympathy. Next: paste your error log, or if there is none, show the results and explain how they differ from what you wanted. Also show versions of both Python and the scipy library you're importing. Third: you have lots of obvious things wrong with the code itself, but it's usually best to start fixing it where the error message points; I'm not familiar with scipi, but I'll try to give you a few pointers anyway. Fourth: you use the "import *" form, which is generally frowned upon for all but trivial scripts. It pollutes the global namespace, and possibly masks built-in functions and variables. Fifth: your names aren't very mnemonic, so somebody not familiar with the code has to spend longer just guessing what things are for. Now for specifics in the code: > from scipy import* > > x = array([0.0,0.0,0.0]) > n=len(x) > tol= 0.00001 > N=30 > > k=1 > while k <= N: > Nowhere in this loop do you modify k or N, so it'll never terminate. > def f(x): > Defining a function inside a loop is seldom useful, and not a technique for beginners. In fact, a beginner should expect all functions to be at module level (left margin), and all methods to be at class level (one indent in). Besides, you never call it or the nested function J. > f= zeros((len(x)),float) > It's bad form to re-use the function name as a local within the function. It works, but probably contributes to your confusion below. > f[0][k]= x[0][k]**2 + x[1][k]-37 > f[1][k]=x[0][k]- x[1][k]**2- 5 > f[2][k]= x[0][k] + x[1][k]+ x[2][k]- 3 > return f[k] > def J(x): > This definition is never reached, so the code is dead. > J= zeros((n,n),float) > for i in range(n): > ei=zeros(n,float) > ei[i]=1.0 > J[:i]=(f(x[k]+tol*ei)-f(x[k]))/tol > return J > > y[k] = -(J.I)*f[k] > Here, you're misusing J and f. If you're trying to call those functions, your syntax is way-off. But if you're trying to use the local variables by those names, realize that the local J is not in scope. > x[k+1]=x[k]+y[k] > You'll never get to these next lines, because the previous while loop never terminates. Perhaps an indentation problem? > if sqrt(dot(f0,f0)/len(x)) < tol: print x > else: > k=k+1 > Not much point in incrementing a loop variable outside the loop. > print 'Too many iterations' > > > There are other things to ask, such as whether you intended to quit after printing x. But the fix for that depends on other things you'll fix first. From jsseabold at gmail.com Fri Jun 26 17:58:06 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Fri, 26 Jun 2009 11:58:06 -0400 Subject: [Tutor] newton's method for system of nonlinear equations In-Reply-To: <2640.146.64.81.22.1246013661.squirrel@galmail.mig.wm.co.za> References: <2640.146.64.81.22.1246013661.squirrel@galmail.mig.wm.co.za> Message-ID: On Fri, Jun 26, 2009 at 6:54 AM, wrote: > Hi, > I am trying to write a program in python that solves a system of nonlinear > equations using newton's method. I don't know what I am doing wrong. > Please help > > from scipy import* > > x = array([0.0,0.0,0.0]) > n=len(x) > tol= 0.00001 > N=30 > > k=1 > while k <= N: > ? ?def f(x): > ? ? ? ?f= zeros((len(x)),float) > ? ? ? ?f[0][k]= x[0][k]**2 + x[1][k]-37 > ? ? ? ?f[1][k]=x[0][k]- x[1][k]**2- 5 > ? ? ? ?f[2][k]= x[0][k] + x[1][k]+ x[2][k]- 3 > ? ? ? ?return f[k] > ? ? ? ?def J(x): > ? ? ? ? ? ?J= zeros((n,n),float) > ? ? ? ? ? ?for i in range(n): > ? ? ? ? ? ? ? ?ei=zeros(n,float) > ? ? ? ? ? ? ? ?ei[i]=1.0 > ? ? ? ? ? ? ? ?J[:i]=(f(x[k]+tol*ei)-f(x[k]))/tol > ? ? ? ? ? ? ? ?return J > > ? ? ? ?y[k] = -(J.I)*f[k] > ? ? ? ?x[k+1]=x[k]+y[k] > > if sqrt(dot(f0,f0)/len(x)) < tol: print x > else: > ? ?k=k+1 > > print 'Too many iterations' > > You might want to have a look at scipy.optimize If you have more (somewhat) SciPy related questions, you might want to ask them on the SciPy mailing list. It's very active. Cheers, Skipper From dineshbvadhia at hotmail.com Fri Jun 26 20:28:03 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 26 Jun 2009 11:28:03 -0700 Subject: [Tutor] array and int Message-ID: Say, you create an array['i'] for signed integers (which take a minimum 2 bytes). A calculation results in an integer that is larger than the range of an 'i'. Normally, Python will convert an 'i' to a 4-byte 'l' integer. But, does the same apply for an array ie. does Python dynamically adjust from array['i'] to array['l'']? Before anyone suggests it, I would be using Numpy for arrays but there isn't a 64-bit version available under Windows that works. Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jun 26 22:20:44 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 26 Jun 2009 16:20:44 -0400 Subject: [Tutor] array and int In-Reply-To: References: Message-ID: <1c2a2c590906261320x612bb80bhf9577460e1284cc6@mail.gmail.com> On Fri, Jun 26, 2009 at 2:28 PM, Dinesh B Vadhia wrote: > Say, you create an array['i'] for signed integers (which take a minimum 2 > bytes).? A calculation results in an integer that is larger than the range > of an 'i'.? Normally, Python will convert an 'i' to a 4-byte 'l' integer. > But, does the same apply for an array ie. does Python dynamically adjust > from array['i'] to array['l'']? No. It's easy enough to try: In [1]: import array In [2]: a = array.array('i') In [3]: a.itemsize Out[3]: 4 In [5]: a.append(1) In [6]: a Out[6]: array('i', [1]) In [7]: x = 2**33 In [8]: x Out[8]: 8589934592L In [9]: a[0] = x --------------------------------------------------------------------------- OverflowError Traceback (most recent call last) C:\Project\Mango\ in () OverflowError: long int too large to convert to int Kent From froslie at gmail.com Fri Jun 26 23:09:00 2009 From: froslie at gmail.com (Pete Froslie) Date: Fri, 26 Jun 2009 17:09:00 -0400 Subject: [Tutor] DOMForm Message-ID: <41fcacc90906261409i55b99e06o36cf5666352835d9@mail.gmail.com> Hi, so I've been using Mechanize as suggested to me through tutor to access web forms and fill them out.. I've found some success though I wish there to be more documentation than docstrings.. as I am new to python and not incredibly experienced with code. I am able to fill forms and submit them in situations such as a 'search-submit' form on a blog. *My problem is evident when I approach a form that appears to be linked to a javascript -- I am unable to submit*(essentially click on the button).. I assume this is because python does not handle javascript. I am now looking at DOMForm as a solution, but am unsure as to weather or not this is correct.. An example of the form I would like to access looks like this: * ********************************************************************************************************* *
*********************************************************************************************************** #the is more like the above I'm leaving out before the standard form entry html such as the following: td align="Left" class="LabelCell">Enter e-mail address of recipient ********************************************************************************************************** The python code I've put together looks like this: *import ClientForm import urllib2 request = urllib2.Request("http://www.qinetiq-nacareers.com/qinetiq/jobboard/SendToFriend.aspx?__JobID=*C2B68228BC44075E") response = urllib2.urlopen(request) forms = ClientForm.ParseResponse(response, backwards_compat=False) response.close() form = forms[0] print form form["Email_To"] = "pfroslie at gmail.com" form["Email_From"] = "pfroslie at gmail.com" form["SenderName"] = "Patrick" form["Comments"] = "this job looks great" request2 = form.click("Send") print form control = form.find_control("Email_To", type="text") print control.name, control.value, control.type print request print request2* i've tried a few other options, but essentially feel my trouble boils down to thos issue with java.. *Thank you so much!-- I appologoze if this post is formatted a little too confusing-- kind of getting use to communicating about pythono.. * * -------------- next part -------------- An HTML attachment was scrubbed... URL: From sato.photo at gmail.com Sat Jun 27 03:56:52 2009 From: sato.photo at gmail.com (Daniel Sato) Date: Fri, 26 Jun 2009 18:56:52 -0700 Subject: [Tutor] Very basic Python question Message-ID: Hi, Let me preface this by saying that I purchased O'Reilly's "Learn Python" yesterday and have no programming experience (I am a photographer by trade) except for a semester of what I think was BASIC on some old apple back in elementary school (circa 1992). I am not sure what details are relevant, so I will try and include as much as possible. I have a MacBook Pro running Mac OSX 10.5.6. I recently dl'ed MacPython 2.5, which installed Python 2.5.4 on my system. When I am in the terminal, I can run a module by typing python fullpath/to/script.py However, when I enter Python from the terminal, by typing python, I can no longer import items in this way unless the .py file is in my user folder /Users/Me. How can I change my settings so that I can import .py files from a separate directory such as /Users/Me/Documents/PyMods? Thank you. -daniel sato -- Daniel Sato http://www.danielsato.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sat Jun 27 07:16:43 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 27 Jun 2009 00:16:43 -0500 Subject: [Tutor] Very basic Python question In-Reply-To: References: Message-ID: <4A45AB3B.6010000@gmail.com> Daniel Sato wrote: > Hi, > > Let me preface this by saying that I purchased O'Reilly's "Learn > Python" yesterday and have no programming experience (I am a > photographer by trade) except for a semester of what I think was BASIC > on some old apple back in elementary school (circa 1992). > > I am not sure what details are relevant, so I will try and include as > much as possible. I have a MacBook Pro running Mac OSX 10.5.6. I > recently dl'ed MacPython 2.5, which installed Python 2.5.4 on my system. > > When I am in the terminal, I can run a module by typing python > fullpath/to/script.py > > However, when I enter Python from the terminal, by typing python, I > can no longer import items in this way unless the .py file is in my > user folder /Users/Me. How can I change my settings so that I can > import .py files from a separate directory such as > /Users/Me/Documents/PyMods? Hi Daniel, You should try uninstalling MacPython. Macintosh computers come with Python preinstalled and you should try to use that version instead. Probably what happened was that, when installing the other version of Python, you messed up some of the references for the paths of libraries and such. If that doesn't work, look for an article on upgrading Python on a mac, it should detail how to fix anything that breaks when you install MacPython. Good luck, and let us know if you have any other problems! From sato.photo at gmail.com Sat Jun 27 07:21:27 2009 From: sato.photo at gmail.com (Daniel Sato) Date: Fri, 26 Jun 2009 22:21:27 -0700 Subject: [Tutor] Very basic Python question In-Reply-To: <4A45AB3B.6010000@gmail.com> References: <4A45AB3B.6010000@gmail.com> Message-ID: Oh, I thought that you could install multiple instances of Python. I recall reading somewhere that they advised installing the latest stable version b/c the one that comes with Apple is often out-dated (as it is whatever version existed when the your particular model came out). On Fri, Jun 26, 2009 at 10:16 PM, Luke Paireepinart wrote: > Daniel Sato wrote: > >> Hi, >> >> Let me preface this by saying that I purchased O'Reilly's "Learn Python" >> yesterday and have no programming experience (I am a photographer by trade) >> except for a semester of what I think was BASIC on some old apple back in >> elementary school (circa 1992). >> >> I am not sure what details are relevant, so I will try and include as much >> as possible. I have a MacBook Pro running Mac OSX 10.5.6. I recently dl'ed >> MacPython 2.5, which installed Python 2.5.4 on my system. >> When I am in the terminal, I can run a module by typing python >> fullpath/to/script.py >> >> However, when I enter Python from the terminal, by typing python, I can no >> longer import items in this way unless the .py file is in my user folder >> /Users/Me. How can I change my settings so that I can import .py files from >> a separate directory such as /Users/Me/Documents/PyMods? >> > > Hi Daniel, > You should try uninstalling MacPython. Macintosh computers come with > Python preinstalled and you should try to use that version instead. > Probably what happened was that, when installing the other version of > Python, you messed up some of the references for the paths of libraries and > such. > > If that doesn't work, look for an article on upgrading Python on a mac, it > should detail how to fix anything that breaks when you install MacPython. > Good luck, and let us know if you have any other problems! > > -- Daniel Sato http://www.danielsato.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sat Jun 27 13:17:52 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 27 Jun 2009 07:17:52 -0400 Subject: [Tutor] Very basic Python question In-Reply-To: References: Message-ID: <4A45FFE0.8060805@ieee.org> Daniel Sato wrote: > > Hi, > > Let me preface this by saying that I purchased O'Reilly's "Learn Python" > yesterday and have no programming experience (I am a photographer by trade) > except for a semester of what I think was BASIC on some old apple back in > elementary school (circa 1992). > > I am not sure what details are relevant, so I will try and include as much > as possible. I have a MacBook Pro running Mac OSX 10.5.6. I recently dl'ed > MacPython 2.5, which installed Python 2.5.4 on my system. > > When I am in the terminal, I can run a module by typing python > fullpath/to/script.py > > However, when I enter Python from the terminal, by typing python, I can no > longer import items in this way unless the .py file is in my user folder > /Users/Me. How can I change my settings so that I can import .py files from > a separate directory such as /Users/Me/Documents/PyMods? > > Thank you. > > -daniel sato > > (Note, I'm using Python2.6 on Windows, so I may not get this quite right. But it'll be close) When Python does an import, it has a search path to use, very similar to the way the shell uses the 'path' variable. This search path may be examined and modified, as sys.path The interpreter knows how to find the modules and packages it was installed with, but not how to find an arbitrary module you just wrote. So you can either put your module in one of the standard places, or add its actual location to the sys.path. Normally while you're experimenting with the interpreter, you want to do the latter. Actually, the interpreter looks one other place for an import, the current working directory. So if you set the cwd to the location of the script.py, it should be able to find it and anything else in the same directory. Naturally, if you have more than one interpreter, you'll want to be able to load the proper one. I keep shell scripts in my path called python26 and python31 for the versions of python I normally use. If I were running a system with a default version, I'd let the script python load that one. So you'd want to add a shell script into your path called python25 (once per installation). Then when you start an interactive session, you use cd /fullpath/to/ python25 >>>>import script >>>>import sys >>>>sys.path ::Advanced techniques, for special circumstances::: Now, there are some differences between python25, python26, and python31. So the following may not be quite right, since I don't use 2.5 any more. But you can add your own directories to the intiial sys.path using the pythonpath variable. And you can modify that variable interactively, or with any python script you *can* load. So if you want to have several directories of python scripts to be available in a single session you can use either of those approaches. From kent37 at tds.net Sat Jun 27 13:35:01 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 27 Jun 2009 07:35:01 -0400 Subject: [Tutor] Very basic Python question In-Reply-To: <4A45AB3B.6010000@gmail.com> References: <4A45AB3B.6010000@gmail.com> Message-ID: <1c2a2c590906270435p566df6e4l6ad07f2ef31fce03@mail.gmail.com> On Sat, Jun 27, 2009 at 1:16 AM, Luke Paireepinart wrote: > You should try uninstalling MacPython. ?Macintosh computers come with Python > preinstalled and you should try to use that version instead. ?Probably what > happened was that, when installing the other version of Python, you messed > up some of the references for the paths of libraries and such. No, that is not necessary. It's fine to install a more modern Python. Daniel just needs to understand and perhaps modify the Python search path, as Dave Angel explained. Kent From paras80 at gmail.com Sat Jun 27 21:40:23 2009 From: paras80 at gmail.com (Paras K.) Date: Sat, 27 Jun 2009 15:40:23 -0400 Subject: [Tutor] Converting a Py2exe Script to a Windows Installer Message-ID: I have been writing many scripts using python and then making them a standalone script using Py2exe. I have the source code for the script. What I am trying to do is, take this script and make it into a windows installer and have a shortcut within the All Programs or on the desktop. Any tutorials or sites out there that will show me how to do this? Let me know. -------------- next part -------------- An HTML attachment was scrubbed... URL: From youthcares.iiba at gmail.com Sat Jun 27 15:42:07 2009 From: youthcares.iiba at gmail.com (julie) Date: Sat, 27 Jun 2009 06:42:07 -0700 Subject: [Tutor] character counter Message-ID: <9f91bfcf0906270642ld9b3ec2k91d26adc3c0ea8de@mail.gmail.com> Hello, I need help with the following problem: *Write a loop that reads each line of a file and counts the number of lines that are read until the total length of the lines is 1,000 characters. Use a break statement to make sure that you don't continue reading the file once the 1,000 characters are read. I figured out how to open a file, count and print the lines, however I cannot figure out or find online ...or anywhere else how to count characters in a file. This is what i have so far: file = open("/Users/meitalamitai/Documents/Computer Science/Python/Homework/Lorem_Ipsum.py") lines = 0 for line in file: lines=lines+1 print '%r has %r lines' % ("Lorem_Ipsum.py", lines) if char >= 1000: break * Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Sun Jun 28 01:09:34 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Sun, 28 Jun 2009 00:09:34 +0100 Subject: [Tutor] character counter In-Reply-To: <9f91bfcf0906270642ld9b3ec2k91d26adc3c0ea8de@mail.gmail.com> References: <9f91bfcf0906270642ld9b3ec2k91d26adc3c0ea8de@mail.gmail.com> Message-ID: 2009/6/27 julie : > Hello, > > I need help with the following problem: > > Write a loop that reads each line of a file and counts the number of lines > that are read until the total length of the lines is 1,000 characters. Use a > break statement to make sure that you don't continue reading the file once > the 1,000 characters are read. > > I figured out how to open a file, count and print the lines, however I > cannot figure out or find online ...or anywhere else how to count characters > in a file. This is what i have so far: > > file = open("/Users/meitalamitai/Documents/Computer > Science/Python/Homework/Lorem_Ipsum.py") > lines = 0 > for line in file: > ??? lines=lines+1 > print '%r has %r lines' % ("Lorem_Ipsum.py", lines) > ?? if char >= 1000: > ??????? break > > Thanks! > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > In python, we don't explictily count, unless we absolutely have to. Instead, in your situation, we measure the length of things. Length is what you need to be searching for. Specifically, finding the length of a string. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From emile at fenx.com Sun Jun 28 01:18:46 2009 From: emile at fenx.com (Emile van Sebille) Date: Sat, 27 Jun 2009 16:18:46 -0700 Subject: [Tutor] character counter In-Reply-To: <9f91bfcf0906270642ld9b3ec2k91d26adc3c0ea8de@mail.gmail.com> References: <9f91bfcf0906270642ld9b3ec2k91d26adc3c0ea8de@mail.gmail.com> Message-ID: On 6/27/2009 6:42 AM julie said... > Hello, > > I need help with the following problem: > > *Write a loop that reads each line of a file and counts the number of > lines that are read until the total length of the lines is 1,000 > characters. Use a break statement to make sure that you don't continue > reading the file once the 1,000 characters are read. > > I figured out how to open a file, count and print the lines, however I > cannot figure out or find online ...or anywhere else how to count > characters in a file. Maybe it helps to know that each line has a length you can determine using: linelen = len(line) Emile > This is what i have so far: > > file = open("/Users/meitalamitai/Documents/Computer > Science/Python/Homework/Lorem_Ipsum.py") > lines = 0 > for line in file: > lines=lines+1 > print '%r has %r lines' % ("Lorem_Ipsum.py", lines) > if char >= 1000: > break * > > Thanks! > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From amit.pureenergy at gmail.com Sun Jun 28 17:00:30 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Sun, 28 Jun 2009 20:30:30 +0530 Subject: [Tutor] intefaces in python Message-ID: Hi , I don't suppose python has a concept of interfaces. But can somebody tell me if their is a way i can implement something like a java interface in python. -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jun 28 19:48:15 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Jun 2009 18:48:15 +0100 Subject: [Tutor] intefaces in python References: Message-ID: "Amit Sethi" wrote > Hi , I don't suppose python has a concept of interfaces. Yes and No, I'll come back to that... > But can somebody tell me if their is a way i can implement > something like a java interface in python. First, can you tell me why you would want to? Java style interfaces tend to make your code much less reusable and much less flexible if you are using a dynamically typed language. There are very few real advantages to them over defining, say, a mixin or using multiple inheritance (which of course Java can't do) The normal way of defining a Java style Python interface class is simply to define a class that has a set of methods thaty either do or return nothing or raise some kind of NotImplementedError exception. But usually providing a mixin is a much more powerful style of programming in Python since you can provide partial implementations of the methods or generic methods that are not dependant on the types of the parameters. Coming back to the original question, Python has a very strong concept of an interface, that is how it checks types, if an interface does not exist it will raise a TypeError. But it does it at runtime and it does it at the method level not the class level. Very different to Microsoft's concept which was designed to meet the needs of COM and was subsequently adopted by Java. There has also been talk of introducing syntax to create interfaces into Python which I personally think is a very, very poor idea! But quite a lot of what I think are poor ideas get intro Python so that doesn't mean much! :-) Alan G. From alan.gauld at btinternet.com Sun Jun 28 19:54:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Jun 2009 18:54:51 +0100 Subject: [Tutor] syntax error References: <254122.50865.qm@web57514.mail.re1.yahoo.com> Message-ID: "Christopher Altieri" wrote > loaded python 3 and 3.1 several times on vista. tried first > command: print "hello world' but keep getting syntax error. > what am I doing wrong? Using Python 3 to learn Python! :-) Seriously, You would be better downgrading to Python 2.6 to learn because v3 has introduced several new concepts (not just print() ) that are not covered in most tutorials. Once you understand Python 2.6 you will be in a better position to understamd v3s new features, and probably by then most tutorials will have caught up. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ And for V3: http://www.alan-g.me.uk/l2p/ From gapetard at stsams.org Sun Jun 28 21:10:47 2009 From: gapetard at stsams.org (Bob Rea) Date: Sun, 28 Jun 2009 15:10:47 -0400 Subject: [Tutor] intefaces in python In-Reply-To: References: Message-ID: <200906281510.48007.gapetard@stsams.org> On Sun June 28 2009 1:48 pm, Alan Gauld wrote: > advantages to them over defining, say, a mixin Noob, here, wanted to know what a mixin is eh, just getting back into learning python googled it, still not sure what it is, but wikipedia says the name come from ice cream mixins at Steve's Ice Cream Parlor Ah yes, i was a frequenter there Will watch out for what it is when I get farther into python may have to name them things like jimmies and heath_bar_crunch -- Bob Rea mailto:gapetard at stsams.org http://www.petard.us http://www.petard.us/blog http://www.petard.us/gallery Where is Bill Stringfellow now that we really need him? From adamc88 at googlemail.com Sun Jun 28 23:42:15 2009 From: adamc88 at googlemail.com (Adam Cunningham) Date: Sun, 28 Jun 2009 22:42:15 +0100 Subject: [Tutor] Tkinter Button Issue Message-ID: Hi, I was hoping someone may be able to help me on an issue I'm having with Tkinter buttons; or more specifically, the background and foreground settings. I've created a program that is supposed to simulate an order system: the first section (frame) is where the user adds items to the order and the second section (frame) is where payment is processed. The second section only activates when the first section has been confirmed by the user; so in the meantime all buttons in the second section are disabled. They are then activated so the user can complete the transaction and the first section is disabled so the order can't be edited during payment. It all seems to be working great except that when a button is 'activated' its appearance loses its foreground and background properties, appearing with the default greyish background and black font. As soon as the mouse hovers over the buttons the colour corrects itself. Does anyone have any idea how I can ensure that the colours appear correctly as soon as the button is activated? Perhaps some way to 'programatically' focus the mouse on the buttons? Sorry if this sounds idiotic, I'm obviously still a newbie. :-) Thanks for your time. Adam -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajarncolin at gmail.com Mon Jun 29 07:26:36 2009 From: ajarncolin at gmail.com (col speed) Date: Mon, 29 Jun 2009 12:26:36 +0700 Subject: [Tutor] freeze Message-ID: <6a1b26420906282226t48d664e3y4dc5162f5e69a822@mail.gmail.com> HI Guys, I have a small programme, called shop.py, that I wish to make into a "frozen binary" ( I think that's right - I'm using Linux Ubuntu 9.04 and I want the programme to work on a windows computer that doesn't have Python installed). I used freeze.py from examples/Tools and everything seemed to be going well (I won't post the output as there is so much), but the last lines are: o M_xml__sax__xmlreader.o M_xmllib.o M_xmlrpclib.o /usr/lib/python2.6/config/libpython2.6.a -L/usr/lib -lz -lpthread -ldl -lutil -lm -o shop /usr/bin/ld: cannot find -lz collect2: ld returned 1 exit status make: *** [shop] Error 1 Any ideas of what is going wrong? I would also like to ask your opinion - the programme is very small (only 1.2kb!). Is there another way ? Am I totally wasting my time? Many thanks Colin From cwitts at compuscan.co.za Mon Jun 29 08:18:10 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 29 Jun 2009 08:18:10 +0200 Subject: [Tutor] character counter In-Reply-To: <9f91bfcf0906270642ld9b3ec2k91d26adc3c0ea8de@mail.gmail.com> References: <9f91bfcf0906270642ld9b3ec2k91d26adc3c0ea8de@mail.gmail.com> Message-ID: <4A485CA2.6020700@compuscan.co.za> julie wrote: > Hello, > > I need help with the following problem: > > *Write a loop that reads each line of a file and counts the number of > lines that are read until the total length of the lines is 1,000 > characters. Use a break statement to make sure that you don't continue > reading the file once the 1,000 characters are read. > > I figured out how to open a file, count and print the lines, however I > cannot figure out or find online ...or anywhere else how to count > characters in a file. This is what i have so far: > > file = open("/Users/meitalamitai/Documents/Computer > Science/Python/Homework/Lorem_Ipsum.py") > lines = 0 > for line in file: > lines=lines+1 > print '%r has %r lines' % ("Lorem_Ipsum.py", lines) > if char >= 1000: > break * > > Thanks! > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Depends what you classify as a character. If it is any character then what Emile said about len(line) will be fine, if it is to exclude new-line characters then you will need to strip them off and then do a length or if it is just printable characters then maybe look at string translation tables and the string.replace methods to cull out what you do not need. -- Kind Regards, Christian Witts From lie.1296 at gmail.com Mon Jun 29 08:23:17 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 29 Jun 2009 16:23:17 +1000 Subject: [Tutor] Tkinter Button Issue In-Reply-To: References: Message-ID: Adam Cunningham wrote: > Hi, I was hoping someone may be able to help me on an issue I'm having > with Tkinter buttons; or more specifically, the background and > foreground settings. > > I've created a program that is supposed to simulate an order system: the > first section (frame) is where the user adds items to the order and the > second section (frame) is where payment is processed. The second section > only activates when the first section has been confirmed by the user; so > in the meantime all buttons in the second section are disabled. They are > then activated so the user can complete the transaction and the first > section is disabled so the order can't be edited during payment. > > It all seems to be working great except that when a button is > 'activated' its appearance loses its foreground and background > properties, appearing with the default greyish background and black > font.. As soon as the mouse hovers over the buttons the colour corrects > itself. A Button (and most other widgets) has three `state`: "normal" (clickable), "active" (mouse hover), and "disabled". "active" in Tk's sense means you hover your mouse on the button, not making the button clickable (which is the "normal" state). These are the properties of a button: | STANDARD OPTIONS | | activebackground, activeforeground, anchor, | background, bitmap, borderwidth, cursor, | disabledforeground, font, foreground | highlightbackground, highlightcolor, | highlightthickness, image, justify, | padx, pady, relief, repeatdelay, | repeatinterval, takefocus, text, | textvariable, underline, wraplength | | WIDGET-SPECIFIC OPTIONS | | command, compound, default, height, | overrelief, state, width You need to change the `background` property to a color of your choosing instead of the `activebackground`. `activebackground` is for background color when the button is hovered. From lie.1296 at gmail.com Mon Jun 29 08:51:49 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 29 Jun 2009 16:51:49 +1000 Subject: [Tutor] intefaces in python In-Reply-To: <200906281510.48007.gapetard@stsams.org> References: <200906281510.48007.gapetard@stsams.org> Message-ID: Bob Rea wrote: > On Sun June 28 2009 1:48 pm, Alan Gauld wrote: >> advantages to them over defining, say, a mixin > > Noob, here, wanted to know what a mixin is > eh, just getting back into learning python > googled it, still not sure what it is, but > wikipedia says the name come from ice cream mixins at > Steve's Ice Cream Parlor > > Ah yes, i was a frequenter there > > Will watch out for what it is when I get farther into python > may have to name them things like jimmies and > heath_bar_crunch > In object-oriented programming languages, a mixin is a class that provides a certain functionality to be inherited by a subclass, while not meant for instantiation (the generating of objects of that class). Inheriting from a mixin is not a form of specialization but is rather a means of collecting functionality. A class may inherit most or all of its functionality from one or more mixins through multiple inheritance. -- http://en.wikipedia.org/wiki/Mixin In regular inheritance, you inherit from another class to inherit its interfaces. In mixin inheritance, you inherit for its implementations. The mixin concept takes it a bit further; the mixin class (parent class) may not be usable by itself (i.e. instantiating a mixin class may not make any sense) and must be inherited . Example: # Flavours class Vanilla(object): pass class Chocolate(object): pass # Additions class Nuts(object): pass class Cookies(object): pass # Items class IceCream(): pass # Usable classes class ChocolateIceCream(Chocolate, IceCream): pass class VanillaAndNutsIceCream(Vanilla, Nuts, IceCream): pass class ChocolateAndCookiesIceCream(Chocolate, Cookies, IceCream): pass Vanilla(), Chocolate(), Nuts(), and Cookies() are not meant to be instantiated directly; they are meant to be inherited. These classes are called mixin classes. In python's standard lib, an example of mixin class is threading.Thread() From milgrom at gmail.com Mon Jun 29 09:03:50 2009 From: milgrom at gmail.com (Alfred Milgrom) Date: Mon, 29 Jun 2009 17:03:50 +1000 Subject: [Tutor] Converting a Py2exe Script to a Windows Installer In-Reply-To: References: Message-ID: <50eadd0a0906290003w51a414bauc3e71854140b332@mail.gmail.com> Quite a while ago I had success in using the Inno Installer. Relatively painless and free. Can't remember all the details but you can start at http://www.jrsoftware.org/isinfo.php All the best, Fred Milgrom On Sun, Jun 28, 2009 at 5:40 AM, Paras K. wrote: > I have been writing many scripts using python and then making them a > standalone script using Py2exe. I have the source code for the script. > > What I am trying to do is, take this script and make it into a windows > installer and have a shortcut within the All Programs or on the desktop. > > Any tutorials or sites out there that will show me how to do this? > > Let me know. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- All the best, Fred -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Mon Jun 29 09:08:36 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 29 Jun 2009 09:08:36 +0200 Subject: [Tutor] freeze In-Reply-To: <6a1b26420906282226t48d664e3y4dc5162f5e69a822@mail.gmail.com> References: <6a1b26420906282226t48d664e3y4dc5162f5e69a822@mail.gmail.com> Message-ID: <4A486874.9070101@tue.nl> col speed wrote: > HI Guys, > I have a small programme, called shop.py, that I wish to make into a > "frozen binary" ( I think that's right - I'm using Linux Ubuntu 9.04 > and I want the programme to work on a windows computer that doesn't > have Python installed). > I used freeze.py from examples/Tools and everything seemed to be going > well (I won't post the output as there is so much), but the last lines > are: > > o M_xml__sax__xmlreader.o M_xmllib.o M_xmlrpclib.o > /usr/lib/python2.6/config/libpython2.6.a -L/usr/lib -lz -lpthread > -ldl -lutil -lm -o shop > /usr/bin/ld: cannot find -lz > collect2: ld returned 1 exit status > make: *** [shop] Error 1 > > Any ideas of what is going wrong? The linker cannot link against the 'z' library :) At my Linux system, that library is at "/usr/lib/libz.a", which comes from the 'zlib-devel' RPM. No doubt Ubuntu has a similar name for the z library. I don't know what you are doing exactly, but it seems to me that a program linked against Linux libraries is not going to work at a non-linux system (much like you cannot run Windows binaries natively at a Linux system). You may need to do the freezing at a Windows system or use a cross-compiler. > I would also like to ask your opinion - the programme is very small > (only 1.2kb!). Is there another way ? Am I totally wasting my time? Install Python at the Windoes machine, and run shop.py in natively would seem like an alternative. Even with freeze, you are basically installing Python, except it has a different name. Albert From andreengels at gmail.com Mon Jun 29 09:28:16 2009 From: andreengels at gmail.com (Andre Engels) Date: Mon, 29 Jun 2009 09:28:16 +0200 Subject: [Tutor] intefaces in python In-Reply-To: References: Message-ID: <6faf39c90906290028j4964347ei453cf32bf5cae32b@mail.gmail.com> On Sun, Jun 28, 2009 at 5:00 PM, Amit Sethi wrote: > Hi , I don't suppose python has a concept of interfaces. But can somebody > tell me if their is a way i can? implement something like a java interface > in python. Sure. Interfaces are just Java's compensation for not having multiple inheritance. Python does have multiple inheritance, so that's what one would use. Although one could also use duck typing, and then use 'nothing' as an implementation... More specific: ======================== Java Interface: public interface MyInterface { string doSomething(string line); string doSomethingElse(string line); } Java Implementation: public class MyImplementation { string doSomething(string line) { return "I did something with" + line; } string doSomethingElse(string line) { return "I did something else." } } ============================== Python Interface: class MyInterface(object): doSomething(line): raise NotImplementedError doSomethingElse(line): raise NotImplementedError Python Implementation: class MyImplementation(MyInterface): doSomething(line): return "I did something with "+line doSomethingElse(line): return "I did something else." ============================== Python interface using duck typing: # Hey guys, when you call something a 'MyInterface', it needs methods doSomething and doSomethingElse Python Implementation using duck typing: class MyImplementation(object): # These things implement MyInterface doSomething(line): return "I did something with "+line doSomethingElse(line): return "I did something else." -- Andr? Engels, andreengels at gmail.com From amit.pureenergy at gmail.com Mon Jun 29 10:34:07 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Mon, 29 Jun 2009 14:04:07 +0530 Subject: [Tutor] intefaces in python In-Reply-To: <6faf39c90906290028j4964347ei453cf32bf5cae32b@mail.gmail.com> References: <6faf39c90906290028j4964347ei453cf32bf5cae32b@mail.gmail.com> Message-ID: class MyInterface(object): doSomething(line): raise NotImplementedError doSomethingElse(line): raise NotImplementedError I think that is exactly the kind of structure i was looking for ... On Mon, Jun 29, 2009 at 12:58 PM, Andre Engels wrote: > On Sun, Jun 28, 2009 at 5:00 PM, Amit Sethi > wrote: > > Hi , I don't suppose python has a concept of interfaces. But can somebody > > tell me if their is a way i can implement something like a java > interface > > in python. > > Sure. Interfaces are just Java's compensation for not having multiple > inheritance. Python does have multiple inheritance, so that's what one > would use. Although one could also use duck typing, and then use > 'nothing' as an implementation... > > More specific: > > ======================== > Java Interface: > public interface MyInterface { > string doSomething(string line); > string doSomethingElse(string line); > } > > Java Implementation: > public class MyImplementation { > string doSomething(string line) { > return "I did something with" + line; > } > string doSomethingElse(string line) { > return "I did something else." > } > } > > ============================== > Python Interface: > > class MyInterface(object): > doSomething(line): > raise NotImplementedError > doSomethingElse(line): > raise NotImplementedError > > Python Implementation: > class MyImplementation(MyInterface): > doSomething(line): > return "I did something with "+line > doSomethingElse(line): > return "I did something else." > > ============================== > Python interface using duck typing: > > # Hey guys, when you call something a 'MyInterface', it needs methods > doSomething and doSomethingElse > > Python Implementation using duck typing: > > class MyImplementation(object): > # These things implement MyInterface > doSomething(line): > return "I did something with "+line > doSomethingElse(line): > return "I did something else." > > > -- > Andr? Engels, andreengels at gmail.com > -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 29 11:19:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Jun 2009 10:19:41 +0100 Subject: [Tutor] intefaces in python References: <6faf39c90906290028j4964347ei453cf32bf5cae32b@mail.gmail.com> Message-ID: "Amit Sethi" wrote > class MyInterface(object): > doSomething(line): > raise NotImplementedError > doSomethingElse(line): > raise NotImplementedError > > I think that is exactly the kind of structure i was looking for ... As a matter of interest, why? What do you anticipate using this for? I have found a few cases where abstract interfaces are useful but they are very few and far between. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From amit.pureenergy at gmail.com Mon Jun 29 11:39:18 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Mon, 29 Jun 2009 15:09:18 +0530 Subject: [Tutor] intefaces in python In-Reply-To: References: <6faf39c90906290028j4964347ei453cf32bf5cae32b@mail.gmail.com> Message-ID: Well I want to implement plug-in like mechanism for an application . I want to define some minimum functions that any body writing a plugin has to implement. For that i thought an interface would be best because in a scenario where the function is not implemented some kind of error would occur. I would love to hear if you think their is a better way to achieve this On Mon, Jun 29, 2009 at 2:49 PM, Alan Gauld wrote: > "Amit Sethi" wrote > >> class MyInterface(object): >> doSomething(line): >> raise NotImplementedError >> doSomethingElse(line): >> raise NotImplementedError >> >> I think that is exactly the kind of structure i was looking for ... >> > > As a matter of interest, why? What do you anticipate using this for? > I have found a few cases where abstract interfaces are useful but they are > very few and far between. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Mon Jun 29 11:44:09 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 29 Jun 2009 11:44:09 +0200 Subject: [Tutor] character counter In-Reply-To: <9f91bfcf0906270642ld9b3ec2k91d26adc3c0ea8de@mail.gmail.com> References: <9f91bfcf0906270642ld9b3ec2k91d26adc3c0ea8de@mail.gmail.com> Message-ID: 2009/6/27 julie : > file = open("/Users/meitalamitai/Documents/Computer > Science/Python/Homework/Lorem_Ipsum.py") > lines = 0 > for line in file: > ??? lines=lines+1 > print '%r has %r lines' % ("Lorem_Ipsum.py", lines) > ?? if char >= 1000: > ??????? break You can do something like below (untested). The below also includes white space and punctiation. If you want to exclude those use strip(). ----- filename = "/Users/meitalamitai/Documents/Computer Science/Python/Homework/Lorem_Ipsum.py" file = open(filename, "r") # Explicitely open the file readonly lines = file.split() # Split the file into a list so we can use len() on it and iterate over the lines linecount = len(lines) # Get the number of lines totalcharcount = 0 # Set initial total count to zero count = 1 # Starting count at one print "The file has %s lines" % linecount for line in lines: charcount = len(line) # Get character count print "Line %s has %s character (including punctuation and white space)." % (count, charcount) totalcharcount += charcount #Add the charcount to the total charcount print "The total file character count is %s" % totallinecount ----- Hope this helps. Greets Sander From alan.gauld at btinternet.com Mon Jun 29 11:46:05 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Jun 2009 10:46:05 +0100 Subject: [Tutor] intefaces in python References: <6faf39c90906290028j4964347ei453cf32bf5cae32b@mail.gmail.com> Message-ID: "Amit Sethi" wrote > Well I want to implement plug-in like mechanism for an application . I > want > to define some minimum functions that any body writing a plugin has to > implement. For that i thought an interface would be best because in a > scenario where the function is not implemented some kind of error would > occur. I would love to hear if you think their is a better way to achieve > this Well you could define a real default plugin class that actually does something. Then anyone who wants to create a plugin can inherit from that and either extend the default functions or override them with something different. That will reduce the code that plug-in writers need to create and prevent any error messages appearing for the user. It also means the default plug in acts as sample code for the interface too. HTH, Alan G. From lev at ithstech.com Mon Jun 29 04:37:52 2009 From: lev at ithstech.com (lev at ithstech.com) Date: Sun, 28 Jun 2009 22:37:52 -0400 Subject: [Tutor] "Print" on 3.1 for Mac? Message-ID: Have I installed something incorrectly in Python 3.1 for Mac if I get a syntax error on print "hello world" ? My Python 2.3.5 executes this just fine. What have I missed? Thanks much for anything, Lev From cwitts at compuscan.co.za Mon Jun 29 12:59:30 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 29 Jun 2009 12:59:30 +0200 Subject: [Tutor] "Print" on 3.1 for Mac? In-Reply-To: References: Message-ID: <4A489E92.2040400@compuscan.co.za> lev at ithstech.com wrote: > Have I installed something incorrectly in Python 3.1 for Mac if I get a > syntax error on > > print "hello world" > > ? > > My Python 2.3.5 executes this just fine. What have I missed? > > Thanks much for anything, Lev > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Please take a read through http://docs.python.org/3.0/whatsnew/3.0.html for a list of changes from the 2.x series to 3.x. It includes the fact that the print command is now a function and needs to be called accordingly, ie. print("Hello world!") -- Kind Regards, Christian Witts From davea at ieee.org Mon Jun 29 13:31:01 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 29 Jun 2009 07:31:01 -0400 Subject: [Tutor] intefaces in python In-Reply-To: References: Message-ID: <4A48A5F5.2080603@ieee.org> Amit Sethi wrote: > Well I want to implement plug-in like mechanism for an application . I want > to define some minimum functions that any body writing a plugin has to > implement. For that i thought an interface would be best because in a > scenario where the function is not implemented some kind of error would > occur. I would love to hear if you think their is a better way to achieve > this In Java, deriving a class from such an interface, but neglecting to implement those methods will cause a compile error (if I recall correctly, it's been several years). In Python, the error will happen at run time. But an existing runtime error will occur even without such an interface, so it wouldn't seem you gain much. In Python, the interface does two things: 1) it's a comment, a common place to look for certain behavior. 2) it's potentially a source for an IDE to provide tool-tips or code completion 3) it can generate a different error, which is perhaps more useful to the developer unsure of how the method is spelled or used. This way he/she knows whether to fix the caller or the implementation. #3 seems valid to me. However, for the particular use-case, you might want to stretch a bit further. Since you've got one "user" (your code), and many "providers" (the plug-in writers) perhaps you could arrange that when the plugin is first encountered, you validate that it has all the required methods and data members. Not by calling them, but by scanning the object for their existence. From cwitts at compuscan.co.za Mon Jun 29 13:55:54 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 29 Jun 2009 13:55:54 +0200 Subject: [Tutor] [Fwd: Re: "Print" on 3.1 for Mac?] Message-ID: <4A48ABCA.2050803@compuscan.co.za> Forwarding to the list. -------- Original Message -------- Subject: Re: [Tutor] "Print" on 3.1 for Mac? Date: Mon, 29 Jun 2009 12:38:43 +0100 From: andr? palma To: Christian Witts References: <4A489E92.2040400 at compuscan.co.za> try to find out if is there any space before "print". Sometimes some text editors put an empty space in the beginning of the lines and sometimes that causes some erros. On Mon, 2009-06-29 at 12:59 +0200, Christian Witts wrote: > lev at ithstech.com wrote: > > Have I installed something incorrectly in Python 3.1 for Mac if I get a > > syntax error on > > > > print "hello world" > > > > ? > > > > My Python 2.3.5 executes this just fine. What have I missed? > > > > Thanks much for anything, Lev > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > Please take a read through http://docs.python.org/3.0/whatsnew/3.0.html > for a list of changes from the 2.x series to 3.x. It includes the fact > that the print command is now a function and needs to be called > accordingly, ie. print("Hello world!") > -- Kind Regards, Christian Witts From amit.pureenergy at gmail.com Mon Jun 29 14:04:21 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Mon, 29 Jun 2009 17:34:21 +0530 Subject: [Tutor] intefaces in python In-Reply-To: <4A48A5F5.2080603@ieee.org> References: <4A48A5F5.2080603@ieee.org> Message-ID: I think ideally i want a compile Error just like java .. but from the discussion here ... i wrote this little example: class a(object): ??? def __init__(self): ??? ??? self.query() ??? ??? try: ??? ??? ??? if self.query_not_implemented==True: ??? ??? ??? ??? raise NotImplementedError ??? ??? except AttributeError: ??? ??? ??? pass ??? def query(self): ??? ????? ??? self.query_not_implemented=True At least by this when ever the derived class object is created without implementing a particular function ,it raises a NotImplementedError which i can later use. @Dave Angel You have said "you could arrange that when the plugin is first encountered, you validate that it has all the required methods and data members. Not by calling them, but by scanning the object for their existence." that would be ideal ... can you enlighten me on this how may one do that. On Mon, Jun 29, 2009 at 5:01 PM, Dave Angel wrote: > > Amit Sethi ?wrote: > >> Well I want to implement plug-in like mechanism for an application . I want >> to define some minimum functions that any body writing a plugin has to >> implement. For that i thought an interface would be best because in a >> scenario where the function is not implemented some kind of error would >> occur. I would love to hear if you think their is a better way to achieve >> this > > In Java, deriving a class from such an interface, but neglecting to implement those methods will cause a compile error (if I recall correctly, it's been several years). ?In Python, the error will happen at run time. ?But an existing runtime error will occur even without such an interface, so it wouldn't seem you gain much. ?In Python, the interface does two things: > > 1) it's a comment, a common place to look for certain behavior. > 2) it's potentially a source for an IDE to provide tool-tips or code completion > 3) it can generate a different error, which is perhaps more useful to the developer unsure of how the method is spelled or used. ?This way he/she knows whether to fix the caller or the implementation. > > #3 seems valid to me. > > > > However, for the particular use-case, you might want to stretch a bit further. ?Since you've got one "user" (your code), and many "providers" (the plug-in writers) ?perhaps you could arrange that when the plugin is first encountered, you validate that it has all the required methods and data members. ?Not by calling them, but by scanning the object for their existence. > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- A-M-I-T S|S From amit.pureenergy at gmail.com Mon Jun 29 14:19:54 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Mon, 29 Jun 2009 17:49:54 +0530 Subject: [Tutor] intefaces in python In-Reply-To: References: <4A48A5F5.2080603@ieee.org> Message-ID: wait even in the above example i would have to run all the functions in __init__ that is plain stupid ... i was just brain storming.... On Mon, Jun 29, 2009 at 5:34 PM, Amit Sethi wrote: > I think ideally i want a compile Error just like java .. but from the > discussion here ... i wrote this little example: > > class a(object): > ??? def __init__(self): > ??? ??? self.query() > ??? ??? try: > ??? ??? ??? if self.query_not_implemented==True: > ??? ??? ??? ??? raise NotImplementedError > ??? ??? except AttributeError: > ??? ??? ??? pass > ??? def query(self): > ??? ????? ??? self.query_not_implemented=True > > At least by this when ever the derived class object is created without > implementing a particular function ,it raises a NotImplementedError > which i can later use. > > > @Dave Angel > > You have said > "you could arrange that when the plugin is first encountered, you > validate that it has all the required methods and data members. ?Not > by calling them, but by scanning the object for their existence." > > that would be ideal ... can you enlighten me on this how may one do that. > > > On Mon, Jun 29, 2009 at 5:01 PM, Dave Angel wrote: >> >> Amit Sethi ?wrote: >> >>> Well I want to implement plug-in like mechanism for an application . I want >>> to define some minimum functions that any body writing a plugin has to >>> implement. For that i thought an interface would be best because in a >>> scenario where the function is not implemented some kind of error would >>> occur. I would love to hear if you think their is a better way to achieve >>> this >> >> In Java, deriving a class from such an interface, but neglecting to implement those methods will cause a compile error (if I recall correctly, it's been several years). ?In Python, the error will happen at run time. ?But an existing runtime error will occur even without such an interface, so it wouldn't seem you gain much. ?In Python, the interface does two things: >> >> 1) it's a comment, a common place to look for certain behavior. >> 2) it's potentially a source for an IDE to provide tool-tips or code completion >> 3) it can generate a different error, which is perhaps more useful to the developer unsure of how the method is spelled or used. ?This way he/she knows whether to fix the caller or the implementation. >> >> #3 seems valid to me. >> >> >> >> However, for the particular use-case, you might want to stretch a bit further. ?Since you've got one "user" (your code), and many "providers" (the plug-in writers) ?perhaps you could arrange that when the plugin is first encountered, you validate that it has all the required methods and data members. ?Not by calling them, but by scanning the object for their existence. >> >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > > > -- > A-M-I-T S|S > -- A-M-I-T S|S From rabidpoobear at gmail.com Mon Jun 29 14:28:26 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 29 Jun 2009 07:28:26 -0500 Subject: [Tutor] intefaces in python In-Reply-To: References: <4A48A5F5.2080603@ieee.org> Message-ID: <4A48B36A.70202@gmail.com> Amit Sethi wrote: > I think ideally i want a compile Error just like java .. Why? For developers, so they'll know if their plugin meets the interface requirements? Have you considered just making a unit test that will call all interface functions with appropriate parameters? Then they can just run the test on their code and if it passes they will know they implemented the minimum required functions (whether they do what they're supposed to do is a different story...) It would provide the same level of interface security as Java would, except it would allow them to decide how much of the contract they need to enforce for their specific application. That's one of the things I like about python... for example, if I want to override stdout so all my print statements go to a file, I just have to create a new class that has a write() method that writes anything it's passed to a file... I don't have to implement all of the other functionality that whatever object resides there before has. So in that case, if I ran your unit test on my replacement stdout, it may say "Hey, you failed the writeline() test, your object doesn't have this!" but since I know I'm not going to use writeline, I can just ignore the warning. Or if I meant for it to have writeline, I can say "oh snap I need to go implement writeline!" But as I said, that wouldn't enforce the interface, just inform them of it if they desired that, which I would personally prefer but you may not. That's really the idea behind duck typing. Assume that they wrote sufficient code to handle whatever you use it for and if they didn't it'll blow up in their face. > @Dave Angel > > You have said > "you could arrange that when the plugin is first encountered, you > validate that it has all the required methods and data members. Not > by calling them, but by scanning the object for their existence." > > that would be ideal ... can you enlighten me on this how may one do that. > > Not sure if it's what he meant, but you can just do a dir(object) and it will return a list with all method / member names. then you could just confirm that the names are there. From amit.pureenergy at gmail.com Mon Jun 29 14:41:06 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Mon, 29 Jun 2009 18:11:06 +0530 Subject: [Tutor] intefaces in python In-Reply-To: <4A48B36A.70202@gmail.com> References: <4A48A5F5.2080603@ieee.org> <4A48B36A.70202@gmail.com> Message-ID: well dir(object) , how would that help . All the functions in base class would automatically be inherited by the objects of plug-in class ... so they would come in the list even if it was not implemented... On Mon, Jun 29, 2009 at 5:58 PM, Luke Paireepinart wrote: > Amit Sethi wrote: >> >> I think ideally i want a compile Error just like java .. > > Why? ?For developers, so they'll know if their plugin meets the interface > requirements? > Have you considered just making a unit test that will call all interface > functions with appropriate parameters? ?Then they can just run the test on > their code and if it passes they will know they implemented the minimum > required functions (whether they do what they're supposed to do is a > different story...) ?It would provide the same level of interface security > as Java would, except it would allow them to decide how much of the contract > they need to enforce for their specific application. That's one of the > things I like about python... for example, if I want to override stdout so > all my print statements go to a file, I just have to create a new class that > has a write() method that writes anything it's passed to a file... I don't > have to implement all of the other functionality that whatever object > resides there before has. ?So in that case, if I ran your unit test on my > replacement stdout, it may say "Hey, you failed the writeline() test, your > object doesn't have this!" but since I know I'm not going to use writeline, > I can just ignore the warning. ?Or if I meant for it to have writeline, I > can say "oh snap I need to go implement writeline!" ?But as I said, that > wouldn't enforce the interface, just inform them of it if they desired that, > which I would personally prefer but you may not. > That's really the idea behind duck typing. ?Assume that they wrote > sufficient code to handle whatever you use it for and if they didn't it'll > blow up in their face. >> >> @Dave Angel >> >> You have said >> "you could arrange that when the plugin is first encountered, you >> validate that it has all the required methods and data members. ?Not >> by calling them, but by scanning the object for their existence." >> >> that would be ideal ... can you enlighten me on this how may one do that. >> >> > > Not sure if it's what he meant, but you can just do a dir(object) and it > will return a list with all method / member names. ?then you could just > confirm that the names are there. > -- A-M-I-T S|S From robert.lummis at gmail.com Mon Jun 29 17:03:24 2009 From: robert.lummis at gmail.com (Robert Lummis) Date: Mon, 29 Jun 2009 11:03:24 -0400 Subject: [Tutor] does python have something like "#include" in C? Message-ID: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> ... or any pre-processing at all? I'm looking for a way to get boiler plate code into the main program file. Of course I could copy and paste it with an editor but I was hoping for something more pythonic. I know about import but that's not the same. -- Robert Lummis From davea at ieee.org Mon Jun 29 17:12:52 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 29 Jun 2009 11:12:52 -0400 Subject: [Tutor] Tutor Digest, Vol 64, Issue 128 In-Reply-To: References: Message-ID: <4A48D9F4.80001@ieee.org> Amit Sethi wrote: > > . On Mon, Jun 29, 2009 at 5:01 PM, Dave Angel wrote: >> > >> > Amit Sethi ?wrote: >> > >> >>> >> Well I want to implement plug-in like mechanism for an application . I want >>> >> to define some minimum functions that any body writing a plugin has to >>> >> implement. For that i thought an interface would be best because in a >>> >> scenario where the function is not implemented some kind of error would >>> >> occur. I would love to hear if you think their is a better way to achieve >>> >> this >>> >> > >> > In Java, deriving a class from such an interface, but neglecting to implement those methods will cause a compile error (if I recall correctly, it's been several years). ?In Python, the error will happen at run time. ?But an existing runtime error will occur even without such an interface, so it wouldn't seem you gain much. ?In Python, the interface does two things: >> > >> > 1) it's a comment, a common place to look for certain behavior. >> > 2) it's potentially a source for an IDE to provide tool-tips or code completion >> > 3) it can generate a different error, which is perhaps more useful to the developer unsure of how the method is spelled or used. ?This way he/she knows whether to fix the caller or the implementation. >> > >> > #3 seems valid to me. >> > >> > >> > >> > However, for the particular use-case, you might want to stretch a bit further. ?Since you've got one "user" (your code), and many "providers" (the plug-in writers) ?perhaps you could arrange that when the plugin is first encountered, you validate that it has all the required methods and data members. ?Not by calling them, but by scanning the object for their existence. >> > > It'd sure be easier if you had a sample of what you're already expecting to do. Then I could use similar names, and refer to things much more easily. It also might matter which version/implementation of Python you're using. I'm using CPython 2.6 on XP. I'll guess that you're using __import__ to import a module based on its name or location. Further, I'll guess that the class name the user is supposed to implement is called Doit, and that if you had used interfaces, they would derive from your interface. So you have code something like: #interfacemodule.py class MyInterface(object): def __init__(self, modulename): for method in ["doSomething", "doSomethingElse"]: m = getattr(self, method, None) if not m: print "Missing attribute %s in module %s, class Doit" % (method, modulename) raise NotImplementedError else: print "Found :", method, m and they have code like: import interfacemodule class Doit(MyInterface): def doSomething(self, line): print "line=", line def doSomethingElse42(self, line): #method name deliberately spelled wrong, to trigger the error print "line=", line After doing the __import__, you instantiate the new class. Something like (untested): x = __import__(filename) newobject = x.Doit(filename) Instantiating that object will test the attributes, making sure everything in your list exists. Once you're sure they do, add the newobject to your list of plugins. There's lots of other choices, but I suspect most will be trickier than this. You may need them, depending on how much you trust your plugin writers. For example, this doesn't help if they neglect to derive from MyInterface. That's no big deal, since you could use a regular function instead of __init__ method, and run it on the object. From srilyk at gmail.com Mon Jun 29 17:21:19 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 29 Jun 2009 10:21:19 -0500 Subject: [Tutor] does python have something like "#include" in C? In-Reply-To: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> References: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> Message-ID: <333efb450906290821v788b34blf3ece023a7fd6d5f@mail.gmail.com> On Mon, Jun 29, 2009 at 10:03 AM, Robert Lummis wrote: > ... or any pre-processing at all? > > I'm looking for a way to get boiler plate code into the main program > file. Of course I could copy and paste it with an editor but I was > hoping for something more pythonic. I know about import but that's not > the same. > actually import is precisely the same. wayne at x61:test$ vi import1.py wayne at x61:test$ vi import2.py wayne at x61:test$ python import1.py Imported The contents of import1? import import2 The contents of import2? print "Imported" You can define functions, classes, etc. you call them as whatever.function(), unless you say from module import * - then it willl import everything into the namespace of your original file. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Mon Jun 29 17:22:45 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 29 Jun 2009 17:22:45 +0200 Subject: [Tutor] does python have something like "#include" in C? In-Reply-To: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> References: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> Message-ID: <4A48DC45.90900@tue.nl> Robert Lummis wrote: > ... or any pre-processing at all? > > I'm looking for a way to get boiler plate code into the main program > file. Of course I could copy and paste it with an editor but I was > hoping for something more pythonic. I know about import but that's not > the same. Python is very good at eliminating boilerplating, so import should be enough normally. Could you give an example of what you want to include that cannot be done with import? Albert From emile at fenx.com Mon Jun 29 17:27:45 2009 From: emile at fenx.com (Emile van Sebille) Date: Mon, 29 Jun 2009 08:27:45 -0700 Subject: [Tutor] does python have something like "#include" in C? In-Reply-To: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> References: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> Message-ID: On 6/29/2009 8:03 AM Robert Lummis said... > ... or any pre-processing at all? > > I'm looking for a way to get boiler plate code into the main program > file. Of course I could copy and paste it with an editor but I was > hoping for something more pythonic. I know about import but that's not > the same. import is the pythonic way. Most boilerplate code I've come across provides basic functionality which is then accessed and used locally to complete the task at hand. In Python you'd write library code to provide that functionality and import and invoke those functions. Emile From alan.gauld at btinternet.com Mon Jun 29 18:21:26 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Jun 2009 17:21:26 +0100 Subject: [Tutor] intefaces in python References: <4A48A5F5.2080603@ieee.org> Message-ID: "Amit Sethi" wrote > I think ideally i want a compile Error just like java .. I think you are trying to make Python act like Java which is always a really bad mistake when using a programming language. As Bjarne Stroustrup used to say (repeatedly) "C++ is not Smalltalk". And Python is not Java. If you stop trying to design like Java and start using the extra power of Python you will find your solutions are both more flexible and more simple. Python does not compile so trying to build in "compile time" checking makes no sense. You could do some checks immediately after class definition or more likely class assignment but how would it really benefit you? Get used to how interpreted dynamic languages work and use their features to your benefit instead of trying to force them to act like statically typed compiled languages. It will give you a great sense of freedom! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jun 29 18:25:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Jun 2009 17:25:04 +0100 Subject: [Tutor] "Print" on 3.1 for Mac? References: Message-ID: wrote > Have I installed something incorrectly in Python 3.1 for Mac if I get a > syntax error on > > print "hello world" > > My Python 2.3.5 executes this just fine. What have I missed? > The "Whats New" document on V3 V3 is radically different to previous versiions and you need to read the Whats New document carefully and change all your code to match. Only change to V3 if you have a really good reason and know what that is, otherwise you are probably better sticking with 2.X for now. Moving to 2.6 is a good migratiion step since there are tools to convert most of your code from 2.6 to 3. But if you are moving from 2.3 to 3 that is a big jump and you should definitely go to 2.6 as an interim step. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jun 29 18:39:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Jun 2009 17:39:16 +0100 Subject: [Tutor] does python have something like "#include" in C? References: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> Message-ID: "Robert Lummis" wrote > I'm looking for a way to get boiler plate code into the main program > file. Of course I could copy and paste it with an editor but I was > hoping for something more pythonic. I know about import but that's not > the same. Others have already pointed out import. Its also worth pointing out that #include is a pretty horrible hack in C that most modern commentators agree would be better removed. Bjarne Stroustrup tried very hard to remove it completely from C++ (apart from including class headers obviously which is akin to Pythons import). But #define and #ifdef etc are all better done in other ways. Pythons import mechanism with namespaces is a far more elegant solution all round. Alan G. From robert.lummis at gmail.com Mon Jun 29 19:23:41 2009 From: robert.lummis at gmail.com (Robert Lummis) Date: Mon, 29 Jun 2009 13:23:41 -0400 Subject: [Tutor] does python have something like "#include" in C? In-Reply-To: <4A48DC45.90900@tue.nl> References: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> <4A48DC45.90900@tue.nl> Message-ID: <71d330f00906291023v5c77a02exd945230bf03d3b9f@mail.gmail.com> Here's an example that seems not possible in python. I'm probably missing something so please enlighten me. I only tried doing this as an exercise to show myself how name references work. I'm not saying it's needed or that it's good practice. I can write the following as a single file and it works as expected: ===snip=== #!/usr/bin/python def show(*args): print for arg in args: print arg + ':', exec('print ' + arg) a=15 b='hello' x=['bob',3] show('a') show('a','b') show('a','b','x') ===snip=== The calls to 'show' output lines like "a: 15" which could be useful for debugging or some such purpose. However, it seems that I can't put the function definition in a file and import it because I can't find a way to refer to an object in the main program file from within a module file. I understand that it's a good thing to contol which namespaces are referenced by which code but isn't there sometimes a need for code in a module to access the main program file's namespace? My example may be a little contrived but isn't this ability legitimately needed at times? On Mon, Jun 29, 2009 at 11:22 AM, A.T.Hofkamp wrote: > Robert Lummis wrote: >> >> ... or any pre-processing at all? >> >> I'm looking for a way to get boiler plate code into the main program >> file. Of course I could copy and paste it with an editor but I was >> hoping for something more pythonic. I know about import but that's not >> the same. > > Python is very good at eliminating boilerplating, so import should be enough > normally. > > Could you give an example of what you want to include that cannot be done > with import? > > Albert > > -- Robert Lummis From wescpy at gmail.com Mon Jun 29 19:46:13 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 29 Jun 2009 10:46:13 -0700 Subject: [Tutor] does python have something like "#include" in C? In-Reply-To: <71d330f00906291023v5c77a02exd945230bf03d3b9f@mail.gmail.com> References: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> <4A48DC45.90900@tue.nl> <71d330f00906291023v5c77a02exd945230bf03d3b9f@mail.gmail.com> Message-ID: <78b3a9580906291046n2577c9ddl49826ba4c19b9f5f@mail.gmail.com> > However, it seems that I can't put the function definition in a file > and import it because I can't find a way to refer to an object in the > main program file from within a module file. I understand that it's a > good thing to contol which namespaces are referenced by which code but > isn't there sometimes a need for code in a module to access the main > program file's namespace? My example may be a little contrived but > isn't this ability legitimately needed at times? robert, you are wrong and right. :-) take your function definition and store in a file called, say showmodule.py. then put the remaining code inside something like foo.py. at the top of foo.py, you'll need: from showmodule import show then everything else will work. there is another syntax that is less recommended, and that is, "from showmodule import *" -- with the danger being exactly what you said above... you are "polluting" your (global) namespace by bringing in *everything* from the other module without much knowledge (necessarily) of what those names are, which may potentially conflict with variables with the same names (if they exist) in your local module. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From srilyk at gmail.com Mon Jun 29 19:47:58 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 29 Jun 2009 12:47:58 -0500 Subject: [Tutor] does python have something like "#include" in C? In-Reply-To: <71d330f00906291023v5c77a02exd945230bf03d3b9f@mail.gmail.com> References: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> <4A48DC45.90900@tue.nl> <71d330f00906291023v5c77a02exd945230bf03d3b9f@mail.gmail.com> Message-ID: <333efb450906291047s54a43b67sab2c9f748ab6a8be@mail.gmail.com> On Mon, Jun 29, 2009 at 12:23 PM, Robert Lummis wrote: > Here's an example that seems not possible in python. I'm probably > missing something so please enlighten me. I only tried doing this as > an exercise to show myself how name references work. I'm not saying > it's needed or that it's good practice. > > I can write the following as a single file and it works as expected: > > ===snip=== > #!/usr/bin/python > > def show(*args): > print > for arg in args: > print arg + ':', > exec('print ' + arg) > > a=15 > b='hello' > x=['bob',3] > > show('a') > show('a','b') > show('a','b','x') > ===snip=== > > The calls to 'show' output lines like "a: 15" which could be useful > for debugging or some such purpose. > > However, it seems that I can't put the function definition in a file > and import it because I can't find a way to refer to an object in the > main program file from within a module file. I understand that it's a > good thing to contol which namespaces are referenced by which code but > isn't there sometimes a need for code in a module to access the main > program file's namespace? My example may be a little contrived but > isn't this ability legitimately needed at times? I can't think of a single legitimate reason the module would need to access the object in the namespace in any way that isn't already provided. Especially in python it breaks the model of what objects are. Strings (and integers AFAIK) are literals. Consider: >>> x[0] = 'c' Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support item assignment When you create a string in c/c++ you have a string of characters, and you can edit it as such. When you say knights = 'who say ni' in python, you are referencing knights to the literal string 'who say ni'. As far as python is considered, every single string combination already exists as an object, and your variable just references that object. At least that's the way I've understood it. So when you're trying to access the namespaces name for the object it's useless because there's nothing you can do with it. (And really it shouldn't be the responsibility of an outside function to modify the value of a variable anyway! It's also bad from a data security POV. You don't want functions messing with your data just by accident) Anyway... that's as far as I've been taught (and taught myself)... anyone notices any errors, please correct them! HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Mon Jun 29 20:08:12 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 29 Jun 2009 11:08:12 -0700 Subject: [Tutor] "Print" on 3.1 for Mac? In-Reply-To: <4A489E92.2040400@compuscan.co.za> References: <4A489E92.2040400@compuscan.co.za> Message-ID: <78b3a9580906291108u5c9d3870qba67eb4f3751bb97@mail.gmail.com> On Mon, Jun 29, 2009 at 3:59 AM, Christian Witts wrote: > lev at ithstech.com wrote: >> >> Have I installed something incorrectly in Python 3.1 for Mac if I get a >> syntax error on >> >> print "hello world" >> >> My Python 2.3.5 executes this just fine. ?What have I missed? > > Please take a read through http://docs.python.org/3.0/whatsnew/3.0.html for > a list of changes from the 2.x series to 3.x. ?It includes the fact that the > print command is now a function and needs to be called accordingly, ie. > print("Hello world!") in addition to reading the "What's New" document, you should also be aware that there is a "2to3" tool that comes with Python that helps port your existing Python 2 scripts to be as 3.x-compliant as they can. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From hyou00 at hotmail.com Mon Jun 29 19:24:04 2009 From: hyou00 at hotmail.com (hyou) Date: Mon, 29 Jun 2009 13:24:04 -0400 Subject: [Tutor] About the vertical bar input Message-ID: Hello, I'm trying to write a script that simply execute a command line like: C:\...(path)..\Devenv solution /build "Debug|Win32" However, in Python the "|" symbol is reserved thus I just can't make the command line above working once I added the "|" sign in it. How can I put the "original" vertical bar in a string? Thanks! Shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jun 29 20:47:40 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Jun 2009 14:47:40 -0400 Subject: [Tutor] does python have something like "#include" in C? In-Reply-To: <71d330f00906291023v5c77a02exd945230bf03d3b9f@mail.gmail.com> References: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> <4A48DC45.90900@tue.nl> <71d330f00906291023v5c77a02exd945230bf03d3b9f@mail.gmail.com> Message-ID: <1c2a2c590906291147s5ebf0b29ncf8be6d443cc7ea4@mail.gmail.com> On Mon, Jun 29, 2009 at 1:23 PM, Robert Lummis wrote: > Here's an example that seems not possible in python. I'm probably > missing something so please enlighten me. I only tried doing this as > an exercise to show myself how name references work. I'm not saying > it's needed or that it's good practice. > > I can write the following as a single file and it works as expected: > > ===snip=== > #!/usr/bin/python > > def show(*args): > ? ?print > ? ?for arg in args: > ? ? ? ? ? ?print arg + ':', > ? ? ? ? ? ?exec('print ' + arg) > > a=15 > b='hello' > x=['bob',3] > > show('a') > show('a','b') > show('a','b','x') > ===snip=== > > The calls to 'show' output lines like "a: 15" which could be useful > for debugging or some such purpose. > > However, it seems that I can't put the function definition in a file > and import it because I can't find a way to refer to an object in the > main program file from within a module file. Right. We did recently discuss ways to implement this function: http://www.mail-archive.com/tutor at python.org/msg35873.html > I understand that it's a > good thing to contol which namespaces are referenced by which code but > isn't there sometimes a need for code in a module to access the main > program file's namespace? My example may be a little contrived but > isn't this ability legitimately needed at times? Generally no, that would be a design smell. Module dependencies should be one-way; if main needs module foo, then foo should not have to know about main. Kent From kent37 at tds.net Mon Jun 29 20:49:07 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Jun 2009 14:49:07 -0400 Subject: [Tutor] does python have something like "#include" in C? In-Reply-To: <78b3a9580906291046n2577c9ddl49826ba4c19b9f5f@mail.gmail.com> References: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> <4A48DC45.90900@tue.nl> <71d330f00906291023v5c77a02exd945230bf03d3b9f@mail.gmail.com> <78b3a9580906291046n2577c9ddl49826ba4c19b9f5f@mail.gmail.com> Message-ID: <1c2a2c590906291149x125b32a7xfe9099ba095b911f@mail.gmail.com> On Mon, Jun 29, 2009 at 1:46 PM, wesley chun wrote: > take your function definition and store in a file called, say > showmodule.py. then put the remaining code inside something like > foo.py. at the top of foo.py, you'll need: > > from showmodule import show > > then everything else will work. I don't think so. The exec in show() must be run in the namespace in which the symbols being displayed are defined. Kent From kent37 at tds.net Mon Jun 29 20:51:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Jun 2009 14:51:36 -0400 Subject: [Tutor] About the vertical bar input In-Reply-To: References: Message-ID: <1c2a2c590906291151j7f92d2b8k368876641fb00ab0@mail.gmail.com> On Mon, Jun 29, 2009 at 1:24 PM, hyou wrote: > I?m trying to write a script that simply execute a command line like: > > C:\...(path)..\Devenv solution /build ?Debug|Win32? > > > > However, in Python the ?|? symbol is reserved thus I just can?t make the > command line above working once I added the ?|? sign in it. > > How can I put the ?original? vertical bar in a string? You can put a vertical bar in a string; In [1]: s = "Debug|Win32" In [2]: print s Debug|Win32 Can you show us the code you tried? My guess is that you are having trouble getting the quoting correct. Kent From wescpy at gmail.com Mon Jun 29 22:02:19 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 29 Jun 2009 13:02:19 -0700 Subject: [Tutor] does python have something like "#include" in C? In-Reply-To: <1c2a2c590906291149x125b32a7xfe9099ba095b911f@mail.gmail.com> References: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> <4A48DC45.90900@tue.nl> <71d330f00906291023v5c77a02exd945230bf03d3b9f@mail.gmail.com> <78b3a9580906291046n2577c9ddl49826ba4c19b9f5f@mail.gmail.com> <1c2a2c590906291149x125b32a7xfe9099ba095b911f@mail.gmail.com> Message-ID: <78b3a9580906291302o76d9f2d2s810c0d994feb102a@mail.gmail.com> >> from showmodule import show >> >> then everything else will work. > > I don't think so. The exec in show() must be run in the namespace in > which the symbols being displayed are defined. yep, you're right. i didn't see the exec. it will only work if the called function somehow had access to the same object references. the OP would have to put the assignments into showmodule.py in addition to show(), leaving only the calls to show() in foo.py. that *should* work. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From davea at ieee.org Mon Jun 29 22:07:56 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 29 Jun 2009 16:07:56 -0400 Subject: [Tutor] About the vertical bar input In-Reply-To: References: Message-ID: <4A491F1C.7020606@ieee.org> "hyou" wrote: > Hello, > > > > I'm trying to write a script that simply execute a command line like: > > C:\...(path)..\Devenv solution /build "Debug|Win32" > > > > However, in Python the "|" symbol is reserved thus I just can't make the > command line above working once I added the "|" sign in it. > > > > How can I put the "original" vertical bar in a string? > > > > Thanks! > > It would help if you mentioned which version of python you're using, and in what OS environment. I can guess you're running some Windows version because of the C:\ but the problem could also be different between XP and Vista, and certainly different between Windows95 and Windows 7. It also would help if you actually showed what you tried, and what the response was. Cut and paste the command window text into your message. I'm going to guess you did not mean "write a script that simply execute a command line like" but instead meant that the command line would be entered in a batch file, or at the command prompt, and that the python script was the first argument to the command line. In your case, the script is called "Devenv.py" and that you replaced most of its path with ellipses. As far as I know, the vertical bar isn't a special character in Python at all. It is, however, special in CMD.EXE, the command interpreter for recent Windows versions. It is used to specify multiple programs on the same command line, where the stdout of the first is piped into the stdin of the next. Similarly, the > and < symbols are used to specify redirection, and the & symbol is used to separate two commands that are to be run sequentially. CMD.EXE isn't the only shell available for Windows, but it's the standard one built into all the recent versions. So I'm guessing that's what you're using. If you're running a different one, such as 4NT, let us know. In some versions of Windows, for example in XP, the | character is not special inside a quoted string. So the example you sort-of supplied would have no problem. To demonstrate, I created a trivial Python script echo2.py: import sys print "Args are ---", sys.argv, "---" Then the following is pasted from a CMD window: M:\Programming\Python\sources\dummy>echo2 How are you? Args are --- ['M:\\Programming\\Python\\sources\\dummy\\echo2.py', 'How', 'are', 'you?'] --- M:\Programming\Python\sources\dummy>echo2 This has a "vertical|bar" Args are --- ['M:\\Programming\\Python\\sources\\dummy\\echo2.py', 'This', 'has' , 'a', 'vertical|bar'] --- M:\Programming\Python\sources\dummy>echo2 This is not|quoted 'quoted' is not recognized as an internal or external command, operable program or batch file. Note that if you cannot do matching quotes, you can get some funny groupings of text. For example, if you have leading quotes but no trailing quotes, then the entire rest of the line will be one element of sys.argv. DaveA From sato.photo at gmail.com Tue Jun 30 00:59:34 2009 From: sato.photo at gmail.com (Daniel Sato) Date: Mon, 29 Jun 2009 15:59:34 -0700 Subject: [Tutor] GASP on OSX 10.5.6 Message-ID: Hi, I am a complete python beginner. I have been going through How to Think Like A Computer Scientist 2nd edition online and have come across installing GASP in chapter 4. Unfortunately, I can't seem to find much documentation on how to install GASP when running OSX and Python 2.6.2. Any help would be greatly appreciated. Thanks! -Daniel -- Daniel Sato http://www.danielsato.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From pythonmac at rebertia.com Tue Jun 30 01:06:20 2009 From: pythonmac at rebertia.com (Chris Rebert) Date: Mon, 29 Jun 2009 16:06:20 -0700 Subject: [Tutor] [Pythonmac-SIG] GASP on OSX 10.5.6 In-Reply-To: References: Message-ID: <50697b2c0906291606l57cfc85akc7aed40aae3c59f2@mail.gmail.com> On Mon, Jun 29, 2009 at 3:59 PM, Daniel Sato wrote: > Hi, > > I am a complete python beginner.? I have been going through How to Think > Like A Computer Scientist 2nd edition online and have come across installing > GASP in chapter 4.? Unfortunately, I can't seem to find much documentation > on how to install GASP when running OSX and Python 2.6.2.? Any help would be > greatly appreciated. Mac OS X apparently not a supported platform: https://answers.launchpad.net/gasp-code/+faq/42 Cheers, Chris -- http://blog.rebertia.com From robert.lummis at gmail.com Tue Jun 30 02:51:23 2009 From: robert.lummis at gmail.com (Robert Lummis) Date: Mon, 29 Jun 2009 20:51:23 -0400 Subject: [Tutor] does python have something like "#include" in C? In-Reply-To: <1c2a2c590906291147s5ebf0b29ncf8be6d443cc7ea4@mail.gmail.com> References: <71d330f00906290803r66d3a01al6f692e6fb9b6fa7d@mail.gmail.com> <4A48DC45.90900@tue.nl> <71d330f00906291023v5c77a02exd945230bf03d3b9f@mail.gmail.com> <1c2a2c590906291147s5ebf0b29ncf8be6d443cc7ea4@mail.gmail.com> Message-ID: <71d330f00906291751v521b459av738e705860798e72@mail.gmail.com> Thanks very much for all your responses. It's pretty clear now that what I thought I could somehow do is not "pythonic" and for good reason. Kent Johnson says it well: "Module dependencies should be one-way" I can buy that. On Mon, Jun 29, 2009 at 2:47 PM, Kent Johnson wrote: > On Mon, Jun 29, 2009 at 1:23 PM, Robert Lummis wrote: >> Here's an example that seems not possible in python. I'm probably >> missing something so please enlighten me. I only tried doing this as >> an exercise to show myself how name references work. I'm not saying >> it's needed or that it's good practice. >> >> I can write the following as a single file and it works as expected: >> >> ===snip=== >> #!/usr/bin/python >> >> def show(*args): >> ? ?print >> ? ?for arg in args: >> ? ? ? ? ? ?print arg + ':', >> ? ? ? ? ? ?exec('print ' + arg) >> >> a=15 >> b='hello' >> x=['bob',3] >> >> show('a') >> show('a','b') >> show('a','b','x') >> ===snip=== >> >> The calls to 'show' output lines like "a: 15" which could be useful >> for debugging or some such purpose. >> >> However, it seems that I can't put the function definition in a file >> and import it because I can't find a way to refer to an object in the >> main program file from within a module file. > > Right. We did recently discuss ways to implement this function: > http://www.mail-archive.com/tutor at python.org/msg35873.html > >> I understand that it's a >> good thing to contol which namespaces are referenced by which code but >> isn't there sometimes a need for code in a module to access the main >> program file's namespace? My example may be a little contrived but >> isn't this ability legitimately needed at times? > > Generally no, that would be a design smell. Module dependencies should > be one-way; if main needs module foo, then foo should not have to know > about main. > > Kent > -- Robert Lummis From metolone+gmane at gmail.com Tue Jun 30 03:13:29 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 29 Jun 2009 18:13:29 -0700 Subject: [Tutor] About the vertical bar input References: Message-ID: "hyou" wrote in message news:BLU143-DS478A37DC2B1DB050E5B96C4300 at phx.gbl... > Hello, > > I'm trying to write a script that simply execute a command line like: > > C:\...(path)..\Devenv solution /build "Debug|Win32" > > However, in Python the "|" symbol is reserved thus I just can't make the > command line above working once I added the "|" sign in it. > > How can I put the "original" vertical bar in a string? Without an example of the code you are using, my guess is you are using os.system to execute a command on Windows. The Windows shell (cmd.exe) uses veritical bar for the pipe command, which sends output from one program into the input of another. The caret(^) is used in the Windows to escape special characters. Example: >>> import os >>> os.system('echo Hello|World') 'World' is not recognized as an internal or external command, operable program or batch file. 255 >>> os.system('echo Hello^|World') Hello|World 0 >>> -Mark From juhasecke at googlemail.com Tue Jun 30 10:37:42 2009 From: juhasecke at googlemail.com (Jan Ulrich Hasecke) Date: Tue, 30 Jun 2009 10:37:42 +0200 Subject: [Tutor] intefaces in python In-Reply-To: References: Message-ID: Am 28.06.2009 um 17:00 schrieb Amit Sethi: > Hi , I don't suppose python has a concept of interfaces. But can > somebody tell me if their is a way i can implement something like a > java interface in python. The Web Framework Zope has a notion of interfaces. http://pypi.python.org/pypi/zope.interface/3.5.1 There are some quite interesting things you can make with interfaces. Eg. the Component Architecture is build on interfaces and adapters. http://wiki.zope.org/zope3/WhatAreInterfaces More on this here: http://docs.zope.org/ juh -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3709 bytes Desc: not available URL: From kgotlelelok at galmail.co.za Tue Jun 30 12:05:59 2009 From: kgotlelelok at galmail.co.za (kgotlelelok at galmail.co.za) Date: Tue, 30 Jun 2009 12:05:59 +0200 (SAST) Subject: [Tutor] newton's method for system of nonlinear equations Message-ID: <3744.146.64.81.22.1246356359.squirrel@galmail.mig.wm.co.za> Hi can someone help me with my program demostrating Newton's method for system of nonlinear equations below. Line 45 gives an error saying return is outside the function and I don't know how to rectify that. I neewd this program to print differnt values of x until the differnce between previous x and present x is less than tol. Please help Thank you from scipy import* tol=0.01 def swapRows(v,i,j): if len(v.getshape()) == 1: v[i],v[j] = v[j],v[i] else: temp = v[i].copy() v[i] = v[j] v[j] = temp def swapCols(v,i,j): temp = v[:,j].copy() v[:,j] = v[:,i] v[:,i] = temp def gaussPivot(a,b,tol=1.0e-12): n = len(b) # Set up scale factors s = zeros((n),float) for i in range(n): s[i] = max(abs(a[i,:])) for k in range(0,n-1): # Row interchange, if needed p = int(argmax(abs(a[k:n,k])/s[k:n])) + k if abs(a[p,k]) < tol: error.err('Matrix is singular') if p != k: swap.swapRows(b,k,p) swap.swapRows(s,k,p) swap.swapRows(a,k,p) # Elimination for i in range(k+1,n): if a[i,k] != 0.0: lam = a[i,k]/a[k,k] a[i,k+1:n] = a [i,k+1:n] - lam*a[k,k+1:n] b[i] = b[i] - lam*b[k] if abs(a[n-1,n-1]) < tol: error.err('Matrix is singular') for k in range(n-1,-1,-1): b[k] = (b[k] - dot(a[k,k+1:n],b[k+1:n]))/a[k,k] return b def newtonRaphson2(f,x,tol=1.0e-9): def jacobian(f,x): h = 1.0e-4 n = len(x) jac = zeros((n,n),float) f0 = f(x) for i in range(n): temp = x[i] x[i] = temp + h f1 = f(x) x[i] = temp jac[:,i] = (f1 - f0)/h return jac,f0 for i in range(30): jac,f0 = jacobian(f,x) if sqrt(dot(f0,f0)/len(x)) < tol: return x dx = gaussPivot(jac,-f0) x = x + dx if sqrt(dot(dx,dx)) < tol*max(max(abs(x)),1.0): return x print 'Too many iterations' def f(x): f = zeros((len(x)),float) f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0 f[1] = 3.0*x[0] + 2.0**x[1] - x[2]**3 + 1.0 f[2] = x[0] + x[1] + x[2] - 5.0 return f x = array([1.0, 1.0, 1.0]) print newtonRaphson2(f,x) raw_input ("\nPress return to exit") ----------------------------------------- This email was sent using SquirrelMail. "Webmail for nuts!" http://squirrelmail.org/ From rabidpoobear at gmail.com Tue Jun 30 12:36:35 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 30 Jun 2009 05:36:35 -0500 Subject: [Tutor] newton's method for system of nonlinear equations In-Reply-To: <3744.146.64.81.22.1246356359.squirrel@galmail.mig.wm.co.za> References: <3744.146.64.81.22.1246356359.squirrel@galmail.mig.wm.co.za> Message-ID: <4A49EAB3.3030501@gmail.com> kgotlelelok at galmail.co.za wrote: > Hi can someone help me with my program demostrating Newton's method for > system of nonlinear equations below. Line 45 gives an error saying return > is outside the function > That's because you have a return outside of a function. > for k in range(n-1,-1,-1): > b[k] = (b[k] - dot(a[k,k+1:n],b[k+1:n]))/a[k,k] > return b Where did you get this code? You haven't given us any indication of your level of python knowledge or what exactly your problem is so it's a little difficult to help you. We don't just fix programs here, we provide guidance. It's not . We'd much rather give you a fishing pole and have you fix it yourself. From dwf at cs.toronto.edu Tue Jun 30 03:11:13 2009 From: dwf at cs.toronto.edu (David Warde-Farley) Date: Mon, 29 Jun 2009 21:11:13 -0400 Subject: [Tutor] [Pythonmac-SIG] GASP on OSX 10.5.6 In-Reply-To: <50697b2c0906291606l57cfc85akc7aed40aae3c59f2@mail.gmail.com> References: <50697b2c0906291606l57cfc85akc7aed40aae3c59f2@mail.gmail.com> Message-ID: <39213C23-2412-434A-83B8-6543388AECF7@cs.toronto.edu> On 29-Jun-09, at 7:06 PM, Chris Rebert wrote: > Mac OS X apparently not a supported platform: > https://answers.launchpad.net/gasp-code/+faq/42 It looks like the code is pure python and depends on pycairo, so in theory it should work provided cairo which has a Quartz backend) and pycairo work (and possibly pygame). MacPorts has cairo and I imagine pycairo is easy_install'able. It's unfortunately a lot of work for a beginner... David From gapetard at stsams.org Tue Jun 30 19:06:40 2009 From: gapetard at stsams.org (Bob Rea) Date: Tue, 30 Jun 2009 13:06:40 -0400 Subject: [Tutor] Needing Help Message-ID: <200906301306.41771.gapetard@stsams.org> I am jsut beginning to learn python form a book. I have run into a problem running a script from the book. I want to ask for help. Shoudl I put the whole script into my email or put it somewhere on the web for you to look at instead. Not sure how this works, script is 68 lines. -- Bob Rea mailto:gapetard at stsams.org http://www.petard.us http://www.petard.us/blog http://www.petard.us/gallery Where is Bill Stringfellow now that we really need him? From dextrous85 at gmail.com Tue Jun 30 19:17:58 2009 From: dextrous85 at gmail.com (vishwajeet singh) Date: Tue, 30 Jun 2009 22:47:58 +0530 Subject: [Tutor] Needing Help In-Reply-To: <200906301306.41771.gapetard@stsams.org> References: <200906301306.41771.gapetard@stsams.org> Message-ID: <5487b3060906301017i479cbaaesb6449a4d69085602@mail.gmail.com> You can put your script in pastebin http://python.pastebin.com/ I don't think any one will mind you pasting code in mail but pastebin makes it easier to read On Tue, Jun 30, 2009 at 10:36 PM, Bob Rea wrote: > I am jsut beginning to learn python form a book. I have run > into a problem running a script from the book. I want to > ask for help. Shoudl I put the whole script into my email > or put it somewhere on the web for you to look at instead. > Not sure how this works, script is 68 lines. > > -- > Bob Rea > mailto:gapetard at stsams.org > http://www.petard.us > http://www.petard.us/blog > http://www.petard.us/gallery > > Where is Bill Stringfellow > now that we really need him? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wodemoneke at gmail.com Tue Jun 30 19:20:40 2009 From: wodemoneke at gmail.com (Daniel Woodhouse) Date: Tue, 30 Jun 2009 20:20:40 +0300 Subject: [Tutor] Needing Help In-Reply-To: <200906301306.41771.gapetard@stsams.org> References: <200906301306.41771.gapetard@stsams.org> Message-ID: <4c0a037d0906301020o683571cfie4f481570ded2059@mail.gmail.com> You can use something like pastebin.com if you don't want to post huge chunks of code. You could also just tell us what problem occurred, was there a traceback (error message)? On Tue, Jun 30, 2009 at 8:06 PM, Bob Rea wrote: > I am jsut beginning to learn python form a book. I have run > into a problem running a script from the book. I want to > ask for help. Shoudl I put the whole script into my email > or put it somewhere on the web for you to look at instead. > Not sure how this works, script is 68 lines. > > -- > Bob Rea > mailto:gapetard at stsams.org > http://www.petard.us > http://www.petard.us/blog > http://www.petard.us/gallery > > Where is Bill Stringfellow > now that we really need him? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From petard at petard.us Tue Jun 30 20:28:56 2009 From: petard at petard.us (Bob Rea) Date: Tue, 30 Jun 2009 14:28:56 -0400 Subject: [Tutor] PYTHONPATH Message-ID: <200906301428.56970.petard@petard.us> In working my way through the book on python, i am working in directories for chapers. Now I am on modules, and some are reused in later chapters. I have set up a directory for the modules. How do I add it to my PYTHONPATH? I can use sys.path.append but that only lasts for the session. -- Bob Rea mailto:petard at petard.us http://www.petard.us http://www.petard.us/blog http://www.petard.us/gallery From petard at petard.us Tue Jun 30 20:33:27 2009 From: petard at petard.us (Bob Rea) Date: Tue, 30 Jun 2009 14:33:27 -0400 Subject: [Tutor] PYTHONPATH-corrected Message-ID: <200906301433.27455.petard@petard.us> In working my way through the book on python, I am working in directories for chapers. Now I am on modules, and some are reused in later chapters. I have set up a directory for the modules. How do I add it to my PYTHONPATH? I can use sys.path.append but that only lasts for the session. This is on a suse linux 10 box -- Bob Rea mailto:petard at petard.us http://www.petard.us http://www.petard.us/blog http://www.petard.us/gallery From bob at telaugos.com Tue Jun 30 20:06:01 2009 From: bob at telaugos.com (Bob Rea) Date: Tue, 30 Jun 2009 14:06:01 -0400 Subject: [Tutor] Needing Help In-Reply-To: <5487b3060906301017i479cbaaesb6449a4d69085602@mail.gmail.com> References: <200906301306.41771.gapetard@stsams.org> <5487b3060906301017i479cbaaesb6449a4d69085602@mail.gmail.com> Message-ID: <200906301406.02104.bob@telaugos.com> On Tue June 30 2009 1:17 pm, vishwajeet singh wrote: > You can put your script in pastebin > http://python.pastebin.com/ > I don't think any one will > mind you pasting code in mail but pastebin makes it > easier to read I am making my way through _Making Use of Python_ by Rashi Gupta. I am using Python 2.4.1 I have run into problems in a script, listed at http://python.pastebin.com/m51bc3388 If I input my own name and dob, it works: bob at gandalf:~/python/MakingUse/Chapter05> python code1.py Enter your first name: Bob Enter your last name: Rea Enter your date of birth, mm-dd-yyyy: 03-05-1943 You can chose one of the following login names: 1. BobR 2. BobR53 3. RBob43 4. BRea66 If I use the data listed in the book, it fails: bob at gandalf:~/python/MakingUse/Chapter05> python code1.py Enter your first name: Laura Enter your last name: Jones Enter your date of birth, mm-dd-yyyy: 12-24-1980 You can chose one of the following login names: 1. LauraJ 2. LauraJ2412 3. JLaura80 Traceback (most recent call last): File "code1.py", line 67, in ? fourth=fname[0]+lname+ age_func() TypeError: cannot concatenate 'str' and 'NoneType' objects What is going on here? Bob Rea petard at petard.us -- Bob Rea mailto:gapetard at stsams.org http://www.petard.us http://www.petard.us/blog http://www.petard.us/gallery Where is Bill Stringfellow now that we really need him? From steve at alchemy.com Tue Jun 30 21:08:13 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 30 Jun 2009 12:08:13 -0700 Subject: [Tutor] PYTHONPATH-corrected In-Reply-To: <200906301433.27455.petard@petard.us> References: <200906301433.27455.petard@petard.us> Message-ID: <20090630190813.GA65674@dragon.alchemy.com> On Tue, Jun 30, 2009 at 02:33:27PM -0400, Bob Rea wrote: > In working my way through the book on python, I am working > in directories for chapers. Now I am on modules, and some > are reused in later chapters. I have set up a directory for > the modules. How do I add it to my PYTHONPATH? > I can use sys.path.append but that only lasts for the > session. You set the variable in your system's environment, which is platform-dependent. For Linux, you'd typically put a line in your ~/.profile or ~/.cshrc or ~/.login or ~/.bashrc or whatever your shell uses per your account set up. So, for example, in a bash/sh shell, you'd say: export PYTHONPATH="/path/to/my/modules" or for csh: setenv PYTHONPATH "/path/to/my/modules" Then starting the next time you log in, that will be set in your environment for you. > This is on a suse linux 10 box > > -- > Bob Rea > mailto:petard at petard.us > http://www.petard.us > http://www.petard.us/blog > http://www.petard.us/gallery > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From srilyk at gmail.com Tue Jun 30 21:27:34 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 30 Jun 2009 14:27:34 -0500 Subject: [Tutor] Needing Help In-Reply-To: <333efb450906301220m260eaa6aw23a6c8baa115cdca@mail.gmail.com> References: <200906301306.41771.gapetard@stsams.org> <5487b3060906301017i479cbaaesb6449a4d69085602@mail.gmail.com> <200906301406.02104.bob@telaugos.com> <333efb450906301220m260eaa6aw23a6c8baa115cdca@mail.gmail.com> Message-ID: <333efb450906301227u76274a83x53ef42fdae41fead@mail.gmail.com> Oops, forgot my reply-to-all On Tue, Jun 30, 2009 at 2:20 PM, Wayne wrote: > On Tue, Jun 30, 2009 at 1:06 PM, Bob Rea wrote: > >> >> If I input my own name and dob, it works: >> bob at gandalf:~/python/MakingUse/Chapter05> python code1.py >> Enter your first name: Bob >> Enter your last name: Rea >> Enter your date of birth, mm-dd-yyyy: 03-05-1943 >> You can chose one of the following login names: >> 1. BobR >> 2. BobR53 >> 3. RBob43 >> 4. BRea66 >> >> If I use the data listed in the book, it fails: >> bob at gandalf:~/python/MakingUse/Chapter05> python code1.py >> Enter your first name: Laura >> Enter your last name: Jones >> Enter your date of birth, mm-dd-yyyy: 12-24-1980 >> You can chose one of the following login names: >> 1. LauraJ >> 2. LauraJ2412 >> 3. JLaura80 >> Traceback (most recent call last): >> File "code1.py", line 67, in ? >> fourth=fname[0]+lname+ age_func() >> TypeError: cannot concatenate 'str' and 'NoneType' objects >> >> What is going on here? >> > > Well the first line after "Traceback" give you the line of code and the > filename. Which happens to be code1.py line 67. > > TypeError is the type of error - specifically you tried to do something > with incompatible types. In this case, adding together a string and > NoneType. > > I'll do a little digging, but my guess is you have a problem with your > age_func() not returning any value. > > HTH, > Wayne > I was correct:def age_func(): age=cur_year-year-1 if month cur_month AND it's not my birthday? You don't return a value. But if you simply unindent the "return" value then it should fix it: def age_func(): age=cur_year-year-1 if month From bob at telaugos.com Tue Jun 30 21:27:17 2009 From: bob at telaugos.com (Bob Rea) Date: Tue, 30 Jun 2009 15:27:17 -0400 Subject: [Tutor] Needing Help In-Reply-To: <333efb450906301220m260eaa6aw23a6c8baa115cdca@mail.gmail.com> References: <200906301306.41771.gapetard@stsams.org> <200906301406.02104.bob@telaugos.com> <333efb450906301220m260eaa6aw23a6c8baa115cdca@mail.gmail.com> Message-ID: <200906301527.20516.bob@telaugos.com> On Tue June 30 2009 3:20 pm, you wrote: > On Tue, Jun 30, 2009 at 1:06 PM, Bob Rea wrote: > > > > If I input my own name and dob, it works: > > bob at gandalf:~/python/MakingUse/Chapter05> python > > code1.py Enter your first name: Bob > > Enter your last name: Rea > > Enter your date of birth, mm-dd-yyyy: 03-05-1943 > > You can chose one of the following login names: > > 1. BobR > > 2. BobR53 > > 3. RBob43 > > 4. BRea66 > > > > If I use the data listed in the book, it fails: > > bob at gandalf:~/python/MakingUse/Chapter05> python > > code1.py Enter your first name: Laura > > Enter your last name: Jones > > Enter your date of birth, mm-dd-yyyy: 12-24-1980 > > You can chose one of the following login names: > > 1. LauraJ > > 2. LauraJ2412 > > 3. JLaura80 > > Traceback (most recent call last): > > File "code1.py", line 67, in ? > > fourth=fname[0]+lname+ age_func() > > TypeError: cannot concatenate 'str' and 'NoneType' > > objects > > > > What is going on here? > > Well the first line after "Traceback" give you the line > of code and the filename. Which happens to be code1.py > line 67. > > TypeError is the type of error - specifically you tried > to do something with incompatible types. In this case, > adding together a string and NoneType. > > I'll do a little digging, but my guess is you have a > problem with your age_func() not returning any value. > > HTH, > Wayne Why doe sit work with a dob in 1943 and not with one in 1980 then, that's what really bugs me -- Bob Rea mailto:gapetard at stsams.org http://www.petard.us http://www.petard.us/blog http://www.petard.us/gallery Where is Bill Stringfellow now that we really need him? From marc.tompkins at gmail.com Tue Jun 30 21:45:00 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 30 Jun 2009 12:45:00 -0700 Subject: [Tutor] Needing Help In-Reply-To: <200906301527.20516.bob@telaugos.com> References: <200906301306.41771.gapetard@stsams.org> <200906301406.02104.bob@telaugos.com> <333efb450906301220m260eaa6aw23a6c8baa115cdca@mail.gmail.com> <200906301527.20516.bob@telaugos.com> Message-ID: <40af687b0906301245n3ffcc950k458e4bf629530965@mail.gmail.com> On Tue, Jun 30, 2009 at 12:27 PM, Bob Rea wrote: > Why doe sit work with a dob in 1943 and not with one in 1980 > then, that's what really bugs me > Nothing to do with the year. Your birth month is BEFORE June; her birth month is after. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: